Commit 544afd82 authored by Vimalasooriya P.G.N.T's avatar Vimalasooriya P.G.N.T

Merge branch 'IT19970646' into 'master'

Insect detection part

See merge request !1
parents 9ec3bb04 5f7ec4f9
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
<component name="PyDocumentationSettings">
<option name="format" value="PLAIN" />
<option name="myDocStringFormat" value="Plain" />
</component>
</module>
\ No newline at end of file
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.9 (fertilizerProjBackend)" project-jdk-type="Python SDK" />
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/fertilizerProjBackend.iml" filepath="$PROJECT_DIR$/.idea/fertilizerProjBackend.iml" />
</modules>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$/fertilizerProjBackend" vcs="Git" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="AutoImportSettings">
<option name="autoReloadType" value="SELECTIVE" />
</component>
<component name="ChangeListManager">
<list default="true" id="effc1f58-4f9a-4fe0-8698-49968642257d" name="Changes" comment="">
<change beforePath="$PROJECT_DIR$/fertilizerProjBackend/index.py" beforeDir="false" afterPath="$PROJECT_DIR$/fertilizerProjBackend/index.py" afterDir="false" />
<change beforePath="$PROJECT_DIR$/fertilizerProjBackend/main.py" beforeDir="false" afterPath="$PROJECT_DIR$/fertilizerProjBackend/main.py" afterDir="false" />
</list>
<option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" />
<option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
<option name="LAST_RESOLUTION" value="IGNORE" />
</component>
<component name="Git.Settings">
<option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$/fertilizerProjBackend" />
</component>
<component name="ProjectId" id="2PrWlojrV5VD7b4PxkFMqEBbvR1" />
<component name="ProjectViewState">
<option name="hideEmptyMiddlePackages" value="true" />
<option name="showLibraryContents" value="true" />
</component>
<component name="PropertiesComponent"><![CDATA[{
"keyToString": {
"RunOnceActivity.OpenProjectViewOnStart": "true",
"RunOnceActivity.ShowReadmeOnStart": "true",
"last_opened_file_path": "C:/Users/user/Desktop/Project/fertilizerProjBackend",
"settings.editor.selected.configurable": "preferences.fileTypes"
}
}]]></component>
<component name="SpellCheckerSettings" RuntimeDictionaries="0" Folders="0" CustomDictionaries="0" DefaultDictionary="application-level" UseSingleDictionary="true" transferred="true" />
<component name="TaskManager">
<task active="true" id="Default" summary="Default task">
<changelist id="effc1f58-4f9a-4fe0-8698-49968642257d" name="Changes" comment="" />
<created>1684215837501</created>
<option name="number" value="Default" />
<option name="presentableId" value="Default" />
<updated>1684215837501</updated>
</task>
<servers />
</component>
</project>
\ No newline at end of file
from flask import Flask
# Define a flask app
app = Flask(__name__)
UPLOAD_FOLDER = 'uploads'
app.secret_key = "secret key"
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
import os
import flask
import json
from flask import render_template, request
from flask import jsonify
from werkzeug.utils import secure_filename
from app import app
from main import getColorPrediction, getInsectPrediction, getLeafPrediction, predictFertilizer
@app.route('/', methods=['GET'])
def index():
# Main page
return render_template('index.html')
@app.route('/predictInsect', methods=['POST'])
def submit_file():
if request.method == 'POST':
if 'file' not in request.files:
return jsonify({'error': 'No file part'})
file = request.files['file']
if file.filename == '':
return jsonify({'error': 'No file selected for uploading'})
if file:
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
label, acc = getInsectPrediction(filename)
response = {
'label': label,
'probability': acc
}
return jsonify(response)
else:
return jsonify({'error': 'Invalid request method'})
@app.route('/predictColor', methods=['POST'])
def submit_file_color():
if request.method == 'POST':
if 'file' not in request.files:
return jsonify({'error': 'No file part'})
file = request.files['file']
if file.filename == '':
return jsonify({'error': 'No file selected for uploading'})
if file:
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
label, acc = getColorPrediction(filename)
response = {
'label': label,
'probability': acc
}
return jsonify(response)
else:
return jsonify({'error': 'Invalid request method'})
@app.route('/predictLeaf', methods=['POST'])
def submit_file_leaf():
if request.method == 'POST':
if 'file' not in request.files:
return jsonify({'error': 'No file part'})
file = request.files['file']
if file.filename == '':
return jsonify({'error': 'No file selected for uploading'})
if file:
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
label, acc = getLeafPrediction(filename)
response = {
'label': label,
'probability': acc
}
return jsonify(response)
else:
return jsonify({'error': 'Invalid request method'})
@app.route('/predictFertilizer', methods=['POST'])
def submit_yield():
msg_received = flask.request.get_json()
rsp = predictFertilizer(msg_received)
return json.dumps(rsp.__dict__)
if __name__ == '__main__':
app.run(debug=True, port=4000)
import tensorflow as tf
import numpy as np
import pandas as pd
from keras_preprocessing.image import load_img
from keras_preprocessing.image import img_to_array
from teachable_machine import TeachableMachine
from sklearn.linear_model import LinearRegression
from response import Response
# Model Saved Path
INSECT_MODEL_PATH = 'models/insect_type_model.h5'
INSECT_MODEL_LABELS_PATH = 'models/insect_type_model_labels.txt'
TYPE_MODEL_PATH = 'models/paddy_or_other_pest_model.h5'
TYPE_MODEL_LABELS_PATH = 'models/paddy_or_other_pest_model_labels.txt'
LEAF_MODEL_PATH = 'models/healthy_disease_leaf_model.h5'
LEAF_MODEL_LABELS_PATH = 'models/healthy_disease_leaf_model_labels.txt'
COLOR_MODEL_PATH = 'models/colors_level_model.h5'
COLOR_MODEL_LABELS_PATH = 'models/colors_level_model_labels.txt'
# Define the mapping from class indices to class labels
type_class_labels = {0: 'PaddyPest', 1: 'OtherPest'}
class_labels = {0: 'rice leaf roller', 1: 'rice leaf caterpillar ', 2: 'paddy stem maggot', 3: 'asiatic rice borer',
4: 'yellow rice borer', 5: 'rice gall midge ', 6: 'Rice Stemfly', 7: 'brown plant hopper',
8: 'white backed plant hopper',
9: 'rice leafhopper', 10: 'Paddy Bug'}
color_labels = {0: 'ColorL2', 1: 'ColorL3', 2: 'ColorL4', 3: 'ColorL5', }
leaf_labels = {0: 'Healthy', 1: 'BrownSpot', 2: 'Hispa', 3: 'LeafBlast', 4: 'Bacterialleafblight'}
def getInsectPrediction(filename):
typeModel = TeachableMachine(model_path=TYPE_MODEL_PATH,
labels_file_path=TYPE_MODEL_LABELS_PATH)
image_path = 'uploads/' + filename
result = typeModel.classify_image(image_path)
print("class_index", result["class_index"])
print("class_name:::", result["class_name"])
print("class_confidence:", result["class_confidence"])
typeLabel = str(result["class_name"]).rstrip()
if typeLabel == 'PaddyPest':
insectModel = TeachableMachine(model_path=INSECT_MODEL_PATH,
labels_file_path=INSECT_MODEL_LABELS_PATH)
image_path = 'uploads/' + filename
result = insectModel.classify_image(image_path)
print("class_index", result["class_index"])
print("class_name:::", result["class_name"])
print("class_confidence:", result["class_confidence"])
insect_label = str(result["class_name"]).rstrip()
probability = str(result["class_confidence"])
return insect_label, probability
else:
print('Not a paddy pest')
return typeLabel, 0.0
def getColorPrediction(filename):
colorModel = TeachableMachine(model_path=COLOR_MODEL_PATH,
labels_file_path=COLOR_MODEL_LABELS_PATH)
image_path = 'uploads/' + filename
result = colorModel.classify_image(image_path)
print("class_index", result["class_index"])
print("class_name:::", result["class_name"])
print("class_confidence:", result["class_confidence"])
colorLabel = str(result["class_name"])
probability = str(result["class_confidence"])
return colorLabel, probability
def getLeafPrediction(filename):
model = TeachableMachine(model_path=LEAF_MODEL_PATH,
labels_file_path=LEAF_MODEL_LABELS_PATH)
image_path = 'uploads/' + filename
result = model.classify_image(image_path)
print("class_index", result["class_index"])
print("class_name:::", result["class_name"])
print("class_confidence:", result["class_confidence"])
label = str(result["class_name"])
probability = str(result["class_confidence"])
return label, probability
def predictFertilizer(msg_received):
try:
type = msg_received["type"]
year = msg_received["year"]
month = msg_received["month"]
keyWord = msg_received["keyWord"]
except:
p1 = Response(1, "Required data missing.", None)
return p1
type = msg_received["type"]
year = msg_received["year"]
month = msg_received["month"]
keyWord = msg_received["keyWord"]
data = ()
if type == 'month':
data = predictFertilizerMonthly(int(year), int(month), keyWord)
elif type == 'year':
data = predictFertilizerYearly(int(year), keyWord).to_dict()
else:
data = predictFertilizer(int(year), int(month), keyWord)
p1 = Response(0, "Success.", data)
return p1
def predictFertilizerMonthly(year, predMonth, predKeyWord):
year = year - 1
# Read the rainfall data into a DataFrame
df = pd.read_csv('csvFiles/fertilizer1.csv')
# Convert the date column to datetime and set it as the index
df['date'] = pd.to_datetime(df['date'])
df.set_index('date', inplace=True)
# Create a new DataFrame that contains only the crop data
crop_df = df[[predKeyWord]]
# Add a column for the month of each data point
crop_df['month'] = crop_df.index.month
# Add a column for the year of each data point
crop_df['year'] = crop_df.index.year
# Create a pivot table that shows the total rainfall for each month and year
rainfall_pivot = crop_df.pivot_table(values=predKeyWord, index='year', columns='month', aggfunc='sum')
# Create a new DataFrame that contains only the data for the previous year
prev_year_df = rainfall_pivot.loc[year]
# Drop the December rainfall data (since we're trying to predict it)
prev_year_df.drop(predMonth, inplace=True)
# Flatten the DataFrame to create two arrays (X and y) for the linear regression model
X = prev_year_df.index.values.reshape(-1, 1)
y = prev_year_df.values.reshape(-1, 1)
# Create a linear regression model and fit it to the data
model = LinearRegression()
model.fit(X, y)
# Predict the rainfall for December of the current year
current_year = pd.Timestamp.now().year
X_pred = [[current_year]]
y_pred = model.predict(X_pred)
# Print the predicted rainfall for December of the current year
print('Our guess for this year\'s December ' + predKeyWord + ' is:', y_pred[0][0])
return y_pred[0][0]
def predictFertilizerYearly(year, predKeyWord):
# Read the rainfall data into a DataFrame
df = pd.read_csv('csvFiles/fertilizer1.csv')
# Convert the date column to datetime and set it as the index
df['date'] = pd.to_datetime(df['date'])
df.set_index('date', inplace=True)
# Create a new DataFrame that contains only the crop data
crop_df = df[[predKeyWord]]
# Add a column for the month of each data point
crop_df['month'] = crop_df.index.month
# Add a column for the year of each data point
crop_df['year'] = crop_df.index.year
# Create a pivot table that shows the total rainfall for each month and year
rainfall_pivot = crop_df.pivot_table(values=predKeyWord, index='year', columns='month', aggfunc='sum')
# Create a new DataFrame that contains only the data for the previous year
prev_year_df = rainfall_pivot.loc[year - 1]
# Drop the December rainfall data (since we're using it as the target variable)
# prev_year_df.drop(predMonth, inplace=True)
# Create a DataFrame to store the predictions
predictions_df = pd.DataFrame(columns=['month', predKeyWord])
# Loop over each month and make a prediction for the next year's rainfall
for month in range(1, 13):
# Create a new DataFrame that contains only the data for the current month
month_df = prev_year_df[[month]]
print(month_df)
# Flatten the DataFrame to create two arrays (X and y) for the linear regression model
X = month_df.index.values.reshape(-1, 1)
y = month_df.values.reshape(-1, 1)
# Create a linear regression model and fit it to the data
model = LinearRegression()
model.fit(X, y)
# Predict the rainfall for the next year
next_year = year
X_pred = [[next_year]]
y_pred = model.predict(X_pred)
# Add the prediction to the predictions DataFrame
predictions_df = predictions_df.append({'month': month, predKeyWord: y_pred[0][0]}, ignore_index=True)
# Print the predicted rainfall for each month of the next year
return predictions_df
absl-py @ file:///home/conda/feedstock_root/build_artifacts/absl-py_1673535674859/work
aiohttp @ file:///Users/runner/miniforge3/conda-bld/aiohttp_1676292777256/work
aiosignal @ file:///home/conda/feedstock_root/build_artifacts/aiosignal_1667935791922/work
anyio==3.6.2
appnope @ file:///Users/ktietz/ci_310/appnope_1643965056645/work
asttokens @ file:///opt/conda/conda-bld/asttokens_1646925590279/work
astunparse @ file:///home/conda/feedstock_root/build_artifacts/astunparse_1610696312422/work
async-timeout @ file:///home/conda/feedstock_root/build_artifacts/async-timeout_1640026696943/work
asyncer==0.0.2
attrs @ file:///home/conda/feedstock_root/build_artifacts/attrs_1683424013410/work
backcall @ file:///home/ktietz/src/ci/backcall_1611930011877/work
blinker @ file:///home/conda/feedstock_root/build_artifacts/blinker_1681349778161/work
Bottleneck @ file:///private/var/folders/nz/j6p8yfhx1mv_0grj5xl4650h0000gp/T/abs_07078715-3ab7-4562-8d3d-d56b0eaa0f7dp504n_ny/croots/recipe/bottleneck_1657175566567/work
brotlipy @ file:///Users/runner/miniforge3/conda-bld/brotlipy_1666764759924/work
cached-property @ file:///home/conda/feedstock_root/build_artifacts/cached_property_1615209429212/work
cachetools @ file:///home/conda/feedstock_root/build_artifacts/cachetools_1674482203741/work
certifi==2023.5.7
cffi @ file:///Users/runner/miniforge3/conda-bld/cffi_1671179893800/work
charset-normalizer @ file:///tmp/build/80754af9/charset-normalizer_1630003229654/work
click @ file:///home/conda/feedstock_root/build_artifacts/click_1666798198223/work
coloredlogs==15.0.1
contourpy @ file:///Users/runner/miniforge3/conda-bld/contourpy_1673633760692/work
cryptography @ file:///Users/runner/miniforge3/conda-bld/cryptography-split_1681508747141/work
cycler @ file:///home/conda/feedstock_root/build_artifacts/cycler_1635519461629/work
debugpy @ file:///Users/ktietz/ci_310/debugpy_1643965577625/work
decorator @ file:///opt/conda/conda-bld/decorator_1643638310831/work
entrypoints @ file:///private/var/folders/nz/j6p8yfhx1mv_0grj5xl4650h0000gp/T/abs_croot-jb01gaox/entrypoints_1650293758411/work
executing @ file:///opt/conda/conda-bld/executing_1646925071911/work
fastapi==0.95.1
filetype==1.2.0
Flask @ file:///opt/conda/conda-bld/flask_1648041541647/work
flatbuffers @ file:///home/conda/feedstock_root/build_artifacts/python-flatbuffers_1674415895114/work
fonttools @ file:///Users/runner/miniforge3/conda-bld/fonttools_1683740659111/work
frozenlist @ file:///Users/runner/miniforge3/conda-bld/frozenlist_1667935502123/work
gast @ file:///home/conda/feedstock_root/build_artifacts/gast_1596839682936/work
google-auth @ file:///home/conda/feedstock_root/build_artifacts/google-auth_1683751600794/work
google-auth-oauthlib==0.4.1
google-pasta==0.2.0
grpcio @ file:///Users/runner/miniforge3/conda-bld/grpc-split_1670307403148/work
h11==0.14.0
h5py @ file:///Users/runner/miniforge3/conda-bld/h5py_1674499087545/work
humanfriendly==10.0
idna @ file:///home/conda/feedstock_root/build_artifacts/idna_1663625384323/work
ImageHash==4.3.1
imageio==2.28.1
importlib-metadata @ file:///home/conda/feedstock_root/build_artifacts/importlib-metadata_1682176699712/work
ipykernel @ file:///private/var/folders/nz/j6p8yfhx1mv_0grj5xl4650h0000gp/T/abs_croot-4yxj69n0/ipykernel_1647009452031/work/dist/ipykernel-6.9.1-py3-none-any.whl
ipython @ file:///private/var/folders/nz/j6p8yfhx1mv_0grj5xl4650h0000gp/T/abs_b42ce53b-9348-4ffe-874e-ee7a7d34be58zn88hkt_/croots/recipe/ipython_1651600151534/work
itsdangerous @ file:///tmp/build/80754af9/itsdangerous_1621432558163/work
jedi @ file:///private/var/folders/nz/j6p8yfhx1mv_0grj5xl4650h0000gp/T/croot-f1t6hma6/jedi_1644315882177/work
Jinja2 @ file:///opt/conda/conda-bld/jinja2_1647436528585/work
joblib @ file:///tmp/build/80754af9/joblib_1635411271373/work
jupyter-client @ file:///private/var/folders/nz/j6p8yfhx1mv_0grj5xl4650h0000gp/T/abs_37f0874a-8189-43c8-984a-7cc5aa7f2a00vekz677y/croots/recipe/jupyter_client_1650622203010/work
jupyter-core @ file:///private/var/folders/nz/j6p8yfhx1mv_0grj5xl4650h0000gp/T/abs_5839c60e-0f30-4a99-b0b9-2b009ec5fec40y9fo9ym/croots/recipe/jupyter_core_1651671230982/work
keras @ file:///Users/rkeith/miniconda3/conda-bld/keras_1678487506171/work/keras-2.11.0-py2.py3-none-any.whl
Keras-Preprocessing @ file:///home/conda/feedstock_root/build_artifacts/keras-preprocessing_1610713559828/work
kiwisolver @ file:///Users/runner/miniforge3/conda-bld/kiwisolver_1666805765141/work
lazy_loader==0.2
llvmlite==0.40.0
Markdown @ file:///home/conda/feedstock_root/build_artifacts/markdown_1679584000376/work
MarkupSafe @ file:///Users/runner/miniforge3/conda-bld/markupsafe_1674135859696/work
matplotlib @ file:///Users/runner/miniforge3/conda-bld/matplotlib-suite_1678135763500/work
matplotlib-inline @ file:///tmp/build/80754af9/matplotlib-inline_1628242447089/work
mpmath==1.3.0
multidict @ file:///Users/runner/miniforge3/conda-bld/multidict_1672339514000/work
munkres==1.1.4
nest-asyncio @ file:///private/var/folders/nz/j6p8yfhx1mv_0grj5xl4650h0000gp/T/abs_croot-xymukih3/nest-asyncio_1649931465456/work
networkx==3.1
numba==0.57.0
numexpr @ file:///private/var/folders/nz/j6p8yfhx1mv_0grj5xl4650h0000gp/T/abs_76yyu1p9jk/croot/numexpr_1683221830860/work
numpy @ file:///Users/runner/miniforge3/conda-bld/numpy_1682210346059/work
oauthlib @ file:///home/conda/feedstock_root/build_artifacts/oauthlib_1666056362788/work
onnxruntime==1.14.1
opencv-python==4.7.0
opencv-python-headless==4.7.0.72
opt-einsum @ file:///home/conda/feedstock_root/build_artifacts/opt_einsum_1617859230218/work
packaging @ file:///home/conda/feedstock_root/build_artifacts/packaging_1681337016113/work
pandas==1.5.3
parso @ file:///opt/conda/conda-bld/parso_1641458642106/work
pexpect @ file:///tmp/build/80754af9/pexpect_1605563209008/work
pickleshare @ file:///tmp/build/80754af9/pickleshare_1606932040724/work
Pillow @ file:///Users/runner/miniforge3/conda-bld/pillow_1680694547271/work
platformdirs @ file:///home/conda/feedstock_root/build_artifacts/platformdirs_1683850015520/work
pooch @ file:///home/conda/feedstock_root/build_artifacts/pooch_1679580333621/work
prompt-toolkit @ file:///tmp/build/80754af9/prompt-toolkit_1633440160888/work
protobuf==4.21.12
ptyprocess @ file:///tmp/build/80754af9/ptyprocess_1609355006118/work/dist/ptyprocess-0.7.0-py2.py3-none-any.whl
pure-eval @ file:///opt/conda/conda-bld/pure_eval_1646925070566/work
pyasn1==0.4.8
pyasn1-modules==0.2.7
pycparser @ file:///home/conda/feedstock_root/build_artifacts/pycparser_1636257122734/work
pydantic==1.10.7
Pygments @ file:///opt/conda/conda-bld/pygments_1644249106324/work
PyJWT @ file:///home/conda/feedstock_root/build_artifacts/pyjwt_1683676063469/work
PyMatting==1.1.8
pyOpenSSL @ file:///home/conda/feedstock_root/build_artifacts/pyopenssl_1680037383858/work
pyparsing @ file:///home/conda/feedstock_root/build_artifacts/pyparsing_1652235407899/work
PySocks @ file:///home/conda/feedstock_root/build_artifacts/pysocks_1661604839144/work
python-dateutil @ file:///tmp/build/80754af9/python-dateutil_1626374649649/work
python-multipart==0.0.6
pytz @ file:///private/var/folders/nz/j6p8yfhx1mv_0grj5xl4650h0000gp/T/abs_c56ru3yml9/croot/pytz_1671697451306/work
pyu2f @ file:///home/conda/feedstock_root/build_artifacts/pyu2f_1604248910016/work
PyWavelets==1.4.1
pyzmq @ file:///Users/ktietz/ci_310/pyzmq_1643964387809/work
rembg==2.0.36
requests @ file:///home/conda/feedstock_root/build_artifacts/requests_1682535435083/work
requests-oauthlib @ file:///home/conda/feedstock_root/build_artifacts/requests-oauthlib_1643557462909/work
rsa @ file:///home/conda/feedstock_root/build_artifacts/rsa_1658328885051/work
scikit-image==0.20.0
scikit-learn @ file:///Users/ktietz/ci_310/scikit-learn_1644264513665/work
scipy @ file:///Users/runner/miniforge3/conda-bld/scipy-split_1683900561684/work/base/dist/scipy-1.10.1-cp310-cp310-macosx_11_0_arm64.whl#sha256=a3c0cd42a1c134ecde8ed82f601d7bcc58f1bd7fe5f748f9322af7396f50d220
seaborn==0.12.2
six @ file:///home/conda/feedstock_root/build_artifacts/six_1620240208055/work
sniffio==1.3.0
stack-data @ file:///opt/conda/conda-bld/stack_data_1646927590127/work
starlette==0.26.1
sympy==1.12
tensorboard @ file:///Users/rkeith/miniconda3/conda-bld/tensorboard_1678488689416/work/tensorboard-2.11.0-py3-none-any.whl
tensorboard-data-server @ file:///var/folders/nz/j6p8yfhx1mv_0grj5xl4650h0000gp/T/abs_91lm1y0ip6/croot/tensorboard-data-server_1670853587549/work/tensorboard_data_server-0.6.1-py3-none-macosx_11_0_arm64.whl
tensorboard-plugin-wit @ file:///home/conda/feedstock_root/build_artifacts/tensorboard-plugin-wit_1641458951060/work/tensorboard_plugin_wit-1.8.1-py3-none-any.whl
tensorflow @ file:///Users/mark/git/feedstocks/tensorflow-feedstock/miniforge3/conda-bld/tensorflow-split_1679779258596/work/tensorflow_pkg/tensorflow-2.11.1-cp310-cp310-macosx_11_0_arm64.whl
tensorflow-estimator @ file:///Users/mark/git/feedstocks/tensorflow-feedstock/miniforge3/conda-bld/tensorflow-split_1679779258596/work/tensorflow-estimator/wheel_dir/tensorflow_estimator-2.11.0-py2.py3-none-any.whl
termcolor @ file:///home/conda/feedstock_root/build_artifacts/termcolor_1682317048417/work
threadpoolctl @ file:///Users/ktietz/demo/mc3/conda-bld/threadpoolctl_1629802263681/work
tifffile==2023.4.12
tornado @ file:///Users/ktietz/ci_310/tornado_1643969120498/work
tqdm==4.65.0
traitlets @ file:///tmp/build/80754af9/traitlets_1636710298902/work
typing_extensions @ file:///home/conda/feedstock_root/build_artifacts/typing_extensions_1678559861143/work
unicodedata2 @ file:///Users/runner/miniforge3/conda-bld/unicodedata2_1667239979860/work
urllib3 @ file:///home/conda/feedstock_root/build_artifacts/urllib3_1678635778344/work
uvicorn==0.22.0
watchdog==3.0.0
wcwidth @ file:///Users/ktietz/demo/mc3/conda-bld/wcwidth_1629357192024/work
Werkzeug @ file:///home/conda/feedstock_root/build_artifacts/werkzeug_1683636301408/work
wrapt @ file:///Users/runner/miniforge3/conda-bld/wrapt_1677485667378/work
yarl @ file:///Users/runner/miniforge3/conda-bld/yarl_1682426738484/work
zipp @ file:///home/conda/feedstock_root/build_artifacts/zipp_1677313463193/work
class Response:
def __init__(self, code, message, data):
self.code = code
self.message = message
self.data = data
from keras.models import load_model
from PIL import Image, ImageOps
import numpy as np
class TeachableMachine(object):
'''
Create your TeachableMachine object to run your trained AI models.
'''
def __init__(self, model_path='keras_model.h5', labels_file_path='labels.txt', model_type='h5') -> None:
self._model_type = model_type.lower()
self._labels_file_path = labels_file_path
self._supported_types = ('keras', 'Keras', 'h5', 'h5py')
np.set_printoptions(suppress=True)
try:
self._model = load_model(model_path, compile=False)
except IOError as e:
print('LoadingModelError: Error while loading Teachable Machine model')
raise IOError(e)
except:
print("LoadingModelError: Error while loading Teachable Machine model")
raise FileNotFoundError
try:
self._labels_file = open(self._labels_file_path, "r").readlines()
except IOError as e:
print('LoadingLabelsError: Error while loading labels.txt file')
raise IOError(e)
except:
print("LoadingLabelsError: Error while loading labels.txt file")
raise FileNotFoundError
self._object_creation_status = self._model_type in self._supported_types
if self._object_creation_status:
print('Teachable Machine Object is created successfully.')
else:
raise 'NotSupportedType: Your model type is not supported, try to use types such as "keras" or "h5".'
def classify_image(self, frame_path: str):
'''To deploy your Teachable Machine Model on a computer/PC
with .h5 extension using TensorFlow.
Parameters:
* (str) frame_path: Provide path of the image to be classified.
Returns:
* class_name: Name of the highest predicted class according to labels.txt file
* class_index: Index or ID of the highest predicted class according to labels.txt file
* predictions: All prediction values for all classes.
'''
try:
frame = Image.open(frame_path)
if frame.mode != "RGB":
frame = frame.convert("RGB")
except FileNotFoundError as e:
print("ImageNotFound: Error in image file.")
raise FileNotFoundError(e)
except TypeError as e:
print(
"ImageTypeError: Error while converting image to RGB format, image type is not supported")
try:
if self._object_creation_status:
return self._get_image_classification(frame)
except BaseException as e:
print('Error in classification process, retrain your model.')
raise e
def _get_image_classification(self, image):
data = self._form_image(image)
prediction = self._model.predict(data)
class_index = np.argmax(prediction)
class_name = self._labels_file[class_index]
class_confidence = prediction[0][class_index]
return {
"class_name": class_name[2:],
"highest_class_name": class_name[2:],
"highest_class_id": class_index,
"class_index": class_index,
"class_id": class_index,
"predictions": prediction,
"all_predictions": prediction,
"class_confidence": class_confidence,
"highest_class_confidence": class_confidence,
}
def _form_image(self, image):
image_data = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32)
crop_size = (224, 224)
image = ImageOps.fit(image, crop_size, Image.Resampling.LANCZOS)
image_array = np.asarray(image)
normalized_image_array = (image_array.astype(np.float32) / 127.0) - 1
image_data[0] = normalized_image_array
return image_data
Subproject commit 6ab1067a166b8de8b41ec98432f6b257192c5ae8
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment