magic_model.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778
  1. import json
  2. from magic_pdf.libs.boxbase import (_is_in, _is_part_overlap, bbox_distance,
  3. bbox_relative_pos, box_area, calculate_iou,
  4. calculate_overlap_area_in_bbox1_area_ratio,
  5. get_overlap_area)
  6. from magic_pdf.libs.commons import fitz, join_path
  7. from magic_pdf.libs.coordinate_transform import get_scale_ratio
  8. from magic_pdf.libs.local_math import float_gt
  9. from magic_pdf.libs.ModelBlockTypeEnum import ModelBlockTypeEnum
  10. from magic_pdf.libs.ocr_content_type import CategoryId, ContentType
  11. from magic_pdf.rw.AbsReaderWriter import AbsReaderWriter
  12. from magic_pdf.rw.DiskReaderWriter import DiskReaderWriter
  13. CAPATION_OVERLAP_AREA_RATIO = 0.6
  14. MERGE_BOX_OVERLAP_AREA_RATIO = 1.1
  15. class MagicModel:
  16. """每个函数没有得到元素的时候返回空list."""
  17. def __fix_axis(self):
  18. for model_page_info in self.__model_list:
  19. need_remove_list = []
  20. page_no = model_page_info['page_info']['page_no']
  21. horizontal_scale_ratio, vertical_scale_ratio = get_scale_ratio(
  22. model_page_info, self.__docs[page_no]
  23. )
  24. layout_dets = model_page_info['layout_dets']
  25. for layout_det in layout_dets:
  26. if layout_det.get('bbox') is not None:
  27. # 兼容直接输出bbox的模型数据,如paddle
  28. x0, y0, x1, y1 = layout_det['bbox']
  29. else:
  30. # 兼容直接输出poly的模型数据,如xxx
  31. x0, y0, _, _, x1, y1, _, _ = layout_det['poly']
  32. bbox = [
  33. int(x0 / horizontal_scale_ratio),
  34. int(y0 / vertical_scale_ratio),
  35. int(x1 / horizontal_scale_ratio),
  36. int(y1 / vertical_scale_ratio),
  37. ]
  38. layout_det['bbox'] = bbox
  39. # 删除高度或者宽度小于等于0的spans
  40. if bbox[2] - bbox[0] <= 0 or bbox[3] - bbox[1] <= 0:
  41. need_remove_list.append(layout_det)
  42. for need_remove in need_remove_list:
  43. layout_dets.remove(need_remove)
  44. def __fix_by_remove_low_confidence(self):
  45. for model_page_info in self.__model_list:
  46. need_remove_list = []
  47. layout_dets = model_page_info['layout_dets']
  48. for layout_det in layout_dets:
  49. if layout_det['score'] <= 0.05:
  50. need_remove_list.append(layout_det)
  51. else:
  52. continue
  53. for need_remove in need_remove_list:
  54. layout_dets.remove(need_remove)
  55. def __fix_by_remove_high_iou_and_low_confidence(self):
  56. for model_page_info in self.__model_list:
  57. need_remove_list = []
  58. layout_dets = model_page_info['layout_dets']
  59. for layout_det1 in layout_dets:
  60. for layout_det2 in layout_dets:
  61. if layout_det1 == layout_det2:
  62. continue
  63. if layout_det1['category_id'] in [
  64. 0,
  65. 1,
  66. 2,
  67. 3,
  68. 4,
  69. 5,
  70. 6,
  71. 7,
  72. 8,
  73. 9,
  74. ] and layout_det2['category_id'] in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]:
  75. if (
  76. calculate_iou(layout_det1['bbox'], layout_det2['bbox'])
  77. > 0.9
  78. ):
  79. if layout_det1['score'] < layout_det2['score']:
  80. layout_det_need_remove = layout_det1
  81. else:
  82. layout_det_need_remove = layout_det2
  83. if layout_det_need_remove not in need_remove_list:
  84. need_remove_list.append(layout_det_need_remove)
  85. else:
  86. continue
  87. else:
  88. continue
  89. for need_remove in need_remove_list:
  90. layout_dets.remove(need_remove)
  91. def __init__(self, model_list: list, docs: fitz.Document):
  92. self.__model_list = model_list
  93. self.__docs = docs
  94. """为所有模型数据添加bbox信息(缩放,poly->bbox)"""
  95. self.__fix_axis()
  96. """删除置信度特别低的模型数据(<0.05),提高质量"""
  97. self.__fix_by_remove_low_confidence()
  98. """删除高iou(>0.9)数据中置信度较低的那个"""
  99. self.__fix_by_remove_high_iou_and_low_confidence()
  100. self.__fix_footnote()
  101. def _bbox_distance(self, bbox1, bbox2):
  102. left, right, bottom, top = bbox_relative_pos(bbox1, bbox2)
  103. flags = [left, right, bottom, top]
  104. count = sum([1 if v else 0 for v in flags])
  105. if count > 1:
  106. return float('inf')
  107. if left or right:
  108. l1 = bbox1[3] - bbox1[1]
  109. l2 = bbox2[3] - bbox2[1]
  110. else:
  111. l1 = bbox1[2] - bbox1[0]
  112. l2 = bbox2[2] - bbox2[0]
  113. if l2 > l1 and (l2 - l1) / l1 > 0.5:
  114. return float('inf')
  115. return bbox_distance(bbox1, bbox2)
  116. def __fix_footnote(self):
  117. # 3: figure, 5: table, 7: footnote
  118. for model_page_info in self.__model_list:
  119. footnotes = []
  120. figures = []
  121. tables = []
  122. for obj in model_page_info['layout_dets']:
  123. if obj['category_id'] == 7:
  124. footnotes.append(obj)
  125. elif obj['category_id'] == 3:
  126. figures.append(obj)
  127. elif obj['category_id'] == 5:
  128. tables.append(obj)
  129. if len(footnotes) * len(figures) == 0:
  130. continue
  131. dis_figure_footnote = {}
  132. dis_table_footnote = {}
  133. for i in range(len(footnotes)):
  134. for j in range(len(figures)):
  135. pos_flag_count = sum(
  136. list(
  137. map(
  138. lambda x: 1 if x else 0,
  139. bbox_relative_pos(
  140. footnotes[i]['bbox'], figures[j]['bbox']
  141. ),
  142. )
  143. )
  144. )
  145. if pos_flag_count > 1:
  146. continue
  147. dis_figure_footnote[i] = min(
  148. self._bbox_distance(figures[j]['bbox'], footnotes[i]['bbox']),
  149. dis_figure_footnote.get(i, float('inf')),
  150. )
  151. for i in range(len(footnotes)):
  152. for j in range(len(tables)):
  153. pos_flag_count = sum(
  154. list(
  155. map(
  156. lambda x: 1 if x else 0,
  157. bbox_relative_pos(
  158. footnotes[i]['bbox'], tables[j]['bbox']
  159. ),
  160. )
  161. )
  162. )
  163. if pos_flag_count > 1:
  164. continue
  165. dis_table_footnote[i] = min(
  166. self._bbox_distance(tables[j]['bbox'], footnotes[i]['bbox']),
  167. dis_table_footnote.get(i, float('inf')),
  168. )
  169. for i in range(len(footnotes)):
  170. if i not in dis_figure_footnote:
  171. continue
  172. if dis_table_footnote.get(i, float('inf')) > dis_figure_footnote[i]:
  173. footnotes[i]['category_id'] = CategoryId.ImageFootnote
  174. def __reduct_overlap(self, bboxes):
  175. N = len(bboxes)
  176. keep = [True] * N
  177. for i in range(N):
  178. for j in range(N):
  179. if i == j:
  180. continue
  181. if _is_in(bboxes[i]['bbox'], bboxes[j]['bbox']):
  182. keep[i] = False
  183. return [bboxes[i] for i in range(N) if keep[i]]
  184. def __tie_up_category_by_distance(
  185. self, page_no, subject_category_id, object_category_id
  186. ):
  187. """假定每个 subject 最多有一个 object (可以有多个相邻的 object 合并为单个 object),每个 object
  188. 只能属于一个 subject."""
  189. ret = []
  190. MAX_DIS_OF_POINT = 10**9 + 7
  191. """
  192. subject 和 object 的 bbox 会合并成一个大的 bbox (named: merged bbox)。
  193. 筛选出所有和 merged bbox 有 overlap 且 overlap 面积大于 object 的面积的 subjects。
  194. 再求出筛选出的 subjects 和 object 的最短距离
  195. """
  196. def search_overlap_between_boxes(
  197. subject_idx, object_idx
  198. ):
  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(
  225. merged_bbox, other_object['bbox']
  226. ) * 1.0 / 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 search_overlap_between_boxes(subject_idx, object_idx) >= MERGE_BOX_OVERLAP_AREA_RATIO:
  327. dis[i][j] = float('inf')
  328. dis[j][i] = dis[i][j]
  329. continue
  330. dis[i][j] = self._bbox_distance(all_bboxes[subject_idx]['bbox'], all_bboxes[object_idx]['bbox'])
  331. dis[j][i] = dis[i][j]
  332. used = set()
  333. for i in range(N):
  334. # 求第 i 个 subject 所关联的 object
  335. if all_bboxes[i]['category_id'] != subject_category_id:
  336. continue
  337. seen = set()
  338. candidates = []
  339. arr = []
  340. for j in range(N):
  341. pos_flag_count = sum(
  342. list(
  343. map(
  344. lambda x: 1 if x else 0,
  345. bbox_relative_pos(
  346. all_bboxes[i]['bbox'], all_bboxes[j]['bbox']
  347. ),
  348. )
  349. )
  350. )
  351. if pos_flag_count > 1:
  352. continue
  353. if (
  354. all_bboxes[j]['category_id'] != object_category_id
  355. or j in used
  356. or dis[i][j] == MAX_DIS_OF_POINT
  357. ):
  358. continue
  359. left, right, _, _ = bbox_relative_pos(
  360. all_bboxes[i]['bbox'], all_bboxes[j]['bbox']
  361. ) # 由 pos_flag_count 相关逻辑保证本段逻辑准确性
  362. if left or right:
  363. one_way_dis = all_bboxes[i]['bbox'][2] - all_bboxes[i]['bbox'][0]
  364. else:
  365. one_way_dis = all_bboxes[i]['bbox'][3] - all_bboxes[i]['bbox'][1]
  366. if dis[i][j] > one_way_dis:
  367. continue
  368. arr.append((dis[i][j], j))
  369. arr.sort(key=lambda x: x[0])
  370. if len(arr) > 0:
  371. """
  372. bug: 离该subject 最近的 object 可能跨越了其它的 subject。
  373. 比如 [this subect] [some sbuject] [the nearest object of subject]
  374. """
  375. if may_find_other_nearest_bbox(i, arr[0][1]) >= arr[0][0]:
  376. candidates.append(arr[0][1])
  377. seen.add(arr[0][1])
  378. # 已经获取初始种子
  379. for j in set(candidates):
  380. tmp = []
  381. for k in range(i + 1, N):
  382. pos_flag_count = sum(
  383. list(
  384. map(
  385. lambda x: 1 if x else 0,
  386. bbox_relative_pos(
  387. all_bboxes[j]['bbox'], all_bboxes[k]['bbox']
  388. ),
  389. )
  390. )
  391. )
  392. if pos_flag_count > 1:
  393. continue
  394. if (
  395. all_bboxes[k]['category_id'] != object_category_id
  396. or k in used
  397. or k in seen
  398. or dis[j][k] == MAX_DIS_OF_POINT
  399. or dis[j][k] > dis[i][j]
  400. ):
  401. continue
  402. is_nearest = True
  403. for ni in range(i + 1, N):
  404. if ni in (j, k) or ni in used or ni in seen:
  405. continue
  406. if not float_gt(dis[ni][k], dis[j][k]):
  407. is_nearest = False
  408. break
  409. if is_nearest:
  410. nx0, ny0, nx1, ny1 = expand_bbbox(list(seen) + [k])
  411. n_dis = bbox_distance(
  412. all_bboxes[i]['bbox'], [nx0, ny0, nx1, ny1]
  413. )
  414. if float_gt(dis[i][j], n_dis):
  415. continue
  416. tmp.append(k)
  417. seen.add(k)
  418. candidates = tmp
  419. if len(candidates) == 0:
  420. break
  421. # 已经获取到某个 figure 下所有的最靠近的 captions,以及最靠近这些 captions 的 captions 。
  422. # 先扩一下 bbox,
  423. ox0, oy0, ox1, oy1 = expand_bbbox(list(seen) + [i])
  424. ix0, iy0, ix1, iy1 = all_bboxes[i]['bbox']
  425. # 分成了 4 个截取空间,需要计算落在每个截取空间下 objects 合并后占据的矩形面积
  426. caption_poses = [
  427. [ox0, oy0, ix0, oy1],
  428. [ox0, oy0, ox1, iy0],
  429. [ox0, iy1, ox1, oy1],
  430. [ix1, oy0, ox1, oy1],
  431. ]
  432. caption_areas = []
  433. for bbox in caption_poses:
  434. embed_arr = []
  435. for idx in seen:
  436. if (
  437. calculate_overlap_area_in_bbox1_area_ratio(
  438. all_bboxes[idx]['bbox'], bbox
  439. )
  440. > CAPATION_OVERLAP_AREA_RATIO
  441. ):
  442. embed_arr.append(idx)
  443. if len(embed_arr) > 0:
  444. embed_x0 = min([all_bboxes[idx]['bbox'][0] for idx in embed_arr])
  445. embed_y0 = min([all_bboxes[idx]['bbox'][1] for idx in embed_arr])
  446. embed_x1 = max([all_bboxes[idx]['bbox'][2] for idx in embed_arr])
  447. embed_y1 = max([all_bboxes[idx]['bbox'][3] for idx in embed_arr])
  448. caption_areas.append(
  449. int(abs(embed_x1 - embed_x0) * abs(embed_y1 - embed_y0))
  450. )
  451. else:
  452. caption_areas.append(0)
  453. subject_object_relation_map[i] = []
  454. if max(caption_areas) > 0:
  455. max_area_idx = caption_areas.index(max(caption_areas))
  456. caption_bbox = caption_poses[max_area_idx]
  457. for j in seen:
  458. if (
  459. calculate_overlap_area_in_bbox1_area_ratio(
  460. all_bboxes[j]['bbox'], caption_bbox
  461. )
  462. > CAPATION_OVERLAP_AREA_RATIO
  463. ):
  464. used.add(j)
  465. subject_object_relation_map[i].append(j)
  466. for i in sorted(subject_object_relation_map.keys()):
  467. result = {
  468. 'subject_body': all_bboxes[i]['bbox'],
  469. 'all': all_bboxes[i]['bbox'],
  470. 'score': all_bboxes[i]['score'],
  471. }
  472. if len(subject_object_relation_map[i]) > 0:
  473. x0 = min(
  474. [all_bboxes[j]['bbox'][0] for j in subject_object_relation_map[i]]
  475. )
  476. y0 = min(
  477. [all_bboxes[j]['bbox'][1] for j in subject_object_relation_map[i]]
  478. )
  479. x1 = max(
  480. [all_bboxes[j]['bbox'][2] for j in subject_object_relation_map[i]]
  481. )
  482. y1 = max(
  483. [all_bboxes[j]['bbox'][3] for j in subject_object_relation_map[i]]
  484. )
  485. result['object_body'] = [x0, y0, x1, y1]
  486. result['all'] = [
  487. min(x0, all_bboxes[i]['bbox'][0]),
  488. min(y0, all_bboxes[i]['bbox'][1]),
  489. max(x1, all_bboxes[i]['bbox'][2]),
  490. max(y1, all_bboxes[i]['bbox'][3]),
  491. ]
  492. ret.append(result)
  493. total_subject_object_dis = 0
  494. # 计算已经配对的 distance 距离
  495. for i in subject_object_relation_map.keys():
  496. for j in subject_object_relation_map[i]:
  497. total_subject_object_dis += bbox_distance(
  498. all_bboxes[i]['bbox'], all_bboxes[j]['bbox']
  499. )
  500. # 计算未匹配的 subject 和 object 的距离(非精确版)
  501. with_caption_subject = set(
  502. [
  503. key
  504. for key in subject_object_relation_map.keys()
  505. if len(subject_object_relation_map[i]) > 0
  506. ]
  507. )
  508. for i in range(N):
  509. if all_bboxes[i]['category_id'] != object_category_id or i in used:
  510. continue
  511. candidates = []
  512. for j in range(N):
  513. if (
  514. all_bboxes[j]['category_id'] != subject_category_id
  515. or j in with_caption_subject
  516. ):
  517. continue
  518. candidates.append((dis[i][j], j))
  519. if len(candidates) > 0:
  520. candidates.sort(key=lambda x: x[0])
  521. total_subject_object_dis += candidates[0][1]
  522. with_caption_subject.add(j)
  523. return ret, total_subject_object_dis
  524. def get_imgs(self, page_no: int):
  525. with_captions, _ = self.__tie_up_category_by_distance(page_no, 3, 4)
  526. with_footnotes, _ = self.__tie_up_category_by_distance(
  527. page_no, 3, CategoryId.ImageFootnote
  528. )
  529. ret = []
  530. N, M = len(with_captions), len(with_footnotes)
  531. assert N == M
  532. for i in range(N):
  533. record = {
  534. 'score': with_captions[i]['score'],
  535. 'img_caption_bbox': with_captions[i].get('object_body', None),
  536. 'img_body_bbox': with_captions[i]['subject_body'],
  537. 'img_footnote_bbox': with_footnotes[i].get('object_body', None),
  538. }
  539. x0 = min(with_captions[i]['all'][0], with_footnotes[i]['all'][0])
  540. y0 = min(with_captions[i]['all'][1], with_footnotes[i]['all'][1])
  541. x1 = max(with_captions[i]['all'][2], with_footnotes[i]['all'][2])
  542. y1 = max(with_captions[i]['all'][3], with_footnotes[i]['all'][3])
  543. record['bbox'] = [x0, y0, x1, y1]
  544. ret.append(record)
  545. return ret
  546. def get_tables(
  547. self, page_no: int
  548. ) -> list: # 3个坐标, caption, table主体,table-note
  549. with_captions, _ = self.__tie_up_category_by_distance(page_no, 5, 6)
  550. with_footnotes, _ = self.__tie_up_category_by_distance(page_no, 5, 7)
  551. ret = []
  552. N, M = len(with_captions), len(with_footnotes)
  553. assert N == M
  554. for i in range(N):
  555. record = {
  556. 'score': with_captions[i]['score'],
  557. 'table_caption_bbox': with_captions[i].get('object_body', None),
  558. 'table_body_bbox': with_captions[i]['subject_body'],
  559. 'table_footnote_bbox': with_footnotes[i].get('object_body', None),
  560. }
  561. x0 = min(with_captions[i]['all'][0], with_footnotes[i]['all'][0])
  562. y0 = min(with_captions[i]['all'][1], with_footnotes[i]['all'][1])
  563. x1 = max(with_captions[i]['all'][2], with_footnotes[i]['all'][2])
  564. y1 = max(with_captions[i]['all'][3], with_footnotes[i]['all'][3])
  565. record['bbox'] = [x0, y0, x1, y1]
  566. ret.append(record)
  567. return ret
  568. def get_equations(self, page_no: int) -> list: # 有坐标,也有字
  569. inline_equations = self.__get_blocks_by_type(
  570. ModelBlockTypeEnum.EMBEDDING.value, page_no, ['latex']
  571. )
  572. interline_equations = self.__get_blocks_by_type(
  573. ModelBlockTypeEnum.ISOLATED.value, page_no, ['latex']
  574. )
  575. interline_equations_blocks = self.__get_blocks_by_type(
  576. ModelBlockTypeEnum.ISOLATE_FORMULA.value, page_no
  577. )
  578. return inline_equations, interline_equations, interline_equations_blocks
  579. def get_discarded(self, page_no: int) -> list: # 自研模型,只有坐标
  580. blocks = self.__get_blocks_by_type(ModelBlockTypeEnum.ABANDON.value, page_no)
  581. return blocks
  582. def get_text_blocks(self, page_no: int) -> list: # 自研模型搞的,只有坐标,没有字
  583. blocks = self.__get_blocks_by_type(ModelBlockTypeEnum.PLAIN_TEXT.value, page_no)
  584. return blocks
  585. def get_title_blocks(self, page_no: int) -> list: # 自研模型,只有坐标,没字
  586. blocks = self.__get_blocks_by_type(ModelBlockTypeEnum.TITLE.value, page_no)
  587. return blocks
  588. def get_ocr_text(self, page_no: int) -> list: # paddle 搞的,有字也有坐标
  589. text_spans = []
  590. model_page_info = self.__model_list[page_no]
  591. layout_dets = model_page_info['layout_dets']
  592. for layout_det in layout_dets:
  593. if layout_det['category_id'] == '15':
  594. span = {
  595. 'bbox': layout_det['bbox'],
  596. 'content': layout_det['text'],
  597. }
  598. text_spans.append(span)
  599. return text_spans
  600. def get_all_spans(self, page_no: int) -> list:
  601. def remove_duplicate_spans(spans):
  602. new_spans = []
  603. for span in spans:
  604. if not any(span == existing_span for existing_span in new_spans):
  605. new_spans.append(span)
  606. return new_spans
  607. all_spans = []
  608. model_page_info = self.__model_list[page_no]
  609. layout_dets = model_page_info['layout_dets']
  610. allow_category_id_list = [3, 5, 13, 14, 15]
  611. """当成span拼接的"""
  612. # 3: 'image', # 图片
  613. # 5: 'table', # 表格
  614. # 13: 'inline_equation', # 行内公式
  615. # 14: 'interline_equation', # 行间公式
  616. # 15: 'text', # ocr识别文本
  617. for layout_det in layout_dets:
  618. category_id = layout_det['category_id']
  619. if category_id in allow_category_id_list:
  620. span = {'bbox': layout_det['bbox'], 'score': layout_det['score']}
  621. if category_id == 3:
  622. span['type'] = ContentType.Image
  623. elif category_id == 5:
  624. # 获取table模型结果
  625. latex = layout_det.get('latex', None)
  626. html = layout_det.get('html', None)
  627. if latex:
  628. span['latex'] = latex
  629. elif html:
  630. span['html'] = html
  631. span['type'] = ContentType.Table
  632. elif category_id == 13:
  633. span['content'] = layout_det['latex']
  634. span['type'] = ContentType.InlineEquation
  635. elif category_id == 14:
  636. span['content'] = layout_det['latex']
  637. span['type'] = ContentType.InterlineEquation
  638. elif category_id == 15:
  639. span['content'] = layout_det['text']
  640. span['type'] = ContentType.Text
  641. all_spans.append(span)
  642. return remove_duplicate_spans(all_spans)
  643. def get_page_size(self, page_no: int): # 获取页面宽高
  644. # 获取当前页的page对象
  645. page = self.__docs[page_no]
  646. # 获取当前页的宽高
  647. page_w = page.rect.width
  648. page_h = page.rect.height
  649. return page_w, page_h
  650. def __get_blocks_by_type(
  651. self, type: int, page_no: int, extra_col: list[str] = []
  652. ) -> list:
  653. blocks = []
  654. for page_dict in self.__model_list:
  655. layout_dets = page_dict.get('layout_dets', [])
  656. page_info = page_dict.get('page_info', {})
  657. page_number = page_info.get('page_no', -1)
  658. if page_no != page_number:
  659. continue
  660. for item in layout_dets:
  661. category_id = item.get('category_id', -1)
  662. bbox = item.get('bbox', None)
  663. if category_id == type:
  664. block = {
  665. 'bbox': bbox,
  666. 'score': item.get('score'),
  667. }
  668. for col in extra_col:
  669. block[col] = item.get(col, None)
  670. blocks.append(block)
  671. return blocks
  672. def get_model_list(self, page_no):
  673. return self.__model_list[page_no]
  674. if __name__ == '__main__':
  675. drw = DiskReaderWriter(r'D:/project/20231108code-clean')
  676. if 0:
  677. pdf_file_path = r'linshixuqiu\19983-00.pdf'
  678. model_file_path = r'linshixuqiu\19983-00_new.json'
  679. pdf_bytes = drw.read(pdf_file_path, AbsReaderWriter.MODE_BIN)
  680. model_json_txt = drw.read(model_file_path, AbsReaderWriter.MODE_TXT)
  681. model_list = json.loads(model_json_txt)
  682. write_path = r'D:\project\20231108code-clean\linshixuqiu\19983-00'
  683. img_bucket_path = 'imgs'
  684. img_writer = DiskReaderWriter(join_path(write_path, img_bucket_path))
  685. pdf_docs = fitz.open('pdf', pdf_bytes)
  686. magic_model = MagicModel(model_list, pdf_docs)
  687. if 1:
  688. model_list = json.loads(
  689. drw.read('/opt/data/pdf/20240418/j.chroma.2009.03.042.json')
  690. )
  691. pdf_bytes = drw.read(
  692. '/opt/data/pdf/20240418/j.chroma.2009.03.042.pdf', AbsReaderWriter.MODE_BIN
  693. )
  694. pdf_docs = fitz.open('pdf', pdf_bytes)
  695. magic_model = MagicModel(model_list, pdf_docs)
  696. for i in range(7):
  697. print(magic_model.get_imgs(i))