Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

ImgBaiduSdk.py 14KB

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