Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

1096 lines
62KB

  1. # -*- coding: utf-8 -*-
  2. import base64
  3. import os
  4. from concurrent.futures import ThreadPoolExecutor
  5. from os.path import join, exists, getsize
  6. from time import time, sleep
  7. from traceback import format_exc
  8. import cv2
  9. from multiprocessing import Process, Queue
  10. from loguru import logger
  11. from common.Constant import init_progess, success_progess
  12. from concurrency.FileUploadThread import ImageTypeImageFileUpload
  13. from concurrency.HeartbeatThread import Heartbeat
  14. from concurrency.PullVideoStreamProcess2 import OnlinePullVideoStreamProcess2, OfflinePullVideoStreamProcess2
  15. from concurrency.PushVideoStreamProcess2 import OnPushStreamProcess2, OffPushStreamProcess2
  16. from util.GPUtils import check_gpu_resource
  17. from util.LogUtils import init_log
  18. from concurrency.CommonThread import Common
  19. from enums.AnalysisStatusEnum import AnalysisStatus
  20. from enums.AnalysisTypeEnum import AnalysisType
  21. from enums.ExceptionEnum import ExceptionType
  22. from enums.ModelTypeEnum2 import ModelType2
  23. from util import TimeUtils
  24. from util.AliyunSdk import ThAliyunVodSdk
  25. from util.CpuUtils import check_cpu
  26. from entity.FeedBack import message_feedback
  27. from exception.CustomerException import ServiceException
  28. from util.ImageUtils import url2Array, add_water_pic
  29. from util.ModelUtils2 import MODEL_CONFIG2
  30. from util.OcrBaiduSdk import OcrBaiduSdk
  31. from enums.BaiduSdkEnum import VehicleEnumVALUE
  32. from enums.ModelTypeEnum import BaiduModelTarget
  33. from util.PlotsUtils import xywh2xyxy2
  34. from util.QueUtil import put_queue, get_no_block_queue, clear_queue
  35. from util.TimeUtils import now_date_to_str, YMDHMSF
  36. class IntelligentRecognitionProcess2(Process):
  37. __slots__ = ('_fb_queue', '_msg', '_analyse_type', '_context', 'event_queue', '_pull_queue', '_hb_queue',
  38. "_image_queue", "_push_queue", '_push_ex_queue')
  39. def __init__(self, *args):
  40. super().__init__()
  41. self._fb_queue, self._msg, self._analyse_type, self._context = args
  42. self.event_queue, self._pull_queue, self._hb_queue, self._image_queue = Queue(), Queue(10), Queue(), Queue()
  43. self._push_queue, self._push_ex_queue = Queue(), Queue()
  44. put_queue(self._fb_queue, message_feedback(self._msg["request_id"],
  45. AnalysisStatus.WAITING.value,
  46. self._analyse_type,
  47. progress=init_progess), timeout=2, is_ex=True)
  48. def sendEvent(self, eBody):
  49. try:
  50. self.event_queue.put(eBody, timeout=2)
  51. except Exception:
  52. logger.error("添加事件到队列超时异常:{}, requestId:{}", format_exc(), self._msg["request_id"])
  53. raise ServiceException(ExceptionType.SERVICE_INNER_EXCEPTION.value[0],
  54. ExceptionType.SERVICE_INNER_EXCEPTION.value[1])
  55. def clear_queue(self):
  56. clear_queue(self.event_queue)
  57. clear_queue(self._pull_queue)
  58. clear_queue(self._hb_queue)
  59. clear_queue(self._image_queue)
  60. clear_queue(self._push_queue)
  61. clear_queue(self._push_ex_queue)
  62. @staticmethod
  63. def ai_dtection(model, frame_list, frame_index_list, request_id):
  64. retResults = MODEL_CONFIG2[model[1]][3]([frame_list, frame_index_list, model[0][1], request_id])[0]
  65. if len(frame_list) == 1:
  66. return model[1], [retResults[2]]
  67. return model[1], retResults[2]
  68. @staticmethod
  69. def build_video_path(context, msg, is_build_or=True):
  70. random_time = now_date_to_str(YMDHMSF)
  71. pre_path = '%s/%s%s' % (context["base_dir"], context["video"]["file_path"], random_time)
  72. end_path = '%s%s' % (msg["request_id"], ".mp4")
  73. if is_build_or:
  74. context["orFilePath"] = '%s%s%s' % (pre_path, "_on_or_", end_path)
  75. context["aiFilePath"] = '%s%s%s' % (pre_path, "_on_ai_", end_path)
  76. @staticmethod
  77. def start_heartbeat(fb_queue, hb_queue, request_id, analyse_type, context):
  78. hb_thread = Heartbeat(fb_queue, hb_queue, request_id, analyse_type, context)
  79. hb_thread.setDaemon(True)
  80. hb_thread.start()
  81. return hb_thread
  82. class OnlineIntelligentRecognitionProcess2(IntelligentRecognitionProcess2):
  83. __slots__ = ()
  84. @staticmethod
  85. def upload_video(base_dir, env, request_id, orFilePath, aiFilePath):
  86. aliyunVodSdk = ThAliyunVodSdk(base_dir, env, request_id)
  87. upload_video_thread_or = Common(aliyunVodSdk.get_play_url, orFilePath, "or_online_%s" % request_id)
  88. upload_video_thread_ai = Common(aliyunVodSdk.get_play_url, aiFilePath, "ai_online_%s" % request_id)
  89. upload_video_thread_or.setDaemon(True)
  90. upload_video_thread_ai.setDaemon(True)
  91. upload_video_thread_or.start()
  92. upload_video_thread_ai.start()
  93. or_url = upload_video_thread_or.get_result()
  94. ai_url = upload_video_thread_ai.get_result()
  95. return or_url, ai_url
  96. @staticmethod
  97. def start_push_stream2(msg, push_queue, image_queue, push_ex_queue, hb_queue, context):
  98. pushProcess = OnPushStreamProcess2(msg, push_queue, image_queue, push_ex_queue, hb_queue, context)
  99. pushProcess.daemon = True
  100. pushProcess.start()
  101. return pushProcess
  102. @staticmethod
  103. def start_pull_stream2(msg, context, fb_queue, pull_queue, image_queue, analyse_type, frame_num):
  104. pullProcess = OnlinePullVideoStreamProcess2(msg, context, fb_queue, pull_queue, image_queue, analyse_type,
  105. frame_num)
  106. pullProcess.daemon = True
  107. pullProcess.start()
  108. return pullProcess
  109. @staticmethod
  110. def checkPT(start_time, service_timeout, pull_process, push_process, hb_thread, push_ex_queue, pull_queue,
  111. request_id):
  112. if time() - start_time > service_timeout:
  113. logger.error("推流超时, requestId: {}", request_id)
  114. raise ServiceException(ExceptionType.PUSH_STREAM_TIMEOUT_EXCEPTION.value[0],
  115. ExceptionType.PUSH_STREAM_TIMEOUT_EXCEPTION.value[1])
  116. if pull_process is not None and not pull_process.is_alive():
  117. while True:
  118. if pull_queue.empty() or pull_queue.qsize() == 0:
  119. break
  120. pull_result = get_no_block_queue(pull_queue)
  121. if pull_result is not None and pull_result[0] == 1:
  122. raise ServiceException(pull_result[1], pull_result[2])
  123. logger.info("拉流进程异常停止, requestId: {}", request_id)
  124. raise Exception("拉流进程异常停止!")
  125. if hb_thread is not None and not hb_thread.is_alive():
  126. logger.info("心跳线程异常停止, requestId: {}", request_id)
  127. raise Exception("心跳线程异常停止!")
  128. if push_process is not None and not push_process.is_alive():
  129. while True:
  130. if push_ex_queue.empty() or push_ex_queue.qsize() == 0:
  131. break
  132. push_result = get_no_block_queue(push_ex_queue)
  133. if push_result is not None and push_result[0] == 1:
  134. raise ServiceException(push_result[1], push_result[2])
  135. logger.info("推流进程异常停止, requestId: {}", request_id)
  136. raise Exception("推流进程异常停止!")
  137. def run(self):
  138. msg, context, analyse_type, ex = self._msg, self._context, self._analyse_type, None
  139. self.build_video_path(context, msg)
  140. request_id, base_dir, env = msg["request_id"], context["base_dir"], context["env"]
  141. # 拉流进程、推流进程、心跳线程
  142. pull_process, push_process, hb_thread = None, None, None
  143. # 事件队列、拉流队列、心跳队列、反馈队列
  144. event_queue, pull_queue, hb_queue, fb_queue = self.event_queue, self._pull_queue, self._hb_queue, self._fb_queue
  145. # 推流队列、推流异常队列、图片队列
  146. push_queue, push_ex_queue, image_queue = self._push_queue, self._push_ex_queue, self._image_queue
  147. service_timeout = int(context["service"]["timeout"])
  148. try:
  149. # 初始化日志
  150. init_log(base_dir, env)
  151. # 打印启动日志
  152. logger.info("开始启动实时分析进程!requestId: {}", request_id)
  153. # 启动拉流进程(包含拉流线程, 图片上传线程)
  154. # 拉流进程初始化时间长, 先启动
  155. pull_process = self.start_pull_stream2(msg, context, fb_queue, pull_queue, image_queue, analyse_type, 100)
  156. # 启动心跳线程
  157. hb_thread = self.start_heartbeat(fb_queue, hb_queue, request_id, analyse_type, context)
  158. # 加载算法模型
  159. model_array = get_model(msg, context, analyse_type)
  160. # 启动推流进程
  161. push_process = self.start_push_stream2(msg, push_queue, image_queue, push_ex_queue, hb_queue, context)
  162. # 第一个参数: 模型是否初始化 0:未初始化 1:初始化
  163. task_status = [0]
  164. draw_config = {}
  165. start_time = time()
  166. with ThreadPoolExecutor(max_workers=3) as t:
  167. while True:
  168. # 检查拉流进程是否正常, 心跳线程是否正常
  169. self.checkPT(start_time, service_timeout, pull_process, push_process, hb_thread, push_ex_queue,
  170. pull_queue, request_id)
  171. # 检查推流是否异常
  172. push_status = get_no_block_queue(push_ex_queue)
  173. if push_status is not None and push_status[0] == 1:
  174. raise ServiceException(push_status[1], push_status[2])
  175. # 获取停止指令
  176. event_result = get_no_block_queue(event_queue)
  177. if event_result:
  178. cmdStr = event_result.get("command")
  179. # 接收到停止指令
  180. if "stop" == cmdStr:
  181. logger.info("实时任务开始停止, requestId: {}", request_id)
  182. pull_process.sendCommand({"command": 'stop'})
  183. pull_result = get_no_block_queue(pull_queue)
  184. if pull_result is None:
  185. sleep(1)
  186. continue
  187. # (4, (frame_list, frame_index_list, all_frames))
  188. if pull_result[0] == 4:
  189. frame_list, frame_index_list, all_frames = pull_result[1]
  190. if len(frame_list) > 0:
  191. # 判断是否已经初始化
  192. if task_status[0] == 0:
  193. task_status[0] = 1
  194. for i, model in enumerate(model_array):
  195. # (modeType, model_param, allowedList, names, rainbows)
  196. model_conf, code = model
  197. model_param = model_conf[1]
  198. MODEL_CONFIG2[code][2](frame_list[0].shape[1], frame_list[0].shape[0], model_conf)
  199. if draw_config.get("font_config") is None:
  200. draw_config["font_config"] = model_param['font_config']
  201. if draw_config.get(code) is None:
  202. draw_config[code] = {}
  203. draw_config[code]["allowedList"] = model_conf[2]
  204. draw_config[code]["rainbows"] = model_conf[4]
  205. draw_config[code]["label_arrays"] = model_param['label_arraylist']
  206. det_array = []
  207. for model in model_array:
  208. result = t.submit(self.ai_dtection, model, frame_list, frame_index_list, request_id)
  209. det_array.append(result)
  210. push_objs = [det.result() for det in det_array]
  211. put_queue(push_queue,
  212. (1, (frame_list, frame_index_list, all_frames, draw_config, push_objs)),
  213. timeout=10)
  214. del det_array, push_objs
  215. del frame_list, frame_index_list, all_frames
  216. elif pull_result[0] == 1:
  217. put_queue(push_queue, (2, 'stop_ex'), timeout=1, is_ex=True)
  218. push_process.join(120)
  219. pull_process.sendCommand({"command": 'stop'})
  220. pull_process.join(120)
  221. raise ServiceException(pull_result[1], pull_result[2])
  222. elif pull_result[0] == 2:
  223. put_queue(push_queue, (2, 'stop'), timeout=1, is_ex=True)
  224. push_process.join(120)
  225. pull_process.sendCommand({"command": 'stop'})
  226. pull_process.join(120)
  227. break
  228. else:
  229. raise Exception("未知拉流状态异常!")
  230. except ServiceException as s:
  231. logger.exception("服务异常,异常编号:{}, 异常描述:{}, requestId: {}", s.code, s.msg, request_id)
  232. ex = s.code, s.msg
  233. except Exception:
  234. logger.error("服务异常: {}, requestId: {},", format_exc(), request_id)
  235. ex = ExceptionType.SERVICE_INNER_EXCEPTION.value[0], ExceptionType.SERVICE_INNER_EXCEPTION.value[1]
  236. finally:
  237. orFilePath, aiFilePath = context["orFilePath"], context["aiFilePath"]
  238. base_dir, env = context["base_dir"], context["env"]
  239. or_url, ai_url, exc = "", "", None
  240. try:
  241. if push_process and push_process.is_alive():
  242. put_queue(push_queue, (2, 'stop_ex'), timeout=1)
  243. logger.info("关闭推流进程, requestId:{}", request_id)
  244. push_process.join(timeout=120)
  245. logger.info("关闭推流进程1, requestId:{}", request_id)
  246. if pull_process and pull_process.is_alive():
  247. pull_process.sendCommand({"command": 'stop_ex'})
  248. pull_process.sendCommand({"command": 'stop'})
  249. logger.info("关闭拉流进程, requestId:{}", request_id)
  250. pull_process.join(timeout=120)
  251. logger.info("关闭拉流进程1, requestId:{}", request_id)
  252. if exists(orFilePath) and exists(aiFilePath) and getsize(orFilePath) > 100:
  253. or_url, ai_url = self.upload_video(base_dir, env, request_id, orFilePath, aiFilePath)
  254. if or_url is None or ai_url is None:
  255. logger.error("原视频或AI视频播放上传VOD失败!, requestId: {}", request_id)
  256. raise ServiceException(ExceptionType.GET_VIDEO_URL_EXCEPTION.value[0],
  257. ExceptionType.GET_VIDEO_URL_EXCEPTION.value[1])
  258. # 停止心跳线程
  259. if hb_thread and hb_thread.is_alive():
  260. put_queue(hb_queue, {"command": "stop"}, timeout=10, is_ex=False)
  261. hb_thread.join(timeout=120)
  262. if exists(orFilePath):
  263. logger.info("开始删除原视频, orFilePath: {}, requestId: {}", orFilePath, request_id)
  264. os.remove(orFilePath)
  265. logger.info("删除原视频成功, orFilePath: {}, requestId: {}", orFilePath, request_id)
  266. if exists(aiFilePath):
  267. logger.info("开始删除AI视频, aiFilePath: {}, requestId: {}", aiFilePath, request_id)
  268. os.remove(aiFilePath)
  269. logger.info("删除AI视频成功, aiFilePath: {}, requestId: {}", aiFilePath, request_id)
  270. # 如果有异常, 检查是否有原视频和AI视频,有则上传,响应失败
  271. if ex:
  272. code, msg = ex
  273. put_queue(fb_queue, message_feedback(request_id, AnalysisStatus.FAILED.value,
  274. analyse_type,
  275. error_code=code,
  276. error_msg=msg,
  277. video_url=or_url,
  278. ai_video_url=ai_url), timeout=10, is_ex=False)
  279. else:
  280. if or_url is None or len(or_url) == 0 or ai_url is None or len(ai_url) == 0:
  281. raise ServiceException(ExceptionType.PUSH_STREAM_TIME_EXCEPTION.value[0],
  282. ExceptionType.PUSH_STREAM_TIME_EXCEPTION.value[1])
  283. put_queue(fb_queue, message_feedback(request_id, AnalysisStatus.SUCCESS.value,
  284. analyse_type,
  285. progress=success_progess,
  286. video_url=or_url,
  287. ai_video_url=ai_url), timeout=10, is_ex=False)
  288. except ServiceException as s:
  289. logger.exception("服务异常,异常编号:{}, 异常描述:{}, requestId: {}", s.code, s.msg, request_id)
  290. exc = s.code, s.msg
  291. except Exception:
  292. logger.error("服务异常: {}, requestId: {},", format_exc(), request_id)
  293. exc = ExceptionType.SERVICE_INNER_EXCEPTION.value[0], ExceptionType.SERVICE_INNER_EXCEPTION.value[1]
  294. finally:
  295. if push_process and push_process.is_alive():
  296. put_queue(push_queue, (2, 'stop_ex'), timeout=1)
  297. logger.info("关闭推流进程, requestId:{}", request_id)
  298. push_process.join(timeout=120)
  299. logger.info("关闭推流进程1, requestId:{}", request_id)
  300. if pull_process and pull_process.is_alive():
  301. pull_process.sendCommand({"command": 'stop_ex'})
  302. pull_process.sendCommand({"command": 'stop'})
  303. logger.info("关闭拉流进程, requestId:{}", request_id)
  304. pull_process.join(timeout=120)
  305. logger.info("关闭拉流进程1, requestId:{}", request_id)
  306. if hb_thread and hb_thread.is_alive():
  307. put_queue(hb_queue, {"command": "stop"}, timeout=10, is_ex=False)
  308. hb_thread.join(timeout=120)
  309. if exc:
  310. code, msg = exc
  311. put_queue(fb_queue, message_feedback(request_id, AnalysisStatus.FAILED.value,
  312. analyse_type,
  313. error_code=code,
  314. error_msg=msg,
  315. video_url=or_url,
  316. ai_video_url=ai_url), timeout=10, is_ex=False)
  317. self.clear_queue()
  318. class OfflineIntelligentRecognitionProcess2(IntelligentRecognitionProcess2):
  319. __slots__ = ()
  320. @staticmethod
  321. def upload_video(base_dir, env, request_id, aiFilePath):
  322. aliyunVodSdk = ThAliyunVodSdk(base_dir, env, request_id)
  323. upload_video_thread_ai = Common(aliyunVodSdk.get_play_url, aiFilePath, "ai_online_%s" % request_id)
  324. upload_video_thread_ai.setDaemon(True)
  325. upload_video_thread_ai.start()
  326. ai_url = upload_video_thread_ai.get_result()
  327. return ai_url
  328. @staticmethod
  329. def start_push_stream2(msg, push_queue, image_queue, push_ex_queue, hb_queue, context):
  330. pushProcess = OffPushStreamProcess2(msg, push_queue, image_queue, push_ex_queue, hb_queue, context)
  331. pushProcess.daemon = True
  332. pushProcess.start()
  333. return pushProcess
  334. @staticmethod
  335. def start_pull_stream2(msg, context, fb_queue, pull_queue, image_queue, analyse_type, frame_num):
  336. pullProcess = OfflinePullVideoStreamProcess2(msg, context, fb_queue, pull_queue, image_queue, analyse_type,
  337. frame_num)
  338. pullProcess.daemon = True
  339. pullProcess.start()
  340. return pullProcess
  341. @staticmethod
  342. def checkPT(start_time, service_timeout, pull_process, push_process, hb_thread, push_ex_queue, pull_queue,
  343. request_id):
  344. if time() - start_time > service_timeout:
  345. logger.error("推流超时, requestId: {}", request_id)
  346. raise ServiceException(ExceptionType.PUSH_STREAM_TIMEOUT_EXCEPTION.value[0],
  347. ExceptionType.PUSH_STREAM_TIMEOUT_EXCEPTION.value[1])
  348. if pull_process is not None and not pull_process.is_alive():
  349. while True:
  350. if pull_queue.empty() or pull_queue.qsize() == 0:
  351. break
  352. pull_result = get_no_block_queue(pull_queue)
  353. if pull_result is not None and pull_result[0] == 1:
  354. raise ServiceException(pull_result[1], pull_result[2])
  355. logger.info("拉流进程异常停止, requestId: {}", request_id)
  356. raise Exception("拉流进程异常停止!")
  357. if hb_thread is not None and not hb_thread.is_alive():
  358. logger.info("心跳线程异常停止, requestId: {}", request_id)
  359. raise Exception("心跳线程异常停止!")
  360. if push_process is not None and not push_process.is_alive():
  361. while True:
  362. if push_ex_queue.empty() or push_ex_queue.qsize() == 0:
  363. break
  364. push_result = get_no_block_queue(push_ex_queue)
  365. if push_result is not None and push_result[0] == 1:
  366. raise ServiceException(push_result[1], push_result[2])
  367. logger.info("推流进程异常停止, requestId: {}", request_id)
  368. raise Exception("推流进程异常停止!")
  369. def run(self):
  370. msg, context, analyse_type, ex = self._msg, self._context, self._analyse_type, None
  371. self.build_video_path(context, msg, is_build_or=False)
  372. request_id, base_dir, env = msg["request_id"], context["base_dir"], context["env"]
  373. # 拉流进程、推流进程
  374. pull_process, push_process = None, None
  375. # 心跳线程
  376. hb_thread = None
  377. # 事件队列、拉流队列、心跳队列、反馈队列
  378. event_queue, pull_queue, hb_queue, fb_queue = self.event_queue, self._pull_queue, self._hb_queue, self._fb_queue
  379. # 推流队列、推流异常队列、图片队列
  380. push_queue, push_ex_queue, image_queue = self._push_queue, self._push_ex_queue, self._image_queue
  381. try:
  382. # 初始化日志
  383. init_log(base_dir, env)
  384. # 打印启动日志
  385. logger.info("开始启动离线分析进程!requestId: {}", request_id)
  386. # 启动拉流进程(包含拉流线程, 图片上传线程)
  387. # 拉流进程初始化时间长, 先启动
  388. pull_process = self.start_pull_stream2(msg, context, fb_queue, pull_queue, image_queue, analyse_type, 100)
  389. # 启动心跳线程
  390. hb_thread = self.start_heartbeat(fb_queue, hb_queue, request_id, analyse_type, context)
  391. # 加载算法模型
  392. model_array = get_model(msg, context, analyse_type)
  393. # 启动推流进程
  394. push_process = self.start_push_stream2(msg, push_queue, image_queue, push_ex_queue, hb_queue, context)
  395. # 第一个参数: 模型是否初始化 0:未初始化 1:初始化
  396. # 第二个参数: 检测是否有问题 0: 没有问题, 1: 有问题
  397. task_status = [0, 0]
  398. draw_config = {}
  399. service_timeout = int(context["service"]["timeout"])
  400. start_time = time()
  401. with ThreadPoolExecutor(max_workers=2) as t:
  402. while True:
  403. # 检查拉流进程是否正常, 心跳线程是否正常
  404. self.checkPT(start_time, service_timeout, pull_process, push_process, hb_thread, push_ex_queue,
  405. pull_queue, request_id)
  406. # 检查推流是否异常
  407. push_status = get_no_block_queue(push_ex_queue)
  408. if push_status is not None and push_status[0] == 1:
  409. raise ServiceException(push_status[1], push_status[2])
  410. # 获取停止指令
  411. event_result = get_no_block_queue(event_queue)
  412. if event_result:
  413. cmdStr = event_result.get("command")
  414. # 接收到停止指令
  415. if "stop" == cmdStr:
  416. logger.info("离线任务开始停止, requestId: {}", request_id)
  417. pull_process.sendCommand({"command": 'stop'})
  418. pull_result = get_no_block_queue(pull_queue)
  419. if pull_result is None:
  420. sleep(1)
  421. continue
  422. # (4, (frame_list, frame_index_list, all_frames))
  423. if pull_result[0] == 4:
  424. frame_list, frame_index_list, all_frames = pull_result[1]
  425. if len(frame_list) > 0:
  426. # 判断是否已经初始化
  427. if task_status[0] == 0:
  428. task_status[0] = 1
  429. for i, model in enumerate(model_array):
  430. model_conf, code = model
  431. model_param = model_conf[1]
  432. # (modeType, model_param, allowedList, names, rainbows)
  433. MODEL_CONFIG2[code][2](frame_list[0].shape[1], frame_list[0].shape[0],
  434. model_conf)
  435. if draw_config.get("font_config") is None:
  436. draw_config["font_config"] = model_param['font_config']
  437. if draw_config.get(code) is None:
  438. draw_config[code] = {}
  439. draw_config[code]["allowedList"] = model_conf[2]
  440. draw_config[code]["rainbows"] = model_conf[4]
  441. draw_config[code]["label_arrays"] = model_param['label_arraylist']
  442. # 多线程并发处理, 经过测试两个线程最优
  443. det_array = []
  444. for model in model_array:
  445. result = t.submit(self.ai_dtection, model, frame_list, frame_index_list, request_id)
  446. det_array.append(result)
  447. push_objs = [det.result() for det in det_array]
  448. put_queue(push_queue,
  449. (1, (frame_list, frame_index_list, all_frames, draw_config, push_objs)),
  450. timeout=10)
  451. del det_array, push_objs
  452. del frame_list, frame_index_list, all_frames
  453. elif pull_result[0] == 1:
  454. put_queue(push_queue, (2, 'stop_ex'), timeout=1, is_ex=True)
  455. logger.info("关闭推流进程, requestId:{}", request_id)
  456. push_process.join(timeout=120)
  457. logger.info("关闭推流进程1, requestId:{}", request_id)
  458. raise ServiceException(pull_result[1], pull_result[2])
  459. elif pull_result[0] == 2:
  460. logger.info("离线任务开始停止, requestId: {}", request_id)
  461. put_queue(push_queue, (2, 'stop'), timeout=1, is_ex=True)
  462. push_process.join(120)
  463. pull_process.sendCommand({"command": 'stop'})
  464. pull_process.join(120)
  465. break
  466. else:
  467. raise Exception("未知拉流状态异常!")
  468. except ServiceException as s:
  469. logger.exception("服务异常,异常编号:{}, 异常描述:{}, requestId: {}", s.code, s.msg, request_id)
  470. ex = s.code, s.msg
  471. except Exception:
  472. logger.error("服务异常: {}, requestId: {},", format_exc(), request_id)
  473. ex = ExceptionType.SERVICE_INNER_EXCEPTION.value[0], ExceptionType.SERVICE_INNER_EXCEPTION.value[1]
  474. finally:
  475. base_dir, env, aiFilePath = context["base_dir"], context["env"], context["aiFilePath"]
  476. ai_url, exc = "", None
  477. try:
  478. if push_process and push_process.is_alive():
  479. put_queue(push_queue, (2, 'stop_ex'), timeout=1)
  480. push_process.join(timeout=120)
  481. if pull_process and pull_process.is_alive():
  482. pull_process.sendCommand({"command": 'stop_ex'})
  483. pull_process.sendCommand({"command": 'stop'})
  484. pull_process.join(timeout=120)
  485. if exists(aiFilePath) and getsize(aiFilePath) > 100:
  486. ai_url = self.upload_video(base_dir, env, request_id, aiFilePath)
  487. if ai_url is None:
  488. logger.error("原视频或AI视频播放上传VOD失败!, requestId: {}", request_id)
  489. raise ServiceException(ExceptionType.GET_VIDEO_URL_EXCEPTION.value[0],
  490. ExceptionType.GET_VIDEO_URL_EXCEPTION.value[1])
  491. # 停止心跳线程
  492. if hb_thread and hb_thread.is_alive():
  493. put_queue(hb_queue, {"command": "stop"}, timeout=2, is_ex=False)
  494. hb_thread.join(timeout=120)
  495. if exists(aiFilePath):
  496. logger.info("开始删除AI视频, aiFilePath: {}, requestId: {}", aiFilePath, request_id)
  497. os.remove(aiFilePath)
  498. logger.info("删除AI视频成功, aiFilePath: {}, requestId: {}", aiFilePath, request_id)
  499. # 如果有异常, 检查是否有原视频和AI视频,有则上传,响应失败
  500. if ex:
  501. code, msg = ex
  502. put_queue(fb_queue, message_feedback(request_id, AnalysisStatus.FAILED.value,
  503. analyse_type,
  504. error_code=code,
  505. error_msg=msg,
  506. ai_video_url=ai_url), timeout=10, is_ex=False)
  507. else:
  508. if ai_url is None or len(ai_url) == 0:
  509. raise ServiceException(ExceptionType.PUSH_STREAM_TIME_EXCEPTION.value[0],
  510. ExceptionType.PUSH_STREAM_TIME_EXCEPTION.value[1])
  511. put_queue(fb_queue, message_feedback(request_id, AnalysisStatus.SUCCESS.value,
  512. analyse_type,
  513. progress=success_progess,
  514. ai_video_url=ai_url), timeout=10, is_ex=False)
  515. except ServiceException as s:
  516. logger.exception("服务异常,异常编号:{}, 异常描述:{}, requestId: {}", s.code, s.msg, request_id)
  517. exc = s.code, s.msg
  518. except Exception:
  519. logger.error("服务异常: {}, requestId: {},", format_exc(), request_id)
  520. exc = ExceptionType.SERVICE_INNER_EXCEPTION.value[0], ExceptionType.SERVICE_INNER_EXCEPTION.value[1]
  521. finally:
  522. if push_process and push_process.is_alive():
  523. put_queue(push_queue, (2, 'stop_ex'), timeout=1)
  524. push_process.join(timeout=120)
  525. if pull_process and pull_process.is_alive():
  526. pull_process.sendCommand({"command": 'stop_ex'})
  527. pull_process.sendCommand({"command": 'stop'})
  528. pull_process.join(timeout=120)
  529. if hb_thread and hb_thread.is_alive():
  530. put_queue(hb_queue, {"command": "stop"}, timeout=10, is_ex=False)
  531. hb_thread.join(timeout=120)
  532. if exc:
  533. code, msg = exc
  534. put_queue(fb_queue, message_feedback(request_id, AnalysisStatus.FAILED.value,
  535. analyse_type,
  536. error_code=code,
  537. error_msg=msg,
  538. ai_video_url=ai_url), timeout=10, is_ex=False)
  539. self.clear_queue()
  540. '''
  541. 图片识别
  542. '''
  543. class PhotosIntelligentRecognitionProcess2(Process):
  544. __slots__ = ("_fb_queue", "_msg", "_analyse_type", "_context", "_image_queue")
  545. def __init__(self, *args):
  546. super().__init__()
  547. self._fb_queue, self._msg, self._analyse_type, self._context = args
  548. self._image_queue = Queue()
  549. put_queue(self._fb_queue, message_feedback(self._msg["request_id"],
  550. AnalysisStatus.WAITING.value,
  551. self._analyse_type,
  552. progress=init_progess), timeout=1, is_ex=True)
  553. self.build_logo(self._msg, self._context)
  554. @staticmethod
  555. def build_logo(msg, context):
  556. logo = None
  557. if context["video"]["video_add_water"]:
  558. logo = msg.get("logo_url")
  559. if logo is not None and len(logo) > 0:
  560. logo = url2Array(logo, enable_ex=False)
  561. if logo is None:
  562. logo = cv2.imread(join(context['base_dir'], "image/logo.png"), -1)
  563. context['logo'] = logo
  564. def epidemic_prevention(self, imageUrl, model, orc, request_id):
  565. try:
  566. # modeType, allowedList, new_device, model, par, img_type
  567. model_conf, code = model
  568. modeType, model_param, allowedList = model_conf
  569. img_type = model_param["img_type"]
  570. image = url2Array(imageUrl)
  571. param = [model_param, image, request_id]
  572. dataBack = MODEL_CONFIG2[code][3](param)
  573. if img_type == 'plate':
  574. carCode = ''
  575. if dataBack is None or dataBack.get("plateImage") is None or len(dataBack.get("plateImage")) == 0:
  576. result = orc.license_plate_recognition(image, request_id)
  577. score = ''
  578. if result is None or result.get("words_result") is None or len(result.get("words_result")) == 0:
  579. logger.error("车牌识别为空: {}", result)
  580. carCode = ''
  581. else:
  582. for word in result.get("words_result"):
  583. if word is not None and word.get("number") is not None:
  584. if len(carCode) == 0:
  585. carCode = word.get("number")
  586. else:
  587. carCode = carCode + "," + word.get("number")
  588. else:
  589. result = orc.license_plate_recognition(dataBack.get("plateImage")[0], request_id)
  590. score = dataBack.get("plateImage")[1]
  591. if result is None or result.get("words_result") is None or len(result.get("words_result")) == 0:
  592. result = orc.license_plate_recognition(image, request_id)
  593. if result is None or result.get("words_result") is None or len(result.get("words_result")) == 0:
  594. logger.error("车牌识别为空: {}", result)
  595. carCode = ''
  596. else:
  597. for word in result.get("words_result"):
  598. if word is not None and word.get("number") is not None:
  599. if len(carCode) == 0:
  600. carCode = word.get("number")
  601. else:
  602. carCode = carCode + "," + word.get("number")
  603. else:
  604. for word in result.get("words_result"):
  605. if word is not None and word.get("number") is not None:
  606. if len(carCode) == 0:
  607. carCode = word.get("number")
  608. else:
  609. carCode = carCode + "," + word.get("number")
  610. if len(carCode) > 0:
  611. plate_result = {'type': str(3), 'modelCode': code, 'carUrl': imageUrl,
  612. 'carCode': carCode,
  613. 'score': score}
  614. put_queue(self._fb_queue, message_feedback(request_id,
  615. AnalysisStatus.RUNNING.value,
  616. AnalysisType.IMAGE.value, "", "",
  617. '',
  618. imageUrl,
  619. imageUrl,
  620. str(code),
  621. str(3),
  622. plate_result),
  623. timeout=1)
  624. if img_type == 'code':
  625. if dataBack is None or dataBack.get("type") is None:
  626. return
  627. # 行程码
  628. if dataBack.get("type") == 1 and 1 in allowedList:
  629. # 手机号
  630. if dataBack.get("phoneNumberImage") is None or len(dataBack.get("phoneNumberImage")) == 0:
  631. phoneNumberRecognition = ''
  632. phone_score = ''
  633. else:
  634. phone = orc.universal_text_recognition(dataBack.get("phoneNumberImage")[0], request_id)
  635. phone_score = dataBack.get("phoneNumberImage")[1]
  636. if phone is None or phone.get("words_result") is None or len(phone.get("words_result")) == 0:
  637. logger.error("手机号识别为空: {}", phone)
  638. phoneNumberRecognition = ''
  639. else:
  640. phoneNumberRecognition = phone.get("words_result")
  641. if dataBack.get("cityImage") is None or len(dataBack.get("cityImage")) == 0:
  642. cityRecognition = ''
  643. city_score = ''
  644. else:
  645. city = orc.universal_text_recognition(dataBack.get("cityImage")[0], request_id)
  646. city_score = dataBack.get("cityImage")[1]
  647. if city is None or city.get("words_result") is None or len(city.get("words_result")) == 0:
  648. logger.error("城市识别为空: {}", city)
  649. cityRecognition = ''
  650. else:
  651. cityRecognition = city.get("words_result")
  652. if len(phoneNumberRecognition) > 0 or len(cityRecognition) > 0:
  653. trip_result = {'type': str(1),
  654. 'modelCode': code,
  655. 'imageUrl': imageUrl,
  656. 'phoneNumberRecognition': phoneNumberRecognition,
  657. 'phone_sorce': phone_score,
  658. 'cityRecognition': cityRecognition,
  659. 'city_score': city_score}
  660. put_queue(self._fb_queue, message_feedback(request_id,
  661. AnalysisStatus.RUNNING.value,
  662. AnalysisType.IMAGE.value, "", "",
  663. '',
  664. imageUrl,
  665. imageUrl,
  666. str(code),
  667. str(1),
  668. trip_result),
  669. timeout=1)
  670. if dataBack.get("type") == 2 and 2 in allowedList:
  671. if dataBack.get("nameImage") is None or len(dataBack.get("nameImage")) == 0:
  672. nameRecognition = ''
  673. name_score = ''
  674. else:
  675. name = orc.universal_text_recognition(dataBack.get("nameImage")[0], request_id)
  676. name_score = dataBack.get("nameImage")[1]
  677. if name is None or name.get("words_result") is None or len(name.get("words_result")) == 0:
  678. logger.error("名字识别为空: {}", name)
  679. nameRecognition = ''
  680. else:
  681. nameRecognition = name.get("words_result")
  682. if dataBack.get("phoneNumberImage") is None or len(dataBack.get("phoneNumberImage")) == 0:
  683. phoneNumberRecognition = ''
  684. phone_score = ''
  685. else:
  686. phone = orc.universal_text_recognition(dataBack.get("phoneNumberImage")[0], request_id)
  687. phone_score = dataBack.get("phoneNumberImage")[1]
  688. if phone is None or phone.get("words_result") is None or len(phone.get("words_result")) == 0:
  689. logger.error("手机号识别为空: {}", phone)
  690. phoneNumberRecognition = ''
  691. else:
  692. phoneNumberRecognition = phone.get("words_result")
  693. if dataBack.get("hsImage") is None or len(dataBack.get("hsImage")) == 0:
  694. hsRecognition = ''
  695. hs_score = ''
  696. else:
  697. hs = orc.universal_text_recognition(dataBack.get("hsImage")[0], request_id)
  698. hs_score = dataBack.get("hsImage")[1]
  699. if hs is None or hs.get("words_result") is None or len(hs.get("words_result")) == 0:
  700. logger.error("核酸识别为空: {}", hs)
  701. hsRecognition = ''
  702. else:
  703. hsRecognition = hs.get("words_result")
  704. if len(nameRecognition) > 0 or len(phoneNumberRecognition) > 0 or len(hsRecognition) > 0:
  705. healthy_result = {'type': str(2),
  706. 'modelCode': code,
  707. 'imageUrl': imageUrl,
  708. 'color': dataBack.get("color"),
  709. 'nameRecognition': nameRecognition,
  710. 'name_score': name_score,
  711. 'phoneNumberRecognition': phoneNumberRecognition,
  712. 'phone_score': phone_score,
  713. 'hsRecognition': hsRecognition,
  714. 'hs_score': hs_score}
  715. put_queue(self._fb_queue, message_feedback(request_id,
  716. AnalysisStatus.RUNNING.value,
  717. AnalysisType.IMAGE.value, "", "",
  718. '',
  719. imageUrl,
  720. imageUrl,
  721. str(code),
  722. str(2),
  723. healthy_result),
  724. timeout=1)
  725. except ServiceException as s:
  726. raise s
  727. except Exception as e:
  728. logger.error("模型分析异常: {}, requestId: {}", format_exc(), request_id)
  729. raise e
  730. '''
  731. # 防疫模型
  732. '''
  733. def epidemicPrevention(self, imageUrls, model, base_dir, env, request_id):
  734. with ThreadPoolExecutor(max_workers=2) as t:
  735. orc = OcrBaiduSdk(base_dir, env)
  736. obj_list = []
  737. for imageUrl in imageUrls:
  738. obj = t.submit(self.epidemic_prevention, imageUrl, model, orc, request_id)
  739. obj_list.append(obj)
  740. for r in obj_list:
  741. r.result(60)
  742. def image_recognition(self, imageUrl, mod, image_queue, logo, request_id):
  743. try:
  744. model_conf, code = mod
  745. model_param = model_conf[1]
  746. image = url2Array(imageUrl)
  747. MODEL_CONFIG2[code][2](image.shape[1], image.shape[0], model_conf)
  748. p_result = MODEL_CONFIG2[code][3]([[image], [0], model_param, request_id])[0]
  749. if p_result is None or len(p_result) < 3 or p_result[2] is None or len(p_result[2]) == 0:
  750. return
  751. if logo:
  752. image = add_water_pic(image, logo, request_id)
  753. # (modeType, model_param, allowedList, names, rainbows)
  754. allowedList = model_conf[2]
  755. label_arraylist = model_param['label_arraylist']
  756. font_config = model_param['font_config']
  757. rainbows = model_conf[4]
  758. det_xywh = {code: {}}
  759. ai_result_list = p_result[2]
  760. for ai_result in ai_result_list:
  761. box, score, cls = xywh2xyxy2(ai_result)
  762. # 如果检测目标在识别任务中,继续处理
  763. if cls in allowedList:
  764. label_array = label_arraylist[cls]
  765. color = rainbows[cls]
  766. cd = det_xywh[code].get(cls)
  767. if cd is None:
  768. det_xywh[code][cls] = [[cls, box, score, label_array, color]]
  769. else:
  770. det_xywh[code][cls].append([cls, box, score, label_array, color])
  771. if len(det_xywh) > 0:
  772. put_queue(image_queue, (1, (det_xywh, imageUrl, image, font_config, "")))
  773. except ServiceException as s:
  774. raise s
  775. except Exception as e:
  776. logger.error("模型分析异常: {}, requestId: {}", format_exc(), self._msg.get("request_id"))
  777. raise e
  778. def publicIdentification(self, imageUrls, mod, image_queue, logo, request_id):
  779. with ThreadPoolExecutor(max_workers=2) as t:
  780. obj_list = []
  781. for imageUrl in imageUrls:
  782. obj = t.submit(self.image_recognition, imageUrl, mod, image_queue, logo, request_id)
  783. obj_list.append(obj)
  784. for r in obj_list:
  785. r.result(60)
  786. '''
  787. 1. imageUrls: 图片url数组,多张图片
  788. 2. mod: 模型对象
  789. 3. image_queue: 图片队列
  790. '''
  791. def baiduRecognition(self, imageUrls, mod, image_queue, logo, request_id):
  792. with ThreadPoolExecutor(max_workers=2) as t:
  793. thread_result = []
  794. for imageUrl in imageUrls:
  795. obj = t.submit(self.baidu_recognition, imageUrl, mod, image_queue, logo, request_id)
  796. thread_result.append(obj)
  797. for r in thread_result:
  798. r.result()
  799. def baidu_recognition(self, imageUrl, mod, image_queue, logo, request_id):
  800. with ThreadPoolExecutor(max_workers=2) as t:
  801. try:
  802. # (modeType, model_param, allowedList, (vehicle_names, person_names), rainbows)
  803. model_conf, code = mod
  804. model_param = model_conf[1]
  805. allowedList = model_conf[2]
  806. rainbows = model_conf[4]
  807. # 图片转数组
  808. img = url2Array(imageUrl)
  809. MODEL_CONFIG2[code][2](img.shape[1], img.shape[0], model_conf)
  810. vehicle_label_arrays = model_param["vehicle_label_arrays"]
  811. person_label_arrays = model_param["person_label_arrays"]
  812. font_config = model_param["font_config"]
  813. obj_list = []
  814. for target in allowedList:
  815. parm = [model_param, target, imageUrl, request_id]
  816. reuslt = t.submit(self.baidu_method, code, parm, img, image_queue, vehicle_label_arrays,
  817. person_label_arrays, font_config, rainbows, logo)
  818. obj_list.append(reuslt)
  819. for r in obj_list:
  820. r.result()
  821. except ServiceException as s:
  822. raise s
  823. except Exception as e:
  824. logger.error("百度AI分析异常: {}, requestId: {}", format_exc(), request_id)
  825. raise e
  826. @staticmethod
  827. def baidu_method(code, parm, img, image_queue, vehicle_label_arrays, person_label_arrays, font_config,
  828. rainbows, logo):
  829. # [model_param, target, imageUrl, request_id]]
  830. request_id = parm[3]
  831. target = parm[1]
  832. image_url = parm[2]
  833. result = MODEL_CONFIG2[code][3](parm)
  834. if target == BaiduModelTarget.VEHICLE_DETECTION.value[1] and result is not None:
  835. vehicleInfo = result.get("vehicle_info")
  836. if vehicleInfo is not None and len(vehicleInfo) > 0:
  837. det_xywh = {code: {}}
  838. copy_frame = img.copy()
  839. for i, info in enumerate(vehicleInfo):
  840. value = VehicleEnumVALUE.get(info.get("type"))
  841. target_num = value.value[2]
  842. label_array = vehicle_label_arrays[target_num]
  843. color = rainbows[target_num]
  844. if value is None:
  845. logger.error("车辆识别出现未支持的目标类型!type:{}, requestId:{}", info.get("type"), request_id)
  846. return
  847. left_top = (int(info.get("location").get("left")), int(info.get("location").get("top")))
  848. right_top = (int(info.get("location").get("left")) + int(info.get("location").get("width")),
  849. int(info.get("location").get("top")))
  850. right_bottom = (int(info.get("location").get("left")) + int(info.get("location").get("width")),
  851. int(info.get("location").get("top")) + int(info.get("location").get("height")))
  852. left_bottom = (int(info.get("location").get("left")),
  853. int(info.get("location").get("top")) + int(info.get("location").get("height")))
  854. box = [left_top, right_top, right_bottom, left_bottom]
  855. score = float("%.2f" % info.get("probability"))
  856. if logo:
  857. copy_frame = add_water_pic(copy_frame, logo, request_id)
  858. if det_xywh[code].get(target) is None:
  859. det_xywh[code][target] = [[target, box, score, label_array, color]]
  860. else:
  861. det_xywh[code][target].append([target, box, score, label_array, color])
  862. info["id"] = str(i)
  863. if len(det_xywh[code]) > 0:
  864. result["type"] = str(target)
  865. result["modelCode"] = code
  866. put_queue(image_queue, (1, (det_xywh, image_url, copy_frame, font_config, result)))
  867. # 人体识别
  868. if target == BaiduModelTarget.HUMAN_DETECTION.value[1] and result is not None:
  869. personInfo = result.get("person_info")
  870. personNum = result.get("person_num")
  871. if personNum is not None and personNum > 0 and personInfo is not None and len(personInfo) > 0:
  872. det_xywh = {code: {}}
  873. copy_frame = img.copy()
  874. for i, info in enumerate(personInfo):
  875. left_top = (int(info.get("location").get("left")), int(info.get("location").get("top")))
  876. right_top = (int(info.get("location").get("left")) + int(info.get("location").get("width")),
  877. int(info.get("location").get("top")))
  878. right_bottom = (int(info.get("location").get("left")) + int(info.get("location").get("width")),
  879. int(info.get("location").get("top")) + int(info.get("location").get("height")))
  880. left_bottom = (int(info.get("location").get("left")),
  881. int(info.get("location").get("top")) + int(info.get("location").get("height")))
  882. box = [left_top, right_top, right_bottom, left_bottom]
  883. score = float("%.2f" % info.get("location").get("score"))
  884. label_array = person_label_arrays[0]
  885. color = rainbows[0]
  886. if logo:
  887. copy_frame = add_water_pic(copy_frame, logo, request_id)
  888. if det_xywh[code].get(target) is None:
  889. det_xywh[code][target] = [[target, box, score, label_array, color]]
  890. else:
  891. det_xywh[code][target].append([target, box, score, label_array, color])
  892. info["id"] = str(i)
  893. if len(det_xywh[code]) > 0:
  894. result["type"] = str(target)
  895. result["modelCode"] = code
  896. put_queue(image_queue, (1, (det_xywh, image_url, copy_frame, font_config, result)))
  897. # 人流量
  898. if target == BaiduModelTarget.PEOPLE_COUNTING.value[1] and result is not None:
  899. base64Image = result.get("image")
  900. if base64Image is not None and len(base64Image) > 0:
  901. baiduImage = base64.b64decode(base64Image)
  902. result["type"] = str(target)
  903. result["modelCode"] = code
  904. del result["image"]
  905. put_queue(image_queue, (1, (None, image_url, baiduImage, None, result)))
  906. @staticmethod
  907. def start_File_upload(*args):
  908. fb_queue, context, msg, image_queue, analyse_type = args
  909. image_thread = ImageTypeImageFileUpload(fb_queue, context, msg, image_queue, analyse_type)
  910. image_thread.setDaemon(True)
  911. image_thread.start()
  912. return image_thread
  913. def run(self):
  914. fb_queue, msg, analyse_type, context = self._fb_queue, self._msg, self._analyse_type, self._context
  915. request_id, logo, image_queue = msg["request_id"], context['logo'], self._image_queue
  916. base_dir, env = context["base_dir"], context["env"]
  917. imageUrls = msg["image_urls"]
  918. image_thread = None
  919. with ThreadPoolExecutor(max_workers=3) as t:
  920. try:
  921. init_log(base_dir, env)
  922. logger.info("开始启动图片识别进程, requestId: {}", request_id)
  923. model_array = get_model(msg, context, analyse_type)
  924. image_thread = self.start_File_upload(fb_queue, context, msg, image_queue, analyse_type)
  925. task_list = []
  926. for model in model_array:
  927. # 百度模型逻辑
  928. if model[1] == ModelType2.BAIDU_MODEL.value[1]:
  929. result = t.submit(self.baiduRecognition, imageUrls, model, image_queue, logo, request_id)
  930. task_list.append(result)
  931. # 防疫模型
  932. elif model[1] == ModelType2.EPIDEMIC_PREVENTION_MODEL.value[1]:
  933. result = t.submit(self.epidemicPrevention, imageUrls, model, base_dir, env, request_id)
  934. task_list.append(result)
  935. # 车牌模型
  936. elif model[1] == ModelType2.PLATE_MODEL.value[1]:
  937. result = t.submit(self.epidemicPrevention, imageUrls, model, base_dir, env, request_id)
  938. task_list.append(result)
  939. else:
  940. result = t.submit(self.publicIdentification, imageUrls, model, image_queue, logo, request_id)
  941. task_list.append(result)
  942. for r in task_list:
  943. r.result(timeout=60)
  944. if image_thread and not image_thread.is_alive():
  945. raise Exception("图片识别图片上传线程异常停止!!!")
  946. if image_thread and image_thread.is_alive():
  947. put_queue(image_queue, (2, 'stop'), timeout=10, is_ex=True)
  948. image_thread.join(120)
  949. logger.info("图片进程任务完成,requestId:{}", request_id)
  950. put_queue(fb_queue, message_feedback(request_id,
  951. AnalysisStatus.SUCCESS.value,
  952. analyse_type,
  953. progress=success_progess), timeout=10, is_ex=True)
  954. except ServiceException as s:
  955. logger.error("图片分析异常,异常编号:{}, 异常描述:{}, requestId:{}", s.code, s.msg, request_id)
  956. put_queue(fb_queue, message_feedback(request_id, AnalysisStatus.FAILED.value,
  957. analyse_type,
  958. s.code,
  959. s.msg))
  960. except Exception:
  961. logger.error("图片分析异常: {}, requestId:{}", format_exc(), request_id)
  962. put_queue(fb_queue, message_feedback(request_id, AnalysisStatus.FAILED.value,
  963. analyse_type,
  964. ExceptionType.SERVICE_INNER_EXCEPTION.value[0],
  965. ExceptionType.SERVICE_INNER_EXCEPTION.value[1]))
  966. finally:
  967. if image_thread and image_thread.is_alive():
  968. put_queue(image_queue, (2, 'stop'), timeout=10, is_ex=True)
  969. image_thread.join(120)
  970. clear_queue(image_queue)
  971. """
  972. "models": [{
  973. "code": "模型编号",
  974. "categories":[{
  975. "id": "模型id",
  976. "config": {
  977. "k1": "v1",
  978. "k2": "v2"
  979. }
  980. }]
  981. }]
  982. """
  983. def get_model(msg, context, analyse_type):
  984. # 初始变量
  985. request_id, base_dir, gpu_name, env = msg["request_id"], context["base_dir"], context["gpu_name"], context["env"]
  986. models, model_num_limit = msg["models"], context["service"]["model"]['limit']
  987. try:
  988. # 实时、离线元组
  989. analyse_type_tuple = (AnalysisType.ONLINE.value, AnalysisType.OFFLINE.value)
  990. # (实时、离线)检查模型组合, 目前只支持3个模型组合
  991. if analyse_type in analyse_type_tuple:
  992. if len(models) > model_num_limit:
  993. raise ServiceException(ExceptionType.MODEL_GROUP_LIMIT_EXCEPTION.value[0],
  994. ExceptionType.MODEL_GROUP_LIMIT_EXCEPTION.value[1])
  995. modelArray, codeArray = [], set()
  996. for model in models:
  997. # 模型编码
  998. code = model["code"]
  999. # 检验code是否重复
  1000. if code in codeArray:
  1001. raise ServiceException(ExceptionType.MODEL_DUPLICATE_EXCEPTION.value[0],
  1002. ExceptionType.MODEL_DUPLICATE_EXCEPTION.value[1])
  1003. codeArray.add(code)
  1004. # 检测目标数组
  1005. needed_objectsIndex = list(set([int(category["id"]) for category in model["categories"]]))
  1006. logger.info("模型编号: {}, 检查目标: {}, requestId: {}", code, needed_objectsIndex, request_id)
  1007. model_method = MODEL_CONFIG2.get(code)
  1008. if model_method is None:
  1009. logger.error("未匹配到对应的模型, requestId:{}", request_id)
  1010. raise ServiceException(ExceptionType.AI_MODEL_MATCH_EXCEPTION.value[0],
  1011. ExceptionType.AI_MODEL_MATCH_EXCEPTION.value[1])
  1012. # 检查cpu资源、gpu资源
  1013. check_cpu(base_dir, request_id)
  1014. gpu_ids = check_gpu_resource(request_id)
  1015. # 如果实时识别、离线识别
  1016. if analyse_type in analyse_type_tuple:
  1017. if model["is_video"] == "1":
  1018. mod = model_method[0](gpu_ids[0], needed_objectsIndex, request_id, gpu_name, base_dir, env)
  1019. modelArray.append((mod.model_conf, code))
  1020. else:
  1021. raise ServiceException(ExceptionType.MODEL_NOT_SUPPORT_VIDEO_EXCEPTION.value[0],
  1022. ExceptionType.MODEL_NOT_SUPPORT_VIDEO_EXCEPTION.value[1],
  1023. model_method[1].value[2])
  1024. # 如果是图片识别
  1025. if analyse_type == AnalysisType.IMAGE.value:
  1026. if model["is_image"] == "1":
  1027. mod = model_method[0](gpu_ids[0], needed_objectsIndex, request_id, gpu_name, base_dir, env)
  1028. modelArray.append((mod.model_conf, code))
  1029. else:
  1030. raise ServiceException(ExceptionType.MODEL_NOT_SUPPORT_IMAGE_EXCEPTION.value[0],
  1031. ExceptionType.MODEL_NOT_SUPPORT_IMAGE_EXCEPTION.value[1],
  1032. model_method[1].value[2])
  1033. if len(modelArray) == 0:
  1034. raise ServiceException(ExceptionType.AI_MODEL_MATCH_EXCEPTION.value[0],
  1035. ExceptionType.AI_MODEL_MATCH_EXCEPTION.value[1])
  1036. return modelArray
  1037. except ServiceException as s:
  1038. raise s
  1039. except Exception:
  1040. logger.error("模型配置处理异常: {}, request_id: {}", format_exc(), request_id)
  1041. raise ServiceException(ExceptionType.MODEL_LOADING_EXCEPTION.value[0],
  1042. ExceptionType.MODEL_LOADING_EXCEPTION.value[1])