magic_model.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  1. import json
  2. import math
  3. from magic_pdf.libs.commons import fitz
  4. from loguru import logger
  5. from magic_pdf.libs.commons import join_path
  6. from magic_pdf.libs.coordinate_transform import get_scale_ratio
  7. from magic_pdf.libs.ocr_content_type import ContentType
  8. from magic_pdf.rw.AbsReaderWriter import AbsReaderWriter
  9. from magic_pdf.rw.DiskReaderWriter import DiskReaderWriter
  10. from magic_pdf.libs.math import float_gt
  11. from magic_pdf.libs.boxbase import (
  12. _is_in,
  13. bbox_relative_pos,
  14. bbox_distance,
  15. _is_part_overlap,
  16. calculate_overlap_area_in_bbox1_area_ratio,
  17. )
  18. from magic_pdf.libs.ModelBlockTypeEnum import ModelBlockTypeEnum
  19. CAPATION_OVERLAP_AREA_RATIO = 0.6
  20. class MagicModel:
  21. """
  22. 每个函数没有得到元素的时候返回空list
  23. """
  24. def __fix_axis(self):
  25. for model_page_info in self.__model_list:
  26. need_remove_list = []
  27. page_no = model_page_info["page_info"]["page_no"]
  28. horizontal_scale_ratio, vertical_scale_ratio = get_scale_ratio(
  29. model_page_info, self.__docs[page_no]
  30. )
  31. layout_dets = model_page_info["layout_dets"]
  32. for layout_det in layout_dets:
  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_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 __init__(self, model_list: list, docs: fitz.Document):
  58. self.__model_list = model_list
  59. self.__docs = docs
  60. self.__fix_axis()
  61. self.__fix_by_confidence()
  62. def __reduct_overlap(self, bboxes):
  63. N = len(bboxes)
  64. keep = [True] * N
  65. for i in range(N):
  66. for j in range(N):
  67. if i == j:
  68. continue
  69. if _is_in(bboxes[i]["bbox"], bboxes[j]["bbox"]):
  70. keep[i] = False
  71. return [bboxes[i] for i in range(N) if keep[i]]
  72. def __tie_up_category_by_distance(
  73. self, page_no, subject_category_id, object_category_id
  74. ):
  75. """
  76. 假定每个 subject 最多有一个 object (可以有多个相邻的 object 合并为单个 object),每个 object 只能属于一个 subject
  77. """
  78. ret = []
  79. MAX_DIS_OF_POINT = 10**9 + 7
  80. def expand_bbox(bbox1, bbox2):
  81. x0 = min(bbox1[0], bbox2[0])
  82. y0 = min(bbox1[1], bbox2[1])
  83. x1 = max(bbox1[2], bbox2[2])
  84. y1 = max(bbox1[3], bbox2[3])
  85. return [x0, y0, x1, y1]
  86. def get_bbox_area(bbox):
  87. return abs(bbox[2] - bbox[0]) * abs(bbox[3] - bbox[1])
  88. # subject 和 object 的 bbox 会合并成一个大的 bbox (named: merged bbox)。 筛选出所有和 merged bbox 有 overlap 且 overlap 面积大于 object 的面积的 subjects。
  89. # 再求出筛选出的 subjects 和 object 的最短距离!
  90. def may_find_other_nearest_bbox(subject_idx, object_idx):
  91. ret = float("inf")
  92. x0 = min(
  93. all_bboxes[subject_idx]["bbox"][0], all_bboxes[object_idx]["bbox"][0]
  94. )
  95. y0 = min(
  96. all_bboxes[subject_idx]["bbox"][1], all_bboxes[object_idx]["bbox"][1]
  97. )
  98. x1 = max(
  99. all_bboxes[subject_idx]["bbox"][2], all_bboxes[object_idx]["bbox"][2]
  100. )
  101. y1 = max(
  102. all_bboxes[subject_idx]["bbox"][3], all_bboxes[object_idx]["bbox"][3]
  103. )
  104. object_area = abs(
  105. all_bboxes[object_idx]["bbox"][2] - all_bboxes[object_idx]["bbox"][0]
  106. ) * abs(
  107. all_bboxes[object_idx]["bbox"][3] - all_bboxes[object_idx]["bbox"][1]
  108. )
  109. for i in range(len(all_bboxes)):
  110. if (
  111. i == subject_idx
  112. or all_bboxes[i]["category_id"] != subject_category_id
  113. ):
  114. continue
  115. if _is_part_overlap([x0, y0, x1, y1], all_bboxes[i]["bbox"]) or _is_in(
  116. all_bboxes[i]["bbox"], [x0, y0, x1, y1]
  117. ):
  118. i_area = abs(
  119. all_bboxes[i]["bbox"][2] - all_bboxes[i]["bbox"][0]
  120. ) * abs(all_bboxes[i]["bbox"][3] - all_bboxes[i]["bbox"][1])
  121. if i_area >= object_area:
  122. ret = min(float("inf"), dis[i][object_idx])
  123. return ret
  124. subjects = self.__reduct_overlap(
  125. list(
  126. map(
  127. lambda x: {"bbox": x["bbox"], "score": x["score"]},
  128. filter(
  129. lambda x: x["category_id"] == subject_category_id,
  130. self.__model_list[page_no]["layout_dets"],
  131. ),
  132. )
  133. )
  134. )
  135. objects = self.__reduct_overlap(
  136. list(
  137. map(
  138. lambda x: {"bbox": x["bbox"], "score": x["score"]},
  139. filter(
  140. lambda x: x["category_id"] == object_category_id,
  141. self.__model_list[page_no]["layout_dets"],
  142. ),
  143. )
  144. )
  145. )
  146. subject_object_relation_map = {}
  147. subjects.sort(
  148. key=lambda x: x["bbox"][0] ** 2 + x["bbox"][1] ** 2
  149. ) # get the distance !
  150. all_bboxes = []
  151. for v in subjects:
  152. all_bboxes.append(
  153. {
  154. "category_id": subject_category_id,
  155. "bbox": v["bbox"],
  156. "score": v["score"],
  157. }
  158. )
  159. for v in objects:
  160. all_bboxes.append(
  161. {
  162. "category_id": object_category_id,
  163. "bbox": v["bbox"],
  164. "score": v["score"],
  165. }
  166. )
  167. N = len(all_bboxes)
  168. dis = [[MAX_DIS_OF_POINT] * N for _ in range(N)]
  169. for i in range(N):
  170. for j in range(i):
  171. if (
  172. all_bboxes[i]["category_id"] == subject_category_id
  173. and all_bboxes[j]["category_id"] == subject_category_id
  174. ):
  175. continue
  176. dis[i][j] = bbox_distance(all_bboxes[i]["bbox"], all_bboxes[j]["bbox"])
  177. dis[j][i] = dis[i][j]
  178. used = set()
  179. for i in range(N):
  180. # 求第 i 个 subject 所关联的 object
  181. if all_bboxes[i]["category_id"] != subject_category_id:
  182. continue
  183. seen = set()
  184. candidates = []
  185. arr = []
  186. for j in range(N):
  187. pos_flag_count = sum(
  188. list(
  189. map(
  190. lambda x: 1 if x else 0,
  191. bbox_relative_pos(
  192. all_bboxes[i]["bbox"], all_bboxes[j]["bbox"]
  193. ),
  194. )
  195. )
  196. )
  197. if pos_flag_count > 1:
  198. continue
  199. if (
  200. all_bboxes[j]["category_id"] != object_category_id
  201. or j in used
  202. or dis[i][j] == MAX_DIS_OF_POINT
  203. ):
  204. continue
  205. left, right, _, _ = bbox_relative_pos(all_bboxes[i]["bbox"], all_bboxes[j]["bbox"]) # 由 pos_flag_count 相关逻辑保证本段逻辑准确性
  206. if left or right:
  207. one_way_dis = all_bboxes[i]["bbox"][2] - all_bboxes[i]["bbox"][0]
  208. else:
  209. one_way_dis = all_bboxes[i]["bbox"][3] - all_bboxes[i]["bbox"][1]
  210. if dis[i][j] > one_way_dis:
  211. continue
  212. arr.append((dis[i][j], j))
  213. arr.sort(key=lambda x: x[0])
  214. if len(arr) > 0:
  215. # bug: 离该subject 最近的 object 可能跨越了其它的 subject 。比如 [this subect] [some sbuject] [the nearest objec of subject]
  216. if may_find_other_nearest_bbox(i, arr[0][1]) >= arr[0][0]:
  217. candidates.append(arr[0][1])
  218. seen.add(arr[0][1])
  219. # 已经获取初始种子
  220. for j in set(candidates):
  221. tmp = []
  222. for k in range(i + 1, N):
  223. pos_flag_count = sum(
  224. list(
  225. map(
  226. lambda x: 1 if x else 0,
  227. bbox_relative_pos(
  228. all_bboxes[j]["bbox"], all_bboxes[k]["bbox"]
  229. ),
  230. )
  231. )
  232. )
  233. if pos_flag_count > 1:
  234. continue
  235. if (
  236. all_bboxes[k]["category_id"] != object_category_id
  237. or k in used
  238. or k in seen
  239. or dis[j][k] == MAX_DIS_OF_POINT
  240. ):
  241. continue
  242. is_nearest = True
  243. for l in range(i + 1, N):
  244. if l in (j, k) or l in used or l in seen:
  245. continue
  246. if not float_gt(dis[l][k], dis[j][k]):
  247. is_nearest = False
  248. break
  249. if is_nearest:
  250. tmp.append(k)
  251. seen.add(k)
  252. candidates = tmp
  253. if len(candidates) == 0:
  254. break
  255. # 已经获取到某个 figure 下所有的最靠近的 captions,以及最靠近这些 captions 的 captions 。
  256. # 先扩一下 bbox,
  257. x0s = [all_bboxes[idx]["bbox"][0] for idx in seen] + [
  258. all_bboxes[i]["bbox"][0]
  259. ]
  260. y0s = [all_bboxes[idx]["bbox"][1] for idx in seen] + [
  261. all_bboxes[i]["bbox"][1]
  262. ]
  263. x1s = [all_bboxes[idx]["bbox"][2] for idx in seen] + [
  264. all_bboxes[i]["bbox"][2]
  265. ]
  266. y1s = [all_bboxes[idx]["bbox"][3] for idx in seen] + [
  267. all_bboxes[i]["bbox"][3]
  268. ]
  269. ox0, oy0, ox1, oy1 = min(x0s), min(y0s), max(x1s), max(y1s)
  270. ix0, iy0, ix1, iy1 = all_bboxes[i]["bbox"]
  271. # 分成了 4 个截取空间,需要计算落在每个截取空间下 objects 合并后占据的矩形面积
  272. caption_poses = [
  273. [ox0, oy0, ix0, oy1],
  274. [ox0, oy0, ox1, iy0],
  275. [ox0, iy1, ox1, oy1],
  276. [ix1, oy0, ox1, oy1],
  277. ]
  278. caption_areas = []
  279. for bbox in caption_poses:
  280. embed_arr = []
  281. for idx in seen:
  282. if (
  283. calculate_overlap_area_in_bbox1_area_ratio(
  284. all_bboxes[idx]["bbox"], bbox
  285. )
  286. > CAPATION_OVERLAP_AREA_RATIO
  287. ):
  288. embed_arr.append(idx)
  289. if len(embed_arr) > 0:
  290. embed_x0 = min([all_bboxes[idx]["bbox"][0] for idx in embed_arr])
  291. embed_y0 = min([all_bboxes[idx]["bbox"][1] for idx in embed_arr])
  292. embed_x1 = max([all_bboxes[idx]["bbox"][2] for idx in embed_arr])
  293. embed_y1 = max([all_bboxes[idx]["bbox"][3] for idx in embed_arr])
  294. caption_areas.append(
  295. int(abs(embed_x1 - embed_x0) * abs(embed_y1 - embed_y0))
  296. )
  297. else:
  298. caption_areas.append(0)
  299. subject_object_relation_map[i] = []
  300. if max(caption_areas) > 0:
  301. max_area_idx = caption_areas.index(max(caption_areas))
  302. caption_bbox = caption_poses[max_area_idx]
  303. for j in seen:
  304. if (
  305. calculate_overlap_area_in_bbox1_area_ratio(
  306. all_bboxes[j]["bbox"], caption_bbox
  307. )
  308. > CAPATION_OVERLAP_AREA_RATIO
  309. ):
  310. used.add(j)
  311. subject_object_relation_map[i].append(j)
  312. for i in sorted(subject_object_relation_map.keys()):
  313. result = {
  314. "subject_body": all_bboxes[i]["bbox"],
  315. "all": all_bboxes[i]["bbox"],
  316. "score": all_bboxes[i]["score"],
  317. }
  318. if len(subject_object_relation_map[i]) > 0:
  319. x0 = min(
  320. [all_bboxes[j]["bbox"][0] for j in subject_object_relation_map[i]]
  321. )
  322. y0 = min(
  323. [all_bboxes[j]["bbox"][1] for j in subject_object_relation_map[i]]
  324. )
  325. x1 = max(
  326. [all_bboxes[j]["bbox"][2] for j in subject_object_relation_map[i]]
  327. )
  328. y1 = max(
  329. [all_bboxes[j]["bbox"][3] for j in subject_object_relation_map[i]]
  330. )
  331. result["object_body"] = [x0, y0, x1, y1]
  332. result["all"] = [
  333. min(x0, all_bboxes[i]["bbox"][0]),
  334. min(y0, all_bboxes[i]["bbox"][1]),
  335. max(x1, all_bboxes[i]["bbox"][2]),
  336. max(y1, all_bboxes[i]["bbox"][3]),
  337. ]
  338. ret.append(result)
  339. total_subject_object_dis = 0
  340. # 计算已经配对的 distance 距离
  341. for i in subject_object_relation_map.keys():
  342. for j in subject_object_relation_map[i]:
  343. total_subject_object_dis += bbox_distance(
  344. all_bboxes[i]["bbox"], all_bboxes[j]["bbox"]
  345. )
  346. # 计算未匹配的 subject 和 object 的距离(非精确版)
  347. with_caption_subject = set(
  348. [
  349. key
  350. for key in subject_object_relation_map.keys()
  351. if len(subject_object_relation_map[i]) > 0
  352. ]
  353. )
  354. for i in range(N):
  355. if all_bboxes[i]["category_id"] != object_category_id or i in used:
  356. continue
  357. candidates = []
  358. for j in range(N):
  359. if (
  360. all_bboxes[j]["category_id"] != subject_category_id
  361. or j in with_caption_subject
  362. ):
  363. continue
  364. candidates.append((dis[i][j], j))
  365. if len(candidates) > 0:
  366. candidates.sort(key=lambda x: x[0])
  367. total_subject_object_dis += candidates[0][1]
  368. with_caption_subject.add(j)
  369. return ret, total_subject_object_dis
  370. def get_imgs(self, page_no: int): # @许瑞
  371. records, _ = self.__tie_up_category_by_distance(page_no, 3, 4)
  372. return [
  373. {
  374. "bbox": record["all"],
  375. "img_body_bbox": record["subject_body"],
  376. "img_caption_bbox": record.get("object_body", None),
  377. "score": record["score"],
  378. }
  379. for record in records
  380. ]
  381. def get_tables(
  382. self, page_no: int
  383. ) -> list: # 3个坐标, caption, table主体,table-note
  384. with_captions, _ = self.__tie_up_category_by_distance(page_no, 5, 6)
  385. with_footnotes, _ = self.__tie_up_category_by_distance(page_no, 5, 7)
  386. ret = []
  387. N, M = len(with_captions), len(with_footnotes)
  388. assert N == M
  389. for i in range(N):
  390. record = {
  391. "score": with_captions[i]["score"],
  392. "table_caption_bbox": with_captions[i].get("object_body", None),
  393. "table_body_bbox": with_captions[i]["subject_body"],
  394. "table_footnote_bbox": with_footnotes[i].get("object_body", None),
  395. }
  396. x0 = min(with_captions[i]["all"][0], with_footnotes[i]["all"][0])
  397. y0 = min(with_captions[i]["all"][1], with_footnotes[i]["all"][1])
  398. x1 = max(with_captions[i]["all"][2], with_footnotes[i]["all"][2])
  399. y1 = max(with_captions[i]["all"][3], with_footnotes[i]["all"][3])
  400. record["bbox"] = [x0, y0, x1, y1]
  401. ret.append(record)
  402. return ret
  403. def get_equations(self, page_no: int) -> list: # 有坐标,也有字
  404. inline_equations = self.__get_blocks_by_type(
  405. ModelBlockTypeEnum.EMBEDDING.value, page_no, ["latex"]
  406. )
  407. interline_equations = self.__get_blocks_by_type(
  408. ModelBlockTypeEnum.ISOLATED.value, page_no, ["latex"]
  409. )
  410. interline_equations_blocks = self.__get_blocks_by_type(
  411. ModelBlockTypeEnum.ISOLATE_FORMULA.value, page_no
  412. )
  413. return inline_equations, interline_equations, interline_equations_blocks
  414. def get_discarded(self, page_no: int) -> list: # 自研模型,只有坐标
  415. blocks = self.__get_blocks_by_type(ModelBlockTypeEnum.ABANDON.value, page_no)
  416. return blocks
  417. def get_text_blocks(self, page_no: int) -> list: # 自研模型搞的,只有坐标,没有字
  418. blocks = self.__get_blocks_by_type(ModelBlockTypeEnum.PLAIN_TEXT.value, page_no)
  419. return blocks
  420. def get_title_blocks(self, page_no: int) -> list: # 自研模型,只有坐标,没字
  421. blocks = self.__get_blocks_by_type(ModelBlockTypeEnum.TITLE.value, page_no)
  422. return blocks
  423. def get_ocr_text(self, page_no: int) -> list: # paddle 搞的,有字也有坐标
  424. text_spans = []
  425. model_page_info = self.__model_list[page_no]
  426. layout_dets = model_page_info["layout_dets"]
  427. for layout_det in layout_dets:
  428. if layout_det["category_id"] == "15":
  429. span = {
  430. "bbox": layout_det["bbox"],
  431. "content": layout_det["text"],
  432. }
  433. text_spans.append(span)
  434. return text_spans
  435. def get_all_spans(self, page_no: int) -> list:
  436. def remove_duplicate_spans(spans):
  437. new_spans = []
  438. for span in spans:
  439. if not any(span == existing_span for existing_span in new_spans):
  440. new_spans.append(span)
  441. return new_spans
  442. all_spans = []
  443. model_page_info = self.__model_list[page_no]
  444. layout_dets = model_page_info["layout_dets"]
  445. allow_category_id_list = [3, 5, 13, 14, 15]
  446. """当成span拼接的"""
  447. # 3: 'image', # 图片
  448. # 5: 'table', # 表格
  449. # 13: 'inline_equation', # 行内公式
  450. # 14: 'interline_equation', # 行间公式
  451. # 15: 'text', # ocr识别文本
  452. for layout_det in layout_dets:
  453. category_id = layout_det["category_id"]
  454. if category_id in allow_category_id_list:
  455. span = {
  456. "bbox": layout_det["bbox"],
  457. "score": layout_det["score"]
  458. }
  459. if category_id == 3:
  460. span["type"] = ContentType.Image
  461. elif category_id == 5:
  462. span["type"] = ContentType.Table
  463. elif category_id == 13:
  464. span["content"] = layout_det["latex"]
  465. span["type"] = ContentType.InlineEquation
  466. elif category_id == 14:
  467. span["content"] = layout_det["latex"]
  468. span["type"] = ContentType.InterlineEquation
  469. elif category_id == 15:
  470. span["content"] = layout_det["text"]
  471. span["type"] = ContentType.Text
  472. all_spans.append(span)
  473. return remove_duplicate_spans(all_spans)
  474. def get_page_size(self, page_no: int): # 获取页面宽高
  475. # 获取当前页的page对象
  476. page = self.__docs[page_no]
  477. # 获取当前页的宽高
  478. page_w = page.rect.width
  479. page_h = page.rect.height
  480. return page_w, page_h
  481. def __get_blocks_by_type(
  482. self, type: int, page_no: int, extra_col: list[str] = []
  483. ) -> list:
  484. blocks = []
  485. for page_dict in self.__model_list:
  486. layout_dets = page_dict.get("layout_dets", [])
  487. page_info = page_dict.get("page_info", {})
  488. page_number = page_info.get("page_no", -1)
  489. if page_no != page_number:
  490. continue
  491. for item in layout_dets:
  492. category_id = item.get("category_id", -1)
  493. bbox = item.get("bbox", None)
  494. if category_id == type:
  495. block = {
  496. "bbox": bbox,
  497. "score": item.get("score"),
  498. }
  499. for col in extra_col:
  500. block[col] = item.get(col, None)
  501. blocks.append(block)
  502. return blocks
  503. def get_model_list(self, page_no):
  504. return self.__model_list[page_no]
  505. if __name__ == "__main__":
  506. drw = DiskReaderWriter(r"D:/project/20231108code-clean")
  507. if 0:
  508. pdf_file_path = r"linshixuqiu\19983-00.pdf"
  509. model_file_path = r"linshixuqiu\19983-00_new.json"
  510. pdf_bytes = drw.read(pdf_file_path, AbsReaderWriter.MODE_BIN)
  511. model_json_txt = drw.read(model_file_path, AbsReaderWriter.MODE_TXT)
  512. model_list = json.loads(model_json_txt)
  513. write_path = r"D:\project\20231108code-clean\linshixuqiu\19983-00"
  514. img_bucket_path = "imgs"
  515. img_writer = DiskReaderWriter(join_path(write_path, img_bucket_path))
  516. pdf_docs = fitz.open("pdf", pdf_bytes)
  517. magic_model = MagicModel(model_list, pdf_docs)
  518. if 1:
  519. model_list = json.loads(
  520. drw.read("/opt/data/pdf/20240418/j.chroma.2009.03.042.json")
  521. )
  522. pdf_bytes = drw.read(
  523. "/opt/data/pdf/20240418/j.chroma.2009.03.042.pdf", AbsReaderWriter.MODE_BIN
  524. )
  525. pdf_docs = fitz.open("pdf", pdf_bytes)
  526. magic_model = MagicModel(model_list, pdf_docs)
  527. for i in range(7):
  528. print(magic_model.get_imgs(i))