-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathweb_api.py
244 lines (192 loc) · 6.79 KB
/
web_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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
import cv2
from PIL import Image
import os
import io
from io import BytesIO
import shutil
import base64
import numpy
import uuid
from flask import Flask, request, Response, jsonify, url_for, send_file, abort
import prediction
from web import app, model_train
import redis
from importlib import reload
from flask_socketio import SocketIO, emit, send
socketio = SocketIO(app, path="/api/predict/socket")
IMG_PATH = os.path.abspath("./temps")
FACES_IMG_ROOT_PATH = os.path.abspath("./faces")
def face_url(student_id, filename):
temp_link = "/api/predict/faces/temp/{student_id}/{filename}"
@app.route('/api/predict/train', methods=['POST'])
def train_task():
r = redis.StrictRedis(host='localhost', port=6379, db=0)
task_id = r.get('current_job')
task = model_train.AsyncResult(task_id)
if task.state == 'PENDING' or task.state == 'RUNNING':
response = {
'ready' : False,
'task': task_id.decode('utf-8'),
'state': task.state
}
else:
result = model_train.apply_async()
response = {
'ready' : False,
'task': 'RUNNING',
'state': result.state
}
r.set('current_job', result.task_id)
if task_id.decode('utf-8') == '':
result = model_train.apply_async()
response = {
'ready' : False,
'task': 'RUNNING',
'state': result.state
}
r.set('current_job', result.task_id)
return jsonify(response)
@app.route('/api/predict/train/reload', methods=['POST'])
def model_reload():
reload(prediction)
return jsonify({'success': True})
@app.route('/api/predict/train/status', methods=['POST'])
def train_status():
r = redis.StrictRedis(host='localhost', port=6379, db=0)
task_id = r.get('current_job')
task = model_train.AsyncResult(task_id)
if task.state == 'PENDING' or task.state == 'RUNNING':
response = {
'ready' : False,
'task' : task_id.decode('utf-8'),
'state': task.state
}
else:
response = {
'ready' : True,
'task' : task_id.decode('utf-8'),
'state': task.state
}
prediction.load_facenet_model()
if task_id.decode('utf-8') == "":
response['ready'] = True
return jsonify(response)
@app.route("/api/predict/train/reset", methods=['post'])
def reset_task():
r = redis.StrictRedis(host='localhost', port=6379, db=0)
r.set('current_job', '')
return jsonify({'success': True})
@app.route("/api/predict/train/<task_id>", methods=['POST'])
def show_result(task_id):
task = model_train.AsyncResult(task_id)
if task.state == 'PENDING':
# job did not start yet
response = {
'state': task.state,
}
elif task.state != 'FAILURE':
response = {
'state': task.state,
}
else:
# something went wrong in the background job
response = {
'state': task.state,
'status': str(task.info), # this is the exception raised
}
return jsonify(response)
@app.route('/api/predict', methods=['POST'])
def predict():
image_file = request.files["image"]
file_loc = os.path.join(IMG_PATH, str(uuid.uuid4()))
image_file.save(file_loc)
img = cv2.imread(file_loc)
results = jsonify(prediction.predict_all(img))
os.remove(file_loc)
return results
@app.route('/api/predict/faces/register', methods=['POST'])
def regis_face():
student_id = request.form['student_id']
student_image = request.files['image']
student_faces_path = os.path.join(IMG_PATH, "faces", student_id)
if(not os.path.isdir(student_faces_path)):
os.makedirs(student_faces_path)
filename = "{}.{}".format(uuid.uuid4(), student_image.filename.split(".")[-1])
save_loc = os.path.join(IMG_PATH, filename)
student_image.save(save_loc)
img = cv2.imread(save_loc)
face_locations = prediction.face_location(img)
temp_face_urls = []
for face_location in face_locations:
face_location = face_location["face_location"]
face_img = prediction.crop_and_resize(img, face_location, (160, 160))
image_uuid = uuid.uuid4()
filename = "{}.png".format(image_uuid)
save_path = os.path.join(IMG_PATH, "faces", student_id, filename)
cv2.imwrite(save_path, face_img)
temp_face_urls.append({
"id": image_uuid,
"url": url_for("temp_face", student_id=student_id, filename=filename)
})
return jsonify(temp_face_urls)
@app.route('/api/predict/faces/temp/<student_id>/<filename>')
def temp_face(student_id, filename):
image_path = os.path.join(IMG_PATH, "faces", student_id, filename)
print(image_path)
print(os.path.isfile(image_path))
if(os.path.isfile(image_path)):
return send_file(image_path)
else:
abort(404)
@app.route('/api/predict/faces/select', methods=['POST'])
def select_face():
student_id = request.form["student_id"]
image_id = request.form["image_id"]
filename = "{}.png".format(image_id)
temp_img_path = os.path.join(IMG_PATH, "faces", student_id)
if(not os.path.isdir(temp_img_path)):
response = jsonify(success=False)
response.status_code = 400
return response
student_faces_path = os.path.join(FACES_IMG_ROOT_PATH, student_id)
source_path = os.path.join(temp_img_path, filename)
dest_path = os.path.join(FACES_IMG_ROOT_PATH, student_id, filename)
if(os.path.isfile(source_path)):
if(not os.path.isdir(student_faces_path)):
os.makedirs(student_faces_path)
os.rename(source_path, dest_path)
shutil.rmtree(temp_img_path)
response = jsonify(success=True)
else:
response = jsonify(success=False)
response.status_code = 400
return response
@socketio.on('message')
def handle_message(message):
emit('response', 'Test')
@socketio.on('predict', namespace='/predict')
def handle_predict(image):
# Decode base64
imgdata = base64.b64decode(str(image))
image = Image.open(io.BytesIO(imgdata))
image_file = cv2.cvtColor(numpy.array(image), cv2.COLOR_BGR2RGB)
# file_loc = os.path.join(IMG_PATH, str(uuid.uuid4()))
# image_file.save(file_loc)
# img = cv2.imread(file_loc)
# Process result
results = prediction.predict_all(image_file)
# os.remove(file_loc)
# Reverse color back
image_file = cv2.cvtColor(image_file, cv2.COLOR_BGR2RGB)
# Encode to base64
pil_img = Image.fromarray(image_file)
buff = BytesIO()
pil_img.save(buff, format="JPEG")
image = base64.b64encode(buff.getvalue()).decode("utf-8")
emit('video', image)
emit('result', results)
@app.route('/api/predict')
def main():
return "Hello Classnalytic!"
if __name__ == "__main__":
app.run(debug=True, host="0.0.0.0")