magic_model.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875
  1. import json
  2. from magic_pdf.data.dataset import Dataset
  3. from magic_pdf.libs.boxbase import (_is_in, _is_part_overlap, bbox_distance,
  4. bbox_relative_pos, box_area, calculate_iou,
  5. calculate_overlap_area_in_bbox1_area_ratio,
  6. get_overlap_area)
  7. from magic_pdf.libs.commons import fitz, join_path
  8. from magic_pdf.libs.coordinate_transform import get_scale_ratio
  9. from magic_pdf.libs.local_math import float_gt
  10. from magic_pdf.libs.ModelBlockTypeEnum import ModelBlockTypeEnum
  11. from magic_pdf.libs.ocr_content_type import CategoryId, ContentType
  12. from magic_pdf.rw.AbsReaderWriter import AbsReaderWriter
  13. from magic_pdf.rw.DiskReaderWriter import DiskReaderWriter
  14. CAPATION_OVERLAP_AREA_RATIO = 0.6
  15. MERGE_BOX_OVERLAP_AREA_RATIO = 1.1
  16. class MagicModel:
  17. """每个函数没有得到元素的时候返回空list."""
  18. def __fix_axis(self):
  19. for model_page_info in self.__model_list:
  20. need_remove_list = []
  21. page_no = model_page_info['page_info']['page_no']
  22. horizontal_scale_ratio, vertical_scale_ratio = get_scale_ratio(
  23. model_page_info, self.__docs.get_page(page_no)
  24. )
  25. layout_dets = model_page_info['layout_dets']
  26. for layout_det in layout_dets:
  27. if layout_det.get('bbox') is not None:
  28. # 兼容直接输出bbox的模型数据,如paddle
  29. x0, y0, x1, y1 = layout_det['bbox']
  30. else:
  31. # 兼容直接输出poly的模型数据,如xxx
  32. x0, y0, _, _, x1, y1, _, _ = layout_det['poly']
  33. bbox = [
  34. int(x0 / horizontal_scale_ratio),
  35. int(y0 / vertical_scale_ratio),
  36. int(x1 / horizontal_scale_ratio),
  37. int(y1 / vertical_scale_ratio),
  38. ]
  39. layout_det['bbox'] = bbox
  40. # 删除高度或者宽度小于等于0的spans
  41. if bbox[2] - bbox[0] <= 0 or bbox[3] - bbox[1] <= 0:
  42. need_remove_list.append(layout_det)
  43. for need_remove in need_remove_list:
  44. layout_dets.remove(need_remove)
  45. def __fix_by_remove_low_confidence(self):
  46. for model_page_info in self.__model_list:
  47. need_remove_list = []
  48. layout_dets = model_page_info['layout_dets']
  49. for layout_det in layout_dets:
  50. if layout_det['score'] <= 0.05:
  51. need_remove_list.append(layout_det)
  52. else:
  53. continue
  54. for need_remove in need_remove_list:
  55. layout_dets.remove(need_remove)
  56. def __fix_by_remove_high_iou_and_low_confidence(self):
  57. for model_page_info in self.__model_list:
  58. need_remove_list = []
  59. layout_dets = model_page_info['layout_dets']
  60. for layout_det1 in layout_dets:
  61. for layout_det2 in layout_dets:
  62. if layout_det1 == layout_det2:
  63. continue
  64. if layout_det1['category_id'] in [
  65. 0,
  66. 1,
  67. 2,
  68. 3,
  69. 4,
  70. 5,
  71. 6,
  72. 7,
  73. 8,
  74. 9,
  75. ] and layout_det2['category_id'] in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]:
  76. if (
  77. calculate_iou(layout_det1['bbox'], layout_det2['bbox'])
  78. > 0.9
  79. ):
  80. if layout_det1['score'] < layout_det2['score']:
  81. layout_det_need_remove = layout_det1
  82. else:
  83. layout_det_need_remove = layout_det2
  84. if layout_det_need_remove not in need_remove_list:
  85. need_remove_list.append(layout_det_need_remove)
  86. else:
  87. continue
  88. else:
  89. continue
  90. for need_remove in need_remove_list:
  91. layout_dets.remove(need_remove)
  92. def __init__(self, model_list: list, docs: Dataset):
  93. self.__model_list = model_list
  94. self.__docs = docs
  95. """为所有模型数据添加bbox信息(缩放,poly->bbox)"""
  96. self.__fix_axis()
  97. """删除置信度特别低的模型数据(<0.05),提高质量"""
  98. self.__fix_by_remove_low_confidence()
  99. """删除高iou(>0.9)数据中置信度较低的那个"""
  100. self.__fix_by_remove_high_iou_and_low_confidence()
  101. self.__fix_footnote()
  102. def _bbox_distance(self, bbox1, bbox2):
  103. left, right, bottom, top = bbox_relative_pos(bbox1, bbox2)
  104. flags = [left, right, bottom, top]
  105. count = sum([1 if v else 0 for v in flags])
  106. if count > 1:
  107. return float('inf')
  108. if left or right:
  109. l1 = bbox1[3] - bbox1[1]
  110. l2 = bbox2[3] - bbox2[1]
  111. else:
  112. l1 = bbox1[2] - bbox1[0]
  113. l2 = bbox2[2] - bbox2[0]
  114. min_l, max_l = min(l1, l2), max(l1, l2)
  115. if (max_l - min_l) * 1.0 / max_l > 0.4:
  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(
  187. self, page_no, subject_category_id, object_category_id
  188. ):
  189. """假定每个 subject 最多有一个 object (可以有多个相邻的 object 合并为单个 object),每个 object
  190. 只能属于一个 subject."""
  191. ret = []
  192. MAX_DIS_OF_POINT = 10**9 + 7
  193. """
  194. subject 和 object 的 bbox 会合并成一个大的 bbox (named: merged bbox)。
  195. 筛选出所有和 merged bbox 有 overlap 且 overlap 面积大于 object 的面积的 subjects。
  196. 再求出筛选出的 subjects 和 object 的最短距离
  197. """
  198. def search_overlap_between_boxes(subject_idx, object_idx):
  199. idxes = [subject_idx, object_idx]
  200. x0s = [all_bboxes[idx]['bbox'][0] for idx in idxes]
  201. y0s = [all_bboxes[idx]['bbox'][1] for idx in idxes]
  202. x1s = [all_bboxes[idx]['bbox'][2] for idx in idxes]
  203. y1s = [all_bboxes[idx]['bbox'][3] for idx in idxes]
  204. merged_bbox = [
  205. min(x0s),
  206. min(y0s),
  207. max(x1s),
  208. max(y1s),
  209. ]
  210. ratio = 0
  211. other_objects = list(
  212. map(
  213. lambda x: {'bbox': x['bbox'], 'score': x['score']},
  214. filter(
  215. lambda x: x['category_id']
  216. not in (object_category_id, subject_category_id),
  217. self.__model_list[page_no]['layout_dets'],
  218. ),
  219. )
  220. )
  221. for other_object in other_objects:
  222. ratio = max(
  223. ratio,
  224. get_overlap_area(merged_bbox, other_object['bbox'])
  225. * 1.0
  226. / box_area(all_bboxes[object_idx]['bbox']),
  227. )
  228. if ratio >= MERGE_BOX_OVERLAP_AREA_RATIO:
  229. break
  230. return ratio
  231. def may_find_other_nearest_bbox(subject_idx, object_idx):
  232. ret = float('inf')
  233. x0 = min(
  234. all_bboxes[subject_idx]['bbox'][0], all_bboxes[object_idx]['bbox'][0]
  235. )
  236. y0 = min(
  237. all_bboxes[subject_idx]['bbox'][1], all_bboxes[object_idx]['bbox'][1]
  238. )
  239. x1 = max(
  240. all_bboxes[subject_idx]['bbox'][2], all_bboxes[object_idx]['bbox'][2]
  241. )
  242. y1 = max(
  243. all_bboxes[subject_idx]['bbox'][3], all_bboxes[object_idx]['bbox'][3]
  244. )
  245. object_area = abs(
  246. all_bboxes[object_idx]['bbox'][2] - all_bboxes[object_idx]['bbox'][0]
  247. ) * abs(
  248. all_bboxes[object_idx]['bbox'][3] - all_bboxes[object_idx]['bbox'][1]
  249. )
  250. for i in range(len(all_bboxes)):
  251. if (
  252. i == subject_idx
  253. or all_bboxes[i]['category_id'] != subject_category_id
  254. ):
  255. continue
  256. if _is_part_overlap([x0, y0, x1, y1], all_bboxes[i]['bbox']) or _is_in(
  257. all_bboxes[i]['bbox'], [x0, y0, x1, y1]
  258. ):
  259. i_area = abs(
  260. all_bboxes[i]['bbox'][2] - all_bboxes[i]['bbox'][0]
  261. ) * abs(all_bboxes[i]['bbox'][3] - all_bboxes[i]['bbox'][1])
  262. if i_area >= object_area:
  263. ret = min(float('inf'), dis[i][object_idx])
  264. return ret
  265. def expand_bbbox(idxes):
  266. x0s = [all_bboxes[idx]['bbox'][0] for idx in idxes]
  267. y0s = [all_bboxes[idx]['bbox'][1] for idx in idxes]
  268. x1s = [all_bboxes[idx]['bbox'][2] for idx in idxes]
  269. y1s = [all_bboxes[idx]['bbox'][3] for idx in idxes]
  270. return min(x0s), min(y0s), max(x1s), max(y1s)
  271. subjects = self.__reduct_overlap(
  272. list(
  273. map(
  274. lambda x: {'bbox': x['bbox'], 'score': x['score']},
  275. filter(
  276. lambda x: x['category_id'] == subject_category_id,
  277. self.__model_list[page_no]['layout_dets'],
  278. ),
  279. )
  280. )
  281. )
  282. objects = self.__reduct_overlap(
  283. list(
  284. map(
  285. lambda x: {'bbox': x['bbox'], 'score': x['score']},
  286. filter(
  287. lambda x: x['category_id'] == object_category_id,
  288. self.__model_list[page_no]['layout_dets'],
  289. ),
  290. )
  291. )
  292. )
  293. subject_object_relation_map = {}
  294. subjects.sort(
  295. key=lambda x: x['bbox'][0] ** 2 + x['bbox'][1] ** 2
  296. ) # get the distance !
  297. all_bboxes = []
  298. for v in subjects:
  299. all_bboxes.append(
  300. {
  301. 'category_id': subject_category_id,
  302. 'bbox': v['bbox'],
  303. 'score': v['score'],
  304. }
  305. )
  306. for v in objects:
  307. all_bboxes.append(
  308. {
  309. 'category_id': object_category_id,
  310. 'bbox': v['bbox'],
  311. 'score': v['score'],
  312. }
  313. )
  314. N = len(all_bboxes)
  315. dis = [[MAX_DIS_OF_POINT] * N for _ in range(N)]
  316. for i in range(N):
  317. for j in range(i):
  318. if (
  319. all_bboxes[i]['category_id'] == subject_category_id
  320. and all_bboxes[j]['category_id'] == subject_category_id
  321. ):
  322. continue
  323. subject_idx, object_idx = i, j
  324. if all_bboxes[j]['category_id'] == subject_category_id:
  325. subject_idx, object_idx = j, i
  326. if (
  327. search_overlap_between_boxes(subject_idx, object_idx)
  328. >= MERGE_BOX_OVERLAP_AREA_RATIO
  329. ):
  330. dis[i][j] = float('inf')
  331. dis[j][i] = dis[i][j]
  332. continue
  333. dis[i][j] = self._bbox_distance(
  334. all_bboxes[subject_idx]['bbox'], all_bboxes[object_idx]['bbox']
  335. )
  336. dis[j][i] = dis[i][j]
  337. used = set()
  338. for i in range(N):
  339. # 求第 i 个 subject 所关联的 object
  340. if all_bboxes[i]['category_id'] != subject_category_id:
  341. continue
  342. seen = set()
  343. candidates = []
  344. arr = []
  345. for j in range(N):
  346. pos_flag_count = sum(
  347. list(
  348. map(
  349. lambda x: 1 if x else 0,
  350. bbox_relative_pos(
  351. all_bboxes[i]['bbox'], all_bboxes[j]['bbox']
  352. ),
  353. )
  354. )
  355. )
  356. if pos_flag_count > 1:
  357. continue
  358. if (
  359. all_bboxes[j]['category_id'] != object_category_id
  360. or j in used
  361. or dis[i][j] == MAX_DIS_OF_POINT
  362. ):
  363. continue
  364. left, right, _, _ = bbox_relative_pos(
  365. all_bboxes[i]['bbox'], all_bboxes[j]['bbox']
  366. ) # 由 pos_flag_count 相关逻辑保证本段逻辑准确性
  367. if left or right:
  368. one_way_dis = all_bboxes[i]['bbox'][2] - all_bboxes[i]['bbox'][0]
  369. else:
  370. one_way_dis = all_bboxes[i]['bbox'][3] - all_bboxes[i]['bbox'][1]
  371. if dis[i][j] > one_way_dis:
  372. continue
  373. arr.append((dis[i][j], j))
  374. arr.sort(key=lambda x: x[0])
  375. if len(arr) > 0:
  376. """
  377. bug: 离该subject 最近的 object 可能跨越了其它的 subject。
  378. 比如 [this subect] [some sbuject] [the nearest object of subject]
  379. """
  380. if may_find_other_nearest_bbox(i, arr[0][1]) >= arr[0][0]:
  381. candidates.append(arr[0][1])
  382. seen.add(arr[0][1])
  383. # 已经获取初始种子
  384. for j in set(candidates):
  385. tmp = []
  386. for k in range(i + 1, N):
  387. pos_flag_count = sum(
  388. list(
  389. map(
  390. lambda x: 1 if x else 0,
  391. bbox_relative_pos(
  392. all_bboxes[j]['bbox'], all_bboxes[k]['bbox']
  393. ),
  394. )
  395. )
  396. )
  397. if pos_flag_count > 1:
  398. continue
  399. if (
  400. all_bboxes[k]['category_id'] != object_category_id
  401. or k in used
  402. or k in seen
  403. or dis[j][k] == MAX_DIS_OF_POINT
  404. or dis[j][k] > dis[i][j]
  405. ):
  406. continue
  407. is_nearest = True
  408. for ni in range(i + 1, N):
  409. if ni in (j, k) or ni in used or ni in seen:
  410. continue
  411. if not float_gt(dis[ni][k], dis[j][k]):
  412. is_nearest = False
  413. break
  414. if is_nearest:
  415. nx0, ny0, nx1, ny1 = expand_bbbox(list(seen) + [k])
  416. n_dis = bbox_distance(
  417. all_bboxes[i]['bbox'], [nx0, ny0, nx1, ny1]
  418. )
  419. if float_gt(dis[i][j], n_dis):
  420. continue
  421. tmp.append(k)
  422. seen.add(k)
  423. candidates = tmp
  424. if len(candidates) == 0:
  425. break
  426. # 已经获取到某个 figure 下所有的最靠近的 captions,以及最靠近这些 captions 的 captions 。
  427. # 先扩一下 bbox,
  428. ox0, oy0, ox1, oy1 = expand_bbbox(list(seen) + [i])
  429. ix0, iy0, ix1, iy1 = all_bboxes[i]['bbox']
  430. # 分成了 4 个截取空间,需要计算落在每个截取空间下 objects 合并后占据的矩形面积
  431. caption_poses = [
  432. [ox0, oy0, ix0, oy1],
  433. [ox0, oy0, ox1, iy0],
  434. [ox0, iy1, ox1, oy1],
  435. [ix1, oy0, ox1, oy1],
  436. ]
  437. caption_areas = []
  438. for bbox in caption_poses:
  439. embed_arr = []
  440. for idx in seen:
  441. if (
  442. calculate_overlap_area_in_bbox1_area_ratio(
  443. all_bboxes[idx]['bbox'], bbox
  444. )
  445. > CAPATION_OVERLAP_AREA_RATIO
  446. ):
  447. embed_arr.append(idx)
  448. if len(embed_arr) > 0:
  449. embed_x0 = min([all_bboxes[idx]['bbox'][0] for idx in embed_arr])
  450. embed_y0 = min([all_bboxes[idx]['bbox'][1] for idx in embed_arr])
  451. embed_x1 = max([all_bboxes[idx]['bbox'][2] for idx in embed_arr])
  452. embed_y1 = max([all_bboxes[idx]['bbox'][3] for idx in embed_arr])
  453. caption_areas.append(
  454. int(abs(embed_x1 - embed_x0) * abs(embed_y1 - embed_y0))
  455. )
  456. else:
  457. caption_areas.append(0)
  458. subject_object_relation_map[i] = []
  459. if max(caption_areas) > 0:
  460. max_area_idx = caption_areas.index(max(caption_areas))
  461. caption_bbox = caption_poses[max_area_idx]
  462. for j in seen:
  463. if (
  464. calculate_overlap_area_in_bbox1_area_ratio(
  465. all_bboxes[j]['bbox'], caption_bbox
  466. )
  467. > CAPATION_OVERLAP_AREA_RATIO
  468. ):
  469. used.add(j)
  470. subject_object_relation_map[i].append(j)
  471. for i in sorted(subject_object_relation_map.keys()):
  472. result = {
  473. 'subject_body': all_bboxes[i]['bbox'],
  474. 'all': all_bboxes[i]['bbox'],
  475. 'score': all_bboxes[i]['score'],
  476. }
  477. if len(subject_object_relation_map[i]) > 0:
  478. x0 = min(
  479. [all_bboxes[j]['bbox'][0] for j in subject_object_relation_map[i]]
  480. )
  481. y0 = min(
  482. [all_bboxes[j]['bbox'][1] for j in subject_object_relation_map[i]]
  483. )
  484. x1 = max(
  485. [all_bboxes[j]['bbox'][2] for j in subject_object_relation_map[i]]
  486. )
  487. y1 = max(
  488. [all_bboxes[j]['bbox'][3] for j in subject_object_relation_map[i]]
  489. )
  490. result['object_body'] = [x0, y0, x1, y1]
  491. result['all'] = [
  492. min(x0, all_bboxes[i]['bbox'][0]),
  493. min(y0, all_bboxes[i]['bbox'][1]),
  494. max(x1, all_bboxes[i]['bbox'][2]),
  495. max(y1, all_bboxes[i]['bbox'][3]),
  496. ]
  497. ret.append(result)
  498. total_subject_object_dis = 0
  499. # 计算已经配对的 distance 距离
  500. for i in subject_object_relation_map.keys():
  501. for j in subject_object_relation_map[i]:
  502. total_subject_object_dis += bbox_distance(
  503. all_bboxes[i]['bbox'], all_bboxes[j]['bbox']
  504. )
  505. # 计算未匹配的 subject 和 object 的距离(非精确版)
  506. with_caption_subject = set(
  507. [
  508. key
  509. for key in subject_object_relation_map.keys()
  510. if len(subject_object_relation_map[i]) > 0
  511. ]
  512. )
  513. for i in range(N):
  514. if all_bboxes[i]['category_id'] != object_category_id or i in used:
  515. continue
  516. candidates = []
  517. for j in range(N):
  518. if (
  519. all_bboxes[j]['category_id'] != subject_category_id
  520. or j in with_caption_subject
  521. ):
  522. continue
  523. candidates.append((dis[i][j], j))
  524. if len(candidates) > 0:
  525. candidates.sort(key=lambda x: x[0])
  526. total_subject_object_dis += candidates[0][1]
  527. with_caption_subject.add(j)
  528. return ret, total_subject_object_dis
  529. def __tie_up_category_by_distance_v2(
  530. self, page_no, subject_category_id, object_category_id
  531. ):
  532. subjects = self.__reduct_overlap(
  533. list(
  534. map(
  535. lambda x: {'bbox': x['bbox'], 'score': x['score']},
  536. filter(
  537. lambda x: x['category_id'] == subject_category_id,
  538. self.__model_list[page_no]['layout_dets'],
  539. ),
  540. )
  541. )
  542. )
  543. objects = self.__reduct_overlap(
  544. list(
  545. map(
  546. lambda x: {'bbox': x['bbox'], 'score': x['score']},
  547. filter(
  548. lambda x: x['category_id'] == object_category_id,
  549. self.__model_list[page_no]['layout_dets'],
  550. ),
  551. )
  552. )
  553. )
  554. subjects.sort(key=lambda x: x['bbox'][0] ** 2 + x['bbox'][1] ** 2)
  555. objects.sort(key=lambda x: x['bbox'][0] ** 2 + x['bbox'][1] ** 2)
  556. dis = [[float('inf')] * len(subjects) for _ in range(len(objects))]
  557. for i, obj in enumerate(objects):
  558. for j, sub in enumerate(subjects):
  559. dis[i][j] = self._bbox_distance(sub['bbox'], obj['bbox'])
  560. sub_obj_map_h = {i: [] for i in range(len(subjects))}
  561. for i in range(len(objects)):
  562. min_l_idx = 0
  563. for j in range(1, len(subjects)):
  564. if dis[i][j] == float('inf'):
  565. continue
  566. if dis[i][j] < dis[i][min_l_idx]:
  567. min_l_idx = j
  568. if dis[i][min_l_idx] < float('inf'):
  569. sub_obj_map_h[min_l_idx].append(i)
  570. else:
  571. print(i, 'no nearest')
  572. ret = []
  573. for i in sub_obj_map_h.keys():
  574. ret.append(
  575. {
  576. 'sub_bbox': subjects[i]['bbox'],
  577. 'obj_bboxes': [objects[j]['bbox'] for j in sub_obj_map_h[i]],
  578. 'sub_idx': i,
  579. }
  580. )
  581. return ret
  582. def get_imgs_v2(self, page_no: int):
  583. with_captions = self.__tie_up_category_by_distance_v2(page_no, 3, 4)
  584. with_footnotes = self.__tie_up_category_by_distance_v2(
  585. page_no, 3, CategoryId.ImageFootnote
  586. )
  587. ret = []
  588. for v in with_captions:
  589. record = {
  590. 'image_bbox': v['sub_bbox'],
  591. 'image_caption_bbox_list': v['obj_bboxes'],
  592. }
  593. filter_idx = v['sub_idx']
  594. d = next(filter(lambda x: x['sub_idx'] == filter_idx, with_footnotes))
  595. record['image_footnote_bbox_list'] = d['obj_bboxes']
  596. ret.append(record)
  597. return ret
  598. def get_tables_v2(self, page_no: int) -> list:
  599. with_captions = self.__tie_up_category_by_distance_v2(page_no, 5, 6)
  600. with_footnotes = self.__tie_up_category_by_distance_v2(page_no, 5, 7)
  601. ret = []
  602. for v in with_captions:
  603. record = {
  604. 'table_bbox': v['sub_bbox'],
  605. 'table_caption_bbox_list': v['obj_bboxes'],
  606. }
  607. filter_idx = v['sub_idx']
  608. d = next(filter(lambda x: x['sub_idx'] == filter_idx, with_footnotes))
  609. record['table_footnote_bbox_list'] = d['obj_bboxes']
  610. ret.append(record)
  611. return ret
  612. def get_imgs(self, page_no: int):
  613. with_captions, _ = self.__tie_up_category_by_distance(page_no, 3, 4)
  614. with_footnotes, _ = self.__tie_up_category_by_distance(
  615. page_no, 3, CategoryId.ImageFootnote
  616. )
  617. ret = []
  618. N, M = len(with_captions), len(with_footnotes)
  619. assert N == M
  620. for i in range(N):
  621. record = {
  622. 'score': with_captions[i]['score'],
  623. 'img_caption_bbox': with_captions[i].get('object_body', None),
  624. 'img_body_bbox': with_captions[i]['subject_body'],
  625. 'img_footnote_bbox': with_footnotes[i].get('object_body', None),
  626. }
  627. x0 = min(with_captions[i]['all'][0], with_footnotes[i]['all'][0])
  628. y0 = min(with_captions[i]['all'][1], with_footnotes[i]['all'][1])
  629. x1 = max(with_captions[i]['all'][2], with_footnotes[i]['all'][2])
  630. y1 = max(with_captions[i]['all'][3], with_footnotes[i]['all'][3])
  631. record['bbox'] = [x0, y0, x1, y1]
  632. ret.append(record)
  633. return ret
  634. def get_tables(
  635. self, page_no: int
  636. ) -> list: # 3个坐标, caption, table主体,table-note
  637. with_captions, _ = self.__tie_up_category_by_distance(page_no, 5, 6)
  638. with_footnotes, _ = self.__tie_up_category_by_distance(page_no, 5, 7)
  639. ret = []
  640. N, M = len(with_captions), len(with_footnotes)
  641. assert N == M
  642. for i in range(N):
  643. record = {
  644. 'score': with_captions[i]['score'],
  645. 'table_caption_bbox': with_captions[i].get('object_body', None),
  646. 'table_body_bbox': with_captions[i]['subject_body'],
  647. 'table_footnote_bbox': with_footnotes[i].get('object_body', None),
  648. }
  649. x0 = min(with_captions[i]['all'][0], with_footnotes[i]['all'][0])
  650. y0 = min(with_captions[i]['all'][1], with_footnotes[i]['all'][1])
  651. x1 = max(with_captions[i]['all'][2], with_footnotes[i]['all'][2])
  652. y1 = max(with_captions[i]['all'][3], with_footnotes[i]['all'][3])
  653. record['bbox'] = [x0, y0, x1, y1]
  654. ret.append(record)
  655. return ret
  656. def get_equations(self, page_no: int) -> list: # 有坐标,也有字
  657. inline_equations = self.__get_blocks_by_type(
  658. ModelBlockTypeEnum.EMBEDDING.value, page_no, ['latex']
  659. )
  660. interline_equations = self.__get_blocks_by_type(
  661. ModelBlockTypeEnum.ISOLATED.value, page_no, ['latex']
  662. )
  663. interline_equations_blocks = self.__get_blocks_by_type(
  664. ModelBlockTypeEnum.ISOLATE_FORMULA.value, page_no
  665. )
  666. return inline_equations, interline_equations, interline_equations_blocks
  667. def get_discarded(self, page_no: int) -> list: # 自研模型,只有坐标
  668. blocks = self.__get_blocks_by_type(ModelBlockTypeEnum.ABANDON.value, page_no)
  669. return blocks
  670. def get_text_blocks(self, page_no: int) -> list: # 自研模型搞的,只有坐标,没有字
  671. blocks = self.__get_blocks_by_type(ModelBlockTypeEnum.PLAIN_TEXT.value, page_no)
  672. return blocks
  673. def get_title_blocks(self, page_no: int) -> list: # 自研模型,只有坐标,没字
  674. blocks = self.__get_blocks_by_type(ModelBlockTypeEnum.TITLE.value, page_no)
  675. return blocks
  676. def get_ocr_text(self, page_no: int) -> list: # paddle 搞的,有字也有坐标
  677. text_spans = []
  678. model_page_info = self.__model_list[page_no]
  679. layout_dets = model_page_info['layout_dets']
  680. for layout_det in layout_dets:
  681. if layout_det['category_id'] == '15':
  682. span = {
  683. 'bbox': layout_det['bbox'],
  684. 'content': layout_det['text'],
  685. }
  686. text_spans.append(span)
  687. return text_spans
  688. def get_all_spans(self, page_no: int) -> list:
  689. def remove_duplicate_spans(spans):
  690. new_spans = []
  691. for span in spans:
  692. if not any(span == existing_span for existing_span in new_spans):
  693. new_spans.append(span)
  694. return new_spans
  695. all_spans = []
  696. model_page_info = self.__model_list[page_no]
  697. layout_dets = model_page_info['layout_dets']
  698. allow_category_id_list = [3, 5, 13, 14, 15]
  699. """当成span拼接的"""
  700. # 3: 'image', # 图片
  701. # 5: 'table', # 表格
  702. # 13: 'inline_equation', # 行内公式
  703. # 14: 'interline_equation', # 行间公式
  704. # 15: 'text', # ocr识别文本
  705. for layout_det in layout_dets:
  706. category_id = layout_det['category_id']
  707. if category_id in allow_category_id_list:
  708. span = {'bbox': layout_det['bbox'], 'score': layout_det['score']}
  709. if category_id == 3:
  710. span['type'] = ContentType.Image
  711. elif category_id == 5:
  712. # 获取table模型结果
  713. latex = layout_det.get('latex', None)
  714. html = layout_det.get('html', None)
  715. if latex:
  716. span['latex'] = latex
  717. elif html:
  718. span['html'] = html
  719. span['type'] = ContentType.Table
  720. elif category_id == 13:
  721. span['content'] = layout_det['latex']
  722. span['type'] = ContentType.InlineEquation
  723. elif category_id == 14:
  724. span['content'] = layout_det['latex']
  725. span['type'] = ContentType.InterlineEquation
  726. elif category_id == 15:
  727. span['content'] = layout_det['text']
  728. span['type'] = ContentType.Text
  729. all_spans.append(span)
  730. return remove_duplicate_spans(all_spans)
  731. def get_page_size(self, page_no: int): # 获取页面宽高
  732. # 获取当前页的page对象
  733. page = self.__docs.get_page(page_no).get_page_info()
  734. # 获取当前页的宽高
  735. page_w = page.w
  736. page_h = page.h
  737. return page_w, page_h
  738. def __get_blocks_by_type(
  739. self, type: int, page_no: int, extra_col: list[str] = []
  740. ) -> list:
  741. blocks = []
  742. for page_dict in self.__model_list:
  743. layout_dets = page_dict.get('layout_dets', [])
  744. page_info = page_dict.get('page_info', {})
  745. page_number = page_info.get('page_no', -1)
  746. if page_no != page_number:
  747. continue
  748. for item in layout_dets:
  749. category_id = item.get('category_id', -1)
  750. bbox = item.get('bbox', None)
  751. if category_id == type:
  752. block = {
  753. 'bbox': bbox,
  754. 'score': item.get('score'),
  755. }
  756. for col in extra_col:
  757. block[col] = item.get(col, None)
  758. blocks.append(block)
  759. return blocks
  760. def get_model_list(self, page_no):
  761. return self.__model_list[page_no]
  762. if __name__ == '__main__':
  763. drw = DiskReaderWriter(r'D:/project/20231108code-clean')
  764. if 0:
  765. pdf_file_path = r'linshixuqiu\19983-00.pdf'
  766. model_file_path = r'linshixuqiu\19983-00_new.json'
  767. pdf_bytes = drw.read(pdf_file_path, AbsReaderWriter.MODE_BIN)
  768. model_json_txt = drw.read(model_file_path, AbsReaderWriter.MODE_TXT)
  769. model_list = json.loads(model_json_txt)
  770. write_path = r'D:\project\20231108code-clean\linshixuqiu\19983-00'
  771. img_bucket_path = 'imgs'
  772. img_writer = DiskReaderWriter(join_path(write_path, img_bucket_path))
  773. pdf_docs = fitz.open('pdf', pdf_bytes)
  774. magic_model = MagicModel(model_list, pdf_docs)
  775. if 1:
  776. model_list = json.loads(
  777. drw.read('/opt/data/pdf/20240418/j.chroma.2009.03.042.json')
  778. )
  779. pdf_bytes = drw.read(
  780. '/opt/data/pdf/20240418/j.chroma.2009.03.042.pdf', AbsReaderWriter.MODE_BIN
  781. )
  782. pdf_docs = fitz.open('pdf', pdf_bytes)
  783. magic_model = MagicModel(model_list, pdf_docs)
  784. for i in range(7):
  785. print(magic_model.get_imgs(i))