Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

1 год назад
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. # -*- coding: utf-8 -*-
  2. import time
  3. import traceback
  4. from os.path import join
  5. from aip import AipImageClassify, AipBodyAnalysis
  6. from loguru import logger
  7. from common.YmlConstant import baidu_yml_path
  8. from enums.BaiduSdkEnum import BAIDUERRORDATA
  9. from enums.ExceptionEnum import ExceptionType
  10. from exception.CustomerException import ServiceException
  11. from util.ImageUtils import url2Content
  12. from util.RWUtils import getConfigs
  13. class AipImageClassifyClient:
  14. __slots__ = ('__client', '__config')
  15. def __init__(self, base_dir, env):
  16. self.__client = None
  17. self.__config = getConfigs(join(base_dir, baidu_yml_path % env))
  18. self.init_client()
  19. # self.lock = Lock()
  20. def init_client(self):
  21. if self.__client is None:
  22. self.__client = AipImageClassify(str(self.__config["vehicle"]["APP_ID"]),
  23. self.__config["vehicle"]["API_KEY"],
  24. self.__config["vehicle"]["SECRET_KEY"])
  25. '''
  26. 车辆检测
  27. '''
  28. def vehicleDetectUrl(self, url, request_id, options={}):
  29. self.init_client()
  30. # try:
  31. # self.lock.acquire()
  32. reply_num = 0
  33. reply_value = None
  34. while True:
  35. try:
  36. options["show"] = "true"
  37. res_image = self.__client.vehicleDetectUrl(url, options)
  38. error_code = res_image.get("error_code")
  39. if error_code:
  40. enum = BAIDUERRORDATA.get(error_code)
  41. # 如果异常编码未知, 返回空值
  42. if enum is None:
  43. logger.error("百度云车辆检测异常!error_code:{}, request_id: {}", error_code, request_id)
  44. return None
  45. # 重试指定次数后,还是异常,输出统一内部异常
  46. if enum.value[3] == 0:
  47. if reply_value is None:
  48. reply_value = enum.value[4]
  49. logger.error("百度云车辆检测异常!error_code:{}, error_msg:{}, reply_num:{}, request_id: {}",
  50. enum.value[0], enum.value[2], reply_num, request_id)
  51. raise Exception()
  52. # 重试指定次数后,还是异常,输出对应的异常
  53. if enum.value[3] == 1:
  54. if reply_value is None:
  55. reply_value = enum.value[4]
  56. raise ServiceException(str(enum.value[0]), enum.value[2])
  57. # 重试指定次数后,还是异常,输出空
  58. if enum.value[3] == 2:
  59. if reply_value is None:
  60. reply_value = enum.value[4]
  61. if reply_num >= reply_value:
  62. return None
  63. raise Exception()
  64. return res_image
  65. except Exception as e:
  66. time.sleep(1)
  67. reply_num += 1
  68. self.init_client()
  69. if reply_num > reply_value:
  70. if isinstance(e, ServiceException):
  71. raise ServiceException(e.code, e.msg)
  72. logger.error("车辆检测识别失败: {}, request_id: {}", traceback.format_exc(), request_id)
  73. raise ServiceException(ExceptionType.SERVICE_INNER_EXCEPTION.value[0],
  74. ExceptionType.SERVICE_INNER_EXCEPTION.value[1])
  75. # except Exception as ee:
  76. # logger.exception("车辆检测加锁异常: {}, request_id: {}", ee, request_id)
  77. # raise ServiceException(ExceptionType.UNIVERSAL_TEXT_RECOGNITION_FAILED.value[0],
  78. # ExceptionType.UNIVERSAL_TEXT_RECOGNITION_FAILED.value[1])
  79. # finally:
  80. # self.lock.release()
  81. '''
  82. 车辆检测
  83. '''
  84. def vehicleDetect(self, iamge, request_id, options={}):
  85. self.init_client()
  86. # try:
  87. # self.lock.acquire()
  88. reply_num = 0
  89. reply_value = None
  90. while True:
  91. try:
  92. options["show"] = "true"
  93. res_image = self.__client.vehicleDetect(iamge, options)
  94. error_code = res_image.get("error_code")
  95. if error_code:
  96. enum = BAIDUERRORDATA.get(error_code)
  97. # 如果异常编码未知, 返回空值
  98. if enum is None:
  99. logger.error("百度云车辆检测异常!error_code:{}, request_id: {}", error_code, request_id)
  100. return None
  101. # 重试指定次数后,还是异常,输出统一内部异常
  102. if enum.value[3] == 0:
  103. if reply_value is None:
  104. reply_value = enum.value[4]
  105. logger.error("百度云车辆检测异常!error_code:{}, error_msg:{}, reply_num:{}, request_id: {}",
  106. enum.value[0], enum.value[2], reply_num, request_id)
  107. raise Exception()
  108. # 重试指定次数后,还是异常,输出对应的异常
  109. if enum.value[3] == 1:
  110. if reply_value is None:
  111. reply_value = enum.value[4]
  112. raise ServiceException(str(enum.value[0]), enum.value[2])
  113. # 重试指定次数后,还是异常,输出空
  114. if enum.value[3] == 2:
  115. if reply_value is None:
  116. reply_value = enum.value[4]
  117. if reply_num >= reply_value:
  118. return None
  119. raise Exception()
  120. return res_image
  121. except Exception as e:
  122. time.sleep(1)
  123. reply_num += 1
  124. self.init_client()
  125. if reply_num > reply_value:
  126. if isinstance(e, ServiceException):
  127. raise ServiceException(e.code, e.msg)
  128. logger.error("车辆检测识别失败: {}, request_id: {}", traceback.format_exc(), request_id)
  129. raise ServiceException(ExceptionType.SERVICE_INNER_EXCEPTION.value[0],
  130. ExceptionType.SERVICE_INNER_EXCEPTION.value[1])
  131. class AipBodyAnalysisClient:
  132. __slots__ = ('__config', '__client')
  133. def __init__(self, base_dir, env):
  134. self.__client = None
  135. self.__config = getConfigs(join(base_dir, baidu_yml_path % env))
  136. self.init_client()
  137. # self.lock = Lock()
  138. def init_client(self):
  139. if self.__client is None:
  140. self.__client = AipBodyAnalysis(str(self.__config["person"]["APP_ID"]), self.__config["person"]["API_KEY"],
  141. self.__config["person"]["SECRET_KEY"])
  142. '''
  143. 人体检测与属性识别
  144. '''
  145. def bodyAttr(self, url, request_id, options={}):
  146. self.init_client()
  147. image = self.readImage(url, request_id)
  148. # try:
  149. # self.lock.acquire()
  150. reply_num = 0
  151. reply_value = None
  152. while True:
  153. try:
  154. options["show"] = "true"
  155. res_image = self.__client.bodyAttr(image, options)
  156. error_code = res_image.get("error_code")
  157. if error_code:
  158. enum = BAIDUERRORDATA.get(error_code)
  159. # 如果异常编码未知, 返回空值
  160. if enum is None:
  161. logger.error("百度云人体检测与属性识别异常!error_code:{}, request_id: {}", error_code, request_id)
  162. return None
  163. # 重试指定次数后,还是异常,输出统一内部异常
  164. if enum.value[3] == 0:
  165. if reply_value is None:
  166. reply_value = enum.value[4]
  167. logger.error("百度云人体检测与属性识别异常!error_code:{}, error_msg:{}, reply_num:{}, request_id: {}",
  168. enum.value[0], enum.value[2], reply_num, request_id)
  169. raise Exception()
  170. # 重试指定次数后,还是异常,输出对应的异常
  171. if enum.value[3] == 1:
  172. if reply_value is None:
  173. reply_value = enum.value[4]
  174. raise ServiceException(str(enum.value[0]), enum.value[2])
  175. # 重试指定次数后,还是异常,输出空
  176. if enum.value[3] == 2:
  177. if reply_value is None:
  178. reply_value = enum.value[4]
  179. if reply_num >= reply_value:
  180. return None
  181. raise Exception()
  182. return res_image
  183. except Exception as e:
  184. time.sleep(0.5)
  185. reply_num += 1
  186. self.init_client()
  187. if reply_num > reply_value:
  188. if isinstance(e, ServiceException):
  189. raise ServiceException(e.code, e.msg)
  190. logger.error("人体检测与属性识别失败: {}, request_id: {}", traceback.format_exc(), request_id)
  191. raise ServiceException(ExceptionType.SERVICE_INNER_EXCEPTION.value[0],
  192. ExceptionType.SERVICE_INNER_EXCEPTION.value[1])
  193. # except Exception as ee:
  194. # logger.exception("车辆检测加锁异常: {}, request_id: {}", ee, request_id)
  195. # raise ServiceException(ExceptionType.UNIVERSAL_TEXT_RECOGNITION_FAILED.value[0],
  196. # ExceptionType.UNIVERSAL_TEXT_RECOGNITION_FAILED.value[1])
  197. # finally:
  198. # self.lock.release()
  199. '''
  200. 人流量统计
  201. '''
  202. def bodyNum(self, url, request_id, options={}):
  203. self.init_client()
  204. image = self.readImage(url, request_id)
  205. # try:
  206. # self.lock.acquire()
  207. reply_num = 0
  208. reply_value = None
  209. while True:
  210. try:
  211. options["show"] = "true"
  212. res_image = self.__client.bodyNum(image, options)
  213. error_code = res_image.get("error_code")
  214. if error_code:
  215. enum = BAIDUERRORDATA.get(error_code)
  216. # 如果异常编码未知, 返回空值
  217. if enum is None:
  218. logger.error("百度云人流量统计异常!error_code:{}, request_id: {}", error_code, request_id)
  219. return None
  220. # 重试指定次数后,还是异常,输出统一内部异常
  221. if enum.value[3] == 0:
  222. if reply_value is None:
  223. reply_value = enum.value[4]
  224. logger.error("百度云人流量统计异常!error_code:{}, error_msg:{}, reply_num:{}, request_id: {}",
  225. enum.value[0], enum.value[2], reply_num, request_id)
  226. raise Exception()
  227. # 重试指定次数后,还是异常,输出对应的异常
  228. if enum.value[3] == 1:
  229. if reply_value is None:
  230. reply_value = enum.value[4]
  231. raise ServiceException(str(enum.value[0]), enum.value[2])
  232. # 重试指定次数后,还是异常,输出空
  233. if enum.value[3] == 2:
  234. if reply_value is None:
  235. reply_value = enum.value[4]
  236. if reply_num >= reply_value:
  237. return None
  238. raise Exception()
  239. return res_image
  240. except Exception as e:
  241. time.sleep(0.5)
  242. reply_num += 1
  243. self.init_client()
  244. if reply_num > reply_value:
  245. if isinstance(e, ServiceException):
  246. raise ServiceException(e.code, e.msg)
  247. logger.exception("人流量统计失败: {}, request_id: {}", traceback.format_exc(), request_id)
  248. raise ServiceException(ExceptionType.SERVICE_INNER_EXCEPTION.value[0],
  249. ExceptionType.SERVICE_INNER_EXCEPTION.value[1])
  250. # except Exception as ee:
  251. # logger.exception("车辆检测加锁异常: {}, request_id: {}", ee, request_id)
  252. # raise ServiceException(ExceptionType.UNIVERSAL_TEXT_RECOGNITION_FAILED.value[0],
  253. # ExceptionType.UNIVERSAL_TEXT_RECOGNITION_FAILED.value[1])
  254. # finally:
  255. # self.lock.release()
  256. def readImage(self, url, request_id):
  257. try:
  258. return url2Content(url)
  259. except Exception as e:
  260. logger.error("读取图片异常!url: {}, request_id: {}, 异常信息:{}", url, request_id, traceback.format_exc())
  261. raise ServiceException(ExceptionType.READ_IAMGE_URL_EXCEPTION.value[0],
  262. ExceptionType.READ_IAMGE_URL_EXCEPTION.value[1])
  263. # if __name__ == '__main__':
  264. # with open(r"D:\work\alg_new\tuoheng_alg\dsp_dev_service.yml", "r", encoding='utf-8') as f:
  265. # file_content = f.read()
  266. # content = yaml.load(file_content, yaml.FullLoader)
  267. # aipImageClassifyClient = AipImageClassifyClient(content)
  268. # aipBodyAnalysisClient = AipBodyAnalysisClient(content)
  269. # url = "https://pic.52112.com/180623/JPG-180623-12/c4cyivkxEh_small.jpg"
  270. # # result = aipImageClassifyClient.vehicleDetectUrl(url, "1111111")
  271. # result = aipBodyAnalysisClient.bodyNum(url, "1111111")
  272. # iamge = base64.b64decode(result.get("image"))
  273. # print(iamge)