-
Notifications
You must be signed in to change notification settings - Fork 8
/
serve.py
68 lines (60 loc) · 2.19 KB
/
serve.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
from flask import Flask, flash, request, redirect, url_for, render_template, session, json
from flask_cors import CORS, cross_origin
from werkzeug.utils import secure_filename
from keras.models import load_model
from keras.preprocessing.image import load_img, img_to_array
from keras import backend as K
import numpy as np
import os
app = Flask(__name__)
TEMP_FOLDER='./temp'
app.config['UPLOAD_FOLDER']=TEMP_FOLDER
app.secret_key = "My secret key"
CORS(app)
prediction = None
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg'}
#Clear previous models from memory
K.clear_session()
#load the model before starting server
resnet_model = load_model("resnet.h5")
resnet_model._make_predict_function()
#Predicting the value and removing the temp
def predict_image(file):
filename=secure_filename(file.filename)
location=os.path.join(app.config['UPLOAD_FOLDER'],filename)
file.save(location)
test_image=load_img(location,color_mode='rgb', target_size = (100, 100))
test_image = img_to_array(test_image)
test_image=np.array([test_image])
prediction = resnet_model.predict(test_image)
os.remove(location)
prediction = prediction.argmax(axis=-1)
#Check for the allowed file extensions
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
#The main web page to be served
@app.route('/')
def index():
return render_template("index.html")
#Exposed api to predict
@app.route("/predict", methods=['POST'])
def predict():
print(request.headers)
# Check the request parameters
if request.method == 'POST':
file = request.files['image']
if 'image' not in request.files:
flash("No file received")
return "No file received"
if file and allowed_file(file.filename):
predict_image(file)
flash (True if prediction == 1 else False)
return json.dumps(True if prediction == 1 else False)
else:
flash('No selected file')
return redirect(request.url)
return "Unidentified Error Occured at server!!"
# start the flask app, allow remote connections
if __name__ == '__main__':
app.run(host='127.0.0.5', debug = True)