您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

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