-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
85 lines (65 loc) · 2.31 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
import os
import io
import numpy as np
import keras
from keras.preprocessing import image
from keras.preprocessing.image import img_to_array
from keras.applications.xception import (
Xception, preprocess_input, decode_predictions)
from keras import backend as K
from flask import Flask, request, redirect, url_for, jsonify
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'Uploads'
model = None
graph = None
def load_model():
global model
global graph
model = Xception(weights="imagenet")
graph = K.get_session().graph
load_model()
def prepare_image(img):
img = img_to_array(img)
img = np.expand_dims(img, axis=0)
img = preprocess_input(img)
# return the processed image
return img
@app.route('/', methods=['GET', 'POST'])
def upload_file():
data = {"success": False}
if request.method == 'POST':
if request.files.get('file'):
file = request.files['file']
filename = file.filename
filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
file.save(filepath)
# Load the saved image using Keras.
# Resize it to the Xception format of 299x299 pixels.
image_size = (299, 299)
im = keras.preprocessing.image.load_img(filepath,
target_size=image_size,
grayscale=False)
# Preprocess the image and prepare it for classification.
image = prepare_image(im)
global graph
with graph.as_default():
preds = model.predict(image)
results = decode_predictions(preds)
data["predictions"] = []
for (imagenetID, label, prob) in results[0]:
r = {"label": label, "probability": float(prob)}
data["predictions"].append(r)
# indicate that the request was a success
data["success"] = True
return jsonify(data)
return '''
<!doctype html>
<title>Upload new File</title>
<h1>Upload new File</h1>
<form method=post enctype=multipart/form-data>
<p><input type=file name=file>
<input type=submit value=Upload>
</form>
'''
if __name__ == "__main__":
app.run(debug=True)