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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. #
  2. # Copyright 2025 The InfiniFlow Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. import logging
  17. import os
  18. import math
  19. import numpy as np
  20. import cv2
  21. from functools import cmp_to_key
  22. from api.utils.file_utils import get_project_base_directory
  23. from .operators import * # noqa: F403
  24. from .operators import preprocess
  25. from . import operators
  26. from .ocr import load_model
  27. class Recognizer:
  28. def __init__(self, label_list, task_name, model_dir=None):
  29. """
  30. If you have trouble downloading HuggingFace models, -_^ this might help!!
  31. For Linux:
  32. export HF_ENDPOINT=https://hf-mirror.com
  33. For Windows:
  34. Good luck
  35. ^_-
  36. """
  37. if not model_dir:
  38. model_dir = os.path.join(
  39. get_project_base_directory(),
  40. "rag/res/deepdoc")
  41. self.ort_sess, self.run_options = load_model(model_dir, task_name)
  42. self.input_names = [node.name for node in self.ort_sess.get_inputs()]
  43. self.output_names = [node.name for node in self.ort_sess.get_outputs()]
  44. self.input_shape = self.ort_sess.get_inputs()[0].shape[2:4]
  45. self.label_list = label_list
  46. @staticmethod
  47. def sort_Y_firstly(arr, threashold):
  48. def cmp(c1, c2):
  49. diff = c1["top"] - c2["top"]
  50. if abs(diff) < threashold:
  51. diff = c1["x0"] - c2["x0"]
  52. return diff
  53. arr = sorted(arr, key=cmp_to_key(cmp))
  54. return arr
  55. @staticmethod
  56. def sort_X_firstly(arr, threashold):
  57. def cmp(c1, c2):
  58. diff = c1["x0"] - c2["x0"]
  59. if abs(diff) < threashold:
  60. diff = c1["top"] - c2["top"]
  61. return diff
  62. arr = sorted(arr, key=cmp_to_key(cmp))
  63. return arr
  64. @staticmethod
  65. def sort_C_firstly(arr, thr=0):
  66. # sort using y1 first and then x1
  67. # sorted(arr, key=lambda r: (r["x0"], r["top"]))
  68. arr = Recognizer.sort_X_firstly(arr, thr)
  69. for i in range(len(arr) - 1):
  70. for j in range(i, -1, -1):
  71. # restore the order using th
  72. if "C" not in arr[j] or "C" not in arr[j + 1]:
  73. continue
  74. if arr[j + 1]["C"] < arr[j]["C"] \
  75. or (
  76. arr[j + 1]["C"] == arr[j]["C"]
  77. and arr[j + 1]["top"] < arr[j]["top"]
  78. ):
  79. tmp = arr[j]
  80. arr[j] = arr[j + 1]
  81. arr[j + 1] = tmp
  82. return arr
  83. @staticmethod
  84. def sort_R_firstly(arr, thr=0):
  85. # sort using y1 first and then x1
  86. # sorted(arr, key=lambda r: (r["top"], r["x0"]))
  87. arr = Recognizer.sort_Y_firstly(arr, thr)
  88. for i in range(len(arr) - 1):
  89. for j in range(i, -1, -1):
  90. if "R" not in arr[j] or "R" not in arr[j + 1]:
  91. continue
  92. if arr[j + 1]["R"] < arr[j]["R"] \
  93. or (
  94. arr[j + 1]["R"] == arr[j]["R"]
  95. and arr[j + 1]["x0"] < arr[j]["x0"]
  96. ):
  97. tmp = arr[j]
  98. arr[j] = arr[j + 1]
  99. arr[j + 1] = tmp
  100. return arr
  101. @staticmethod
  102. def overlapped_area(a, b, ratio=True):
  103. tp, btm, x0, x1 = a["top"], a["bottom"], a["x0"], a["x1"]
  104. if b["x0"] > x1 or b["x1"] < x0:
  105. return 0
  106. if b["bottom"] < tp or b["top"] > btm:
  107. return 0
  108. x0_ = max(b["x0"], x0)
  109. x1_ = min(b["x1"], x1)
  110. assert x0_ <= x1_, "Bbox mismatch! T:{},B:{},X0:{},X1:{} ==> {}".format(
  111. tp, btm, x0, x1, b)
  112. tp_ = max(b["top"], tp)
  113. btm_ = min(b["bottom"], btm)
  114. assert tp_ <= btm_, "Bbox mismatch! T:{},B:{},X0:{},X1:{} => {}".format(
  115. tp, btm, x0, x1, b)
  116. ov = (btm_ - tp_) * (x1_ - x0_) if x1 - \
  117. x0 != 0 and btm - tp != 0 else 0
  118. if ov > 0 and ratio:
  119. ov /= (x1 - x0) * (btm - tp)
  120. return ov
  121. @staticmethod
  122. def layouts_cleanup(boxes, layouts, far=2, thr=0.7):
  123. def notOverlapped(a, b):
  124. return any([a["x1"] < b["x0"],
  125. a["x0"] > b["x1"],
  126. a["bottom"] < b["top"],
  127. a["top"] > b["bottom"]])
  128. i = 0
  129. while i + 1 < len(layouts):
  130. j = i + 1
  131. while j < min(i + far, len(layouts)) \
  132. and (layouts[i].get("type", "") != layouts[j].get("type", "")
  133. or notOverlapped(layouts[i], layouts[j])):
  134. j += 1
  135. if j >= min(i + far, len(layouts)):
  136. i += 1
  137. continue
  138. if Recognizer.overlapped_area(layouts[i], layouts[j]) < thr \
  139. and Recognizer.overlapped_area(layouts[j], layouts[i]) < thr:
  140. i += 1
  141. continue
  142. if layouts[i].get("score") and layouts[j].get("score"):
  143. if layouts[i]["score"] > layouts[j]["score"]:
  144. layouts.pop(j)
  145. else:
  146. layouts.pop(i)
  147. continue
  148. area_i, area_i_1 = 0, 0
  149. for b in boxes:
  150. if not notOverlapped(b, layouts[i]):
  151. area_i += Recognizer.overlapped_area(b, layouts[i], False)
  152. if not notOverlapped(b, layouts[j]):
  153. area_i_1 += Recognizer.overlapped_area(b, layouts[j], False)
  154. if area_i > area_i_1:
  155. layouts.pop(j)
  156. else:
  157. layouts.pop(i)
  158. return layouts
  159. def create_inputs(self, imgs, im_info):
  160. """generate input for different model type
  161. Args:
  162. imgs (list(numpy)): list of images (np.ndarray)
  163. im_info (list(dict)): list of image info
  164. Returns:
  165. inputs (dict): input of model
  166. """
  167. inputs = {}
  168. im_shape = []
  169. scale_factor = []
  170. if len(imgs) == 1:
  171. inputs['image'] = np.array((imgs[0],)).astype('float32')
  172. inputs['im_shape'] = np.array(
  173. (im_info[0]['im_shape'],)).astype('float32')
  174. inputs['scale_factor'] = np.array(
  175. (im_info[0]['scale_factor'],)).astype('float32')
  176. return inputs
  177. for e in im_info:
  178. im_shape.append(np.array((e['im_shape'],)).astype('float32'))
  179. scale_factor.append(np.array((e['scale_factor'],)).astype('float32'))
  180. inputs['im_shape'] = np.concatenate(im_shape, axis=0)
  181. inputs['scale_factor'] = np.concatenate(scale_factor, axis=0)
  182. imgs_shape = [[e.shape[1], e.shape[2]] for e in imgs]
  183. max_shape_h = max([e[0] for e in imgs_shape])
  184. max_shape_w = max([e[1] for e in imgs_shape])
  185. padding_imgs = []
  186. for img in imgs:
  187. im_c, im_h, im_w = img.shape[:]
  188. padding_im = np.zeros(
  189. (im_c, max_shape_h, max_shape_w), dtype=np.float32)
  190. padding_im[:, :im_h, :im_w] = img
  191. padding_imgs.append(padding_im)
  192. inputs['image'] = np.stack(padding_imgs, axis=0)
  193. return inputs
  194. @staticmethod
  195. def find_overlapped(box, boxes_sorted_by_y, naive=False):
  196. if not boxes_sorted_by_y:
  197. return
  198. bxs = boxes_sorted_by_y
  199. s, e, ii = 0, len(bxs), 0
  200. while s < e and not naive:
  201. ii = (e + s) // 2
  202. pv = bxs[ii]
  203. if box["bottom"] < pv["top"]:
  204. e = ii
  205. continue
  206. if box["top"] > pv["bottom"]:
  207. s = ii + 1
  208. continue
  209. break
  210. while s < ii:
  211. if box["top"] > bxs[s]["bottom"]:
  212. s += 1
  213. break
  214. while e - 1 > ii:
  215. if box["bottom"] < bxs[e - 1]["top"]:
  216. e -= 1
  217. break
  218. max_overlaped_i, max_overlaped = None, 0
  219. for i in range(s, e):
  220. ov = Recognizer.overlapped_area(bxs[i], box)
  221. if ov <= max_overlaped:
  222. continue
  223. max_overlaped_i = i
  224. max_overlaped = ov
  225. return max_overlaped_i
  226. @staticmethod
  227. def find_horizontally_tightest_fit(box, boxes):
  228. if not boxes:
  229. return
  230. min_dis, min_i = 1000000, None
  231. for i,b in enumerate(boxes):
  232. if box.get("layoutno", "0") != b.get("layoutno", "0"):
  233. continue
  234. dis = min(abs(box["x0"] - b["x0"]), abs(box["x1"] - b["x1"]), abs(box["x0"]+box["x1"] - b["x1"] - b["x0"])/2)
  235. if dis < min_dis:
  236. min_i = i
  237. min_dis = dis
  238. return min_i
  239. @staticmethod
  240. def find_overlapped_with_threashold(box, boxes, thr=0.3):
  241. if not boxes:
  242. return
  243. max_overlapped_i, max_overlapped, _max_overlapped = None, thr, 0
  244. s, e = 0, len(boxes)
  245. for i in range(s, e):
  246. ov = Recognizer.overlapped_area(box, boxes[i])
  247. _ov = Recognizer.overlapped_area(boxes[i], box)
  248. if (ov, _ov) < (max_overlapped, _max_overlapped):
  249. continue
  250. max_overlapped_i = i
  251. max_overlapped = ov
  252. _max_overlapped = _ov
  253. return max_overlapped_i
  254. def preprocess(self, image_list):
  255. inputs = []
  256. if "scale_factor" in self.input_names:
  257. preprocess_ops = []
  258. for op_info in [
  259. {'interp': 2, 'keep_ratio': False, 'target_size': [800, 608], 'type': 'LinearResize'},
  260. {'is_scale': True, 'mean': [0.485, 0.456, 0.406], 'std': [0.229, 0.224, 0.225], 'type': 'StandardizeImage'},
  261. {'type': 'Permute'},
  262. {'stride': 32, 'type': 'PadStride'}
  263. ]:
  264. new_op_info = op_info.copy()
  265. op_type = new_op_info.pop('type')
  266. preprocess_ops.append(getattr(operators, op_type)(**new_op_info))
  267. for im_path in image_list:
  268. im, im_info = preprocess(im_path, preprocess_ops)
  269. inputs.append({"image": np.array((im,)).astype('float32'),
  270. "scale_factor": np.array((im_info["scale_factor"],)).astype('float32')})
  271. else:
  272. hh, ww = self.input_shape
  273. for img in image_list:
  274. h, w = img.shape[:2]
  275. img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
  276. img = cv2.resize(np.array(img).astype('float32'), (ww, hh))
  277. # Scale input pixel values to 0 to 1
  278. img /= 255.0
  279. img = img.transpose(2, 0, 1)
  280. img = img[np.newaxis, :, :, :].astype(np.float32)
  281. inputs.append({self.input_names[0]: img, "scale_factor": [w/ww, h/hh]})
  282. return inputs
  283. def postprocess(self, boxes, inputs, thr):
  284. if "scale_factor" in self.input_names:
  285. bb = []
  286. for b in boxes:
  287. clsid, bbox, score = int(b[0]), b[2:], b[1]
  288. if score < thr:
  289. continue
  290. if clsid >= len(self.label_list):
  291. continue
  292. bb.append({
  293. "type": self.label_list[clsid].lower(),
  294. "bbox": [float(t) for t in bbox.tolist()],
  295. "score": float(score)
  296. })
  297. return bb
  298. def xywh2xyxy(x):
  299. # [x, y, w, h] to [x1, y1, x2, y2]
  300. y = np.copy(x)
  301. y[:, 0] = x[:, 0] - x[:, 2] / 2
  302. y[:, 1] = x[:, 1] - x[:, 3] / 2
  303. y[:, 2] = x[:, 0] + x[:, 2] / 2
  304. y[:, 3] = x[:, 1] + x[:, 3] / 2
  305. return y
  306. def compute_iou(box, boxes):
  307. # Compute xmin, ymin, xmax, ymax for both boxes
  308. xmin = np.maximum(box[0], boxes[:, 0])
  309. ymin = np.maximum(box[1], boxes[:, 1])
  310. xmax = np.minimum(box[2], boxes[:, 2])
  311. ymax = np.minimum(box[3], boxes[:, 3])
  312. # Compute intersection area
  313. intersection_area = np.maximum(0, xmax - xmin) * np.maximum(0, ymax - ymin)
  314. # Compute union area
  315. box_area = (box[2] - box[0]) * (box[3] - box[1])
  316. boxes_area = (boxes[:, 2] - boxes[:, 0]) * (boxes[:, 3] - boxes[:, 1])
  317. union_area = box_area + boxes_area - intersection_area
  318. # Compute IoU
  319. iou = intersection_area / union_area
  320. return iou
  321. def iou_filter(boxes, scores, iou_threshold):
  322. sorted_indices = np.argsort(scores)[::-1]
  323. keep_boxes = []
  324. while sorted_indices.size > 0:
  325. # Pick the last box
  326. box_id = sorted_indices[0]
  327. keep_boxes.append(box_id)
  328. # Compute IoU of the picked box with the rest
  329. ious = compute_iou(boxes[box_id, :], boxes[sorted_indices[1:], :])
  330. # Remove boxes with IoU over the threshold
  331. keep_indices = np.where(ious < iou_threshold)[0]
  332. # print(keep_indices.shape, sorted_indices.shape)
  333. sorted_indices = sorted_indices[keep_indices + 1]
  334. return keep_boxes
  335. boxes = np.squeeze(boxes).T
  336. # Filter out object confidence scores below threshold
  337. scores = np.max(boxes[:, 4:], axis=1)
  338. boxes = boxes[scores > thr, :]
  339. scores = scores[scores > thr]
  340. if len(boxes) == 0:
  341. return []
  342. # Get the class with the highest confidence
  343. class_ids = np.argmax(boxes[:, 4:], axis=1)
  344. boxes = boxes[:, :4]
  345. input_shape = np.array([inputs["scale_factor"][0], inputs["scale_factor"][1], inputs["scale_factor"][0], inputs["scale_factor"][1]])
  346. boxes = np.multiply(boxes, input_shape, dtype=np.float32)
  347. boxes = xywh2xyxy(boxes)
  348. unique_class_ids = np.unique(class_ids)
  349. indices = []
  350. for class_id in unique_class_ids:
  351. class_indices = np.where(class_ids == class_id)[0]
  352. class_boxes = boxes[class_indices, :]
  353. class_scores = scores[class_indices]
  354. class_keep_boxes = iou_filter(class_boxes, class_scores, 0.2)
  355. indices.extend(class_indices[class_keep_boxes])
  356. return [{
  357. "type": self.label_list[class_ids[i]].lower(),
  358. "bbox": [float(t) for t in boxes[i].tolist()],
  359. "score": float(scores[i])
  360. } for i in indices]
  361. def __call__(self, image_list, thr=0.7, batch_size=16):
  362. res = []
  363. imgs = []
  364. for i in range(len(image_list)):
  365. if not isinstance(image_list[i], np.ndarray):
  366. imgs.append(np.array(image_list[i]))
  367. else:
  368. imgs.append(image_list[i])
  369. batch_loop_cnt = math.ceil(float(len(imgs)) / batch_size)
  370. for i in range(batch_loop_cnt):
  371. start_index = i * batch_size
  372. end_index = min((i + 1) * batch_size, len(imgs))
  373. batch_image_list = imgs[start_index:end_index]
  374. inputs = self.preprocess(batch_image_list)
  375. logging.debug("preprocess")
  376. for ins in inputs:
  377. bb = self.postprocess(self.ort_sess.run(None, {k:v for k,v in ins.items() if k in self.input_names}, self.run_options)[0], ins, thr)
  378. res.append(bb)
  379. #seeit.save_results(image_list, res, self.label_list, threshold=thr)
  380. return res