magic_model.py 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046
  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, _is_part_overlap, bbox_distance,
  6. bbox_relative_pos, box_area, calculate_iou,
  7. calculate_overlap_area_in_bbox1_area_ratio,
  8. get_overlap_area)
  9. from magic_pdf.libs.coordinate_transform import get_scale_ratio
  10. from magic_pdf.libs.local_math import float_gt
  11. from magic_pdf.pre_proc.remove_bbox_overlap import _remove_overlap_between_bbox
  12. CAPATION_OVERLAP_AREA_RATIO = 0.6
  13. MERGE_BOX_OVERLAP_AREA_RATIO = 1.1
  14. class PosRelationEnum(enum.Enum):
  15. LEFT = 'left'
  16. RIGHT = 'right'
  17. UP = 'up'
  18. BOTTOM = 'bottom'
  19. ALL = 'all'
  20. class MagicModel:
  21. """每个函数没有得到元素的时候返回空list."""
  22. def __fix_axis(self):
  23. for model_page_info in self.__model_list:
  24. need_remove_list = []
  25. page_no = model_page_info['page_info']['page_no']
  26. horizontal_scale_ratio, vertical_scale_ratio = get_scale_ratio(
  27. model_page_info, self.__docs.get_page(page_no)
  28. )
  29. layout_dets = model_page_info['layout_dets']
  30. for layout_det in layout_dets:
  31. if layout_det.get('bbox') is not None:
  32. # 兼容直接输出bbox的模型数据,如paddle
  33. x0, y0, x1, y1 = layout_det['bbox']
  34. else:
  35. # 兼容直接输出poly的模型数据,如xxx
  36. x0, y0, _, _, x1, y1, _, _ = layout_det['poly']
  37. bbox = [
  38. int(x0 / horizontal_scale_ratio),
  39. int(y0 / vertical_scale_ratio),
  40. int(x1 / horizontal_scale_ratio),
  41. int(y1 / vertical_scale_ratio),
  42. ]
  43. layout_det['bbox'] = bbox
  44. # 删除高度或者宽度小于等于0的spans
  45. if bbox[2] - bbox[0] <= 0 or bbox[3] - bbox[1] <= 0:
  46. need_remove_list.append(layout_det)
  47. for need_remove in need_remove_list:
  48. layout_dets.remove(need_remove)
  49. def __fix_by_remove_low_confidence(self):
  50. for model_page_info in self.__model_list:
  51. need_remove_list = []
  52. layout_dets = model_page_info['layout_dets']
  53. for layout_det in layout_dets:
  54. if layout_det['score'] <= 0.05:
  55. need_remove_list.append(layout_det)
  56. else:
  57. continue
  58. for need_remove in need_remove_list:
  59. layout_dets.remove(need_remove)
  60. def __fix_by_remove_high_iou_and_low_confidence(self):
  61. for model_page_info in self.__model_list:
  62. need_remove_list = []
  63. layout_dets = model_page_info['layout_dets']
  64. for layout_det1 in layout_dets:
  65. for layout_det2 in layout_dets:
  66. if layout_det1 == layout_det2:
  67. continue
  68. if layout_det1['category_id'] in [
  69. 0,
  70. 1,
  71. 2,
  72. 3,
  73. 4,
  74. 5,
  75. 6,
  76. 7,
  77. 8,
  78. 9,
  79. ] and layout_det2['category_id'] in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]:
  80. if (
  81. calculate_iou(layout_det1['bbox'], layout_det2['bbox'])
  82. > 0.9
  83. ):
  84. if layout_det1['score'] < layout_det2['score']:
  85. layout_det_need_remove = layout_det1
  86. else:
  87. layout_det_need_remove = layout_det2
  88. if layout_det_need_remove not in need_remove_list:
  89. need_remove_list.append(layout_det_need_remove)
  90. else:
  91. continue
  92. else:
  93. continue
  94. for need_remove in need_remove_list:
  95. layout_dets.remove(need_remove)
  96. def __init__(self, model_list: list, docs: Dataset):
  97. self.__model_list = model_list
  98. self.__docs = docs
  99. """为所有模型数据添加bbox信息(缩放,poly->bbox)"""
  100. self.__fix_axis()
  101. """删除置信度特别低的模型数据(<0.05),提高质量"""
  102. self.__fix_by_remove_low_confidence()
  103. """删除高iou(>0.9)数据中置信度较低的那个"""
  104. self.__fix_by_remove_high_iou_and_low_confidence()
  105. self.__fix_footnote()
  106. def _bbox_distance(self, bbox1, bbox2):
  107. left, right, bottom, top = bbox_relative_pos(bbox1, bbox2)
  108. flags = [left, right, bottom, top]
  109. count = sum([1 if v else 0 for v in flags])
  110. if count > 1:
  111. return float('inf')
  112. if left or right:
  113. l1 = bbox1[3] - bbox1[1]
  114. l2 = bbox2[3] - bbox2[1]
  115. else:
  116. l1 = bbox1[2] - bbox1[0]
  117. l2 = bbox2[2] - bbox2[0]
  118. if l2 > l1 and (l2 - l1) / l1 > 0.3:
  119. return float('inf')
  120. return bbox_distance(bbox1, bbox2)
  121. def __fix_footnote(self):
  122. # 3: figure, 5: table, 7: footnote
  123. for model_page_info in self.__model_list:
  124. footnotes = []
  125. figures = []
  126. tables = []
  127. for obj in model_page_info['layout_dets']:
  128. if obj['category_id'] == 7:
  129. footnotes.append(obj)
  130. elif obj['category_id'] == 3:
  131. figures.append(obj)
  132. elif obj['category_id'] == 5:
  133. tables.append(obj)
  134. if len(footnotes) * len(figures) == 0:
  135. continue
  136. dis_figure_footnote = {}
  137. dis_table_footnote = {}
  138. for i in range(len(footnotes)):
  139. for j in range(len(figures)):
  140. pos_flag_count = sum(
  141. list(
  142. map(
  143. lambda x: 1 if x else 0,
  144. bbox_relative_pos(
  145. footnotes[i]['bbox'], figures[j]['bbox']
  146. ),
  147. )
  148. )
  149. )
  150. if pos_flag_count > 1:
  151. continue
  152. dis_figure_footnote[i] = min(
  153. self._bbox_distance(figures[j]['bbox'], footnotes[i]['bbox']),
  154. dis_figure_footnote.get(i, float('inf')),
  155. )
  156. for i in range(len(footnotes)):
  157. for j in range(len(tables)):
  158. pos_flag_count = sum(
  159. list(
  160. map(
  161. lambda x: 1 if x else 0,
  162. bbox_relative_pos(
  163. footnotes[i]['bbox'], tables[j]['bbox']
  164. ),
  165. )
  166. )
  167. )
  168. if pos_flag_count > 1:
  169. continue
  170. dis_table_footnote[i] = min(
  171. self._bbox_distance(tables[j]['bbox'], footnotes[i]['bbox']),
  172. dis_table_footnote.get(i, float('inf')),
  173. )
  174. for i in range(len(footnotes)):
  175. if i not in dis_figure_footnote:
  176. continue
  177. if dis_table_footnote.get(i, float('inf')) > dis_figure_footnote[i]:
  178. footnotes[i]['category_id'] = CategoryId.ImageFootnote
  179. def __reduct_overlap(self, bboxes):
  180. N = len(bboxes)
  181. keep = [True] * N
  182. for i in range(N):
  183. for j in range(N):
  184. if i == j:
  185. continue
  186. if _is_in(bboxes[i]['bbox'], bboxes[j]['bbox']):
  187. keep[i] = False
  188. return [bboxes[i] for i in range(N) if keep[i]]
  189. def __tie_up_category_by_distance(
  190. self, page_no, subject_category_id, object_category_id
  191. ):
  192. """假定每个 subject 最多有一个 object (可以有多个相邻的 object 合并为单个 object),每个 object
  193. 只能属于一个 subject."""
  194. ret = []
  195. MAX_DIS_OF_POINT = 10**9 + 7
  196. """
  197. subject 和 object 的 bbox 会合并成一个大的 bbox (named: merged bbox)。
  198. 筛选出所有和 merged bbox 有 overlap 且 overlap 面积大于 object 的面积的 subjects。
  199. 再求出筛选出的 subjects 和 object 的最短距离
  200. """
  201. def search_overlap_between_boxes(subject_idx, object_idx):
  202. idxes = [subject_idx, object_idx]
  203. x0s = [all_bboxes[idx]['bbox'][0] for idx in idxes]
  204. y0s = [all_bboxes[idx]['bbox'][1] for idx in idxes]
  205. x1s = [all_bboxes[idx]['bbox'][2] for idx in idxes]
  206. y1s = [all_bboxes[idx]['bbox'][3] for idx in idxes]
  207. merged_bbox = [
  208. min(x0s),
  209. min(y0s),
  210. max(x1s),
  211. max(y1s),
  212. ]
  213. ratio = 0
  214. other_objects = list(
  215. map(
  216. lambda x: {'bbox': x['bbox'], 'score': x['score']},
  217. filter(
  218. lambda x: x['category_id']
  219. not in (object_category_id, subject_category_id),
  220. self.__model_list[page_no]['layout_dets'],
  221. ),
  222. )
  223. )
  224. for other_object in other_objects:
  225. ratio = max(
  226. ratio,
  227. get_overlap_area(merged_bbox, other_object['bbox'])
  228. * 1.0
  229. / box_area(all_bboxes[object_idx]['bbox']),
  230. )
  231. if ratio >= MERGE_BOX_OVERLAP_AREA_RATIO:
  232. break
  233. return ratio
  234. def may_find_other_nearest_bbox(subject_idx, object_idx):
  235. ret = float('inf')
  236. x0 = min(
  237. all_bboxes[subject_idx]['bbox'][0], all_bboxes[object_idx]['bbox'][0]
  238. )
  239. y0 = min(
  240. all_bboxes[subject_idx]['bbox'][1], all_bboxes[object_idx]['bbox'][1]
  241. )
  242. x1 = max(
  243. all_bboxes[subject_idx]['bbox'][2], all_bboxes[object_idx]['bbox'][2]
  244. )
  245. y1 = max(
  246. all_bboxes[subject_idx]['bbox'][3], all_bboxes[object_idx]['bbox'][3]
  247. )
  248. object_area = abs(
  249. all_bboxes[object_idx]['bbox'][2] - all_bboxes[object_idx]['bbox'][0]
  250. ) * abs(
  251. all_bboxes[object_idx]['bbox'][3] - all_bboxes[object_idx]['bbox'][1]
  252. )
  253. for i in range(len(all_bboxes)):
  254. if (
  255. i == subject_idx
  256. or all_bboxes[i]['category_id'] != subject_category_id
  257. ):
  258. continue
  259. if _is_part_overlap([x0, y0, x1, y1], all_bboxes[i]['bbox']) or _is_in(
  260. all_bboxes[i]['bbox'], [x0, y0, x1, y1]
  261. ):
  262. i_area = abs(
  263. all_bboxes[i]['bbox'][2] - all_bboxes[i]['bbox'][0]
  264. ) * abs(all_bboxes[i]['bbox'][3] - all_bboxes[i]['bbox'][1])
  265. if i_area >= object_area:
  266. ret = min(float('inf'), dis[i][object_idx])
  267. return ret
  268. def expand_bbbox(idxes):
  269. x0s = [all_bboxes[idx]['bbox'][0] for idx in idxes]
  270. y0s = [all_bboxes[idx]['bbox'][1] for idx in idxes]
  271. x1s = [all_bboxes[idx]['bbox'][2] for idx in idxes]
  272. y1s = [all_bboxes[idx]['bbox'][3] for idx in idxes]
  273. return min(x0s), min(y0s), max(x1s), max(y1s)
  274. subjects = self.__reduct_overlap(
  275. list(
  276. map(
  277. lambda x: {'bbox': x['bbox'], 'score': x['score']},
  278. filter(
  279. lambda x: x['category_id'] == subject_category_id,
  280. self.__model_list[page_no]['layout_dets'],
  281. ),
  282. )
  283. )
  284. )
  285. objects = self.__reduct_overlap(
  286. list(
  287. map(
  288. lambda x: {'bbox': x['bbox'], 'score': x['score']},
  289. filter(
  290. lambda x: x['category_id'] == object_category_id,
  291. self.__model_list[page_no]['layout_dets'],
  292. ),
  293. )
  294. )
  295. )
  296. subject_object_relation_map = {}
  297. subjects.sort(
  298. key=lambda x: x['bbox'][0] ** 2 + x['bbox'][1] ** 2
  299. ) # get the distance !
  300. all_bboxes = []
  301. for v in subjects:
  302. all_bboxes.append(
  303. {
  304. 'category_id': subject_category_id,
  305. 'bbox': v['bbox'],
  306. 'score': v['score'],
  307. }
  308. )
  309. for v in objects:
  310. all_bboxes.append(
  311. {
  312. 'category_id': object_category_id,
  313. 'bbox': v['bbox'],
  314. 'score': v['score'],
  315. }
  316. )
  317. N = len(all_bboxes)
  318. dis = [[MAX_DIS_OF_POINT] * N for _ in range(N)]
  319. for i in range(N):
  320. for j in range(i):
  321. if (
  322. all_bboxes[i]['category_id'] == subject_category_id
  323. and all_bboxes[j]['category_id'] == subject_category_id
  324. ):
  325. continue
  326. subject_idx, object_idx = i, j
  327. if all_bboxes[j]['category_id'] == subject_category_id:
  328. subject_idx, object_idx = j, i
  329. if (
  330. search_overlap_between_boxes(subject_idx, object_idx)
  331. >= MERGE_BOX_OVERLAP_AREA_RATIO
  332. ):
  333. dis[i][j] = float('inf')
  334. dis[j][i] = dis[i][j]
  335. continue
  336. dis[i][j] = self._bbox_distance(
  337. all_bboxes[subject_idx]['bbox'], all_bboxes[object_idx]['bbox']
  338. )
  339. dis[j][i] = dis[i][j]
  340. used = set()
  341. for i in range(N):
  342. # 求第 i 个 subject 所关联的 object
  343. if all_bboxes[i]['category_id'] != subject_category_id:
  344. continue
  345. seen = set()
  346. candidates = []
  347. arr = []
  348. for j in range(N):
  349. pos_flag_count = sum(
  350. list(
  351. map(
  352. lambda x: 1 if x else 0,
  353. bbox_relative_pos(
  354. all_bboxes[i]['bbox'], all_bboxes[j]['bbox']
  355. ),
  356. )
  357. )
  358. )
  359. if pos_flag_count > 1:
  360. continue
  361. if (
  362. all_bboxes[j]['category_id'] != object_category_id
  363. or j in used
  364. or dis[i][j] == MAX_DIS_OF_POINT
  365. ):
  366. continue
  367. left, right, _, _ = bbox_relative_pos(
  368. all_bboxes[i]['bbox'], all_bboxes[j]['bbox']
  369. ) # 由 pos_flag_count 相关逻辑保证本段逻辑准确性
  370. if left or right:
  371. one_way_dis = all_bboxes[i]['bbox'][2] - all_bboxes[i]['bbox'][0]
  372. else:
  373. one_way_dis = all_bboxes[i]['bbox'][3] - all_bboxes[i]['bbox'][1]
  374. if dis[i][j] > one_way_dis:
  375. continue
  376. arr.append((dis[i][j], j))
  377. arr.sort(key=lambda x: x[0])
  378. if len(arr) > 0:
  379. """
  380. bug: 离该subject 最近的 object 可能跨越了其它的 subject。
  381. 比如 [this subect] [some sbuject] [the nearest object of subject]
  382. """
  383. if may_find_other_nearest_bbox(i, arr[0][1]) >= arr[0][0]:
  384. candidates.append(arr[0][1])
  385. seen.add(arr[0][1])
  386. # 已经获取初始种子
  387. for j in set(candidates):
  388. tmp = []
  389. for k in range(i + 1, N):
  390. pos_flag_count = sum(
  391. list(
  392. map(
  393. lambda x: 1 if x else 0,
  394. bbox_relative_pos(
  395. all_bboxes[j]['bbox'], all_bboxes[k]['bbox']
  396. ),
  397. )
  398. )
  399. )
  400. if pos_flag_count > 1:
  401. continue
  402. if (
  403. all_bboxes[k]['category_id'] != object_category_id
  404. or k in used
  405. or k in seen
  406. or dis[j][k] == MAX_DIS_OF_POINT
  407. or dis[j][k] > dis[i][j]
  408. ):
  409. continue
  410. is_nearest = True
  411. for ni in range(i + 1, N):
  412. if ni in (j, k) or ni in used or ni in seen:
  413. continue
  414. if not float_gt(dis[ni][k], dis[j][k]):
  415. is_nearest = False
  416. break
  417. if is_nearest:
  418. nx0, ny0, nx1, ny1 = expand_bbbox(list(seen) + [k])
  419. n_dis = bbox_distance(
  420. all_bboxes[i]['bbox'], [nx0, ny0, nx1, ny1]
  421. )
  422. if float_gt(dis[i][j], n_dis):
  423. continue
  424. tmp.append(k)
  425. seen.add(k)
  426. candidates = tmp
  427. if len(candidates) == 0:
  428. break
  429. # 已经获取到某个 figure 下所有的最靠近的 captions,以及最靠近这些 captions 的 captions 。
  430. # 先扩一下 bbox,
  431. ox0, oy0, ox1, oy1 = expand_bbbox(list(seen) + [i])
  432. ix0, iy0, ix1, iy1 = all_bboxes[i]['bbox']
  433. # 分成了 4 个截取空间,需要计算落在每个截取空间下 objects 合并后占据的矩形面积
  434. caption_poses = [
  435. [ox0, oy0, ix0, oy1],
  436. [ox0, oy0, ox1, iy0],
  437. [ox0, iy1, ox1, oy1],
  438. [ix1, oy0, ox1, oy1],
  439. ]
  440. caption_areas = []
  441. for bbox in caption_poses:
  442. embed_arr = []
  443. for idx in seen:
  444. if (
  445. calculate_overlap_area_in_bbox1_area_ratio(
  446. all_bboxes[idx]['bbox'], bbox
  447. )
  448. > CAPATION_OVERLAP_AREA_RATIO
  449. ):
  450. embed_arr.append(idx)
  451. if len(embed_arr) > 0:
  452. embed_x0 = min([all_bboxes[idx]['bbox'][0] for idx in embed_arr])
  453. embed_y0 = min([all_bboxes[idx]['bbox'][1] for idx in embed_arr])
  454. embed_x1 = max([all_bboxes[idx]['bbox'][2] for idx in embed_arr])
  455. embed_y1 = max([all_bboxes[idx]['bbox'][3] for idx in embed_arr])
  456. caption_areas.append(
  457. int(abs(embed_x1 - embed_x0) * abs(embed_y1 - embed_y0))
  458. )
  459. else:
  460. caption_areas.append(0)
  461. subject_object_relation_map[i] = []
  462. if max(caption_areas) > 0:
  463. max_area_idx = caption_areas.index(max(caption_areas))
  464. caption_bbox = caption_poses[max_area_idx]
  465. for j in seen:
  466. if (
  467. calculate_overlap_area_in_bbox1_area_ratio(
  468. all_bboxes[j]['bbox'], caption_bbox
  469. )
  470. > CAPATION_OVERLAP_AREA_RATIO
  471. ):
  472. used.add(j)
  473. subject_object_relation_map[i].append(j)
  474. for i in sorted(subject_object_relation_map.keys()):
  475. result = {
  476. 'subject_body': all_bboxes[i]['bbox'],
  477. 'all': all_bboxes[i]['bbox'],
  478. 'score': all_bboxes[i]['score'],
  479. }
  480. if len(subject_object_relation_map[i]) > 0:
  481. x0 = min(
  482. [all_bboxes[j]['bbox'][0] for j in subject_object_relation_map[i]]
  483. )
  484. y0 = min(
  485. [all_bboxes[j]['bbox'][1] for j in subject_object_relation_map[i]]
  486. )
  487. x1 = max(
  488. [all_bboxes[j]['bbox'][2] for j in subject_object_relation_map[i]]
  489. )
  490. y1 = max(
  491. [all_bboxes[j]['bbox'][3] for j in subject_object_relation_map[i]]
  492. )
  493. result['object_body'] = [x0, y0, x1, y1]
  494. result['all'] = [
  495. min(x0, all_bboxes[i]['bbox'][0]),
  496. min(y0, all_bboxes[i]['bbox'][1]),
  497. max(x1, all_bboxes[i]['bbox'][2]),
  498. max(y1, all_bboxes[i]['bbox'][3]),
  499. ]
  500. ret.append(result)
  501. total_subject_object_dis = 0
  502. # 计算已经配对的 distance 距离
  503. for i in subject_object_relation_map.keys():
  504. for j in subject_object_relation_map[i]:
  505. total_subject_object_dis += bbox_distance(
  506. all_bboxes[i]['bbox'], all_bboxes[j]['bbox']
  507. )
  508. # 计算未匹配的 subject 和 object 的距离(非精确版)
  509. with_caption_subject = set(
  510. [
  511. key
  512. for key in subject_object_relation_map.keys()
  513. if len(subject_object_relation_map[i]) > 0
  514. ]
  515. )
  516. for i in range(N):
  517. if all_bboxes[i]['category_id'] != object_category_id or i in used:
  518. continue
  519. candidates = []
  520. for j in range(N):
  521. if (
  522. all_bboxes[j]['category_id'] != subject_category_id
  523. or j in with_caption_subject
  524. ):
  525. continue
  526. candidates.append((dis[i][j], j))
  527. if len(candidates) > 0:
  528. candidates.sort(key=lambda x: x[0])
  529. total_subject_object_dis += candidates[0][1]
  530. with_caption_subject.add(j)
  531. return ret, total_subject_object_dis
  532. def __tie_up_category_by_distance_v2(
  533. self,
  534. page_no: int,
  535. subject_category_id: int,
  536. object_category_id: int,
  537. priority_pos: PosRelationEnum,
  538. ):
  539. """_summary_
  540. Args:
  541. page_no (int): _description_
  542. subject_category_id (int): _description_
  543. object_category_id (int): _description_
  544. priority_pos (PosRelationEnum): _description_
  545. Returns:
  546. _type_: _description_
  547. """
  548. AXIS_MULPLICITY = 0.5
  549. subjects = self.__reduct_overlap(
  550. list(
  551. map(
  552. lambda x: {'bbox': x['bbox'], 'score': x['score']},
  553. filter(
  554. lambda x: x['category_id'] == subject_category_id,
  555. self.__model_list[page_no]['layout_dets'],
  556. ),
  557. )
  558. )
  559. )
  560. objects = self.__reduct_overlap(
  561. list(
  562. map(
  563. lambda x: {'bbox': x['bbox'], 'score': x['score']},
  564. filter(
  565. lambda x: x['category_id'] == object_category_id,
  566. self.__model_list[page_no]['layout_dets'],
  567. ),
  568. )
  569. )
  570. )
  571. M = len(objects)
  572. subjects.sort(key=lambda x: x['bbox'][0] ** 2 + x['bbox'][1] ** 2)
  573. objects.sort(key=lambda x: x['bbox'][0] ** 2 + x['bbox'][1] ** 2)
  574. sub_obj_map_h = {i: [] for i in range(len(subjects))}
  575. dis_by_directions = {
  576. 'top': [[-1, float('inf')]] * M,
  577. 'bottom': [[-1, float('inf')]] * M,
  578. 'left': [[-1, float('inf')]] * M,
  579. 'right': [[-1, float('inf')]] * M,
  580. }
  581. for i, obj in enumerate(objects):
  582. l_x_axis, l_y_axis = (
  583. obj['bbox'][2] - obj['bbox'][0],
  584. obj['bbox'][3] - obj['bbox'][1],
  585. )
  586. axis_unit = min(l_x_axis, l_y_axis)
  587. for j, sub in enumerate(subjects):
  588. bbox1, bbox2, _ = _remove_overlap_between_bbox(
  589. objects[i]['bbox'], subjects[j]['bbox']
  590. )
  591. left, right, bottom, top = bbox_relative_pos(bbox1, bbox2)
  592. flags = [left, right, bottom, top]
  593. if sum([1 if v else 0 for v in flags]) > 1:
  594. continue
  595. if left:
  596. if dis_by_directions['left'][i][1] > bbox_distance(
  597. obj['bbox'], sub['bbox']
  598. ):
  599. dis_by_directions['left'][i] = [
  600. j,
  601. bbox_distance(obj['bbox'], sub['bbox']),
  602. ]
  603. if right:
  604. if dis_by_directions['right'][i][1] > bbox_distance(
  605. obj['bbox'], sub['bbox']
  606. ):
  607. dis_by_directions['right'][i] = [
  608. j,
  609. bbox_distance(obj['bbox'], sub['bbox']),
  610. ]
  611. if bottom:
  612. if dis_by_directions['bottom'][i][1] > bbox_distance(
  613. obj['bbox'], sub['bbox']
  614. ):
  615. dis_by_directions['bottom'][i] = [
  616. j,
  617. bbox_distance(obj['bbox'], sub['bbox']),
  618. ]
  619. if top:
  620. if dis_by_directions['top'][i][1] > bbox_distance(
  621. obj['bbox'], sub['bbox']
  622. ):
  623. dis_by_directions['top'][i] = [
  624. j,
  625. bbox_distance(obj['bbox'], sub['bbox']),
  626. ]
  627. if (
  628. dis_by_directions['top'][i][1] != float('inf')
  629. and dis_by_directions['bottom'][i][1] != float('inf')
  630. and priority_pos in (PosRelationEnum.BOTTOM, PosRelationEnum.UP)
  631. ):
  632. RATIO = 3
  633. if (
  634. abs(
  635. dis_by_directions['top'][i][1]
  636. - dis_by_directions['bottom'][i][1]
  637. )
  638. < RATIO * axis_unit
  639. ):
  640. if priority_pos == PosRelationEnum.BOTTOM:
  641. sub_obj_map_h[dis_by_directions['bottom'][i][0]].append(i)
  642. else:
  643. sub_obj_map_h[dis_by_directions['top'][i][0]].append(i)
  644. continue
  645. if dis_by_directions['left'][i][1] != float('inf') or dis_by_directions[
  646. 'right'
  647. ][i][1] != float('inf'):
  648. if dis_by_directions['left'][i][1] != float(
  649. 'inf'
  650. ) and dis_by_directions['right'][i][1] != float('inf'):
  651. if AXIS_MULPLICITY * axis_unit >= abs(
  652. dis_by_directions['left'][i][1]
  653. - dis_by_directions['right'][i][1]
  654. ):
  655. left_sub_bbox = subjects[dis_by_directions['left'][i][0]][
  656. 'bbox'
  657. ]
  658. right_sub_bbox = subjects[dis_by_directions['right'][i][0]][
  659. 'bbox'
  660. ]
  661. left_sub_bbox_y_axis = left_sub_bbox[3] - left_sub_bbox[1]
  662. right_sub_bbox_y_axis = right_sub_bbox[3] - right_sub_bbox[1]
  663. if (
  664. abs(left_sub_bbox_y_axis - l_y_axis)
  665. + dis_by_directions['left'][i][0]
  666. > abs(right_sub_bbox_y_axis - l_y_axis)
  667. + dis_by_directions['right'][i][0]
  668. ):
  669. left_or_right = dis_by_directions['right'][i]
  670. else:
  671. left_or_right = dis_by_directions['left'][i]
  672. else:
  673. left_or_right = dis_by_directions['left'][i]
  674. if left_or_right[1] > dis_by_directions['right'][i][1]:
  675. left_or_right = dis_by_directions['right'][i]
  676. else:
  677. left_or_right = dis_by_directions['left'][i]
  678. if left_or_right[1] == float('inf'):
  679. left_or_right = dis_by_directions['right'][i]
  680. else:
  681. left_or_right = [-1, float('inf')]
  682. if dis_by_directions['top'][i][1] != float('inf') or dis_by_directions[
  683. 'bottom'
  684. ][i][1] != float('inf'):
  685. if dis_by_directions['top'][i][1] != float('inf') and dis_by_directions[
  686. 'bottom'
  687. ][i][1] != float('inf'):
  688. if AXIS_MULPLICITY * axis_unit >= abs(
  689. dis_by_directions['top'][i][1]
  690. - dis_by_directions['bottom'][i][1]
  691. ):
  692. top_bottom = subjects[dis_by_directions['bottom'][i][0]]['bbox']
  693. bottom_top = subjects[dis_by_directions['top'][i][0]]['bbox']
  694. top_bottom_x_axis = top_bottom[2] - top_bottom[0]
  695. bottom_top_x_axis = bottom_top[2] - bottom_top[0]
  696. if (
  697. abs(top_bottom_x_axis - l_x_axis)
  698. + dis_by_directions['bottom'][i][1]
  699. > abs(bottom_top_x_axis - l_x_axis)
  700. + dis_by_directions['top'][i][1]
  701. ):
  702. top_or_bottom = dis_by_directions['top'][i]
  703. else:
  704. top_or_bottom = dis_by_directions['bottom'][i]
  705. else:
  706. top_or_bottom = dis_by_directions['top'][i]
  707. if top_or_bottom[1] > dis_by_directions['bottom'][i][1]:
  708. top_or_bottom = dis_by_directions['bottom'][i]
  709. else:
  710. top_or_bottom = dis_by_directions['top'][i]
  711. if top_or_bottom[1] == float('inf'):
  712. top_or_bottom = dis_by_directions['bottom'][i]
  713. else:
  714. top_or_bottom = [-1, float('inf')]
  715. if left_or_right[1] != float('inf') or top_or_bottom[1] != float('inf'):
  716. if left_or_right[1] != float('inf') and top_or_bottom[1] != float(
  717. 'inf'
  718. ):
  719. if AXIS_MULPLICITY * axis_unit >= abs(
  720. left_or_right[1] - top_or_bottom[1]
  721. ):
  722. y_axis_bbox = subjects[left_or_right[0]]['bbox']
  723. x_axis_bbox = subjects[top_or_bottom[0]]['bbox']
  724. if (
  725. abs((x_axis_bbox[2] - x_axis_bbox[0]) - l_x_axis) / l_x_axis
  726. > abs((y_axis_bbox[3] - y_axis_bbox[1]) - l_y_axis)
  727. / l_y_axis
  728. ):
  729. sub_obj_map_h[left_or_right[0]].append(i)
  730. else:
  731. sub_obj_map_h[top_or_bottom[0]].append(i)
  732. else:
  733. if left_or_right[1] > top_or_bottom[1]:
  734. sub_obj_map_h[top_or_bottom[0]].append(i)
  735. else:
  736. sub_obj_map_h[left_or_right[0]].append(i)
  737. else:
  738. if left_or_right[1] != float('inf'):
  739. sub_obj_map_h[left_or_right[0]].append(i)
  740. else:
  741. sub_obj_map_h[top_or_bottom[0]].append(i)
  742. ret = []
  743. for i in sub_obj_map_h.keys():
  744. ret.append(
  745. {
  746. 'sub_bbox': {
  747. 'bbox': subjects[i]['bbox'],
  748. 'score': subjects[i]['score'],
  749. },
  750. 'obj_bboxes': [
  751. {'score': objects[j]['score'], 'bbox': objects[j]['bbox']}
  752. for j in sub_obj_map_h[i]
  753. ],
  754. 'sub_idx': i,
  755. }
  756. )
  757. return ret
  758. def get_imgs_v2(self, page_no: int):
  759. with_captions = self.__tie_up_category_by_distance_v2(
  760. page_no, 3, 4, PosRelationEnum.BOTTOM
  761. )
  762. with_footnotes = self.__tie_up_category_by_distance_v2(
  763. page_no, 3, CategoryId.ImageFootnote, PosRelationEnum.ALL
  764. )
  765. ret = []
  766. for v in with_captions:
  767. record = {
  768. 'image_body': v['sub_bbox'],
  769. 'image_caption_list': v['obj_bboxes'],
  770. }
  771. filter_idx = v['sub_idx']
  772. d = next(filter(lambda x: x['sub_idx'] == filter_idx, with_footnotes))
  773. record['image_footnote_list'] = d['obj_bboxes']
  774. ret.append(record)
  775. return ret
  776. def get_tables_v2(self, page_no: int) -> list:
  777. with_captions = self.__tie_up_category_by_distance_v2(
  778. page_no, 5, 6, PosRelationEnum.UP
  779. )
  780. with_footnotes = self.__tie_up_category_by_distance_v2(
  781. page_no, 5, 7, PosRelationEnum.ALL
  782. )
  783. ret = []
  784. for v in with_captions:
  785. record = {
  786. 'table_body': v['sub_bbox'],
  787. 'table_caption_list': v['obj_bboxes'],
  788. }
  789. filter_idx = v['sub_idx']
  790. d = next(filter(lambda x: x['sub_idx'] == filter_idx, with_footnotes))
  791. record['table_footnote_list'] = d['obj_bboxes']
  792. ret.append(record)
  793. return ret
  794. def get_imgs(self, page_no: int):
  795. with_captions, _ = self.__tie_up_category_by_distance(page_no, 3, 4)
  796. with_footnotes, _ = self.__tie_up_category_by_distance(
  797. page_no, 3, CategoryId.ImageFootnote
  798. )
  799. ret = []
  800. N, M = len(with_captions), len(with_footnotes)
  801. assert N == M
  802. for i in range(N):
  803. record = {
  804. 'score': with_captions[i]['score'],
  805. 'img_caption_bbox': with_captions[i].get('object_body', None),
  806. 'img_body_bbox': with_captions[i]['subject_body'],
  807. 'img_footnote_bbox': with_footnotes[i].get('object_body', None),
  808. }
  809. x0 = min(with_captions[i]['all'][0], with_footnotes[i]['all'][0])
  810. y0 = min(with_captions[i]['all'][1], with_footnotes[i]['all'][1])
  811. x1 = max(with_captions[i]['all'][2], with_footnotes[i]['all'][2])
  812. y1 = max(with_captions[i]['all'][3], with_footnotes[i]['all'][3])
  813. record['bbox'] = [x0, y0, x1, y1]
  814. ret.append(record)
  815. return ret
  816. def get_tables(
  817. self, page_no: int
  818. ) -> list: # 3个坐标, caption, table主体,table-note
  819. with_captions, _ = self.__tie_up_category_by_distance(page_no, 5, 6)
  820. with_footnotes, _ = self.__tie_up_category_by_distance(page_no, 5, 7)
  821. ret = []
  822. N, M = len(with_captions), len(with_footnotes)
  823. assert N == M
  824. for i in range(N):
  825. record = {
  826. 'score': with_captions[i]['score'],
  827. 'table_caption_bbox': with_captions[i].get('object_body', None),
  828. 'table_body_bbox': with_captions[i]['subject_body'],
  829. 'table_footnote_bbox': with_footnotes[i].get('object_body', None),
  830. }
  831. x0 = min(with_captions[i]['all'][0], with_footnotes[i]['all'][0])
  832. y0 = min(with_captions[i]['all'][1], with_footnotes[i]['all'][1])
  833. x1 = max(with_captions[i]['all'][2], with_footnotes[i]['all'][2])
  834. y1 = max(with_captions[i]['all'][3], with_footnotes[i]['all'][3])
  835. record['bbox'] = [x0, y0, x1, y1]
  836. ret.append(record)
  837. return ret
  838. def get_equations(self, page_no: int) -> list: # 有坐标,也有字
  839. inline_equations = self.__get_blocks_by_type(
  840. ModelBlockTypeEnum.EMBEDDING.value, page_no, ['latex']
  841. )
  842. interline_equations = self.__get_blocks_by_type(
  843. ModelBlockTypeEnum.ISOLATED.value, page_no, ['latex']
  844. )
  845. interline_equations_blocks = self.__get_blocks_by_type(
  846. ModelBlockTypeEnum.ISOLATE_FORMULA.value, page_no
  847. )
  848. return inline_equations, interline_equations, interline_equations_blocks
  849. def get_discarded(self, page_no: int) -> list: # 自研模型,只有坐标
  850. blocks = self.__get_blocks_by_type(ModelBlockTypeEnum.ABANDON.value, page_no)
  851. return blocks
  852. def get_text_blocks(self, page_no: int) -> list: # 自研模型搞的,只有坐标,没有字
  853. blocks = self.__get_blocks_by_type(ModelBlockTypeEnum.PLAIN_TEXT.value, page_no)
  854. return blocks
  855. def get_title_blocks(self, page_no: int) -> list: # 自研模型,只有坐标,没字
  856. blocks = self.__get_blocks_by_type(ModelBlockTypeEnum.TITLE.value, page_no)
  857. return blocks
  858. def get_ocr_text(self, page_no: int) -> list: # paddle 搞的,有字也有坐标
  859. text_spans = []
  860. model_page_info = self.__model_list[page_no]
  861. layout_dets = model_page_info['layout_dets']
  862. for layout_det in layout_dets:
  863. if layout_det['category_id'] == '15':
  864. span = {
  865. 'bbox': layout_det['bbox'],
  866. 'content': layout_det['text'],
  867. }
  868. text_spans.append(span)
  869. return text_spans
  870. def get_all_spans(self, page_no: int) -> list:
  871. def remove_duplicate_spans(spans):
  872. new_spans = []
  873. for span in spans:
  874. if not any(span == existing_span for existing_span in new_spans):
  875. new_spans.append(span)
  876. return new_spans
  877. all_spans = []
  878. model_page_info = self.__model_list[page_no]
  879. layout_dets = model_page_info['layout_dets']
  880. allow_category_id_list = [3, 5, 13, 14, 15]
  881. """当成span拼接的"""
  882. # 3: 'image', # 图片
  883. # 5: 'table', # 表格
  884. # 13: 'inline_equation', # 行内公式
  885. # 14: 'interline_equation', # 行间公式
  886. # 15: 'text', # ocr识别文本
  887. for layout_det in layout_dets:
  888. category_id = layout_det['category_id']
  889. if category_id in allow_category_id_list:
  890. span = {'bbox': layout_det['bbox'], 'score': layout_det['score']}
  891. if category_id == 3:
  892. span['type'] = ContentType.Image
  893. elif category_id == 5:
  894. # 获取table模型结果
  895. latex = layout_det.get('latex', None)
  896. html = layout_det.get('html', None)
  897. if latex:
  898. span['latex'] = latex
  899. elif html:
  900. span['html'] = html
  901. span['type'] = ContentType.Table
  902. elif category_id == 13:
  903. span['content'] = layout_det['latex']
  904. span['type'] = ContentType.InlineEquation
  905. elif category_id == 14:
  906. span['content'] = layout_det['latex']
  907. span['type'] = ContentType.InterlineEquation
  908. elif category_id == 15:
  909. span['content'] = layout_det['text']
  910. span['type'] = ContentType.Text
  911. all_spans.append(span)
  912. return remove_duplicate_spans(all_spans)
  913. def get_page_size(self, page_no: int): # 获取页面宽高
  914. # 获取当前页的page对象
  915. page = self.__docs.get_page(page_no).get_page_info()
  916. # 获取当前页的宽高
  917. page_w = page.w
  918. page_h = page.h
  919. return page_w, page_h
  920. def __get_blocks_by_type(
  921. self, type: int, page_no: int, extra_col: list[str] = []
  922. ) -> list:
  923. blocks = []
  924. for page_dict in self.__model_list:
  925. layout_dets = page_dict.get('layout_dets', [])
  926. page_info = page_dict.get('page_info', {})
  927. page_number = page_info.get('page_no', -1)
  928. if page_no != page_number:
  929. continue
  930. for item in layout_dets:
  931. category_id = item.get('category_id', -1)
  932. bbox = item.get('bbox', None)
  933. if category_id == type:
  934. block = {
  935. 'bbox': bbox,
  936. 'score': item.get('score'),
  937. }
  938. for col in extra_col:
  939. block[col] = item.get(col, None)
  940. blocks.append(block)
  941. return blocks
  942. def get_model_list(self, page_no):
  943. return self.__model_list[page_no]