TEST.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  1. from hub import methods, Global, numpy_method, camera_handle
  2. from factories.line_manage import LineManage
  3. import base64
  4. import cv2
  5. import os
  6. class TEST(object):
  7. @classmethod
  8. def test002(cls, **params):
  9. """
  10. """
  11. try:
  12. # --- define ---
  13. run_at = methods.now_ts()
  14. condition = {
  15. 'face_name': {'$ne': None},
  16. }
  17. total = Global.mdb.get_count('Face', condition)
  18. items = Global.mdb.filter('Face', condition)
  19. count = 0
  20. for item in items:
  21. # --- log ---
  22. count += 1
  23. methods.debug_log('TEST.test002', f"m-24: {count}/{total}")
  24. # --- check ---
  25. face_image_path = item.get('face_feature_info_list')[0].get('face_image_path')
  26. face_image_path = f"{face_image_path[:-4]}-fake.jpg"
  27. if not os.path.isfile(face_image_path):
  28. continue
  29. # --- 提取特征 ---
  30. image_array = cv2.imread(face_image_path)
  31. result = Global.scrfd_agent.inference_with_image_array(image_array)
  32. face_image = result[0].get('align_face')
  33. face_features = Global.arcface_agent.get_face_features_normalization_by_image_array(face_image)
  34. # --- check null ---
  35. if face_features is None:
  36. methods.debug_log('TEST.test002', f"m-46: face_features is None! | {face_image_path}")
  37. continue
  38. # --- update ---
  39. face_uuid = str(item.get('_id'))
  40. face_feature_info_list = item.get('face_feature_info_list')
  41. face_feature_info_list.append(
  42. {
  43. 'face_object_confidence': 1.0,
  44. 'face_features': methods.pickle_dumps(face_features),
  45. 'face_image_path': face_image_path,
  46. 'detector_name': 'scrfd',
  47. 'mask_on_face_is': False,
  48. }
  49. )
  50. Global.mdb.update_one_by_id('Face', face_uuid, {'face_feature_info_list': face_feature_info_list})
  51. methods.debug_log('TEST.test002', f"m-62: face_image_path -> {face_image_path} | {face_uuid}")
  52. # --- log ---
  53. methods.debug_log('TEST.test002', f"m-32: time use {round(methods.now_ts() - run_at, 2)}s, "
  54. f"update count is {count}")
  55. return dict(code=0, details=f"end.")
  56. except Exception as exception:
  57. methods.debug_log('TEST.test002', f"m-84: exception | {exception}")
  58. methods.debug_log('TEST.test002', f"m-84: traceback | {methods.trace_log()}")
  59. return dict(code=-1, details=f"{methods.trace_log()}")
  60. @classmethod
  61. def test001(cls, **params):
  62. """批量导入人脸特征数据"""
  63. try:
  64. # --- define ---
  65. api = Global.get_yzw_client()
  66. db1 = Global.get_mariadb_client()
  67. db2 = Global.get_mongodb_client()
  68. run_at = methods.now_ts()
  69. # --- get mariadb.worker_info ---
  70. count = 0
  71. items = db1.get_all('worker_info')
  72. for item in items:
  73. # --- debug log ---
  74. count += 1
  75. if count % 1000 == 0:
  76. methods.debug_log('TEST.test001', f"count: {count}")
  77. # --- check null ---
  78. if not item.image_path:
  79. continue
  80. # --- set tags if not exists ---
  81. data = db2.get_one(Global.dataset_name, {'prc_id': item.worker_id})
  82. project_name_tags = data.get('project_name_tags', list())
  83. worker_type_tags = data.get('worker_type_tags', list())
  84. if item.project_name and item.project_name not in project_name_tags:
  85. project_name_tags.append(item.project_name)
  86. if item.worker_type and item.worker_type not in worker_type_tags:
  87. worker_type_tags.append(item.worker_type)
  88. # --- set face if not exists ---
  89. face_features = data.get('face_features')
  90. if not face_features:
  91. # --- check null ---
  92. image_bytes = api.get_image(item.image_path)
  93. if not image_bytes:
  94. # methods.debug_log('TEST.test001', f"d1: {item.worker_id}")
  95. continue
  96. # --- get face features ---
  97. face_features = DetectFaceEngine.get_face_features_by_image_bytes(image_bytes)
  98. # methods.debug_log('TEST.test001', f"d1: {face_features}")
  99. # --- check null ---
  100. if not face_features:
  101. # methods.debug_log('TEST.test001', f"d1: {item.worker_id}")
  102. continue
  103. # --- set mongodb.VisitorInfo ---
  104. unique_dict = {
  105. 'prc_id': item.worker_id,
  106. }
  107. update_dict = {
  108. 'face_name': item.worker_name,
  109. 'face_path': f"https://lwres.yzw.cn/{item.image_path}",
  110. 'face_features': methods.pickle_dumps(face_features),
  111. 'project_name_tags': project_name_tags,
  112. 'worker_type_tags': worker_type_tags,
  113. }
  114. db2.update_one(Global.dataset_name, unique_dict, update_dict)
  115. # break
  116. methods.debug_log('TEST.test001', f"t1: {methods.now_ts() - run_at}s")
  117. return dict(code=0, details=f"end.")
  118. except Exception as exception:
  119. methods.debug_log('TEST.test001', f"m-84: exception | {exception}")
  120. methods.debug_log('TEST.test001', f"m-84: traceback | {methods.trace_log()}")
  121. return dict(code=-1, details=f"{methods.trace_log()}")
  122. @classmethod
  123. def test004(cls, **params):
  124. """更新 mongo.VisitorTags 表数据"""
  125. run_at = methods.now_ts()
  126. try:
  127. # --- update mongodb.VisitorInfo ---
  128. mdb = Global.get_mongodb_client()
  129. for item in mdb.get_all(Global.dataset_name):
  130. # --- update ProjectName ---
  131. project_name_tags = item.get('project_name_tags', [])
  132. for project_name in project_name_tags:
  133. unique_dict = {
  134. 'tag_type': 'ProjectName',
  135. 'tag_name': project_name,
  136. }
  137. update_dict = {}
  138. mdb.update_one('VisitorTags', unique_dict, update_dict)
  139. # --- update ProjectName ---
  140. worker_type_tags = item.get('worker_type_tags', [])
  141. for worker_type in worker_type_tags:
  142. unique_dict = {
  143. 'tag_type': 'WorkerType',
  144. 'tag_name': worker_type,
  145. }
  146. update_dict = {}
  147. mdb.update_one('VisitorTags', unique_dict, update_dict)
  148. # --- todo 遍历 VisitorTags 表 然后更新每条数据的 face_amout 字段 统计每个标签所属的人数
  149. methods.debug_log('TEST.test004', f"m1: {methods.now_ts() - run_at}s")
  150. return dict(code=0)
  151. except Exception as exception:
  152. methods.debug_log('TEST.test004', f"m-124: exception | {exception}")
  153. methods.debug_log('TEST.test004', f"m-124: traceback | {methods.trace_log()}")
  154. return dict(code=-1, details=f"{methods.trace_log()}")
  155. @classmethod
  156. def test006(cls, **params):
  157. """
  158. crop_img=np.array(faces[i]) # 每张图中的单个人脸图像
  159. cv2.imwrite('crop.jpg',crop_img)
  160. """
  161. try:
  162. # --- define ---
  163. mdb = Global.get_mongodb_client()
  164. item = mdb.get_one_by_id('Face', '622fffd65bda389a51c96c24')
  165. face_features_1 = methods.pickle_loads(item.get('face_features'))
  166. item = mdb.get_one_by_id('Face', '622fff612ae2021a236e2c90')
  167. face_features_2 = methods.pickle_loads(item.get('face_features'))
  168. dist = Global.arcface_agent.compare_faces_by_normalization(face_features_1, face_features_2)
  169. methods.debug_log('TEST.test006', f"m-196: dist: {dist}")
  170. return dict(code=0, details=f"End.", dist=dist)
  171. except Exception as exception:
  172. methods.debug_log('TEST.test006', f"m-124: exception | {exception}")
  173. methods.debug_log('TEST.test006', f"m-124: traceback | {methods.trace_log()}")
  174. return dict(code=-1, details=f"{methods.trace_log()}")
  175. @classmethod
  176. def test007(cls, **params):
  177. """url测试websocket在线信息"""
  178. try:
  179. line_total = LineManage.get_line_total()
  180. line_state = LineManage.get_line_state()
  181. return dict(code=0, line_total=line_total, line_state=line_state)
  182. except Exception as exception:
  183. methods.debug_log('TEST.test007', f"m-161: exception | {exception}")
  184. methods.debug_log('TEST.test007', f"m-161: traceback | {methods.trace_log()}")
  185. return dict(code=-1, details=f"{methods.trace_log()}")
  186. @classmethod
  187. def test008(cls, **params):
  188. """"""
  189. try:
  190. # --- define ---
  191. api = Global.cscec_agent()
  192. # --- get face b64 ---
  193. file_path = f"/home/server/resources/vms-files/2021-0826-160627-600346.pickle"
  194. image = methods.load_pickle_file(file_path) # 解压
  195. frame = numpy_method.to_array(image) # list to numpy array
  196. _, image = cv2.imencode('.jpg', frame)
  197. base64_data = base64.b64encode(image) # byte to b64 byte
  198. s = base64_data.decode() # byte to str
  199. face_image_b64 = f'data:image/jpeg;base64,{s}'
  200. # --- test push_face ---
  201. methods.debug_log('TEST.test008', f"m-236: {type(methods.now_string())}")
  202. api.push_face(face_image_b64=face_image_b64, now_at=methods.now_string())
  203. # --- test push_face_log ---
  204. api.push_face_log()
  205. # --- test ---
  206. api.pull_alarm_list()
  207. api.pull_alarm_group_list()
  208. return dict(code=0, details=f"end.")
  209. except Exception as exception:
  210. methods.debug_log('TEST.test008', f"m-196: exception | {exception}")
  211. methods.debug_log('TEST.test008', f"m-196: traceback | {methods.trace_log()}")
  212. return dict(code=-1, details=f"{methods.trace_log()}")
  213. @classmethod
  214. def test009(cls, **params):
  215. """"""
  216. try:
  217. file_path = '/home/server/resources/vms-files/2021-0822-161705-929476.pickle'
  218. image = methods.load_pickle_file(file_path) # 解压
  219. frame = numpy_method.to_array(image) # list to numpy array
  220. _, image = cv2.imencode('.jpg', frame)
  221. base64_data = base64.b64encode(image) # byte to b64 byte
  222. s = base64_data.decode() # byte to str
  223. face_image_b64 = f'data:image/jpeg;base64,{s}'
  224. return dict(code=0, face_image_b64=face_image_b64)
  225. except Exception as exception:
  226. methods.debug_log('TEST.test009', f"m-214: exception | {exception}")
  227. methods.debug_log('TEST.test009', f"m-214: traceback | {methods.trace_log()}")
  228. return dict(code=-1, details=f"{methods.trace_log()}")
  229. @classmethod
  230. def test011(cls, **params):
  231. """
  232. 下载语音文件
  233. http://192.168.30.13:8800/api?module=TEST&method=test011&mp3_name=2021-08-17-14-38-49-223380.mp3
  234. http://192.168.30.13:8800/api?module=TEST&method=test011&mp3_name=2021-08-17-14-59-15-665168.mp3
  235. """
  236. try:
  237. # --- check ---
  238. mp3_name = params.get('mp3_name')
  239. if not mp3_name:
  240. return dict(code=1, details=f"something is wrong.")
  241. # --- check ---
  242. file_path = f"/home/server/resources/mp3-files/{mp3_name}"
  243. if not methods.is_file(file_path):
  244. return dict(code=2, details=f"something is wrong.")
  245. return methods.read_bytes(file_path)
  246. except Exception as exception:
  247. methods.debug_log('Task.test011', f"m-239: exception | {exception}")
  248. methods.debug_log('Task.test011', f"m-239: traceback | {methods.trace_log()}")
  249. return dict(code=-1, details=f"{methods.trace_log()}")
  250. @classmethod
  251. def test012(cls, **params):
  252. """
  253. 录入人脸图片
  254. """
  255. try:
  256. # --- 提取特征 ---
  257. # file_name = 'IMG_20220315_101522.jpg'
  258. # file_name = 'IMG_20220315_101649.jpg'
  259. # file_name = '2022-0324-154547-015729.jpg'
  260. # file_name = 'bing.jpg'
  261. file_name = 'qiang.jpg'
  262. image_array = cv2.imread(f'/home/server/resources/TestData/2022/0315/{file_name}')
  263. # --- 剪裁人脸 ---
  264. # inference_result = Global.scrfd_agent.inference(image_array)
  265. # image_array = inference_result[0].get('face_image')
  266. # --- 特征提取 ---
  267. face_features = Global.arcface_agent.get_face_features_normalization_by_image_array(image_array)
  268. # --- save file ---
  269. save_at = methods.now_string('%Y-%m%d-%H%M%S-%f')
  270. face_file_path = f"/home/server/resources/vms-files/{save_at}.jpg"
  271. cv2.imwrite(face_file_path, image_array)
  272. # --- save mongodb ---
  273. """
  274. Face: 陌生人脸表
  275. Face.face_features: 人脸特征
  276. Face.face_image_path: 人脸图像文件路径
  277. Face.create_at: 录入时间
  278. Face.prc_id: 身份证号
  279. Face.face_image_url: 人脸地址
  280. Face.face_name: 人员姓名
  281. """
  282. unique_dict = {
  283. 'prc_id': file_name,
  284. }
  285. update_dict = {
  286. 'face_features': methods.pickle_dumps(face_features),
  287. 'face_image_path': face_file_path,
  288. 'create_at': methods.now_ts(),
  289. 'face_image_url': None,
  290. # 'face_name': 'zhang',
  291. # 'face_name': 'bing',
  292. 'face_name': '陆强',
  293. }
  294. Global.mdb.update_one('Face', unique_dict, update_dict)
  295. return dict(code=0, details=f"end.")
  296. except Exception as exception:
  297. methods.debug_log('TEST.test012', f"m-297: exception | {exception}")
  298. methods.debug_log('TEST.test012', f"m-297: traceback | {methods.trace_log()}")
  299. return dict(code=-1, details=f"{methods.trace_log()}")
  300. @classmethod
  301. def test013(cls, **params):
  302. """对比人脸图像的相似度"""
  303. try:
  304. # --- test 1 ---
  305. # face_path = '/home/server/resources/vms-files/2022-0507-152213-741783.jpg'
  306. # result = Global.scrfd_agent.inference(face_path)
  307. # face_image = result[0].get('face_image')
  308. # face_features_0 = Global.arcface_agent.get_face_features_normalization_by_image_array(face_image)
  309. # face_path = '/home/server/resources/TestData/2022/0513/lq1.jpg'
  310. # result = Global.scrfd_agent.inference(face_path)
  311. # face_image = result[0].get('face_image')
  312. # face_features_1 = Global.arcface_agent.get_face_features_normalization_by_image_array(face_image)
  313. # face_path = '/home/server/resources/TestData/2022/0513/lq2.jpg'
  314. # result = Global.scrfd_agent.inference(face_path)
  315. # face_image = result[0].get('face_image')
  316. # face_features_2 = Global.arcface_agent.get_face_features_normalization_by_image_array(face_image)
  317. # dist_1 = Global.arcface_agent.compare_faces_by_normalization(face_features_0, face_features_1)
  318. # dist_2 = Global.arcface_agent.compare_faces_by_normalization(face_features_0, face_features_2)
  319. # --- test 2 ---
  320. # face_path = '/home/server/resources/TestData/2022/0531-1/001.jpg' # 0.7584765553474426
  321. # face_path = '/home/server/resources/TestData/2022/0531-1/002.jpg' # 0.8457706868648529
  322. face_path = '/home/server/resources/TestData/2022/0531-1/004.jpg' # 0.8554660677909851 0.8809504210948944
  323. # face_path = '/home/server/resources/TestData/2022/0531-1/009.jpg' # 0.7084800899028778
  324. image_array = cv2.imread(face_path)
  325. result = Global.scrfd_agent.inference_with_image_array(image_array)
  326. # face_image = result[0].get('raw_face')
  327. face_image = result[0].get('align_face')
  328. face_features_1 = Global.arcface_agent.get_face_features_normalization_by_image_array(face_image)
  329. # face_path = '/home/server/resources/TestData/2022/0531-1/101.jpg' # 0.7629551887512207
  330. # face_path = '/home/server/resources/TestData/2022/0531-1/102.jpg' # 0.8441838622093201
  331. face_path = '/home/server/resources/TestData/2022/0531-1/104.jpg' # 0.8168102502822876 0.8709447979927063
  332. # face_path = '/home/server/resources/TestData/2022/0531-1/109.jpg' # 0.6636235117912292
  333. image_array = cv2.imread(face_path)
  334. result = Global.scrfd_agent.inference_with_image_array(image_array)
  335. # face_image = result[0].get('raw_face')
  336. face_image = result[0].get('align_face')
  337. face_features_2 = Global.arcface_agent.get_face_features_normalization_by_image_array(face_image)
  338. # face_path = '/home/server/resources/TestData/2022/0531-1/201.jpg'
  339. # face_path = '/home/server/resources/TestData/2022/0531-1/202.jpg'
  340. face_path = '/home/server/resources/TestData/2022/0531-1/204.jpg'
  341. # face_path = '/home/server/resources/TestData/2022/0531-1/209.jpg'
  342. image_array = cv2.imread(face_path)
  343. result = Global.scrfd_agent.inference_with_image_array(image_array)
  344. # face_image = result[0].get('raw_face')
  345. face_image = result[0].get('align_face')
  346. face_features_3 = Global.arcface_agent.get_face_features_normalization_by_image_array(face_image)
  347. dist_1 = Global.arcface_agent.compare_faces_by_normalization(face_features_1, face_features_3)
  348. dist_2 = Global.arcface_agent.compare_faces_by_normalization(face_features_2, face_features_3)
  349. return dict(code=0, dist_1=dist_1, dist_2=dist_2)
  350. except Exception as exception:
  351. methods.debug_log('TEST.test013', f"m-214: exception | {exception}")
  352. methods.debug_log('TEST.test013', f"m-214: traceback | {methods.trace_log()}")
  353. return dict(code=-1, details=f"{methods.trace_log()}")
  354. @classmethod
  355. def test014(cls, **params):
  356. """
  357. 对比人脸图像的相似度
  358. face-uuid
  359. 62a008b32bb1ca6081d36b1a
  360. base
  361. 629eb0fb1ef13cc2688962a4
  362. """
  363. try:
  364. # item = Global.mdb.get_one_by_id('Face', '627621d4013c78548cee0020') # 于佑飞
  365. # item = Global.mdb.get_one_by_id('Face', '62761dc5013c78548cedfff4') # 王彦杰
  366. item = Global.mdb.get_one_by_id('Face', '629eb0fb1ef13cc2688962a4') # test
  367. face_features_0 = methods.pickle_loads(item.get('face_feature_info_list')[0].get('face_features'))
  368. item = Global.mdb.get_one_by_id('Face', '62a008b32bb1ca6081d36b1a') # test
  369. face_features_1 = methods.pickle_loads(item.get('face_feature_info_list')[0].get('face_features'))
  370. # face_path = '/home/server/resources/TestData/2022/0527/1653640682.jpg'
  371. # face_path = '/home/server/resources/TestData/2022/0527/1653640715.jpg'
  372. # image_array = cv2.imread(face_path)
  373. # result = Global.scrfd_agent.inference_with_image_array(image_array)
  374. # # face_image = result[0].get('raw_face')
  375. # face_image = result[0].get('align_face')
  376. # face_features_1 = Global.arcface_agent.get_face_features_normalization_by_image_array(face_image)
  377. dist_1 = Global.arcface_agent.compare_faces_by_normalization(face_features_0, face_features_1)
  378. return dict(code=0, dist_1=dist_1)
  379. except Exception as exception:
  380. methods.debug_log('TEST.test014', f"m-214: exception | {exception}")
  381. methods.debug_log('TEST.test014', f"m-214: traceback | {methods.trace_log()}")
  382. return dict(code=-1, details=f"{methods.trace_log()}")
  383. @classmethod
  384. def test015(cls, **params):
  385. """
  386. 检索相似人脸
  387. """
  388. try:
  389. # face_path = '/home/server/resources/TestData/2022/0527/1653640682.jpg'
  390. face_path = '/home/server/resources/TestData/2022/0629/20220629090605.jpg'
  391. image_array = cv2.imread(face_path)
  392. result = Global.scrfd_agent.inference_with_image_array(image_array)
  393. face_image = result[0].get('align_face')
  394. face_features_0 = Global.arcface_agent.get_face_features_normalization_by_image_array(face_image)
  395. # --- fill face_dict ---
  396. face_dict = dict()
  397. condition = {
  398. 'face_name': {'$ne': None}, # 只获取人为标注的底库
  399. }
  400. items = Global.mdb.filter('Face', condition)
  401. for index, item in enumerate(items):
  402. # --- define ---
  403. face_uuid = str(item.get('_id'))
  404. face_dict[face_uuid] = list()
  405. # --- check ---
  406. face_feature_info_list = item.get('face_feature_info_list')
  407. if not face_feature_info_list:
  408. continue
  409. # --- fill ---
  410. for face_feature_info in face_feature_info_list:
  411. face_features = face_feature_info.get('face_features')
  412. if not face_features:
  413. continue
  414. if methods.pickle_loads(face_features) is None:
  415. continue
  416. d1 = methods.pickle_loads(face_features), face_feature_info.get('face_image_path')
  417. face_dict[face_uuid].append(d1)
  418. run_at = methods.now_ts(unit='ms')
  419. face_uuid, face_dist, base_face_image_path = Global.arcface_agent.search_face_v2(face_features_0, face_dict)
  420. use_time = round((methods.now_ts(unit='ms') - run_at), 2)
  421. methods.debug_log('TEST.test015', f"m-439: use time {use_time}ms")
  422. return dict(code=0, face_uuid=face_uuid, face_dist=face_dist, base_face_image_path=base_face_image_path,
  423. use_time=use_time)
  424. except Exception as exception:
  425. methods.debug_log('TEST.test015', f"m-214: exception | {exception}")
  426. methods.debug_log('TEST.test015', f"m-214: traceback | {methods.trace_log()}")
  427. return dict(code=-1, details=f"{methods.trace_log()}")