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

148 lines
6.3KB

  1. import time
  2. import traceback
  3. from os.path import join
  4. import cv2
  5. from aip import AipOcr
  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.RWUtils import getConfigs
  12. class OcrBaiduSdk:
  13. __slots__ = ('client', "__config")
  14. def __init__(self, base_dir, env):
  15. self.client = None
  16. self.__config = getConfigs(join(base_dir, baidu_yml_path % env))
  17. self.init_client()
  18. def init_client(self):
  19. if self.client is None:
  20. self.client = AipOcr(str(self.__config["orc"]["APP_ID"]),
  21. self.__config["orc"]["API_KEY"],
  22. self.__config["orc"]["SECRET_KEY"])
  23. '''
  24. {
  25. "log_id": 2471272194,
  26. "words_result_num": 2,
  27. "words_result":
  28. [
  29. {"words": " TSINGTAO"},
  30. {"words": "青島睥酒"}
  31. ]
  32. }
  33. '''
  34. def universal_text_recognition(self, image, request_id):
  35. reply_num = 0
  36. reply_value = None
  37. while True:
  38. try:
  39. or_result, or_image = cv2.imencode(".jpg", image)
  40. options = {
  41. "language_type": "CHN_ENG",
  42. "detect_direction": "true",
  43. "detect_language": "true",
  44. "probability": "true"
  45. }
  46. res_image = self.client.basicGeneral(or_image.tobytes(), options)
  47. error_code = res_image.get("error_code")
  48. if error_code:
  49. enum = BAIDUERRORDATA.get(error_code)
  50. # 如果异常编码未知, 返回空值
  51. if enum is None:
  52. logger.error("百度云人流量统计异常!error_code:{}, request_id: {}", error_code, request_id)
  53. return None
  54. # 重试指定次数后,还是异常,输出统一内部异常
  55. if enum.value[3] == 0:
  56. if reply_value is None:
  57. reply_value = enum.value[4]
  58. logger.error("百度云人流量统计异常!error_code:{}, error_msg:{}, reply_num:{}, request_id: {}",
  59. enum.value[0], enum.value[2], reply_num, request_id)
  60. raise Exception()
  61. # 重试指定次数后,还是异常,输出对应的异常
  62. if enum.value[3] == 1:
  63. if reply_value is None:
  64. reply_value = enum.value[4]
  65. raise ServiceException(str(enum.value[0]), enum.value[2])
  66. # 重试指定次数后,还是异常,输出空
  67. if enum.value[3] == 2:
  68. if reply_value is None:
  69. reply_value = enum.value[4]
  70. if reply_num >= reply_value:
  71. return None
  72. raise Exception()
  73. return res_image
  74. except Exception as e:
  75. time.sleep(1)
  76. reply_num += 0.5
  77. self.init_client()
  78. if reply_num > reply_value:
  79. if isinstance(e, ServiceException):
  80. raise ServiceException(e.code, e.msg)
  81. logger.error("通用文字识别失败: {}, request_id: {}", traceback.format_exc(), request_id)
  82. raise ServiceException(ExceptionType.SERVICE_INNER_EXCEPTION.value[0],
  83. ExceptionType.SERVICE_INNER_EXCEPTION.value[1])
  84. '''
  85. {
  86. "log_id": 3583925545,
  87. "words_result": {
  88. "color": "blue",
  89. "number": "苏HS7766"
  90. }
  91. }
  92. '''
  93. def license_plate_recognition(self, image, request_id):
  94. reply_num = 0
  95. reply_value = None
  96. while True:
  97. try:
  98. or_result, or_image = cv2.imencode(".jpg", image)
  99. res_image = self.client.licensePlate(or_image.tobytes(), {"multi_detect": "true"})
  100. error_code = res_image.get("error_code")
  101. if error_code:
  102. enum = BAIDUERRORDATA.get(error_code)
  103. # 如果异常编码未知, 返回空值
  104. if enum is None:
  105. logger.error("百度云人流量统计异常!error_code:{}, request_id: {}", error_code, request_id)
  106. return None
  107. # 重试指定次数后,还是异常,输出统一内部异常
  108. if enum.value[3] == 0:
  109. if reply_value is None:
  110. reply_value = enum.value[4]
  111. logger.error("百度云人流量统计异常!error_code:{}, error_msg:{}, reply_num:{}, request_id: {}",
  112. enum.value[0], enum.value[2], reply_num, request_id)
  113. raise Exception()
  114. # 重试指定次数后,还是异常,输出对应的异常
  115. if enum.value[3] == 1:
  116. if reply_value is None:
  117. reply_value = enum.value[4]
  118. raise ServiceException(str(enum.value[0]), enum.value[2])
  119. # 重试指定次数后,还是异常,输出空
  120. if enum.value[3] == 2:
  121. if reply_value is None:
  122. reply_value = enum.value[4]
  123. if reply_num >= reply_value:
  124. return None
  125. raise Exception()
  126. return res_image
  127. except Exception as e:
  128. time.sleep(1)
  129. reply_num += 1
  130. self.init_client()
  131. if reply_num > reply_value:
  132. if isinstance(e, ServiceException):
  133. raise ServiceException(e.code, e.msg)
  134. logger.error("车牌识别失败: {}, request_id: {}", traceback.format_exc(), request_id)
  135. raise ServiceException(ExceptionType.SERVICE_INNER_EXCEPTION.value[0],
  136. ExceptionType.SERVICE_INNER_EXCEPTION.value[1])