Skip to content

Commit

Permalink
Added predictions mapper imfing#2
Browse files Browse the repository at this point in the history
  • Loading branch information
saadali1996 committed Jan 6, 2020
1 parent 039a037 commit b2a54fe
Showing 1 changed file with 40 additions and 35 deletions.
75 changes: 40 additions & 35 deletions app.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import json
import os
import sys

# Flask
from PIL import Image
from flask import Flask, redirect, url_for, request, render_template, Response, jsonify, redirect
from keras_applications import imagenet_utils
from werkzeug.utils import secure_filename
from gevent.pywsgi import WSGIServer

Expand All @@ -12,51 +15,57 @@

from keras.applications.vgg16 import preprocess_input
from tensorflow.keras.models import load_model
from tensorflow.keras.preprocessing import image
from keras.backend import backend as K
from keras import backend as K

K.clear_session()
# Some utilites
import numpy as np
from util import base64_to_pil


# Declare a flask app
app = Flask(__name__)

TARGET_CLASSES = {
0: "Normal",
1: "Tuberculosis"


}

print('Model loaded. Check http://127.0.0.1:5000/')


graph = tf.get_default_graph()
# Model saved with Keras model.save()
MODEL_PATH = 'models/model.h5'

# Load your own trained model
model = load_model(MODEL_PATH)
model._make_predict_function() # Necessary
model._make_predict_function() # Necessary
print('Model loaded. Start serving...')


def model_predict(img, model):
img = img.resize((96, 96))

def model_predict(img):
# Preprocessing the image
x = image.img_to_array(img)
# x = np.true_divide(x, 255)
img = np.reshape(img, [1,96, 96, 3])
# 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='tf')
img = prepare_image(img)
preds = []
with tf.Session(graph=graph) as sess:
sess.run(tf.global_variables_initializer())

preds = model.predict(img)

return preds


def prepare_image(image):
# if the image mode is not RGB, convert it
if image.mode != "RGB":
image = image.convert("RGB")

preds = model.predict(img)
return preds
im = image.resize((96, 96), Image.ANTIALIAS)
doc = keras.preprocessing.image.img_to_array(im) # -> numpy array

doc = np.expand_dims(doc, axis=0)

return doc


@app.route('/', methods=['GET'])
Expand All @@ -67,32 +76,28 @@ def index():

@app.route('/predict', methods=['GET', 'POST'])
def predict():
prediction = {"Message": "Cannot process"}
if request.method == 'POST':
# Get the image from post request
img = base64_to_pil(request.json)

# Save the image to ./uploads
# img.save("./uploads/image.png")
try:

# Get the image from post request
img = base64_to_pil(request.json)

# Make prediction
preds = model_predict(img, model)
print(preds)
# Make prediction
preds = model_predict(img)
index_min = np.argmin(preds[0])

# Process your result for human
# pred_proba = "{:.3f}".format(np.amax(preds)) # Max probability
# pred_class = decode_predictions(preds, top=1) # ImageNet Decode
return jsonify(result=TARGET_CLASSES[index_min], probability=json.dumps(str(preds[0][index_min])))

# result = str(pred_class[0][0][1]) # Convert to string
# result = result.replace('_', ' ').capitalize()
#
# # Serialize the result, you can add additional fields
# return jsonify(result=result, probability=pred_proba)
except Exception as ex:
return None

return None


if __name__ == '__main__':
# app.run(port=5002, threaded=False)
# app.run(port=5000, threaded=False, debug=False)

# Serve the app with gevent
http_server = WSGIServer(('0.0.0.0', 5000), app)
Expand Down

0 comments on commit b2a54fe

Please sign in to comment.