magic_model.py 30 KB

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