magic_model.py 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023
  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.pre_proc.remove_bbox_overlap import _remove_overlap_between_bbox
  13. from magic_pdf.rw.AbsReaderWriter import AbsReaderWriter
  14. from magic_pdf.rw.DiskReaderWriter import DiskReaderWriter
  15. CAPATION_OVERLAP_AREA_RATIO = 0.6
  16. MERGE_BOX_OVERLAP_AREA_RATIO = 1.1
  17. class MagicModel:
  18. """每个函数没有得到元素的时候返回空list."""
  19. def __fix_axis(self):
  20. for model_page_info in self.__model_list:
  21. need_remove_list = []
  22. page_no = model_page_info['page_info']['page_no']
  23. horizontal_scale_ratio, vertical_scale_ratio = get_scale_ratio(
  24. model_page_info, self.__docs.get_page(page_no)
  25. )
  26. layout_dets = model_page_info['layout_dets']
  27. for layout_det in layout_dets:
  28. if layout_det.get('bbox') is not None:
  29. # 兼容直接输出bbox的模型数据,如paddle
  30. x0, y0, x1, y1 = layout_det['bbox']
  31. else:
  32. # 兼容直接输出poly的模型数据,如xxx
  33. x0, y0, _, _, x1, y1, _, _ = layout_det['poly']
  34. bbox = [
  35. int(x0 / horizontal_scale_ratio),
  36. int(y0 / vertical_scale_ratio),
  37. int(x1 / horizontal_scale_ratio),
  38. int(y1 / vertical_scale_ratio),
  39. ]
  40. layout_det['bbox'] = bbox
  41. # 删除高度或者宽度小于等于0的spans
  42. if bbox[2] - bbox[0] <= 0 or bbox[3] - bbox[1] <= 0:
  43. need_remove_list.append(layout_det)
  44. for need_remove in need_remove_list:
  45. layout_dets.remove(need_remove)
  46. def __fix_by_remove_low_confidence(self):
  47. for model_page_info in self.__model_list:
  48. need_remove_list = []
  49. layout_dets = model_page_info['layout_dets']
  50. for layout_det in layout_dets:
  51. if layout_det['score'] <= 0.05:
  52. need_remove_list.append(layout_det)
  53. else:
  54. continue
  55. for need_remove in need_remove_list:
  56. layout_dets.remove(need_remove)
  57. def __fix_by_remove_high_iou_and_low_confidence(self):
  58. for model_page_info in self.__model_list:
  59. need_remove_list = []
  60. layout_dets = model_page_info['layout_dets']
  61. for layout_det1 in layout_dets:
  62. for layout_det2 in layout_dets:
  63. if layout_det1 == layout_det2:
  64. continue
  65. if layout_det1['category_id'] in [
  66. 0,
  67. 1,
  68. 2,
  69. 3,
  70. 4,
  71. 5,
  72. 6,
  73. 7,
  74. 8,
  75. 9,
  76. ] and layout_det2['category_id'] in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]:
  77. if (
  78. calculate_iou(layout_det1['bbox'], layout_det2['bbox'])
  79. > 0.9
  80. ):
  81. if layout_det1['score'] < layout_det2['score']:
  82. layout_det_need_remove = layout_det1
  83. else:
  84. layout_det_need_remove = layout_det2
  85. if layout_det_need_remove not in need_remove_list:
  86. need_remove_list.append(layout_det_need_remove)
  87. else:
  88. continue
  89. else:
  90. continue
  91. for need_remove in need_remove_list:
  92. layout_dets.remove(need_remove)
  93. def __init__(self, model_list: list, docs: Dataset):
  94. self.__model_list = model_list
  95. self.__docs = docs
  96. """为所有模型数据添加bbox信息(缩放,poly->bbox)"""
  97. self.__fix_axis()
  98. """删除置信度特别低的模型数据(<0.05),提高质量"""
  99. self.__fix_by_remove_low_confidence()
  100. """删除高iou(>0.9)数据中置信度较低的那个"""
  101. self.__fix_by_remove_high_iou_and_low_confidence()
  102. self.__fix_footnote()
  103. def _bbox_distance(self, bbox1, bbox2):
  104. left, right, bottom, top = bbox_relative_pos(bbox1, bbox2)
  105. flags = [left, right, bottom, top]
  106. count = sum([1 if v else 0 for v in flags])
  107. if count > 1:
  108. return float('inf')
  109. if left or right:
  110. l1 = bbox1[3] - bbox1[1]
  111. l2 = bbox2[3] - bbox2[1]
  112. else:
  113. l1 = bbox1[2] - bbox1[0]
  114. l2 = bbox2[2] - bbox2[0]
  115. if l2 > l1 and (l2 - l1) / l1 > 0.3:
  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. AXIS_MULPLICITY = 0.5
  533. subjects = self.__reduct_overlap(
  534. list(
  535. map(
  536. lambda x: {'bbox': x['bbox'], 'score': x['score']},
  537. filter(
  538. lambda x: x['category_id'] == subject_category_id,
  539. self.__model_list[page_no]['layout_dets'],
  540. ),
  541. )
  542. )
  543. )
  544. objects = self.__reduct_overlap(
  545. list(
  546. map(
  547. lambda x: {'bbox': x['bbox'], 'score': x['score']},
  548. filter(
  549. lambda x: x['category_id'] == object_category_id,
  550. self.__model_list[page_no]['layout_dets'],
  551. ),
  552. )
  553. )
  554. )
  555. M = len(objects)
  556. subjects.sort(key=lambda x: x['bbox'][0] ** 2 + x['bbox'][1] ** 2)
  557. objects.sort(key=lambda x: x['bbox'][0] ** 2 + x['bbox'][1] ** 2)
  558. sub_obj_map_h = {i: [] for i in range(len(subjects))}
  559. dis_by_directions = {
  560. 'top': [[-1, float('inf')]] * M,
  561. 'bottom': [[-1, float('inf')]] * M,
  562. 'left': [[-1, float('inf')]] * M,
  563. 'right': [[-1, float('inf')]] * M,
  564. }
  565. for i, obj in enumerate(objects):
  566. l_x_axis, l_y_axis = (
  567. obj['bbox'][2] - obj['bbox'][0],
  568. obj['bbox'][3] - obj['bbox'][1],
  569. )
  570. axis_unit = min(l_x_axis, l_y_axis)
  571. for j, sub in enumerate(subjects):
  572. bbox1, bbox2, _ = _remove_overlap_between_bbox(
  573. objects[i]['bbox'], subjects[j]['bbox']
  574. )
  575. left, right, bottom, top = bbox_relative_pos(bbox1, bbox2)
  576. flags = [left, right, bottom, top]
  577. if sum([1 if v else 0 for v in flags]) > 1:
  578. continue
  579. if left:
  580. if dis_by_directions['left'][i][1] > bbox_distance(
  581. obj['bbox'], sub['bbox']
  582. ):
  583. dis_by_directions['left'][i] = [
  584. j,
  585. bbox_distance(obj['bbox'], sub['bbox']),
  586. ]
  587. if right:
  588. if dis_by_directions['right'][i][1] > bbox_distance(
  589. obj['bbox'], sub['bbox']
  590. ):
  591. dis_by_directions['right'][i] = [
  592. j,
  593. bbox_distance(obj['bbox'], sub['bbox']),
  594. ]
  595. if bottom:
  596. if dis_by_directions['bottom'][i][1] > bbox_distance(
  597. obj['bbox'], sub['bbox']
  598. ):
  599. dis_by_directions['bottom'][i] = [
  600. j,
  601. bbox_distance(obj['bbox'], sub['bbox']),
  602. ]
  603. if top:
  604. if dis_by_directions['top'][i][1] > bbox_distance(
  605. obj['bbox'], sub['bbox']
  606. ):
  607. dis_by_directions['top'][i] = [
  608. j,
  609. bbox_distance(obj['bbox'], sub['bbox']),
  610. ]
  611. if dis_by_directions['left'][i][1] != float('inf') or dis_by_directions[
  612. 'right'
  613. ][i][1] != float('inf'):
  614. if dis_by_directions['left'][i][1] != float(
  615. 'inf'
  616. ) and dis_by_directions['right'][i][1] != float('inf'):
  617. if AXIS_MULPLICITY * axis_unit >= abs(
  618. dis_by_directions['left'][i][1]
  619. - dis_by_directions['right'][i][1]
  620. ):
  621. left_sub_bbox = subjects[dis_by_directions['left'][i][0]][
  622. 'bbox'
  623. ]
  624. right_sub_bbox = subjects[dis_by_directions['right'][i][0]][
  625. 'bbox'
  626. ]
  627. left_sub_bbox_y_axis = left_sub_bbox[3] - left_sub_bbox[1]
  628. right_sub_bbox_y_axis = right_sub_bbox[3] - right_sub_bbox[1]
  629. if (
  630. abs(left_sub_bbox_y_axis - l_y_axis)
  631. + dis_by_directions['left'][i][0]
  632. > abs(right_sub_bbox_y_axis - l_y_axis)
  633. + dis_by_directions['right'][i][0]
  634. ):
  635. left_or_right = dis_by_directions['right'][i]
  636. else:
  637. left_or_right = dis_by_directions['left'][i]
  638. else:
  639. left_or_right = dis_by_directions['left'][i]
  640. if left_or_right[1] > dis_by_directions['right'][i][1]:
  641. left_or_right = dis_by_directions['right'][i]
  642. else:
  643. left_or_right = dis_by_directions['left'][i]
  644. if left_or_right[1] == float('inf'):
  645. left_or_right = dis_by_directions['right'][i]
  646. else:
  647. left_or_right = [-1, float('inf')]
  648. if dis_by_directions['top'][i][1] != float('inf') or dis_by_directions[
  649. 'bottom'
  650. ][i][1] != float('inf'):
  651. if dis_by_directions['top'][i][1] != float('inf') and dis_by_directions[
  652. 'bottom'
  653. ][i][1] != float('inf'):
  654. if AXIS_MULPLICITY * axis_unit >= abs(
  655. dis_by_directions['top'][i][1]
  656. - dis_by_directions['bottom'][i][1]
  657. ):
  658. top_bottom = subjects[dis_by_directions['bottom'][i][0]]['bbox']
  659. bottom_top = subjects[dis_by_directions['top'][i][0]]['bbox']
  660. top_bottom_x_axis = top_bottom[2] - top_bottom[0]
  661. bottom_top_x_axis = bottom_top[2] - bottom_top[0]
  662. if abs(top_bottom_x_axis - l_x_axis) + dis_by_directions['bottom'][i][1] > abs(
  663. bottom_top_x_axis - l_x_axis
  664. ) + dis_by_directions['top'][i][1]:
  665. top_or_bottom = dis_by_directions['top'][i]
  666. else:
  667. top_or_bottom = dis_by_directions['bottom'][i]
  668. else:
  669. top_or_bottom = dis_by_directions['top'][i]
  670. if top_or_bottom[1] > dis_by_directions['bottom'][i][1]:
  671. top_or_bottom = dis_by_directions['bottom'][i]
  672. else:
  673. top_or_bottom = dis_by_directions['top'][i]
  674. if top_or_bottom[1] == float('inf'):
  675. top_or_bottom = dis_by_directions['bottom'][i]
  676. else:
  677. top_or_bottom = [-1, float('inf')]
  678. if left_or_right[1] != float('inf') or top_or_bottom[1] != float('inf'):
  679. if left_or_right[1] != float('inf') and top_or_bottom[1] != float(
  680. 'inf'
  681. ):
  682. if AXIS_MULPLICITY * axis_unit >= abs(
  683. left_or_right[1] - top_or_bottom[1]
  684. ):
  685. y_axis_bbox = subjects[left_or_right[0]]['bbox']
  686. x_axis_bbox = subjects[top_or_bottom[0]]['bbox']
  687. if (
  688. abs((x_axis_bbox[2] - x_axis_bbox[0]) - l_x_axis) / l_x_axis
  689. > abs((y_axis_bbox[3] - y_axis_bbox[1]) - l_y_axis)
  690. / l_y_axis
  691. ):
  692. sub_obj_map_h[left_or_right[0]].append(i)
  693. else:
  694. sub_obj_map_h[top_or_bottom[0]].append(i)
  695. else:
  696. if left_or_right[1] > top_or_bottom[1]:
  697. sub_obj_map_h[top_or_bottom[0]].append(i)
  698. else:
  699. sub_obj_map_h[left_or_right[0]].append(i)
  700. else:
  701. if left_or_right[1] != float('inf'):
  702. sub_obj_map_h[left_or_right[0]].append(i)
  703. else:
  704. sub_obj_map_h[top_or_bottom[0]].append(i)
  705. ret = []
  706. for i in sub_obj_map_h.keys():
  707. ret.append(
  708. {
  709. 'sub_bbox': {
  710. 'bbox': subjects[i]['bbox'],
  711. 'score': subjects[i]['score'],
  712. },
  713. 'obj_bboxes': [
  714. {'score': objects[j]['score'], 'bbox': objects[j]['bbox']}
  715. for j in sub_obj_map_h[i]
  716. ],
  717. 'sub_idx': i,
  718. }
  719. )
  720. return ret
  721. def get_imgs_v2(self, page_no: int):
  722. with_captions = self.__tie_up_category_by_distance_v2(page_no, 3, 4)
  723. with_footnotes = self.__tie_up_category_by_distance_v2(
  724. page_no, 3, CategoryId.ImageFootnote
  725. )
  726. ret = []
  727. for v in with_captions:
  728. record = {
  729. 'image_body': v['sub_bbox'],
  730. 'image_caption_list': v['obj_bboxes'],
  731. }
  732. filter_idx = v['sub_idx']
  733. d = next(filter(lambda x: x['sub_idx'] == filter_idx, with_footnotes))
  734. record['image_footnote_list'] = d['obj_bboxes']
  735. ret.append(record)
  736. return ret
  737. def get_tables_v2(self, page_no: int) -> list:
  738. with_captions = self.__tie_up_category_by_distance_v2(page_no, 5, 6)
  739. with_footnotes = self.__tie_up_category_by_distance_v2(page_no, 5, 7)
  740. ret = []
  741. for v in with_captions:
  742. record = {
  743. 'table_body': v['sub_bbox'],
  744. 'table_caption_list': v['obj_bboxes'],
  745. }
  746. filter_idx = v['sub_idx']
  747. d = next(filter(lambda x: x['sub_idx'] == filter_idx, with_footnotes))
  748. record['table_footnote_list'] = d['obj_bboxes']
  749. ret.append(record)
  750. return ret
  751. def get_imgs(self, page_no: int):
  752. with_captions, _ = self.__tie_up_category_by_distance(page_no, 3, 4)
  753. with_footnotes, _ = self.__tie_up_category_by_distance(
  754. page_no, 3, CategoryId.ImageFootnote
  755. )
  756. ret = []
  757. N, M = len(with_captions), len(with_footnotes)
  758. assert N == M
  759. for i in range(N):
  760. record = {
  761. 'score': with_captions[i]['score'],
  762. 'img_caption_bbox': with_captions[i].get('object_body', None),
  763. 'img_body_bbox': with_captions[i]['subject_body'],
  764. 'img_footnote_bbox': with_footnotes[i].get('object_body', None),
  765. }
  766. x0 = min(with_captions[i]['all'][0], with_footnotes[i]['all'][0])
  767. y0 = min(with_captions[i]['all'][1], with_footnotes[i]['all'][1])
  768. x1 = max(with_captions[i]['all'][2], with_footnotes[i]['all'][2])
  769. y1 = max(with_captions[i]['all'][3], with_footnotes[i]['all'][3])
  770. record['bbox'] = [x0, y0, x1, y1]
  771. ret.append(record)
  772. return ret
  773. def get_tables(
  774. self, page_no: int
  775. ) -> list: # 3个坐标, caption, table主体,table-note
  776. with_captions, _ = self.__tie_up_category_by_distance(page_no, 5, 6)
  777. with_footnotes, _ = self.__tie_up_category_by_distance(page_no, 5, 7)
  778. ret = []
  779. N, M = len(with_captions), len(with_footnotes)
  780. assert N == M
  781. for i in range(N):
  782. record = {
  783. 'score': with_captions[i]['score'],
  784. 'table_caption_bbox': with_captions[i].get('object_body', None),
  785. 'table_body_bbox': with_captions[i]['subject_body'],
  786. 'table_footnote_bbox': with_footnotes[i].get('object_body', None),
  787. }
  788. x0 = min(with_captions[i]['all'][0], with_footnotes[i]['all'][0])
  789. y0 = min(with_captions[i]['all'][1], with_footnotes[i]['all'][1])
  790. x1 = max(with_captions[i]['all'][2], with_footnotes[i]['all'][2])
  791. y1 = max(with_captions[i]['all'][3], with_footnotes[i]['all'][3])
  792. record['bbox'] = [x0, y0, x1, y1]
  793. ret.append(record)
  794. return ret
  795. def get_equations(self, page_no: int) -> list: # 有坐标,也有字
  796. inline_equations = self.__get_blocks_by_type(
  797. ModelBlockTypeEnum.EMBEDDING.value, page_no, ['latex']
  798. )
  799. interline_equations = self.__get_blocks_by_type(
  800. ModelBlockTypeEnum.ISOLATED.value, page_no, ['latex']
  801. )
  802. interline_equations_blocks = self.__get_blocks_by_type(
  803. ModelBlockTypeEnum.ISOLATE_FORMULA.value, page_no
  804. )
  805. return inline_equations, interline_equations, interline_equations_blocks
  806. def get_discarded(self, page_no: int) -> list: # 自研模型,只有坐标
  807. blocks = self.__get_blocks_by_type(ModelBlockTypeEnum.ABANDON.value, page_no)
  808. return blocks
  809. def get_text_blocks(self, page_no: int) -> list: # 自研模型搞的,只有坐标,没有字
  810. blocks = self.__get_blocks_by_type(ModelBlockTypeEnum.PLAIN_TEXT.value, page_no)
  811. return blocks
  812. def get_title_blocks(self, page_no: int) -> list: # 自研模型,只有坐标,没字
  813. blocks = self.__get_blocks_by_type(ModelBlockTypeEnum.TITLE.value, page_no)
  814. return blocks
  815. def get_ocr_text(self, page_no: int) -> list: # paddle 搞的,有字也有坐标
  816. text_spans = []
  817. model_page_info = self.__model_list[page_no]
  818. layout_dets = model_page_info['layout_dets']
  819. for layout_det in layout_dets:
  820. if layout_det['category_id'] == '15':
  821. span = {
  822. 'bbox': layout_det['bbox'],
  823. 'content': layout_det['text'],
  824. }
  825. text_spans.append(span)
  826. return text_spans
  827. def get_all_spans(self, page_no: int) -> list:
  828. def remove_duplicate_spans(spans):
  829. new_spans = []
  830. for span in spans:
  831. if not any(span == existing_span for existing_span in new_spans):
  832. new_spans.append(span)
  833. return new_spans
  834. all_spans = []
  835. model_page_info = self.__model_list[page_no]
  836. layout_dets = model_page_info['layout_dets']
  837. allow_category_id_list = [3, 5, 13, 14, 15]
  838. """当成span拼接的"""
  839. # 3: 'image', # 图片
  840. # 5: 'table', # 表格
  841. # 13: 'inline_equation', # 行内公式
  842. # 14: 'interline_equation', # 行间公式
  843. # 15: 'text', # ocr识别文本
  844. for layout_det in layout_dets:
  845. category_id = layout_det['category_id']
  846. if category_id in allow_category_id_list:
  847. span = {'bbox': layout_det['bbox'], 'score': layout_det['score']}
  848. if category_id == 3:
  849. span['type'] = ContentType.Image
  850. elif category_id == 5:
  851. # 获取table模型结果
  852. latex = layout_det.get('latex', None)
  853. html = layout_det.get('html', None)
  854. if latex:
  855. span['latex'] = latex
  856. elif html:
  857. span['html'] = html
  858. span['type'] = ContentType.Table
  859. elif category_id == 13:
  860. span['content'] = layout_det['latex']
  861. span['type'] = ContentType.InlineEquation
  862. elif category_id == 14:
  863. span['content'] = layout_det['latex']
  864. span['type'] = ContentType.InterlineEquation
  865. elif category_id == 15:
  866. span['content'] = layout_det['text']
  867. span['type'] = ContentType.Text
  868. all_spans.append(span)
  869. return remove_duplicate_spans(all_spans)
  870. def get_page_size(self, page_no: int): # 获取页面宽高
  871. # 获取当前页的page对象
  872. page = self.__docs.get_page(page_no).get_page_info()
  873. # 获取当前页的宽高
  874. page_w = page.w
  875. page_h = page.h
  876. return page_w, page_h
  877. def __get_blocks_by_type(
  878. self, type: int, page_no: int, extra_col: list[str] = []
  879. ) -> list:
  880. blocks = []
  881. for page_dict in self.__model_list:
  882. layout_dets = page_dict.get('layout_dets', [])
  883. page_info = page_dict.get('page_info', {})
  884. page_number = page_info.get('page_no', -1)
  885. if page_no != page_number:
  886. continue
  887. for item in layout_dets:
  888. category_id = item.get('category_id', -1)
  889. bbox = item.get('bbox', None)
  890. if category_id == type:
  891. block = {
  892. 'bbox': bbox,
  893. 'score': item.get('score'),
  894. }
  895. for col in extra_col:
  896. block[col] = item.get(col, None)
  897. blocks.append(block)
  898. return blocks
  899. def get_model_list(self, page_no):
  900. return self.__model_list[page_no]
  901. if __name__ == '__main__':
  902. drw = DiskReaderWriter(r'D:/project/20231108code-clean')
  903. if 0:
  904. pdf_file_path = r'linshixuqiu\19983-00.pdf'
  905. model_file_path = r'linshixuqiu\19983-00_new.json'
  906. pdf_bytes = drw.read(pdf_file_path, AbsReaderWriter.MODE_BIN)
  907. model_json_txt = drw.read(model_file_path, AbsReaderWriter.MODE_TXT)
  908. model_list = json.loads(model_json_txt)
  909. write_path = r'D:\project\20231108code-clean\linshixuqiu\19983-00'
  910. img_bucket_path = 'imgs'
  911. img_writer = DiskReaderWriter(join_path(write_path, img_bucket_path))
  912. pdf_docs = fitz.open('pdf', pdf_bytes)
  913. magic_model = MagicModel(model_list, pdf_docs)
  914. if 1:
  915. model_list = json.loads(
  916. drw.read('/opt/data/pdf/20240418/j.chroma.2009.03.042.json')
  917. )
  918. pdf_bytes = drw.read(
  919. '/opt/data/pdf/20240418/j.chroma.2009.03.042.pdf', AbsReaderWriter.MODE_BIN
  920. )
  921. pdf_docs = fitz.open('pdf', pdf_bytes)
  922. magic_model = MagicModel(model_list, pdf_docs)
  923. for i in range(7):
  924. print(magic_model.get_imgs(i))