-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
53 lines (43 loc) · 1.39 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
import os
import json
import time
from flask import Flask, request, jsonify, make_response, g
from predict import get_prediction, transform_image, render_prediction
app = Flask('flask-demo-ml')
@app.before_request
def before_request_func():
g.timings = {}
from functools import wraps
def time_this(func):
@wraps(func)
def wrapper(*args, **kwargs):
start = time.time()
r = func(*args, **kwargs)
end = time.time()
g.timings = (end - start)*1000
return r
return wrapper
@app.after_request
def after_request_func(response):
# just append timings to the output response:
d = json.loads(response.get_data())
d['time'] = str(g.timings)
response.set_data(json.dumps(d))
return response
@app.route('/', methods=['GET'])
def status():
return make_response(jsonify('OK'), 200)
@app.route('/predict', methods=['POST'])
@time_this
def predict():
if request.method == 'POST':
file = request.files['file']
if file is not None:
input_tensor = transform_image(file)
prediction_idx = get_prediction(input_tensor)
class_id, class_name = render_prediction(prediction_idx)
return jsonify({'class_id': class_id, 'class_name': class_name})
if __name__ == "__main__":
host = os.environ.get('APP_HOST', '0.0.0.0')
port = os.environ.get('APP_PORT', 5000)
app.run(host=host, port=port)