-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapi.py
More file actions
87 lines (69 loc) · 2.51 KB
/
api.py
File metadata and controls
87 lines (69 loc) · 2.51 KB
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
#importing Modules
from keras.applications import ResNet50
from keras.preprocessing.image import img_to_array
from keras.applications import imagenet_utils
import tensorflow as tf
from PIL import Image
import numpy as np
import flask
import base64
import io
import sys
app= flask.Flask(__name__)
model = None
#Load Model
def load_model():
#loading model
global model
model = ResNet50(weights="imagenet")
#loading Model Graph
global graph
graph = tf.get_default_graph()
def prepare_image(image,target):
#image Preprocessing Module
#Check if Image is in RGB or not if not then convert it using PIL
if(image.mode != "RGB"):
image=image.convert("RGB")
#image preprocessing to make sure that the imput image size matches the input tensor size
image = image.resize(target)
#converting image to an image array using PIL library
image = img_to_array(image)
#Making the image suitable for tensor input
image = np.expand_dims(image,axis=0)
#preprocessing the image to make it ready for input to the model
image = imagenet_utils.preprocess_input(image)
return image
@app.route("/api",methods=["POST"])
def predict():
data = {"success":False}
#Check that image is uploaded to the server
if(flask.request.method == "POST"):
if(flask.request.files.get("image")):
#debug Flag
print("Entered into Core ML Engine",file=sys.stdout)
#Read the image using PIL
image = flask.request.files["image"].read()
image = Image.open(io.BytesIO(image))
#Process image
image = prepare_image(image, target=(224, 224))
#use tf graph to predict the output
with graph.as_default():
preds = model.predict(image)
#Storing the predicted classes into list
results = imagenet_utils.decode_predictions(preds)
data["predictions"] = []
#iterate over the result to find predicted output
for(imagenetID,label,prob) in results[0]:
r = {"label":label,"probability":float(prob)}
data["predictions"].append(r)
#This flag indicates that process was successful
data["success"]=True
#return Json Data to the users
return flask.jsonify(data)
@app.route("/")
def home():
return flask.render_template("index.html")
if __name__ =="__main__":
print(("**Please Wait We are making all systems"))
load_model()
app.run(host='127.0.0.1',port=8080)