-
Notifications
You must be signed in to change notification settings - Fork 0
/
matcher_starter.py
229 lines (196 loc) · 7.31 KB
/
matcher_starter.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
#coding:UTF-8
import json
import multiprocessing
import matcher.search as manager
import threading
import schedule
from common.config.config import config_info
import time
from matcher.index_load_task import check_and_load
from flask import Flask, request, jsonify, make_response
import os
from common.remote.vc_service import _instance as vc_instance
from common.utils.log import logger
from common.utils import *
from matcher.app import app_states
from common import constants
process = multiprocessing.current_process()
# set the name
process.name = 'WaterMarkMatcherProcess_'+str(process.pid)
app = Flask(__name__)
app.logger.handlers = logger._core.handlers
app.logger.propagate = False
local_vars = threading.local()
config = config_info
tmpDir = config.tmp_dir
basedir = os.path.abspath(os.path.dirname(__file__)) # 获取当前项目的绝对路径
local_path = threading.local()
app.config['UPLOAD_FOLDER'] = tmpDir # 设置文件上传的目标文件夹
@app.route('/match/matchFile', methods=['POST'])
def api_matchFile():
times = time.time()
file_dir = os.path.join(basedir, app.config['UPLOAD_FOLDER']) # 拼接成合法文件夹地址
seqNo = request.form.get('seqNo')
app_id = request.form.get('appId')
topK = int(request.form.get('size'))
threshold = float(request.form.get('threshold'))
if not os.path.exists(file_dir):
os.makedirs(file_dir) # 文件夹不存在就创建
f = request.files['file']
# 存储到本地
local_vars.times = times
local_vars.seqNo = seqNo
tmpFile = f'{time.time_ns()}{os.getpid()}'
path = os.path.join(file_dir, tmpFile)
local_path.path=path
f.stream.seek(0)
f.save(path)
used = str(time.time() - times)
logger.info("{} save file use time = {} ", seqNo,used)
times = time.time()
features = vc_instance.getFeature(path, seqNo)
used = str(time.time() - times)
logger.info("{} vc_instance getFeature use time = {} ", seqNo,used)
times = time.time()
positive, files = manager.search(app_id, features, topK, threshold)
used = str(time.time() - times)
logger.info("{} manager search use time = {} ", seqNo,used)
res = {
"responseCode": "000000000",
"responseMessage": "Success",
"responseData": {
"positive": str(positive),
"files": files
}
}
logger.debug("positive {} {}".format(positive, type(positive)))
rst = make_response(res)
rst.headers['Access-Control-Allow-Origin'] = '*'
used = str(time.time() - times)
monitorLogs = f'{{"code": "match","bizSeqNo": "{seqNo}","resCode": "000000000","message": "Success","usedTime": {used}}}'
logger.bind(app=True).info(monitorLogs)
logger.info("{} succeed", seqNo)
return rst, 200
@app.route('/match/scan', methods=['POST'])
def api_scan():
times = time.time()
file_dir = os.path.join(basedir, app.config['UPLOAD_FOLDER']) # 拼接成合法文件夹地址
seqNo = request.form.get('seqNo')
threshold = float(request.form.get('threshold'))
pageNo = int(request.form.get('pageNo'))
pageSize = int(request.form.get('pageSize'))
if not os.path.exists(file_dir):
os.makedirs(file_dir) # 文件夹不存在就创建
f = request.files['file']
local_vars.times = times
local_vars.seqNo = seqNo
# 存储到本地
tmpFile = f'{time.time_ns()}{os.getpid()}'
path = os.path.join(file_dir, tmpFile)
local_path.path = path
f.stream.seek(0)
f.save(path)
used = str(time.time() - times)
logger.info("{} save file use time = {} ", seqNo, used)
times = time.time()
features = vc_instance.getFeature(path, seqNo)
used = str(time.time() - times)
logger.info("{} vc_instance getFeature use time = {} ", seqNo, used)
times = time.time()
scan_result = manager.scan(features, threshold, pageSize, pageNo)
used = str(time.time() - times)
logger.info("{} manager search use time = {} ", seqNo, used)
res = {
"responseCode": "000000000",
"responseMessage": "Success",
"responseData":scan_result
}
rst = make_response(res)
rst.headers['Access-Control-Allow-Origin'] = '*'
used = str(time.time() - times)
monitorLogs = f'{{"code": "match","bizSeqNo": "{seqNo}","resCode": "000000000","message": "Success","usedTime": {used}}}'
logger.bind(app=True).info(monitorLogs)
logger.info("{} succeed", seqNo)
return rst, 200
@app.errorhandler(Exception)
def framework_error(e):
# os.remove(local_path.path)
error_return = {
"responseCode": constants.ERR_INTERNAL,
"responseMessage": "INTERNAL_ERROR"
}
if isinstance(e, MatcherError):
error_return['responseCode'] = e.code
error_return['responseMessage'] = e.message
res = jsonify(error_return)
rst = make_response(res)
seqNo = local_vars.seqNo
used = str(time.time() - local_vars.times)
err_code = error_return['responseCode']
err_msg = str(error_return['responseMessage']).replace('"', '').replace("'", '').replace(",", " ").replace(":", " ")
monitorLogs = f'{{"code": "WMmatch","bizSeqNo": "{seqNo}","resCode": "{err_code}","message": "{err_msg}","usedTime": {used}}}'
logger.bind(app=True).info(monitorLogs)
logger.error("OnError: {}".format(e))
logger.exception(e)
return rst, 200
from wm.wm_match_manager import wmMatchManager
@app.route('/match/wm/auth', methods=['POST'])
def api_wm_match():
times = time.time()
seqNo = request.form.get('seqNo')
unique_hash = request.form.get('uniqueHash')
threshold = float(request.form.get('threshold'))
f = request.files['file'].read()
local_vars.times = times
local_vars.seqNo = seqNo
features = vc_instance.getFeatureByStream(f, seqNo)
used = str(time.time() - times)
logger.info("{} vc_instance getFeature use time = {} ", seqNo, used)
times = time.time()
positive, cos_similarity,uniqueId,failReason = wmMatchManager.match(features, threshold, unique_hash)
used = str(time.time() - times)
res = {
"responseCode": "000000000",
"responseMessage": "Success",
"responseData": {
"positive": str(positive),
"similarity": cos_similarity,
"uniqueId" : uniqueId,
"failReason" : failReason
}
}
logger.info("tx [{}] wmMatchManager match use time = [{}], threshold = [{}], res = [{}]", seqNo,used, str(threshold), res)
rst = make_response(res)
rst.headers['Access-Control-Allow-Origin'] = '*'
used = str(time.time() - local_vars.times)
monitorLogs = f'{{"code": "WMmatch","bizSeqNo": "{seqNo}","resCode": "000000000","message": "Success","usedTime": {used}}}'
logger.bind(app=True).info(monitorLogs)
return rst, 200
def tasklist():
#清空任务
schedule.clear()
#创建一个按秒间隔执行任务
schedule.every(config_info.index_load_interval_seconds).seconds.do(check_and_load)
while True:
schedule.run_pending()
time.sleep(1)
def startTasks():
thread = threading.Thread(target=tasklist)
thread.start()
#
#
# 磁盘加载
# check_and_load()
# 启动定时任务
# startTasks()
if __name__ == '__main__':
logger.debug("started")
# 磁盘加载
# check_and_load()
# 启动定时任务
# startTasks()
# 启动网站
app.run(port=int(config.port))
# #
# print(res)
# #