Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

recognizer.py 17KB

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