magic_model.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771
  1. import enum
  2. from magic_pdf.config.model_block_type import ModelBlockTypeEnum
  3. from magic_pdf.config.ocr_content_type import CategoryId, ContentType
  4. from magic_pdf.data.dataset import Dataset
  5. from magic_pdf.libs.boxbase import (_is_in, bbox_distance, bbox_relative_pos,
  6. calculate_iou)
  7. from magic_pdf.libs.coordinate_transform import get_scale_ratio
  8. from magic_pdf.pre_proc.remove_bbox_overlap import _remove_overlap_between_bbox
  9. CAPATION_OVERLAP_AREA_RATIO = 0.6
  10. MERGE_BOX_OVERLAP_AREA_RATIO = 1.1
  11. class PosRelationEnum(enum.Enum):
  12. LEFT = 'left'
  13. RIGHT = 'right'
  14. UP = 'up'
  15. BOTTOM = 'bottom'
  16. ALL = 'all'
  17. class MagicModel:
  18. """每个函数没有得到元素的时候返回空list."""
  19. def __fix_axis(self):
  20. for model_page_info in self.__model_list:
  21. need_remove_list = []
  22. page_no = model_page_info['page_info']['page_no']
  23. horizontal_scale_ratio, vertical_scale_ratio = get_scale_ratio(
  24. model_page_info, self.__docs.get_page(page_no)
  25. )
  26. layout_dets = model_page_info['layout_dets']
  27. for layout_det in layout_dets:
  28. if layout_det.get('bbox') is not None:
  29. # 兼容直接输出bbox的模型数据,如paddle
  30. x0, y0, x1, y1 = layout_det['bbox']
  31. else:
  32. # 兼容直接输出poly的模型数据,如xxx
  33. x0, y0, _, _, x1, y1, _, _ = layout_det['poly']
  34. bbox = [
  35. int(x0 / horizontal_scale_ratio),
  36. int(y0 / vertical_scale_ratio),
  37. int(x1 / horizontal_scale_ratio),
  38. int(y1 / vertical_scale_ratio),
  39. ]
  40. layout_det['bbox'] = bbox
  41. # 删除高度或者宽度小于等于0的spans
  42. if bbox[2] - bbox[0] <= 0 or bbox[3] - bbox[1] <= 0:
  43. need_remove_list.append(layout_det)
  44. for need_remove in need_remove_list:
  45. layout_dets.remove(need_remove)
  46. def __fix_by_remove_low_confidence(self):
  47. for model_page_info in self.__model_list:
  48. need_remove_list = []
  49. layout_dets = model_page_info['layout_dets']
  50. for layout_det in layout_dets:
  51. if layout_det['score'] <= 0.05:
  52. need_remove_list.append(layout_det)
  53. else:
  54. continue
  55. for need_remove in need_remove_list:
  56. layout_dets.remove(need_remove)
  57. def __fix_by_remove_high_iou_and_low_confidence(self):
  58. for model_page_info in self.__model_list:
  59. need_remove_list = []
  60. layout_dets = model_page_info['layout_dets']
  61. for layout_det1 in layout_dets:
  62. for layout_det2 in layout_dets:
  63. if layout_det1 == layout_det2:
  64. continue
  65. if layout_det1['category_id'] in [
  66. 0,
  67. 1,
  68. 2,
  69. 3,
  70. 4,
  71. 5,
  72. 6,
  73. 7,
  74. 8,
  75. 9,
  76. ] and layout_det2['category_id'] in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]:
  77. if (
  78. calculate_iou(layout_det1['bbox'], layout_det2['bbox'])
  79. > 0.9
  80. ):
  81. if layout_det1['score'] < layout_det2['score']:
  82. layout_det_need_remove = layout_det1
  83. else:
  84. layout_det_need_remove = layout_det2
  85. if layout_det_need_remove not in need_remove_list:
  86. need_remove_list.append(layout_det_need_remove)
  87. else:
  88. continue
  89. else:
  90. continue
  91. for need_remove in need_remove_list:
  92. layout_dets.remove(need_remove)
  93. def __init__(self, model_list: list, docs: Dataset):
  94. self.__model_list = model_list
  95. self.__docs = docs
  96. """为所有模型数据添加bbox信息(缩放,poly->bbox)"""
  97. self.__fix_axis()
  98. """删除置信度特别低的模型数据(<0.05),提高质量"""
  99. self.__fix_by_remove_low_confidence()
  100. """删除高iou(>0.9)数据中置信度较低的那个"""
  101. self.__fix_by_remove_high_iou_and_low_confidence()
  102. self.__fix_footnote()
  103. def _bbox_distance(self, bbox1, bbox2):
  104. left, right, bottom, top = bbox_relative_pos(bbox1, bbox2)
  105. flags = [left, right, bottom, top]
  106. count = sum([1 if v else 0 for v in flags])
  107. if count > 1:
  108. return float('inf')
  109. if left or right:
  110. l1 = bbox1[3] - bbox1[1]
  111. l2 = bbox2[3] - bbox2[1]
  112. else:
  113. l1 = bbox1[2] - bbox1[0]
  114. l2 = bbox2[2] - bbox2[0]
  115. if l2 > l1 and (l2 - l1) / l1 > 0.3:
  116. return float('inf')
  117. return bbox_distance(bbox1, bbox2)
  118. def __fix_footnote(self):
  119. # 3: figure, 5: table, 7: footnote
  120. for model_page_info in self.__model_list:
  121. footnotes = []
  122. figures = []
  123. tables = []
  124. for obj in model_page_info['layout_dets']:
  125. if obj['category_id'] == 7:
  126. footnotes.append(obj)
  127. elif obj['category_id'] == 3:
  128. figures.append(obj)
  129. elif obj['category_id'] == 5:
  130. tables.append(obj)
  131. if len(footnotes) * len(figures) == 0:
  132. continue
  133. dis_figure_footnote = {}
  134. dis_table_footnote = {}
  135. for i in range(len(footnotes)):
  136. for j in range(len(figures)):
  137. pos_flag_count = sum(
  138. list(
  139. map(
  140. lambda x: 1 if x else 0,
  141. bbox_relative_pos(
  142. footnotes[i]['bbox'], figures[j]['bbox']
  143. ),
  144. )
  145. )
  146. )
  147. if pos_flag_count > 1:
  148. continue
  149. dis_figure_footnote[i] = min(
  150. self._bbox_distance(figures[j]['bbox'], footnotes[i]['bbox']),
  151. dis_figure_footnote.get(i, float('inf')),
  152. )
  153. for i in range(len(footnotes)):
  154. for j in range(len(tables)):
  155. pos_flag_count = sum(
  156. list(
  157. map(
  158. lambda x: 1 if x else 0,
  159. bbox_relative_pos(
  160. footnotes[i]['bbox'], tables[j]['bbox']
  161. ),
  162. )
  163. )
  164. )
  165. if pos_flag_count > 1:
  166. continue
  167. dis_table_footnote[i] = min(
  168. self._bbox_distance(tables[j]['bbox'], footnotes[i]['bbox']),
  169. dis_table_footnote.get(i, float('inf')),
  170. )
  171. for i in range(len(footnotes)):
  172. if i not in dis_figure_footnote:
  173. continue
  174. if dis_table_footnote.get(i, float('inf')) > dis_figure_footnote[i]:
  175. footnotes[i]['category_id'] = CategoryId.ImageFootnote
  176. def __reduct_overlap(self, bboxes):
  177. N = len(bboxes)
  178. keep = [True] * N
  179. for i in range(N):
  180. for j in range(N):
  181. if i == j:
  182. continue
  183. if _is_in(bboxes[i]['bbox'], bboxes[j]['bbox']):
  184. keep[i] = False
  185. return [bboxes[i] for i in range(N) if keep[i]]
  186. def __tie_up_category_by_distance_v2(
  187. self,
  188. page_no: int,
  189. subject_category_id: int,
  190. object_category_id: int,
  191. priority_pos: PosRelationEnum,
  192. ):
  193. """_summary_
  194. Args:
  195. page_no (int): _description_
  196. subject_category_id (int): _description_
  197. object_category_id (int): _description_
  198. priority_pos (PosRelationEnum): _description_
  199. Returns:
  200. _type_: _description_
  201. """
  202. AXIS_MULPLICITY = 0.5
  203. subjects = self.__reduct_overlap(
  204. list(
  205. map(
  206. lambda x: {'bbox': x['bbox'], 'score': x['score']},
  207. filter(
  208. lambda x: x['category_id'] == subject_category_id,
  209. self.__model_list[page_no]['layout_dets'],
  210. ),
  211. )
  212. )
  213. )
  214. objects = self.__reduct_overlap(
  215. list(
  216. map(
  217. lambda x: {'bbox': x['bbox'], 'score': x['score']},
  218. filter(
  219. lambda x: x['category_id'] == object_category_id,
  220. self.__model_list[page_no]['layout_dets'],
  221. ),
  222. )
  223. )
  224. )
  225. M = len(objects)
  226. subjects.sort(key=lambda x: x['bbox'][0] ** 2 + x['bbox'][1] ** 2)
  227. objects.sort(key=lambda x: x['bbox'][0] ** 2 + x['bbox'][1] ** 2)
  228. sub_obj_map_h = {i: [] for i in range(len(subjects))}
  229. dis_by_directions = {
  230. 'top': [[-1, float('inf')]] * M,
  231. 'bottom': [[-1, float('inf')]] * M,
  232. 'left': [[-1, float('inf')]] * M,
  233. 'right': [[-1, float('inf')]] * M,
  234. }
  235. for i, obj in enumerate(objects):
  236. l_x_axis, l_y_axis = (
  237. obj['bbox'][2] - obj['bbox'][0],
  238. obj['bbox'][3] - obj['bbox'][1],
  239. )
  240. axis_unit = min(l_x_axis, l_y_axis)
  241. for j, sub in enumerate(subjects):
  242. bbox1, bbox2, _ = _remove_overlap_between_bbox(
  243. objects[i]['bbox'], subjects[j]['bbox']
  244. )
  245. left, right, bottom, top = bbox_relative_pos(bbox1, bbox2)
  246. flags = [left, right, bottom, top]
  247. if sum([1 if v else 0 for v in flags]) > 1:
  248. continue
  249. if left:
  250. if dis_by_directions['left'][i][1] > bbox_distance(
  251. obj['bbox'], sub['bbox']
  252. ):
  253. dis_by_directions['left'][i] = [
  254. j,
  255. bbox_distance(obj['bbox'], sub['bbox']),
  256. ]
  257. if right:
  258. if dis_by_directions['right'][i][1] > bbox_distance(
  259. obj['bbox'], sub['bbox']
  260. ):
  261. dis_by_directions['right'][i] = [
  262. j,
  263. bbox_distance(obj['bbox'], sub['bbox']),
  264. ]
  265. if bottom:
  266. if dis_by_directions['bottom'][i][1] > bbox_distance(
  267. obj['bbox'], sub['bbox']
  268. ):
  269. dis_by_directions['bottom'][i] = [
  270. j,
  271. bbox_distance(obj['bbox'], sub['bbox']),
  272. ]
  273. if top:
  274. if dis_by_directions['top'][i][1] > bbox_distance(
  275. obj['bbox'], sub['bbox']
  276. ):
  277. dis_by_directions['top'][i] = [
  278. j,
  279. bbox_distance(obj['bbox'], sub['bbox']),
  280. ]
  281. if (
  282. dis_by_directions['top'][i][1] != float('inf')
  283. and dis_by_directions['bottom'][i][1] != float('inf')
  284. and priority_pos in (PosRelationEnum.BOTTOM, PosRelationEnum.UP)
  285. ):
  286. RATIO = 3
  287. if (
  288. abs(
  289. dis_by_directions['top'][i][1]
  290. - dis_by_directions['bottom'][i][1]
  291. )
  292. < RATIO * axis_unit
  293. ):
  294. if priority_pos == PosRelationEnum.BOTTOM:
  295. sub_obj_map_h[dis_by_directions['bottom'][i][0]].append(i)
  296. else:
  297. sub_obj_map_h[dis_by_directions['top'][i][0]].append(i)
  298. continue
  299. if dis_by_directions['left'][i][1] != float('inf') or dis_by_directions[
  300. 'right'
  301. ][i][1] != float('inf'):
  302. if dis_by_directions['left'][i][1] != float(
  303. 'inf'
  304. ) and dis_by_directions['right'][i][1] != float('inf'):
  305. if AXIS_MULPLICITY * axis_unit >= abs(
  306. dis_by_directions['left'][i][1]
  307. - dis_by_directions['right'][i][1]
  308. ):
  309. left_sub_bbox = subjects[dis_by_directions['left'][i][0]][
  310. 'bbox'
  311. ]
  312. right_sub_bbox = subjects[dis_by_directions['right'][i][0]][
  313. 'bbox'
  314. ]
  315. left_sub_bbox_y_axis = left_sub_bbox[3] - left_sub_bbox[1]
  316. right_sub_bbox_y_axis = right_sub_bbox[3] - right_sub_bbox[1]
  317. if (
  318. abs(left_sub_bbox_y_axis - l_y_axis)
  319. + dis_by_directions['left'][i][0]
  320. > abs(right_sub_bbox_y_axis - l_y_axis)
  321. + dis_by_directions['right'][i][0]
  322. ):
  323. left_or_right = dis_by_directions['right'][i]
  324. else:
  325. left_or_right = dis_by_directions['left'][i]
  326. else:
  327. left_or_right = dis_by_directions['left'][i]
  328. if left_or_right[1] > dis_by_directions['right'][i][1]:
  329. left_or_right = dis_by_directions['right'][i]
  330. else:
  331. left_or_right = dis_by_directions['left'][i]
  332. if left_or_right[1] == float('inf'):
  333. left_or_right = dis_by_directions['right'][i]
  334. else:
  335. left_or_right = [-1, float('inf')]
  336. if dis_by_directions['top'][i][1] != float('inf') or dis_by_directions[
  337. 'bottom'
  338. ][i][1] != float('inf'):
  339. if dis_by_directions['top'][i][1] != float('inf') and dis_by_directions[
  340. 'bottom'
  341. ][i][1] != float('inf'):
  342. if AXIS_MULPLICITY * axis_unit >= abs(
  343. dis_by_directions['top'][i][1]
  344. - dis_by_directions['bottom'][i][1]
  345. ):
  346. top_bottom = subjects[dis_by_directions['bottom'][i][0]]['bbox']
  347. bottom_top = subjects[dis_by_directions['top'][i][0]]['bbox']
  348. top_bottom_x_axis = top_bottom[2] - top_bottom[0]
  349. bottom_top_x_axis = bottom_top[2] - bottom_top[0]
  350. if (
  351. abs(top_bottom_x_axis - l_x_axis)
  352. + dis_by_directions['bottom'][i][1]
  353. > abs(bottom_top_x_axis - l_x_axis)
  354. + dis_by_directions['top'][i][1]
  355. ):
  356. top_or_bottom = dis_by_directions['top'][i]
  357. else:
  358. top_or_bottom = dis_by_directions['bottom'][i]
  359. else:
  360. top_or_bottom = dis_by_directions['top'][i]
  361. if top_or_bottom[1] > dis_by_directions['bottom'][i][1]:
  362. top_or_bottom = dis_by_directions['bottom'][i]
  363. else:
  364. top_or_bottom = dis_by_directions['top'][i]
  365. if top_or_bottom[1] == float('inf'):
  366. top_or_bottom = dis_by_directions['bottom'][i]
  367. else:
  368. top_or_bottom = [-1, float('inf')]
  369. if left_or_right[1] != float('inf') or top_or_bottom[1] != float('inf'):
  370. if left_or_right[1] != float('inf') and top_or_bottom[1] != float(
  371. 'inf'
  372. ):
  373. if AXIS_MULPLICITY * axis_unit >= abs(
  374. left_or_right[1] - top_or_bottom[1]
  375. ):
  376. y_axis_bbox = subjects[left_or_right[0]]['bbox']
  377. x_axis_bbox = subjects[top_or_bottom[0]]['bbox']
  378. if (
  379. abs((x_axis_bbox[2] - x_axis_bbox[0]) - l_x_axis) / l_x_axis
  380. > abs((y_axis_bbox[3] - y_axis_bbox[1]) - l_y_axis)
  381. / l_y_axis
  382. ):
  383. sub_obj_map_h[left_or_right[0]].append(i)
  384. else:
  385. sub_obj_map_h[top_or_bottom[0]].append(i)
  386. else:
  387. if left_or_right[1] > top_or_bottom[1]:
  388. sub_obj_map_h[top_or_bottom[0]].append(i)
  389. else:
  390. sub_obj_map_h[left_or_right[0]].append(i)
  391. else:
  392. if left_or_right[1] != float('inf'):
  393. sub_obj_map_h[left_or_right[0]].append(i)
  394. else:
  395. sub_obj_map_h[top_or_bottom[0]].append(i)
  396. ret = []
  397. for i in sub_obj_map_h.keys():
  398. ret.append(
  399. {
  400. 'sub_bbox': {
  401. 'bbox': subjects[i]['bbox'],
  402. 'score': subjects[i]['score'],
  403. },
  404. 'obj_bboxes': [
  405. {'score': objects[j]['score'], 'bbox': objects[j]['bbox']}
  406. for j in sub_obj_map_h[i]
  407. ],
  408. 'sub_idx': i,
  409. }
  410. )
  411. return ret
  412. def __tie_up_category_by_distance_v3(
  413. self,
  414. page_no: int,
  415. subject_category_id: int,
  416. object_category_id: int,
  417. priority_pos: PosRelationEnum,
  418. ):
  419. subjects = self.__reduct_overlap(
  420. list(
  421. map(
  422. lambda x: {'bbox': x['bbox'], 'score': x['score']},
  423. filter(
  424. lambda x: x['category_id'] == subject_category_id,
  425. self.__model_list[page_no]['layout_dets'],
  426. ),
  427. )
  428. )
  429. )
  430. objects = self.__reduct_overlap(
  431. list(
  432. map(
  433. lambda x: {'bbox': x['bbox'], 'score': x['score']},
  434. filter(
  435. lambda x: x['category_id'] == object_category_id,
  436. self.__model_list[page_no]['layout_dets'],
  437. ),
  438. )
  439. )
  440. )
  441. ret = []
  442. N, M = len(subjects), len(objects)
  443. subjects.sort(key=lambda x: x['bbox'][0] ** 2 + x['bbox'][1] ** 2)
  444. objects.sort(key=lambda x: x['bbox'][0] ** 2 + x['bbox'][1] ** 2)
  445. OBJ_IDX_OFFSET = 10000
  446. SUB_BIT_KIND, OBJ_BIT_KIND = 0, 1
  447. all_boxes_with_idx = [(i, SUB_BIT_KIND, sub['bbox'][0], sub['bbox'][1]) for i, sub in enumerate(subjects)] + [(i + OBJ_IDX_OFFSET , OBJ_BIT_KIND, obj['bbox'][0], obj['bbox'][1]) for i, obj in enumerate(objects)]
  448. seen_idx = set()
  449. seen_sub_idx = set()
  450. while N > len(seen_sub_idx):
  451. candidates = []
  452. for idx, kind, x0, y0 in all_boxes_with_idx:
  453. if idx in seen_idx:
  454. continue
  455. candidates.append((idx, kind, x0, y0))
  456. if len(candidates) == 0:
  457. break
  458. left_x = min([v[2] for v in candidates])
  459. top_y = min([v[3] for v in candidates])
  460. candidates.sort(key=lambda x: (x[2]-left_x) ** 2 + (x[3] - top_y) ** 2)
  461. fst_idx, fst_kind, left_x, top_y = candidates[0]
  462. candidates.sort(key=lambda x: (x[2] - left_x) ** 2 + (x[3] - top_y)**2)
  463. nxt = None
  464. for i in range(1, len(candidates)):
  465. if candidates[i][1] ^ fst_kind == 1:
  466. nxt = candidates[i]
  467. break
  468. if nxt is None:
  469. break
  470. if fst_kind == SUB_BIT_KIND:
  471. sub_idx, obj_idx = fst_idx, nxt[0] - OBJ_IDX_OFFSET
  472. else:
  473. sub_idx, obj_idx = nxt[0], fst_idx - OBJ_IDX_OFFSET
  474. pair_dis = bbox_distance(subjects[sub_idx]['bbox'], objects[obj_idx]['bbox'])
  475. nearest_dis = float('inf')
  476. for i in range(N):
  477. if i in seen_idx or i == sub_idx:continue
  478. nearest_dis = min(nearest_dis, bbox_distance(subjects[i]['bbox'], objects[obj_idx]['bbox']))
  479. if pair_dis >= 3*nearest_dis:
  480. seen_idx.add(sub_idx)
  481. continue
  482. seen_idx.add(sub_idx)
  483. seen_idx.add(obj_idx + OBJ_IDX_OFFSET)
  484. seen_sub_idx.add(sub_idx)
  485. ret.append(
  486. {
  487. 'sub_bbox': {
  488. 'bbox': subjects[sub_idx]['bbox'],
  489. 'score': subjects[sub_idx]['score'],
  490. },
  491. 'obj_bboxes': [
  492. {'score': objects[obj_idx]['score'], 'bbox': objects[obj_idx]['bbox']}
  493. ],
  494. 'sub_idx': sub_idx,
  495. }
  496. )
  497. for i in range(len(objects)):
  498. j = i + OBJ_IDX_OFFSET
  499. if j in seen_idx:
  500. continue
  501. seen_idx.add(j)
  502. nearest_dis, nearest_sub_idx = float('inf'), -1
  503. for k in range(len(subjects)):
  504. dis = bbox_distance(objects[i]['bbox'], subjects[k]['bbox'])
  505. if dis < nearest_dis:
  506. nearest_dis = dis
  507. nearest_sub_idx = k
  508. for k in range(len(subjects)):
  509. if k != nearest_sub_idx: continue
  510. if k in seen_sub_idx:
  511. for kk in range(len(ret)):
  512. if ret[kk]['sub_idx'] == k:
  513. ret[kk]['obj_bboxes'].append({'score': objects[i]['score'], 'bbox': objects[i]['bbox']})
  514. break
  515. else:
  516. ret.append(
  517. {
  518. 'sub_bbox': {
  519. 'bbox': subjects[k]['bbox'],
  520. 'score': subjects[k]['score'],
  521. },
  522. 'obj_bboxes': [
  523. {'score': objects[i]['score'], 'bbox': objects[i]['bbox']}
  524. ],
  525. 'sub_idx': k,
  526. }
  527. )
  528. seen_sub_idx.add(k)
  529. seen_idx.add(k)
  530. for i in range(len(subjects)):
  531. if i in seen_sub_idx:
  532. continue
  533. ret.append(
  534. {
  535. 'sub_bbox': {
  536. 'bbox': subjects[i]['bbox'],
  537. 'score': subjects[i]['score'],
  538. },
  539. 'obj_bboxes': [],
  540. 'sub_idx': i,
  541. }
  542. )
  543. return ret
  544. def get_imgs_v2(self, page_no: int):
  545. with_captions = self.__tie_up_category_by_distance_v3(
  546. page_no, 3, 4, PosRelationEnum.BOTTOM
  547. )
  548. with_footnotes = self.__tie_up_category_by_distance_v3(
  549. page_no, 3, CategoryId.ImageFootnote, PosRelationEnum.ALL
  550. )
  551. ret = []
  552. for v in with_captions:
  553. record = {
  554. 'image_body': v['sub_bbox'],
  555. 'image_caption_list': v['obj_bboxes'],
  556. }
  557. filter_idx = v['sub_idx']
  558. d = next(filter(lambda x: x['sub_idx'] == filter_idx, with_footnotes))
  559. record['image_footnote_list'] = d['obj_bboxes']
  560. ret.append(record)
  561. return ret
  562. def get_tables_v2(self, page_no: int) -> list:
  563. with_captions = self.__tie_up_category_by_distance_v3(
  564. page_no, 5, 6, PosRelationEnum.UP
  565. )
  566. with_footnotes = self.__tie_up_category_by_distance_v3(
  567. page_no, 5, 7, PosRelationEnum.ALL
  568. )
  569. ret = []
  570. for v in with_captions:
  571. record = {
  572. 'table_body': v['sub_bbox'],
  573. 'table_caption_list': v['obj_bboxes'],
  574. }
  575. filter_idx = v['sub_idx']
  576. d = next(filter(lambda x: x['sub_idx'] == filter_idx, with_footnotes))
  577. record['table_footnote_list'] = d['obj_bboxes']
  578. ret.append(record)
  579. return ret
  580. def get_imgs(self, page_no: int):
  581. return self.get_imgs_v2(page_no)
  582. def get_tables(
  583. self, page_no: int
  584. ) -> list: # 3个坐标, caption, table主体,table-note
  585. return self.get_tables_v2(page_no)
  586. def get_equations(self, page_no: int) -> list: # 有坐标,也有字
  587. inline_equations = self.__get_blocks_by_type(
  588. ModelBlockTypeEnum.EMBEDDING.value, page_no, ['latex']
  589. )
  590. interline_equations = self.__get_blocks_by_type(
  591. ModelBlockTypeEnum.ISOLATED.value, page_no, ['latex']
  592. )
  593. interline_equations_blocks = self.__get_blocks_by_type(
  594. ModelBlockTypeEnum.ISOLATE_FORMULA.value, page_no
  595. )
  596. return inline_equations, interline_equations, interline_equations_blocks
  597. def get_discarded(self, page_no: int) -> list: # 自研模型,只有坐标
  598. blocks = self.__get_blocks_by_type(ModelBlockTypeEnum.ABANDON.value, page_no)
  599. return blocks
  600. def get_text_blocks(self, page_no: int) -> list: # 自研模型搞的,只有坐标,没有字
  601. blocks = self.__get_blocks_by_type(ModelBlockTypeEnum.PLAIN_TEXT.value, page_no)
  602. return blocks
  603. def get_title_blocks(self, page_no: int) -> list: # 自研模型,只有坐标,没字
  604. blocks = self.__get_blocks_by_type(ModelBlockTypeEnum.TITLE.value, page_no)
  605. return blocks
  606. def get_ocr_text(self, page_no: int) -> list: # paddle 搞的,有字也有坐标
  607. text_spans = []
  608. model_page_info = self.__model_list[page_no]
  609. layout_dets = model_page_info['layout_dets']
  610. for layout_det in layout_dets:
  611. if layout_det['category_id'] == '15':
  612. span = {
  613. 'bbox': layout_det['bbox'],
  614. 'content': layout_det['text'],
  615. }
  616. text_spans.append(span)
  617. return text_spans
  618. def get_all_spans(self, page_no: int) -> list:
  619. def remove_duplicate_spans(spans):
  620. new_spans = []
  621. for span in spans:
  622. if not any(span == existing_span for existing_span in new_spans):
  623. new_spans.append(span)
  624. return new_spans
  625. all_spans = []
  626. model_page_info = self.__model_list[page_no]
  627. layout_dets = model_page_info['layout_dets']
  628. allow_category_id_list = [3, 5, 13, 14, 15]
  629. """当成span拼接的"""
  630. # 3: 'image', # 图片
  631. # 5: 'table', # 表格
  632. # 13: 'inline_equation', # 行内公式
  633. # 14: 'interline_equation', # 行间公式
  634. # 15: 'text', # ocr识别文本
  635. for layout_det in layout_dets:
  636. category_id = layout_det['category_id']
  637. if category_id in allow_category_id_list:
  638. span = {'bbox': layout_det['bbox'], 'score': layout_det['score']}
  639. if category_id == 3:
  640. span['type'] = ContentType.Image
  641. elif category_id == 5:
  642. # 获取table模型结果
  643. latex = layout_det.get('latex', None)
  644. html = layout_det.get('html', None)
  645. if latex:
  646. span['latex'] = latex
  647. elif html:
  648. span['html'] = html
  649. span['type'] = ContentType.Table
  650. elif category_id == 13:
  651. span['content'] = layout_det['latex']
  652. span['type'] = ContentType.InlineEquation
  653. elif category_id == 14:
  654. span['content'] = layout_det['latex']
  655. span['type'] = ContentType.InterlineEquation
  656. elif category_id == 15:
  657. span['content'] = layout_det['text']
  658. span['type'] = ContentType.Text
  659. all_spans.append(span)
  660. return remove_duplicate_spans(all_spans)
  661. def get_page_size(self, page_no: int): # 获取页面宽高
  662. # 获取当前页的page对象
  663. page = self.__docs.get_page(page_no).get_page_info()
  664. # 获取当前页的宽高
  665. page_w = page.w
  666. page_h = page.h
  667. return page_w, page_h
  668. def __get_blocks_by_type(
  669. self, type: int, page_no: int, extra_col: list[str] = []
  670. ) -> list:
  671. blocks = []
  672. for page_dict in self.__model_list:
  673. layout_dets = page_dict.get('layout_dets', [])
  674. page_info = page_dict.get('page_info', {})
  675. page_number = page_info.get('page_no', -1)
  676. if page_no != page_number:
  677. continue
  678. for item in layout_dets:
  679. category_id = item.get('category_id', -1)
  680. bbox = item.get('bbox', None)
  681. if category_id == type:
  682. block = {
  683. 'bbox': bbox,
  684. 'score': item.get('score'),
  685. }
  686. for col in extra_col:
  687. block[col] = item.get(col, None)
  688. blocks.append(block)
  689. return blocks
  690. def get_model_list(self, page_no):
  691. return self.__model_list[page_no]