magic_model.py 42 KB

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