forked from FrankOcean/smart_exam
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
257 lines (213 loc) · 9.35 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
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
245
246
247
248
249
250
251
252
253
254
255
256
257
from flask import Flask, request, Response, render_template, jsonify, make_response, send_from_directory, copy_current_request_context,redirect,url_for
from werkzeug.utils import secure_filename
import uuid, datetime, threading
from strUtil import Pic_str
from face import detect_faces
from cheat_detect import cheat_detect_fuc
from opt import *
from deepface import DeepFace
app = Flask(__name__) # 实例Flask应用
# 设置图片保存文件夹
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
# 跨域支持
def after_request(resp):
resp.headers['Access-Control-Allow-Origin'] = '*'
return resp
app.after_request(after_request)
# 判断文件后缀是否在列表中
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[-1] in ALLOW_EXTENSIONS
# 首页
@app.route('/')
def hello_world():
return render_template('upload.html')
# 心跳检测
@app.route("/check", methods=["GET"])
def check():
return 'Im live'
# 上传图片
@app.route("/upload_image", methods=['POST', "GET"])
def uploads():
if request.method == 'POST':
# 获取文件
file = request.files['file']
# 检测文件格式
if file and allowed_file(file.filename):
# secure_filename方法会去掉文件名中的中文,获取文件的后缀名
file_name_hz = secure_filename(file.filename).split('.')[-1]
# 使用uuid生成唯一图片名
first_name = str(uuid.uuid4())
# 将 uuid和后缀拼接为 完整的文件名
file_name = first_name + '.' + file_name_hz
# 保存原图
file.save(os.path.join(app.config['UPLOAD_FOLDER'], file_name))
# 返回原本和缩略图的 完整浏览链接
return {"code": '200', "image_url": image_url + file_name, "message": "上传成功"}
else:
return "格式错误,仅支持jpg、png、jpeg格式文件"
return {"code": '503', "data": "", "message": "仅支持post方法"}
# 网页上传图片
@app.route('/up_photo', methods=['POST'], strict_slashes=False)
def api_upload():
file_dir = os.path.join(basedir, app.config['UPLOAD_FOLDER'])
if not os.path.exists(file_dir):
os.makedirs(file_dir)
f = request.files['photo']
if f and allowed_file(f.filename):
fname = secure_filename(f.filename)
ext = fname.rsplit('.', 1)[1]
new_filename = Pic_str().create_uuid() + '.' + ext
f.save(os.path.join(file_dir, new_filename))
print(os.path.join(file_dir, new_filename))
return jsonify({"success": 200, "msg": "上传成功"})
else:
return jsonify({"error": 1001, "msg": "上传失败"})
# show photo
@app.route('/show/<string:filename>', methods=['GET'])
def show_photo(filename):
file_dir = os.path.join(basedir, app.config['UPLOAD_FOLDER'])
if request.method == 'GET':
if filename is None:
pass
else:
image_data = open(os.path.join(file_dir, '%s' % filename), "rb").read()
response = make_response(image_data)
response.headers['Content-Type'] = 'image/png'
return response
else:
pass
# 图片获取地址 用于存放静态文件
@app.route("/image/<imageId>")
def get_frame(imageId):
# 图片上传保存的路径
try:
with open(r'./static/image/{}'.format(imageId), 'rb') as f:
image = f.read()
result = Response(image, mimetype="image/jpg")
return result
except BaseException as e:
return {"code": '503', "data": str(e), "message": "图片不存在"}
@app.route('/download/<string:filename>', methods=['GET'])
def download(filename):
if request.method == "GET":
if os.path.isfile(os.path.join(UPLOAD_FOLDER, filename)):
return send_from_directory(UPLOAD_FOLDER, filename, as_attachment=True)
pass
# 人脸检测
@app.route("/face_detect", methods=['POST', "GET"])
def face_detect():
# 使用uuid生成唯一图片名
first_name = str(uuid.uuid4())
@copy_current_request_context
def save_file(closeAfterWrite):
# 这段代码是将上传的文件写入到我们的文件存储,确保文件存在
print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + " i am doing")
f = request.files['file']
# secure_filename方法会去掉文件名中的中文,获取文件的后缀名
file_name_hz = secure_filename(f.filename).split('.')[-1]
# 将 uuid和后缀拼接为 完整的文件名
file_name = first_name + '.' + file_name_hz
# 保存原图
f.save(os.path.join(UPLOAD_FOLDER, file_name))
closeAfterWrite()
print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + " write done")
detect_faces(file_name, first_name, file_name_hz)
def passExit():
pass
if request.method == 'POST':
f = request.files['file']
if f and allowed_file(f.filename):
# 创建一个新的线程,用于保存文件
normalExit = f.stream.close
f.stream.close = passExit
t = threading.Thread(target=save_file, args=(normalExit,))
t.start()
return {"code": '200', "result": os.path.join(RESULT_FOLDER, first_name + '_result.txt')}
else:
return "格式错误,仅支持jpg、png、jpeg格式文件"
else:
return {"code": '500'}
# 人脸对比
@app.route("/face_compare_detect", methods=['POST', "GET"])
def face_compare_detect():
# 使用uuid生成唯一图片名
first_name = str(uuid.uuid4())
@copy_current_request_context
def save_file(closeAfterWrite):
# 这段代码是将上传的文件写入到我们的文件存储,确保文件存在
print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + " i am doing")
# f = request.files['file']
img1 = request.files['img1_path']
img2 = request.files['img2_path']
# secure_filename方法会去掉文件名中的中文,获取文件的后缀名
file_name_hz1 = secure_filename(img1.filename).split('.')[-1]
file_name_hz2 = secure_filename(img2.filename).split('.')[-1]
# 将 uuid和后缀拼接为 完整的文件名
img1_name = first_name + '.' + file_name_hz1
img2_name = first_name + '.' + file_name_hz2
# 保存原图
img1.save(os.path.join(UPLOAD_FOLDER, img1_name))
img2.save(os.path.join(UPLOAD_FOLDER, img2_name))
closeAfterWrite()
print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + " write done")
result = DeepFace.verify(img1_path = os.path.join(UPLOAD_FOLDER, img1_name), img2_path = os.path.join(UPLOAD_FOLDER, img2_name), model_name="Facenet")
print(result)
# 保存结果
with open(os.path.join(RESULT_FOLDER, first_name + '_result.txt'), 'w') as f:
f.write(str(result))
def passExit():
pass
if request.method == 'POST':
img1 = request.files['img1_path']
img2 = request.files['img2_path']
if img1 and img2 and allowed_file(img1.filename):
# 创建一个新的线程,用于保存文件
normalExit = img1.stream.close
img1.stream.close = passExit
img2.stream.close = passExit
t = threading.Thread(target=save_file, args=(normalExit,))
t.start()
return {"code": '200', "result": os.path.join(RESULT_FOLDER, first_name + '_result.txt')}
else:
return "格式错误,仅支持jpg、png、jpeg格式文件"
else:
return {}
# 作弊检测
@app.route("/cheat_detect", methods=['POST', "GET"])
def cheat_detect():
# 使用uuid生成唯一图片名
first_name = str(uuid.uuid4())
@copy_current_request_context
def save_file(closeAfterWrite):
# 这段代码是将上传的文件写入到我们的文件存储,确保文件存在
print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + " i am doing")
f = request.files['file']
# secure_filename方法会去掉文件名中的中文,获取文件的后缀名
file_name_hz = secure_filename(f.filename).split('.')[-1]
# 将 uuid和后缀拼接为 完整的文件名
file_name = first_name + '.' + file_name_hz
# 保存原图
f.save(os.path.join(UPLOAD_FOLDER, file_name))
closeAfterWrite()
print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + " write done")
result = cheat_detect_fuc(os.path.join(UPLOAD_FOLDER, file_name), first_name)
print(result)
with open(os.path.join(RESULT_FOLDER, first_name + '_result.txt'), 'w') as f:
f.write(str(result))
def passExit():
pass
if request.method == 'POST':
f = request.files['file']
if f and allowed_file(f.filename):
# 创建一个新的线程,用于保存文件
normalExit = f.stream.close
f.stream.close = passExit
t = threading.Thread(target=save_file, args=(normalExit,))
t.start()
return {"code": '200', "result": os.path.join(RESULT_FOLDER, first_name + '_result.txt'), 'image_url':"static/image/{}.jpg".format(first_name)}
else:
return "格式错误,仅支持jpg、png、jpeg格式文件"
else:
return {}
if __name__ == "__main__":
app.run(host='0.0.0.0', port=port, debug=True) # 项目入口