-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.py
103 lines (85 loc) · 3.2 KB
/
api.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
"""
Receive a multipart data with field file
Return a json file has 3 field
("objects" ("class", "conf", "bbox" ("x", "y", "w", "h")), "code", "description")
curl -F "[email protected]" 0.0.0.0:8080
"""
import os
import sys
import tempfile
import cv2
import matplotlib.pyplot as plt
from flask import Flask, request, jsonify, render_template
from werkzeug import secure_filename
import model
ALLOWED_EXTENSIONS = set(['bmp', 'png', 'jpg', 'jpeg', 'tif', 'tiff'])
app = Flask(__name__)
app.config['TEMP_FOLDER'] = '/tmp/'
app.secret_key = 'qcuong98 super secret key'
app.config['SESSION_TYPE'] = 'filesystem'
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
def run_model(files, model_id):
result = {
"objects": [],
"code": -1,
"description": "Processing"
}
try:
if 'file' not in files:
result["code"] = 1
result["description"] = "Invalid request data"
return jsonify(result), 400
file = files['file']
if allowed_file(file.filename):
safe_name = secure_filename(file.filename)
_, temp_name = tempfile.mkstemp(
prefix = safe_name.split('.')[-2] + "_",
suffix = "." + safe_name.split('.')[-1])
file_dir = os.path.join(app.config['TEMP_FOLDER'], temp_name)
file.save(file_dir)
objs = model.detect(model_id, file_dir)
img = cv2.imread(file_dir)
height, width = img.shape[:2]
if os.path.exists(file_dir):
os.remove(file_dir)
for obj in objs:
x, y, w, h = obj[2]
x_1 = max(0, int(x - w/2))
y_1 = max(0, int(y - h/2))
x_2 = min(width, int(x + w/2))
y_2 = min(height, int(y + h/2))
result["objects"].append({
"class": obj[0].decode('UTF-8'),
"conf": obj[1],
"bbox": {
"x": x_1,
"y": y_1,
"w": x_2 - x_1,
"h": y_2 - y_1
}
})
result["code"] = 0
result["description"] = "OK"
return jsonify(result), 200
else:
result["code"] = 2
result["description"] = "File extension isn't supported"
return jsonify(result), 400
except Exception as e:
result["code"] = -1
result["description"] = "Error: %s" % e
return jsonify(result), 500
@app.route("/model_1", methods = ["POST"])
def use_model_1():
return run_model(request.files, model_1)
@app.route("/model_2", methods = ["POST"])
def use_model_2():
return run_model(request.files, model_2)
@app.route("/", methods = ["GET"])
def demo():
return render_template('home.html')
model_1 = model.get_model("cfg/coco.data", "cfg/yolov3.cfg", "weights/yolov3.weights")
model_2 = model.get_model("cfg/yologo.data", "cfg/yologo.cfg", "weights/yologo.weights")
if (__name__ == '__main__'):
app.run(host = "0.0.0.0", port = 8080)