magic_model.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780
  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. minL, maxL = min(l1, l2), max(l1, l2)
  111. if (maxL - minL) / minL > 0.5:
  112. return float('inf')
  113. if bottom or top:
  114. l1 = bbox1[2] - bbox1[0]
  115. l2 = bbox2[2] - bbox2[0]
  116. minL, maxL = min(l1, l2), max(l1, l2)
  117. if (maxL - minL) / minL > 0.5:
  118. return float('inf')
  119. return bbox_distance(bbox1, bbox2)
  120. def __fix_footnote(self):
  121. # 3: figure, 5: table, 7: footnote
  122. for model_page_info in self.__model_list:
  123. footnotes = []
  124. figures = []
  125. tables = []
  126. for obj in model_page_info['layout_dets']:
  127. if obj['category_id'] == 7:
  128. footnotes.append(obj)
  129. elif obj['category_id'] == 3:
  130. figures.append(obj)
  131. elif obj['category_id'] == 5:
  132. tables.append(obj)
  133. if len(footnotes) * len(figures) == 0:
  134. continue
  135. dis_figure_footnote = {}
  136. dis_table_footnote = {}
  137. for i in range(len(footnotes)):
  138. for j in range(len(figures)):
  139. pos_flag_count = sum(
  140. list(
  141. map(
  142. lambda x: 1 if x else 0,
  143. bbox_relative_pos(
  144. footnotes[i]['bbox'], figures[j]['bbox']
  145. ),
  146. )
  147. )
  148. )
  149. if pos_flag_count > 1:
  150. continue
  151. dis_figure_footnote[i] = min(
  152. self._bbox_distance(figures[j]['bbox'], footnotes[i]['bbox']),
  153. dis_figure_footnote.get(i, float('inf')),
  154. )
  155. for i in range(len(footnotes)):
  156. for j in range(len(tables)):
  157. pos_flag_count = sum(
  158. list(
  159. map(
  160. lambda x: 1 if x else 0,
  161. bbox_relative_pos(
  162. footnotes[i]['bbox'], tables[j]['bbox']
  163. ),
  164. )
  165. )
  166. )
  167. if pos_flag_count > 1:
  168. continue
  169. dis_table_footnote[i] = min(
  170. self._bbox_distance(tables[j]['bbox'], footnotes[i]['bbox']),
  171. dis_table_footnote.get(i, float('inf')),
  172. )
  173. for i in range(len(footnotes)):
  174. if i not in dis_figure_footnote:
  175. continue
  176. if dis_table_footnote.get(i, float('inf')) > dis_figure_footnote[i]:
  177. footnotes[i]['category_id'] = CategoryId.ImageFootnote
  178. def __reduct_overlap(self, bboxes):
  179. N = len(bboxes)
  180. keep = [True] * N
  181. for i in range(N):
  182. for j in range(N):
  183. if i == j:
  184. continue
  185. if _is_in(bboxes[i]['bbox'], bboxes[j]['bbox']):
  186. keep[i] = False
  187. return [bboxes[i] for i in range(N) if keep[i]]
  188. def __tie_up_category_by_distance(
  189. self, page_no, subject_category_id, object_category_id
  190. ):
  191. """假定每个 subject 最多有一个 object (可以有多个相邻的 object 合并为单个 object),每个 object
  192. 只能属于一个 subject."""
  193. ret = []
  194. MAX_DIS_OF_POINT = 10**9 + 7
  195. """
  196. subject 和 object 的 bbox 会合并成一个大的 bbox (named: merged bbox)。
  197. 筛选出所有和 merged bbox 有 overlap 且 overlap 面积大于 object 的面积的 subjects。
  198. 再求出筛选出的 subjects 和 object 的最短距离
  199. """
  200. def search_overlap_between_boxes(
  201. subject_idx, object_idx
  202. ):
  203. idxes = [subject_idx, object_idx]
  204. x0s = [all_bboxes[idx]['bbox'][0] for idx in idxes]
  205. y0s = [all_bboxes[idx]['bbox'][1] for idx in idxes]
  206. x1s = [all_bboxes[idx]['bbox'][2] for idx in idxes]
  207. y1s = [all_bboxes[idx]['bbox'][3] for idx in idxes]
  208. merged_bbox = [
  209. min(x0s),
  210. min(y0s),
  211. max(x1s),
  212. max(y1s),
  213. ]
  214. ratio = 0
  215. other_objects = list(
  216. map(
  217. lambda x: {'bbox': x['bbox'], 'score': x['score']},
  218. filter(
  219. lambda x: x['category_id']
  220. not in (object_category_id, subject_category_id),
  221. self.__model_list[page_no]['layout_dets'],
  222. ),
  223. )
  224. )
  225. for other_object in other_objects:
  226. ratio = max(
  227. ratio,
  228. get_overlap_area(
  229. merged_bbox, other_object['bbox']
  230. ) * 1.0 / box_area(all_bboxes[object_idx]['bbox'])
  231. )
  232. if ratio >= MERGE_BOX_OVERLAP_AREA_RATIO:
  233. break
  234. return ratio
  235. def may_find_other_nearest_bbox(subject_idx, object_idx):
  236. ret = float('inf')
  237. x0 = min(
  238. all_bboxes[subject_idx]['bbox'][0], all_bboxes[object_idx]['bbox'][0]
  239. )
  240. y0 = min(
  241. all_bboxes[subject_idx]['bbox'][1], all_bboxes[object_idx]['bbox'][1]
  242. )
  243. x1 = max(
  244. all_bboxes[subject_idx]['bbox'][2], all_bboxes[object_idx]['bbox'][2]
  245. )
  246. y1 = max(
  247. all_bboxes[subject_idx]['bbox'][3], all_bboxes[object_idx]['bbox'][3]
  248. )
  249. object_area = abs(
  250. all_bboxes[object_idx]['bbox'][2] - all_bboxes[object_idx]['bbox'][0]
  251. ) * abs(
  252. all_bboxes[object_idx]['bbox'][3] - all_bboxes[object_idx]['bbox'][1]
  253. )
  254. for i in range(len(all_bboxes)):
  255. if (
  256. i == subject_idx
  257. or all_bboxes[i]['category_id'] != subject_category_id
  258. ):
  259. continue
  260. if _is_part_overlap([x0, y0, x1, y1], all_bboxes[i]['bbox']) or _is_in(
  261. all_bboxes[i]['bbox'], [x0, y0, x1, y1]
  262. ):
  263. i_area = abs(
  264. all_bboxes[i]['bbox'][2] - all_bboxes[i]['bbox'][0]
  265. ) * abs(all_bboxes[i]['bbox'][3] - all_bboxes[i]['bbox'][1])
  266. if i_area >= object_area:
  267. ret = min(float('inf'), dis[i][object_idx])
  268. return ret
  269. def expand_bbbox(idxes):
  270. x0s = [all_bboxes[idx]['bbox'][0] for idx in idxes]
  271. y0s = [all_bboxes[idx]['bbox'][1] for idx in idxes]
  272. x1s = [all_bboxes[idx]['bbox'][2] for idx in idxes]
  273. y1s = [all_bboxes[idx]['bbox'][3] for idx in idxes]
  274. return min(x0s), min(y0s), max(x1s), max(y1s)
  275. subjects = self.__reduct_overlap(
  276. list(
  277. map(
  278. lambda x: {'bbox': x['bbox'], 'score': x['score']},
  279. filter(
  280. lambda x: x['category_id'] == subject_category_id,
  281. self.__model_list[page_no]['layout_dets'],
  282. ),
  283. )
  284. )
  285. )
  286. objects = self.__reduct_overlap(
  287. list(
  288. map(
  289. lambda x: {'bbox': x['bbox'], 'score': x['score']},
  290. filter(
  291. lambda x: x['category_id'] == object_category_id,
  292. self.__model_list[page_no]['layout_dets'],
  293. ),
  294. )
  295. )
  296. )
  297. subject_object_relation_map = {}
  298. subjects.sort(
  299. key=lambda x: x['bbox'][0] ** 2 + x['bbox'][1] ** 2
  300. ) # get the distance !
  301. all_bboxes = []
  302. for v in subjects:
  303. all_bboxes.append(
  304. {
  305. 'category_id': subject_category_id,
  306. 'bbox': v['bbox'],
  307. 'score': v['score'],
  308. }
  309. )
  310. for v in objects:
  311. all_bboxes.append(
  312. {
  313. 'category_id': object_category_id,
  314. 'bbox': v['bbox'],
  315. 'score': v['score'],
  316. }
  317. )
  318. N = len(all_bboxes)
  319. dis = [[MAX_DIS_OF_POINT] * N for _ in range(N)]
  320. for i in range(N):
  321. for j in range(i):
  322. if (
  323. all_bboxes[i]['category_id'] == subject_category_id
  324. and all_bboxes[j]['category_id'] == subject_category_id
  325. ):
  326. continue
  327. subject_idx, object_idx = i, j
  328. if all_bboxes[j]['category_id'] == subject_category_id:
  329. subject_idx, object_idx = j, i
  330. if search_overlap_between_boxes(subject_idx, object_idx) >= MERGE_BOX_OVERLAP_AREA_RATIO:
  331. dis[i][j] = float('inf')
  332. dis[j][i] = dis[i][j]
  333. continue
  334. dis[i][j] = self._bbox_distance(all_bboxes[i]['bbox'], all_bboxes[j]['bbox'])
  335. dis[j][i] = dis[i][j]
  336. used = set()
  337. for i in range(N):
  338. # 求第 i 个 subject 所关联的 object
  339. if all_bboxes[i]['category_id'] != subject_category_id:
  340. continue
  341. seen = set()
  342. candidates = []
  343. arr = []
  344. for j in range(N):
  345. pos_flag_count = sum(
  346. list(
  347. map(
  348. lambda x: 1 if x else 0,
  349. bbox_relative_pos(
  350. all_bboxes[i]['bbox'], all_bboxes[j]['bbox']
  351. ),
  352. )
  353. )
  354. )
  355. if pos_flag_count > 1:
  356. continue
  357. if (
  358. all_bboxes[j]['category_id'] != object_category_id
  359. or j in used
  360. or dis[i][j] == MAX_DIS_OF_POINT
  361. ):
  362. continue
  363. left, right, _, _ = bbox_relative_pos(
  364. all_bboxes[i]['bbox'], all_bboxes[j]['bbox']
  365. ) # 由 pos_flag_count 相关逻辑保证本段逻辑准确性
  366. if left or right:
  367. one_way_dis = all_bboxes[i]['bbox'][2] - all_bboxes[i]['bbox'][0]
  368. else:
  369. one_way_dis = all_bboxes[i]['bbox'][3] - all_bboxes[i]['bbox'][1]
  370. if dis[i][j] > one_way_dis:
  371. continue
  372. arr.append((dis[i][j], j))
  373. arr.sort(key=lambda x: x[0])
  374. if len(arr) > 0:
  375. """
  376. bug: 离该subject 最近的 object 可能跨越了其它的 subject。
  377. 比如 [this subect] [some sbuject] [the nearest object of subject]
  378. """
  379. if may_find_other_nearest_bbox(i, arr[0][1]) >= arr[0][0]:
  380. candidates.append(arr[0][1])
  381. seen.add(arr[0][1])
  382. # 已经获取初始种子
  383. for j in set(candidates):
  384. tmp = []
  385. for k in range(i + 1, N):
  386. pos_flag_count = sum(
  387. list(
  388. map(
  389. lambda x: 1 if x else 0,
  390. bbox_relative_pos(
  391. all_bboxes[j]['bbox'], all_bboxes[k]['bbox']
  392. ),
  393. )
  394. )
  395. )
  396. if pos_flag_count > 1:
  397. continue
  398. if (
  399. all_bboxes[k]['category_id'] != object_category_id
  400. or k in used
  401. or k in seen
  402. or dis[j][k] == MAX_DIS_OF_POINT
  403. or dis[j][k] > dis[i][j]
  404. ):
  405. continue
  406. is_nearest = True
  407. for ni in range(i + 1, N):
  408. if ni in (j, k) or ni in used or ni in seen:
  409. continue
  410. if not float_gt(dis[ni][k], dis[j][k]):
  411. is_nearest = False
  412. break
  413. if is_nearest:
  414. nx0, ny0, nx1, ny1 = expand_bbbox(list(seen) + [k])
  415. n_dis = self._bbox_distance(
  416. all_bboxes[i]['bbox'], [nx0, ny0, nx1, ny1]
  417. )
  418. if float_gt(dis[i][j], n_dis):
  419. continue
  420. tmp.append(k)
  421. seen.add(k)
  422. candidates = tmp
  423. if len(candidates) == 0:
  424. break
  425. # 已经获取到某个 figure 下所有的最靠近的 captions,以及最靠近这些 captions 的 captions 。
  426. # 先扩一下 bbox,
  427. ox0, oy0, ox1, oy1 = expand_bbbox(list(seen) + [i])
  428. ix0, iy0, ix1, iy1 = all_bboxes[i]['bbox']
  429. # 分成了 4 个截取空间,需要计算落在每个截取空间下 objects 合并后占据的矩形面积
  430. caption_poses = [
  431. [ox0, oy0, ix0, oy1],
  432. [ox0, oy0, ox1, iy0],
  433. [ox0, iy1, ox1, oy1],
  434. [ix1, oy0, ox1, oy1],
  435. ]
  436. caption_areas = []
  437. for bbox in caption_poses:
  438. embed_arr = []
  439. for idx in seen:
  440. if (
  441. calculate_overlap_area_in_bbox1_area_ratio(
  442. all_bboxes[idx]['bbox'], bbox
  443. )
  444. > CAPATION_OVERLAP_AREA_RATIO
  445. ):
  446. embed_arr.append(idx)
  447. if len(embed_arr) > 0:
  448. embed_x0 = min([all_bboxes[idx]['bbox'][0] for idx in embed_arr])
  449. embed_y0 = min([all_bboxes[idx]['bbox'][1] for idx in embed_arr])
  450. embed_x1 = max([all_bboxes[idx]['bbox'][2] for idx in embed_arr])
  451. embed_y1 = max([all_bboxes[idx]['bbox'][3] for idx in embed_arr])
  452. caption_areas.append(
  453. int(abs(embed_x1 - embed_x0) * abs(embed_y1 - embed_y0))
  454. )
  455. else:
  456. caption_areas.append(0)
  457. subject_object_relation_map[i] = []
  458. if max(caption_areas) > 0:
  459. max_area_idx = caption_areas.index(max(caption_areas))
  460. caption_bbox = caption_poses[max_area_idx]
  461. for j in seen:
  462. if (
  463. calculate_overlap_area_in_bbox1_area_ratio(
  464. all_bboxes[j]['bbox'], caption_bbox
  465. )
  466. > CAPATION_OVERLAP_AREA_RATIO
  467. ):
  468. used.add(j)
  469. subject_object_relation_map[i].append(j)
  470. for i in sorted(subject_object_relation_map.keys()):
  471. result = {
  472. 'subject_body': all_bboxes[i]['bbox'],
  473. 'all': all_bboxes[i]['bbox'],
  474. 'score': all_bboxes[i]['score'],
  475. }
  476. if len(subject_object_relation_map[i]) > 0:
  477. x0 = min(
  478. [all_bboxes[j]['bbox'][0] for j in subject_object_relation_map[i]]
  479. )
  480. y0 = min(
  481. [all_bboxes[j]['bbox'][1] for j in subject_object_relation_map[i]]
  482. )
  483. x1 = max(
  484. [all_bboxes[j]['bbox'][2] for j in subject_object_relation_map[i]]
  485. )
  486. y1 = max(
  487. [all_bboxes[j]['bbox'][3] for j in subject_object_relation_map[i]]
  488. )
  489. result['object_body'] = [x0, y0, x1, y1]
  490. result['all'] = [
  491. min(x0, all_bboxes[i]['bbox'][0]),
  492. min(y0, all_bboxes[i]['bbox'][1]),
  493. max(x1, all_bboxes[i]['bbox'][2]),
  494. max(y1, all_bboxes[i]['bbox'][3]),
  495. ]
  496. ret.append(result)
  497. total_subject_object_dis = 0
  498. # 计算已经配对的 distance 距离
  499. for i in subject_object_relation_map.keys():
  500. for j in subject_object_relation_map[i]:
  501. total_subject_object_dis += self._bbox_distance(
  502. all_bboxes[i]['bbox'], all_bboxes[j]['bbox']
  503. )
  504. # 计算未匹配的 subject 和 object 的距离(非精确版)
  505. with_caption_subject = set(
  506. [
  507. key
  508. for key in subject_object_relation_map.keys()
  509. if len(subject_object_relation_map[i]) > 0
  510. ]
  511. )
  512. for i in range(N):
  513. if all_bboxes[i]['category_id'] != object_category_id or i in used:
  514. continue
  515. candidates = []
  516. for j in range(N):
  517. if (
  518. all_bboxes[j]['category_id'] != subject_category_id
  519. or j in with_caption_subject
  520. ):
  521. continue
  522. candidates.append((dis[i][j], j))
  523. if len(candidates) > 0:
  524. candidates.sort(key=lambda x: x[0])
  525. total_subject_object_dis += candidates[0][1]
  526. with_caption_subject.add(j)
  527. return ret, total_subject_object_dis
  528. def get_imgs(self, page_no: int):
  529. with_captions, _ = self.__tie_up_category_by_distance(page_no, 3, 4)
  530. with_footnotes, _ = self.__tie_up_category_by_distance(
  531. page_no, 3, CategoryId.ImageFootnote
  532. )
  533. ret = []
  534. N, M = len(with_captions), len(with_footnotes)
  535. assert N == M
  536. for i in range(N):
  537. record = {
  538. 'score': with_captions[i]['score'],
  539. 'img_caption_bbox': with_captions[i].get('object_body', None),
  540. 'img_body_bbox': with_captions[i]['subject_body'],
  541. 'img_footnote_bbox': with_footnotes[i].get('object_body', None),
  542. }
  543. x0 = min(with_captions[i]['all'][0], with_footnotes[i]['all'][0])
  544. y0 = min(with_captions[i]['all'][1], with_footnotes[i]['all'][1])
  545. x1 = max(with_captions[i]['all'][2], with_footnotes[i]['all'][2])
  546. y1 = max(with_captions[i]['all'][3], with_footnotes[i]['all'][3])
  547. record['bbox'] = [x0, y0, x1, y1]
  548. ret.append(record)
  549. return ret
  550. def get_tables(
  551. self, page_no: int
  552. ) -> list: # 3个坐标, caption, table主体,table-note
  553. with_captions, _ = self.__tie_up_category_by_distance(page_no, 5, 6)
  554. with_footnotes, _ = self.__tie_up_category_by_distance(page_no, 5, 7)
  555. ret = []
  556. N, M = len(with_captions), len(with_footnotes)
  557. assert N == M
  558. for i in range(N):
  559. record = {
  560. 'score': with_captions[i]['score'],
  561. 'table_caption_bbox': with_captions[i].get('object_body', None),
  562. 'table_body_bbox': with_captions[i]['subject_body'],
  563. 'table_footnote_bbox': with_footnotes[i].get('object_body', None),
  564. }
  565. x0 = min(with_captions[i]['all'][0], with_footnotes[i]['all'][0])
  566. y0 = min(with_captions[i]['all'][1], with_footnotes[i]['all'][1])
  567. x1 = max(with_captions[i]['all'][2], with_footnotes[i]['all'][2])
  568. y1 = max(with_captions[i]['all'][3], with_footnotes[i]['all'][3])
  569. record['bbox'] = [x0, y0, x1, y1]
  570. ret.append(record)
  571. return ret
  572. def get_equations(self, page_no: int) -> list: # 有坐标,也有字
  573. inline_equations = self.__get_blocks_by_type(
  574. ModelBlockTypeEnum.EMBEDDING.value, page_no, ['latex']
  575. )
  576. interline_equations = self.__get_blocks_by_type(
  577. ModelBlockTypeEnum.ISOLATED.value, page_no, ['latex']
  578. )
  579. interline_equations_blocks = self.__get_blocks_by_type(
  580. ModelBlockTypeEnum.ISOLATE_FORMULA.value, page_no
  581. )
  582. return inline_equations, interline_equations, interline_equations_blocks
  583. def get_discarded(self, page_no: int) -> list: # 自研模型,只有坐标
  584. blocks = self.__get_blocks_by_type(ModelBlockTypeEnum.ABANDON.value, page_no)
  585. return blocks
  586. def get_text_blocks(self, page_no: int) -> list: # 自研模型搞的,只有坐标,没有字
  587. blocks = self.__get_blocks_by_type(ModelBlockTypeEnum.PLAIN_TEXT.value, page_no)
  588. return blocks
  589. def get_title_blocks(self, page_no: int) -> list: # 自研模型,只有坐标,没字
  590. blocks = self.__get_blocks_by_type(ModelBlockTypeEnum.TITLE.value, page_no)
  591. return blocks
  592. def get_ocr_text(self, page_no: int) -> list: # paddle 搞的,有字也有坐标
  593. text_spans = []
  594. model_page_info = self.__model_list[page_no]
  595. layout_dets = model_page_info['layout_dets']
  596. for layout_det in layout_dets:
  597. if layout_det['category_id'] == '15':
  598. span = {
  599. 'bbox': layout_det['bbox'],
  600. 'content': layout_det['text'],
  601. }
  602. text_spans.append(span)
  603. return text_spans
  604. def get_all_spans(self, page_no: int) -> list:
  605. def remove_duplicate_spans(spans):
  606. new_spans = []
  607. for span in spans:
  608. if not any(span == existing_span for existing_span in new_spans):
  609. new_spans.append(span)
  610. return new_spans
  611. all_spans = []
  612. model_page_info = self.__model_list[page_no]
  613. layout_dets = model_page_info['layout_dets']
  614. allow_category_id_list = [3, 5, 13, 14, 15]
  615. """当成span拼接的"""
  616. # 3: 'image', # 图片
  617. # 5: 'table', # 表格
  618. # 13: 'inline_equation', # 行内公式
  619. # 14: 'interline_equation', # 行间公式
  620. # 15: 'text', # ocr识别文本
  621. for layout_det in layout_dets:
  622. category_id = layout_det['category_id']
  623. if category_id in allow_category_id_list:
  624. span = {'bbox': layout_det['bbox'], 'score': layout_det['score']}
  625. if category_id == 3:
  626. span['type'] = ContentType.Image
  627. elif category_id == 5:
  628. # 获取table模型结果
  629. latex = layout_det.get('latex', None)
  630. html = layout_det.get('html', None)
  631. if latex:
  632. span['latex'] = latex
  633. elif html:
  634. span['html'] = html
  635. span['type'] = ContentType.Table
  636. elif category_id == 13:
  637. span['content'] = layout_det['latex']
  638. span['type'] = ContentType.InlineEquation
  639. elif category_id == 14:
  640. span['content'] = layout_det['latex']
  641. span['type'] = ContentType.InterlineEquation
  642. elif category_id == 15:
  643. span['content'] = layout_det['text']
  644. span['type'] = ContentType.Text
  645. all_spans.append(span)
  646. return remove_duplicate_spans(all_spans)
  647. def get_page_size(self, page_no: int): # 获取页面宽高
  648. # 获取当前页的page对象
  649. page = self.__docs[page_no]
  650. # 获取当前页的宽高
  651. page_w = page.rect.width
  652. page_h = page.rect.height
  653. return page_w, page_h
  654. def __get_blocks_by_type(
  655. self, type: int, page_no: int, extra_col: list[str] = []
  656. ) -> list:
  657. blocks = []
  658. for page_dict in self.__model_list:
  659. layout_dets = page_dict.get('layout_dets', [])
  660. page_info = page_dict.get('page_info', {})
  661. page_number = page_info.get('page_no', -1)
  662. if page_no != page_number:
  663. continue
  664. for item in layout_dets:
  665. category_id = item.get('category_id', -1)
  666. bbox = item.get('bbox', None)
  667. if category_id == type:
  668. block = {
  669. 'bbox': bbox,
  670. 'score': item.get('score'),
  671. }
  672. for col in extra_col:
  673. block[col] = item.get(col, None)
  674. blocks.append(block)
  675. return blocks
  676. def get_model_list(self, page_no):
  677. return self.__model_list[page_no]
  678. if __name__ == '__main__':
  679. drw = DiskReaderWriter(r'D:/project/20231108code-clean')
  680. if 0:
  681. pdf_file_path = r'linshixuqiu\19983-00.pdf'
  682. model_file_path = r'linshixuqiu\19983-00_new.json'
  683. pdf_bytes = drw.read(pdf_file_path, AbsReaderWriter.MODE_BIN)
  684. model_json_txt = drw.read(model_file_path, AbsReaderWriter.MODE_TXT)
  685. model_list = json.loads(model_json_txt)
  686. write_path = r'D:\project\20231108code-clean\linshixuqiu\19983-00'
  687. img_bucket_path = 'imgs'
  688. img_writer = DiskReaderWriter(join_path(write_path, img_bucket_path))
  689. pdf_docs = fitz.open('pdf', pdf_bytes)
  690. magic_model = MagicModel(model_list, pdf_docs)
  691. if 1:
  692. model_list = json.loads(
  693. drw.read('/opt/data/pdf/20240418/j.chroma.2009.03.042.json')
  694. )
  695. pdf_bytes = drw.read(
  696. '/opt/data/pdf/20240418/j.chroma.2009.03.042.pdf', AbsReaderWriter.MODE_BIN
  697. )
  698. pdf_docs = fitz.open('pdf', pdf_bytes)
  699. magic_model = MagicModel(model_list, pdf_docs)
  700. for i in range(7):
  701. print(magic_model.get_imgs(i))