-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.py
279 lines (225 loc) · 8.69 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
from __future__ import division, print_function
import sys
import os
import glob
import re
import numpy as np
import joblib
import cv2
from PIL import Image, ImageOps
from werkzeug.utils import secure_filename
from gevent.pywsgi import WSGIServer
from tensorflow.keras.models import load_model
from keras.models import load_model as kl
from tensorflow.keras.preprocessing import image
from tensorflow.python.keras.applications.vgg16 import preprocess_input
from flask import Flask, redirect, url_for, request, render_template
# Define a flask app
app = Flask(__name__, template_folder='static')
APP_ROOT = os.path.dirname(os.path.abspath(__file__))
lst = ['Malignant','Beningn','no skin ']
# Disable scientific notation for clarity
np.set_printoptions(suppress=True)
brainmodel = kl("./model/tumor_prediction.h5")
pneumoniamodel = load_model("./model/Pneumonia-DENSENET.h5")
malarialmodel = kl("./model/malariaModel.h5") # Necessary
def maleriamodel_predict(img_path, model):
img = image.load_img(img_path, target_size=(130, 130))
# Preprocessing the image
x = image.img_to_array(img)
# x = np.true_divide(x, 255)
x = np.expand_dims(x, axis=0)
# Be careful how your trained model deals with the input
# otherwise, it won't make correct prediction!
# x = preprocess_input(x, mode='caffe')
images = np.vstack([x])
preds = malarialmodel.predict(images, batch_size=16)
print(preds)
return preds
def HeartValuePredictor(to_predict_list, size):
to_predict = np.array(to_predict_list).reshape(1,size)
if(size==7):
loaded_model = joblib.load(r'./model/heart_model.pkl')
result = loaded_model.predict(to_predict)
return result[0]
def pneumoniamodel_predict(img_path, model):
img = image.load_img(img_path, target_size=(224, 224))
# Preprocessing the image
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = x / 255.0
preds = model.predict(x)
return preds
def brainmodel_predict(img_path, model):
img = image.load_img(img_path, target_size=(224, 224))
# Preprocessing the image
x = image.img_to_array(img)
# x = np.true_divide(x, 255)
x = np.expand_dims(x, axis=0)
# Be careful how your trained model deals with the input
# otherwise, it won't make correct prediction!
images = preprocess_input(x)
# images = np.vstack([x])
preds = model.predict(images, batch_size=16)
return preds
@app.route('/', methods=['GET'])
def homepage():
# Main page
return render_template('base/index.html')
@app.route('/pneumonia/', methods=['GET'])
def pneumonia():
# Main page
return render_template('pneumonia/home.html')
@app.route('/pneumonia/home.html', methods=['GET'])
def pneumoniahome():
# Main page
return render_template('pneumonia/home.html')
@app.route('/pneumonia/test',methods=['GET'])
def pneumoniatest():
return render_template('pneumonia/predict.html')
@app.route('/pneumonia/predict', methods=['GET', 'POST'])
def upload():
if request.method == 'POST':
print("hanji-------------------------")
# Get the file from post request
f = request.files['file']
# Save the file to ./uploads
basepath = os.path.dirname(__file__)
file_path = os.path.join(
basepath, 'uploads', secure_filename(f.filename))
f.save(file_path)
# Make prediction
preds = pneumoniamodel_predict(file_path, pneumoniamodel)
# Process your result for human
# pred_class = preds.argmax(axis=-1) # Simple argmax
pred_class = preds.argmax(axis = 1) # ImageNet Decode
if(pred_class[0] == 0):
answer = "Normal"
else:
answer = "Pneumonia"
result = answer # Convert to string
return result
return None
@app.route("/heart/test", methods=['GET'])
def cancer():
return render_template("heart/index.html")
@app.route('/heart/predict', methods = ["POST"])
def predict():
if request.method == "POST":
to_predict_list = request.form.to_dict()
to_predict_list = list(to_predict_list.values())
to_predict_list = list(map(float, to_predict_list))
#diabetes
if(len(to_predict_list)==7):
result = HeartValuePredictor(to_predict_list,7)
if(int(result)==1):
prediction = "Sorry you chances of getting the disease. Please consult the doctor immediately"
else:
prediction = "No need to fear. You have no dangerous symptoms of the disease"
return(render_template("heart/result.html", prediction_text=prediction))
@app.route('/malaria/test', methods=['GET'])
def malaria():
# Main page
return render_template("malaria/index.html")
@app.route('/malaria/predict', methods=['GET', 'POST'])
def malariaupload():
if request.method == 'POST':
# Get the file from post request
f = request.files['file']
# Save the file to ./uploads
basepath = os.path.dirname(__file__)
file_path = os.path.join(
basepath, 'uploads', secure_filename(f.filename))
f.save(file_path)
# Make prediction
preds = maleriamodel_predict(file_path, malaria)
# Process your result for human
# pred_class = preds.argmax(axis=-1) # Simple argmax
# pred_class = decode_predictions(preds, top=1) # ImageNet Decode
result = str(preds[0])
if preds > 0:
return "Uninfected"
else: # Convert to string
return "Infected"
return None
@app.route("/skin/test" ,methods=['GET'])
def skin():
return render_template("skin/upload.html")
@app.route("/skin/predict", methods=["POST"])
def skinupload():
target = os.path.join(APP_ROOT, 'static')
print(target)
if not os.path.isdir(target):
os.mkdir(target)
else:
print("Couldn't create upload directory: {}".format(target))
print(request.files.getlist("file"))
for upload in request.files.getlist("file"):
print(upload)
print("{} is the file name".format(upload.filename))
filename = upload.filename
destination = "/".join([target, filename])
print ("Accept incoming file:", filename)
print ("Save it to:", destination)
upload.save(destination)
# Load the model
skinmodel = load_model('./model/skin.h5',compile=False)
data = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32)
# Replace this with the path to your image
folder='static'
ex=folder+'/'+filename
image = Image.open(ex)
img=cv2.imread(ex)
img = cv2.resize(img, (0, 0), fx = 0.2, fy = 0.2)
#resize the image to a 224x224 with the same strategy as in TM2:
#resizing the image to be at least 224x224 and then cropping from the center
size = (224, 224)
image = ImageOps.fit(image, size, Image.ANTIALIAS)
#turn the image into a numpy array
image_array = np.asarray(image)
if len(image_array.shape) == 2: # ----------------Change here
image_array.resize(224, 224, 1)
# display the resized image
#image.show()
#cv2_imshow(img)
# Normalize the image
normalized_image_array = (image_array.astype(np.float32) / 127.0) - 1
# Load the image into the array
data[0] = normalized_image_array
# run the inference
prediction = skinmodel.predict(data)
#print(type(prediction))
prediction = list(prediction)
print(prediction)
class1=round(prediction[0][0]*100,2)
class2=round(prediction[0][1]*100,2)
class3=round(prediction[0][2]*100,2)
print(class1,class2,class3)
return render_template("skin/result.html",image_name=filename,class1=class1,class2=class2,class3=class3)
@app.route("/brain/test" ,methods=['GET'])
def brain():
# Main page
return render_template('brain/index.html')
@app.route('/brain/predict', methods=['GET', 'POST'])
def brainupload():
if request.method == 'POST':
# Get the file from post request
f = request.files['file']
# Save the file to ./uploads
basepath = os.path.dirname(__file__)
file_path = os.path.join(
basepath, 'uploads', secure_filename(f.filename))
f.save(file_path)
# Make prediction
preds = brainmodel_predict(file_path, brainmodel)
# Process your result for human
# pred_class = preds.argmax(axis=-1) # Simple argmax
# pred_class = decode_predictions(preds, top=1) # ImageNet Decode
# result = str(preds[0])
if preds[0][0] >= 0.9:
return "This image is NOT Tumorous."
elif preds[0][0] < 0.9: # Convert to string
return "Warning! This image is tumorous."
return None
if __name__ == '__main__':
app.run(host='0.0.0.0', port=80)