Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  1. # Licensed under the Apache License, Version 2.0 (the "License");
  2. # you may not use this file except in compliance with the License.
  3. # You may obtain a copy of the License at
  4. #
  5. # http://www.apache.org/licenses/LICENSE-2.0
  6. #
  7. # Unless required by applicable law or agreed to in writing, software
  8. # distributed under the License is distributed on an "AS IS" BASIS,
  9. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. # See the License for the specific language governing permissions and
  11. # limitations under the License.
  12. #
  13. import copy
  14. import time
  15. import os
  16. from huggingface_hub import snapshot_download
  17. from .operators import *
  18. import numpy as np
  19. import onnxruntime as ort
  20. from api.utils.file_utils import get_project_base_directory
  21. from .postprocess import build_post_process
  22. from rag.settings import cron_logger
  23. def transform(data, ops=None):
  24. """ transform """
  25. if ops is None:
  26. ops = []
  27. for op in ops:
  28. data = op(data)
  29. if data is None:
  30. return None
  31. return data
  32. def create_operators(op_param_list, global_config=None):
  33. """
  34. create operators based on the config
  35. Args:
  36. params(list): a dict list, used to create some operators
  37. """
  38. assert isinstance(
  39. op_param_list, list), ('operator config should be a list')
  40. ops = []
  41. for operator in op_param_list:
  42. assert isinstance(operator,
  43. dict) and len(operator) == 1, "yaml format error"
  44. op_name = list(operator)[0]
  45. param = {} if operator[op_name] is None else operator[op_name]
  46. if global_config is not None:
  47. param.update(global_config)
  48. op = eval(op_name)(**param)
  49. ops.append(op)
  50. return ops
  51. def load_model(model_dir, nm):
  52. model_file_path = os.path.join(model_dir, nm + ".onnx")
  53. if not os.path.exists(model_file_path):
  54. raise ValueError("not find model file path {}".format(
  55. model_file_path))
  56. sess = ort.InferenceSession(model_file_path)
  57. return sess, sess.get_inputs()[0]
  58. class TextRecognizer(object):
  59. def __init__(self, model_dir):
  60. self.rec_image_shape = [int(v) for v in "3, 48, 320".split(",")]
  61. self.rec_batch_num = 16
  62. postprocess_params = {
  63. 'name': 'CTCLabelDecode',
  64. "character_dict_path": os.path.join(get_project_base_directory(), "rag/res", "ocr.res"),
  65. "use_space_char": True
  66. }
  67. self.postprocess_op = build_post_process(postprocess_params)
  68. self.predictor, self.input_tensor = load_model(model_dir, 'rec')
  69. def resize_norm_img(self, img, max_wh_ratio):
  70. imgC, imgH, imgW = self.rec_image_shape
  71. assert imgC == img.shape[2]
  72. imgW = int((imgH * max_wh_ratio))
  73. w = self.input_tensor.shape[3:][0]
  74. if isinstance(w, str):
  75. pass
  76. elif w is not None and w > 0:
  77. imgW = w
  78. h, w = img.shape[:2]
  79. ratio = w / float(h)
  80. if math.ceil(imgH * ratio) > imgW:
  81. resized_w = imgW
  82. else:
  83. resized_w = int(math.ceil(imgH * ratio))
  84. resized_image = cv2.resize(img, (resized_w, imgH))
  85. resized_image = resized_image.astype('float32')
  86. resized_image = resized_image.transpose((2, 0, 1)) / 255
  87. resized_image -= 0.5
  88. resized_image /= 0.5
  89. padding_im = np.zeros((imgC, imgH, imgW), dtype=np.float32)
  90. padding_im[:, :, 0:resized_w] = resized_image
  91. return padding_im
  92. def resize_norm_img_vl(self, img, image_shape):
  93. imgC, imgH, imgW = image_shape
  94. img = img[:, :, ::-1] # bgr2rgb
  95. resized_image = cv2.resize(
  96. img, (imgW, imgH), interpolation=cv2.INTER_LINEAR)
  97. resized_image = resized_image.astype('float32')
  98. resized_image = resized_image.transpose((2, 0, 1)) / 255
  99. return resized_image
  100. def resize_norm_img_srn(self, img, image_shape):
  101. imgC, imgH, imgW = image_shape
  102. img_black = np.zeros((imgH, imgW))
  103. im_hei = img.shape[0]
  104. im_wid = img.shape[1]
  105. if im_wid <= im_hei * 1:
  106. img_new = cv2.resize(img, (imgH * 1, imgH))
  107. elif im_wid <= im_hei * 2:
  108. img_new = cv2.resize(img, (imgH * 2, imgH))
  109. elif im_wid <= im_hei * 3:
  110. img_new = cv2.resize(img, (imgH * 3, imgH))
  111. else:
  112. img_new = cv2.resize(img, (imgW, imgH))
  113. img_np = np.asarray(img_new)
  114. img_np = cv2.cvtColor(img_np, cv2.COLOR_BGR2GRAY)
  115. img_black[:, 0:img_np.shape[1]] = img_np
  116. img_black = img_black[:, :, np.newaxis]
  117. row, col, c = img_black.shape
  118. c = 1
  119. return np.reshape(img_black, (c, row, col)).astype(np.float32)
  120. def srn_other_inputs(self, image_shape, num_heads, max_text_length):
  121. imgC, imgH, imgW = image_shape
  122. feature_dim = int((imgH / 8) * (imgW / 8))
  123. encoder_word_pos = np.array(range(0, feature_dim)).reshape(
  124. (feature_dim, 1)).astype('int64')
  125. gsrm_word_pos = np.array(range(0, max_text_length)).reshape(
  126. (max_text_length, 1)).astype('int64')
  127. gsrm_attn_bias_data = np.ones((1, max_text_length, max_text_length))
  128. gsrm_slf_attn_bias1 = np.triu(gsrm_attn_bias_data, 1).reshape(
  129. [-1, 1, max_text_length, max_text_length])
  130. gsrm_slf_attn_bias1 = np.tile(
  131. gsrm_slf_attn_bias1,
  132. [1, num_heads, 1, 1]).astype('float32') * [-1e9]
  133. gsrm_slf_attn_bias2 = np.tril(gsrm_attn_bias_data, -1).reshape(
  134. [-1, 1, max_text_length, max_text_length])
  135. gsrm_slf_attn_bias2 = np.tile(
  136. gsrm_slf_attn_bias2,
  137. [1, num_heads, 1, 1]).astype('float32') * [-1e9]
  138. encoder_word_pos = encoder_word_pos[np.newaxis, :]
  139. gsrm_word_pos = gsrm_word_pos[np.newaxis, :]
  140. return [
  141. encoder_word_pos, gsrm_word_pos, gsrm_slf_attn_bias1,
  142. gsrm_slf_attn_bias2
  143. ]
  144. def process_image_srn(self, img, image_shape, num_heads, max_text_length):
  145. norm_img = self.resize_norm_img_srn(img, image_shape)
  146. norm_img = norm_img[np.newaxis, :]
  147. [encoder_word_pos, gsrm_word_pos, gsrm_slf_attn_bias1, gsrm_slf_attn_bias2] = \
  148. self.srn_other_inputs(image_shape, num_heads, max_text_length)
  149. gsrm_slf_attn_bias1 = gsrm_slf_attn_bias1.astype(np.float32)
  150. gsrm_slf_attn_bias2 = gsrm_slf_attn_bias2.astype(np.float32)
  151. encoder_word_pos = encoder_word_pos.astype(np.int64)
  152. gsrm_word_pos = gsrm_word_pos.astype(np.int64)
  153. return (norm_img, encoder_word_pos, gsrm_word_pos, gsrm_slf_attn_bias1,
  154. gsrm_slf_attn_bias2)
  155. def resize_norm_img_sar(self, img, image_shape,
  156. width_downsample_ratio=0.25):
  157. imgC, imgH, imgW_min, imgW_max = image_shape
  158. h = img.shape[0]
  159. w = img.shape[1]
  160. valid_ratio = 1.0
  161. # make sure new_width is an integral multiple of width_divisor.
  162. width_divisor = int(1 / width_downsample_ratio)
  163. # resize
  164. ratio = w / float(h)
  165. resize_w = math.ceil(imgH * ratio)
  166. if resize_w % width_divisor != 0:
  167. resize_w = round(resize_w / width_divisor) * width_divisor
  168. if imgW_min is not None:
  169. resize_w = max(imgW_min, resize_w)
  170. if imgW_max is not None:
  171. valid_ratio = min(1.0, 1.0 * resize_w / imgW_max)
  172. resize_w = min(imgW_max, resize_w)
  173. resized_image = cv2.resize(img, (resize_w, imgH))
  174. resized_image = resized_image.astype('float32')
  175. # norm
  176. if image_shape[0] == 1:
  177. resized_image = resized_image / 255
  178. resized_image = resized_image[np.newaxis, :]
  179. else:
  180. resized_image = resized_image.transpose((2, 0, 1)) / 255
  181. resized_image -= 0.5
  182. resized_image /= 0.5
  183. resize_shape = resized_image.shape
  184. padding_im = -1.0 * np.ones((imgC, imgH, imgW_max), dtype=np.float32)
  185. padding_im[:, :, 0:resize_w] = resized_image
  186. pad_shape = padding_im.shape
  187. return padding_im, resize_shape, pad_shape, valid_ratio
  188. def resize_norm_img_spin(self, img):
  189. img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  190. # return padding_im
  191. img = cv2.resize(img, tuple([100, 32]), cv2.INTER_CUBIC)
  192. img = np.array(img, np.float32)
  193. img = np.expand_dims(img, -1)
  194. img = img.transpose((2, 0, 1))
  195. mean = [127.5]
  196. std = [127.5]
  197. mean = np.array(mean, dtype=np.float32)
  198. std = np.array(std, dtype=np.float32)
  199. mean = np.float32(mean.reshape(1, -1))
  200. stdinv = 1 / np.float32(std.reshape(1, -1))
  201. img -= mean
  202. img *= stdinv
  203. return img
  204. def resize_norm_img_svtr(self, img, image_shape):
  205. imgC, imgH, imgW = image_shape
  206. resized_image = cv2.resize(
  207. img, (imgW, imgH), interpolation=cv2.INTER_LINEAR)
  208. resized_image = resized_image.astype('float32')
  209. resized_image = resized_image.transpose((2, 0, 1)) / 255
  210. resized_image -= 0.5
  211. resized_image /= 0.5
  212. return resized_image
  213. def resize_norm_img_abinet(self, img, image_shape):
  214. imgC, imgH, imgW = image_shape
  215. resized_image = cv2.resize(
  216. img, (imgW, imgH), interpolation=cv2.INTER_LINEAR)
  217. resized_image = resized_image.astype('float32')
  218. resized_image = resized_image / 255.
  219. mean = np.array([0.485, 0.456, 0.406])
  220. std = np.array([0.229, 0.224, 0.225])
  221. resized_image = (
  222. resized_image - mean[None, None, ...]) / std[None, None, ...]
  223. resized_image = resized_image.transpose((2, 0, 1))
  224. resized_image = resized_image.astype('float32')
  225. return resized_image
  226. def norm_img_can(self, img, image_shape):
  227. img = cv2.cvtColor(
  228. img, cv2.COLOR_BGR2GRAY) # CAN only predict gray scale image
  229. if self.rec_image_shape[0] == 1:
  230. h, w = img.shape
  231. _, imgH, imgW = self.rec_image_shape
  232. if h < imgH or w < imgW:
  233. padding_h = max(imgH - h, 0)
  234. padding_w = max(imgW - w, 0)
  235. img_padded = np.pad(img, ((0, padding_h), (0, padding_w)),
  236. 'constant',
  237. constant_values=(255))
  238. img = img_padded
  239. img = np.expand_dims(img, 0) / 255.0 # h,w,c -> c,h,w
  240. img = img.astype('float32')
  241. return img
  242. def __call__(self, img_list):
  243. img_num = len(img_list)
  244. # Calculate the aspect ratio of all text bars
  245. width_list = []
  246. for img in img_list:
  247. width_list.append(img.shape[1] / float(img.shape[0]))
  248. # Sorting can speed up the recognition process
  249. indices = np.argsort(np.array(width_list))
  250. rec_res = [['', 0.0]] * img_num
  251. batch_num = self.rec_batch_num
  252. st = time.time()
  253. for beg_img_no in range(0, img_num, batch_num):
  254. end_img_no = min(img_num, beg_img_no + batch_num)
  255. norm_img_batch = []
  256. imgC, imgH, imgW = self.rec_image_shape[:3]
  257. max_wh_ratio = imgW / imgH
  258. # max_wh_ratio = 0
  259. for ino in range(beg_img_no, end_img_no):
  260. h, w = img_list[indices[ino]].shape[0:2]
  261. wh_ratio = w * 1.0 / h
  262. max_wh_ratio = max(max_wh_ratio, wh_ratio)
  263. for ino in range(beg_img_no, end_img_no):
  264. norm_img = self.resize_norm_img(img_list[indices[ino]],
  265. max_wh_ratio)
  266. norm_img = norm_img[np.newaxis, :]
  267. norm_img_batch.append(norm_img)
  268. norm_img_batch = np.concatenate(norm_img_batch)
  269. norm_img_batch = norm_img_batch.copy()
  270. input_dict = {}
  271. input_dict[self.input_tensor.name] = norm_img_batch
  272. outputs = self.predictor.run(None, input_dict)
  273. preds = outputs[0]
  274. rec_result = self.postprocess_op(preds)
  275. for rno in range(len(rec_result)):
  276. rec_res[indices[beg_img_no + rno]] = rec_result[rno]
  277. return rec_res, time.time() - st
  278. class TextDetector(object):
  279. def __init__(self, model_dir):
  280. pre_process_list = [{
  281. 'DetResizeForTest': {
  282. 'limit_side_len': 960,
  283. 'limit_type': "max",
  284. }
  285. }, {
  286. 'NormalizeImage': {
  287. 'std': [0.229, 0.224, 0.225],
  288. 'mean': [0.485, 0.456, 0.406],
  289. 'scale': '1./255.',
  290. 'order': 'hwc'
  291. }
  292. }, {
  293. 'ToCHWImage': None
  294. }, {
  295. 'KeepKeys': {
  296. 'keep_keys': ['image', 'shape']
  297. }
  298. }]
  299. postprocess_params = {"name": "DBPostProcess", "thresh": 0.3, "box_thresh": 0.6, "max_candidates": 1000,
  300. "unclip_ratio": 1.5, "use_dilation": False, "score_mode": "fast", "box_type": "quad"}
  301. self.postprocess_op = build_post_process(postprocess_params)
  302. self.predictor, self.input_tensor = load_model(model_dir, 'det')
  303. img_h, img_w = self.input_tensor.shape[2:]
  304. if isinstance(img_h, str) or isinstance(img_w, str):
  305. pass
  306. elif img_h is not None and img_w is not None and img_h > 0 and img_w > 0:
  307. pre_process_list[0] = {
  308. 'DetResizeForTest': {
  309. 'image_shape': [img_h, img_w]
  310. }
  311. }
  312. self.preprocess_op = create_operators(pre_process_list)
  313. def order_points_clockwise(self, pts):
  314. rect = np.zeros((4, 2), dtype="float32")
  315. s = pts.sum(axis=1)
  316. rect[0] = pts[np.argmin(s)]
  317. rect[2] = pts[np.argmax(s)]
  318. tmp = np.delete(pts, (np.argmin(s), np.argmax(s)), axis=0)
  319. diff = np.diff(np.array(tmp), axis=1)
  320. rect[1] = tmp[np.argmin(diff)]
  321. rect[3] = tmp[np.argmax(diff)]
  322. return rect
  323. def clip_det_res(self, points, img_height, img_width):
  324. for pno in range(points.shape[0]):
  325. points[pno, 0] = int(min(max(points[pno, 0], 0), img_width - 1))
  326. points[pno, 1] = int(min(max(points[pno, 1], 0), img_height - 1))
  327. return points
  328. def filter_tag_det_res(self, dt_boxes, image_shape):
  329. img_height, img_width = image_shape[0:2]
  330. dt_boxes_new = []
  331. for box in dt_boxes:
  332. if isinstance(box, list):
  333. box = np.array(box)
  334. box = self.order_points_clockwise(box)
  335. box = self.clip_det_res(box, img_height, img_width)
  336. rect_width = int(np.linalg.norm(box[0] - box[1]))
  337. rect_height = int(np.linalg.norm(box[0] - box[3]))
  338. if rect_width <= 3 or rect_height <= 3:
  339. continue
  340. dt_boxes_new.append(box)
  341. dt_boxes = np.array(dt_boxes_new)
  342. return dt_boxes
  343. def filter_tag_det_res_only_clip(self, dt_boxes, image_shape):
  344. img_height, img_width = image_shape[0:2]
  345. dt_boxes_new = []
  346. for box in dt_boxes:
  347. if isinstance(box, list):
  348. box = np.array(box)
  349. box = self.clip_det_res(box, img_height, img_width)
  350. dt_boxes_new.append(box)
  351. dt_boxes = np.array(dt_boxes_new)
  352. return dt_boxes
  353. def __call__(self, img):
  354. ori_im = img.copy()
  355. data = {'image': img}
  356. st = time.time()
  357. data = transform(data, self.preprocess_op)
  358. img, shape_list = data
  359. if img is None:
  360. return None, 0
  361. img = np.expand_dims(img, axis=0)
  362. shape_list = np.expand_dims(shape_list, axis=0)
  363. img = img.copy()
  364. input_dict = {}
  365. input_dict[self.input_tensor.name] = img
  366. outputs = self.predictor.run(None, input_dict)
  367. post_result = self.postprocess_op({"maps": outputs[0]}, shape_list)
  368. dt_boxes = post_result[0]['points']
  369. dt_boxes = self.filter_tag_det_res(dt_boxes, ori_im.shape)
  370. return dt_boxes, time.time() - st
  371. class OCR(object):
  372. def __init__(self, model_dir=None):
  373. """
  374. If you have trouble downloading HuggingFace models, -_^ this might help!!
  375. For Linux:
  376. export HF_ENDPOINT=https://hf-mirror.com
  377. For Windows:
  378. Good luck
  379. ^_-
  380. """
  381. if not model_dir:
  382. model_dir = snapshot_download(repo_id="InfiniFlow/ocr")
  383. self.text_detector = TextDetector(model_dir)
  384. self.text_recognizer = TextRecognizer(model_dir)
  385. self.drop_score = 0.5
  386. self.crop_image_res_index = 0
  387. def get_rotate_crop_image(self, img, points):
  388. '''
  389. img_height, img_width = img.shape[0:2]
  390. left = int(np.min(points[:, 0]))
  391. right = int(np.max(points[:, 0]))
  392. top = int(np.min(points[:, 1]))
  393. bottom = int(np.max(points[:, 1]))
  394. img_crop = img[top:bottom, left:right, :].copy()
  395. points[:, 0] = points[:, 0] - left
  396. points[:, 1] = points[:, 1] - top
  397. '''
  398. assert len(points) == 4, "shape of points must be 4*2"
  399. img_crop_width = int(
  400. max(
  401. np.linalg.norm(points[0] - points[1]),
  402. np.linalg.norm(points[2] - points[3])))
  403. img_crop_height = int(
  404. max(
  405. np.linalg.norm(points[0] - points[3]),
  406. np.linalg.norm(points[1] - points[2])))
  407. pts_std = np.float32([[0, 0], [img_crop_width, 0],
  408. [img_crop_width, img_crop_height],
  409. [0, img_crop_height]])
  410. M = cv2.getPerspectiveTransform(points, pts_std)
  411. dst_img = cv2.warpPerspective(
  412. img,
  413. M, (img_crop_width, img_crop_height),
  414. borderMode=cv2.BORDER_REPLICATE,
  415. flags=cv2.INTER_CUBIC)
  416. dst_img_height, dst_img_width = dst_img.shape[0:2]
  417. if dst_img_height * 1.0 / dst_img_width >= 1.5:
  418. dst_img = np.rot90(dst_img)
  419. return dst_img
  420. def sorted_boxes(self, dt_boxes):
  421. """
  422. Sort text boxes in order from top to bottom, left to right
  423. args:
  424. dt_boxes(array):detected text boxes with shape [4, 2]
  425. return:
  426. sorted boxes(array) with shape [4, 2]
  427. """
  428. num_boxes = dt_boxes.shape[0]
  429. sorted_boxes = sorted(dt_boxes, key=lambda x: (x[0][1], x[0][0]))
  430. _boxes = list(sorted_boxes)
  431. for i in range(num_boxes - 1):
  432. for j in range(i, -1, -1):
  433. if abs(_boxes[j + 1][0][1] - _boxes[j][0][1]) < 10 and \
  434. (_boxes[j + 1][0][0] < _boxes[j][0][0]):
  435. tmp = _boxes[j]
  436. _boxes[j] = _boxes[j + 1]
  437. _boxes[j + 1] = tmp
  438. else:
  439. break
  440. return _boxes
  441. def __call__(self, img, cls=True):
  442. time_dict = {'det': 0, 'rec': 0, 'cls': 0, 'all': 0}
  443. if img is None:
  444. return None, None, time_dict
  445. start = time.time()
  446. ori_im = img.copy()
  447. dt_boxes, elapse = self.text_detector(img)
  448. time_dict['det'] = elapse
  449. if dt_boxes is None:
  450. end = time.time()
  451. time_dict['all'] = end - start
  452. return None, None, time_dict
  453. else:
  454. cron_logger.debug("dt_boxes num : {}, elapsed : {}".format(
  455. len(dt_boxes), elapse))
  456. img_crop_list = []
  457. dt_boxes = self.sorted_boxes(dt_boxes)
  458. for bno in range(len(dt_boxes)):
  459. tmp_box = copy.deepcopy(dt_boxes[bno])
  460. img_crop = self.get_rotate_crop_image(ori_im, tmp_box)
  461. img_crop_list.append(img_crop)
  462. rec_res, elapse = self.text_recognizer(img_crop_list)
  463. time_dict['rec'] = elapse
  464. cron_logger.debug("rec_res num : {}, elapsed : {}".format(
  465. len(rec_res), elapse))
  466. filter_boxes, filter_rec_res = [], []
  467. for box, rec_result in zip(dt_boxes, rec_res):
  468. text, score = rec_result
  469. if score >= self.drop_score:
  470. filter_boxes.append(box)
  471. filter_rec_res.append(rec_result)
  472. end = time.time()
  473. time_dict['all'] = end - start
  474. #for bno in range(len(img_crop_list)):
  475. # print(f"{bno}, {rec_res[bno]}")
  476. return list(zip([a.tolist() for a in filter_boxes], filter_rec_res))