magic_model.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  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], bboxes[j]):
  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. subjects = self.__reduct_overlap(
  81. list(
  82. map(
  83. lambda x: x["bbox"],
  84. filter(
  85. lambda x: x["category_id"] == subject_category_id,
  86. self.__model_list[page_no]["layout_dets"],
  87. ),
  88. )
  89. )
  90. )
  91. objects = self.__reduct_overlap(
  92. list(
  93. map(
  94. lambda x: x["bbox"],
  95. filter(
  96. lambda x: x["category_id"] == object_category_id,
  97. self.__model_list[page_no]["layout_dets"],
  98. ),
  99. )
  100. )
  101. )
  102. subject_object_relation_map = {}
  103. subjects.sort(key=lambda x: x[0] ** 2 + x[1] ** 2) # get the distance !
  104. all_bboxes = []
  105. for v in subjects:
  106. all_bboxes.append({"category_id": subject_category_id, "bbox": v})
  107. for v in objects:
  108. all_bboxes.append({"category_id": object_category_id, "bbox": v})
  109. N = len(all_bboxes)
  110. dis = [[MAX_DIS_OF_POINT] * N for _ in range(N)]
  111. for i in range(N):
  112. for j in range(i):
  113. if (
  114. all_bboxes[i]["category_id"] == subject_category_id
  115. and all_bboxes[j]["category_id"] == subject_category_id
  116. ):
  117. continue
  118. dis[i][j] = bbox_distance(all_bboxes[i]["bbox"], all_bboxes[j]["bbox"])
  119. dis[j][i] = dis[i][j]
  120. used = set()
  121. for i in range(N):
  122. # 求第 i 个 subject 所关联的 object
  123. if all_bboxes[i]["category_id"] != subject_category_id:
  124. continue
  125. seen = set()
  126. candidates = []
  127. arr = []
  128. for j in range(N):
  129. pos_flag_count = sum(
  130. list(
  131. map(
  132. lambda x: 1 if x else 0,
  133. bbox_relative_pos(
  134. all_bboxes[i]["bbox"], all_bboxes[j]["bbox"]
  135. ),
  136. )
  137. )
  138. )
  139. if pos_flag_count > 1:
  140. continue
  141. if (
  142. all_bboxes[j]["category_id"] != object_category_id
  143. or j in used
  144. or dis[i][j] == MAX_DIS_OF_POINT
  145. ):
  146. continue
  147. arr.append((dis[i][j], j))
  148. arr.sort(key=lambda x: x[0])
  149. if len(arr) > 0:
  150. candidates.append(arr[0][1])
  151. seen.add(arr[0][1])
  152. # 已经获取初始种子
  153. for j in set(candidates):
  154. tmp = []
  155. for k in range(i + 1, N):
  156. pos_flag_count = sum(
  157. list(
  158. map(
  159. lambda x: 1 if x else 0,
  160. bbox_relative_pos(
  161. all_bboxes[j]["bbox"], all_bboxes[k]["bbox"]
  162. ),
  163. )
  164. )
  165. )
  166. if pos_flag_count > 1:
  167. continue
  168. if (
  169. all_bboxes[k]["category_id"] != object_category_id
  170. or k in used
  171. or k in seen
  172. or dis[j][k] == MAX_DIS_OF_POINT
  173. ):
  174. continue
  175. is_nearest = True
  176. for l in range(i + 1, N):
  177. if l in (j, k) or l in used or l in seen:
  178. continue
  179. if not float_gt(dis[l][k], dis[j][k]):
  180. is_nearest = False
  181. break
  182. if is_nearest:
  183. tmp.append(k)
  184. seen.add(k)
  185. candidates = tmp
  186. if len(candidates) == 0:
  187. break
  188. # 已经获取到某个 figure 下所有的最靠近的 captions,以及最靠近这些 captions 的 captions 。
  189. # 先扩一下 bbox,
  190. x0s = [all_bboxes[idx]["bbox"][0] for idx in seen] + [
  191. all_bboxes[i]["bbox"][0]
  192. ]
  193. y0s = [all_bboxes[idx]["bbox"][1] for idx in seen] + [
  194. all_bboxes[i]["bbox"][1]
  195. ]
  196. x1s = [all_bboxes[idx]["bbox"][2] for idx in seen] + [
  197. all_bboxes[i]["bbox"][2]
  198. ]
  199. y1s = [all_bboxes[idx]["bbox"][3] for idx in seen] + [
  200. all_bboxes[i]["bbox"][3]
  201. ]
  202. ox0, oy0, ox1, oy1 = min(x0s), min(y0s), max(x1s), max(y1s)
  203. ix0, iy0, ix1, iy1 = all_bboxes[i]["bbox"]
  204. # 分成了 4 个截取空间,需要计算落在每个截取空间下 objects 合并后占据的矩形面积
  205. caption_poses = [
  206. [ox0, oy0, ix0, oy1],
  207. [ox0, oy0, ox1, iy0],
  208. [ox0, iy1, ox1, oy1],
  209. [ix1, oy0, ox1, oy1],
  210. ]
  211. caption_areas = []
  212. for bbox in caption_poses:
  213. embed_arr = []
  214. for idx in seen:
  215. if calculate_overlap_area_in_bbox1_area_ratio(all_bboxes[idx]["bbox"], bbox) > CAPATION_OVERLAP_AREA_RATIO:
  216. embed_arr.append(idx)
  217. if len(embed_arr) > 0:
  218. embed_x0 = min([all_bboxes[idx]["bbox"][0] for idx in embed_arr])
  219. embed_y0 = min([all_bboxes[idx]["bbox"][1] for idx in embed_arr])
  220. embed_x1 = max([all_bboxes[idx]["bbox"][2] for idx in embed_arr])
  221. embed_y1 = max([all_bboxes[idx]["bbox"][3] for idx in embed_arr])
  222. caption_areas.append(
  223. int(abs(embed_x1 - embed_x0) * abs(embed_y1 - embed_y0))
  224. )
  225. else:
  226. caption_areas.append(0)
  227. subject_object_relation_map[i] = []
  228. if max(caption_areas) > 0:
  229. max_area_idx = caption_areas.index(max(caption_areas))
  230. caption_bbox = caption_poses[max_area_idx]
  231. for j in seen:
  232. if calculate_overlap_area_in_bbox1_area_ratio(all_bboxes[j]["bbox"], caption_bbox) > CAPATION_OVERLAP_AREA_RATIO:
  233. used.add(j)
  234. subject_object_relation_map[i].append(j)
  235. for i in sorted(subject_object_relation_map.keys()):
  236. result = {
  237. "subject_body": all_bboxes[i]["bbox"],
  238. "all": all_bboxes[i]["bbox"],
  239. }
  240. if len(subject_object_relation_map[i]) > 0:
  241. x0 = min(
  242. [all_bboxes[j]["bbox"][0] for j in subject_object_relation_map[i]]
  243. )
  244. y0 = min(
  245. [all_bboxes[j]["bbox"][1] for j in subject_object_relation_map[i]]
  246. )
  247. x1 = max(
  248. [all_bboxes[j]["bbox"][2] for j in subject_object_relation_map[i]]
  249. )
  250. y1 = max(
  251. [all_bboxes[j]["bbox"][3] for j in subject_object_relation_map[i]]
  252. )
  253. result["object_body"] = [x0, y0, x1, y1]
  254. result["all"] = [
  255. min(x0, all_bboxes[i]["bbox"][0]),
  256. min(y0, all_bboxes[i]["bbox"][1]),
  257. max(x1, all_bboxes[i]["bbox"][2]),
  258. max(y1, all_bboxes[i]["bbox"][3]),
  259. ]
  260. ret.append(result)
  261. total_subject_object_dis = 0
  262. # 计算已经配对的 distance 距离
  263. for i in subject_object_relation_map.keys():
  264. for j in subject_object_relation_map[i]:
  265. total_subject_object_dis += bbox_distance(
  266. all_bboxes[i]["bbox"], all_bboxes[j]["bbox"]
  267. )
  268. # 计算未匹配的 subject 和 object 的距离(非精确版)
  269. with_caption_subject = set(
  270. [
  271. key
  272. for key in subject_object_relation_map.keys()
  273. if len(subject_object_relation_map[i]) > 0
  274. ]
  275. )
  276. for i in range(N):
  277. if all_bboxes[i]["category_id"] != object_category_id or i in used:
  278. continue
  279. candidates = []
  280. for j in range(N):
  281. if (
  282. all_bboxes[j]["category_id"] != subject_category_id
  283. or j in with_caption_subject
  284. ):
  285. continue
  286. candidates.append((dis[i][j], j))
  287. if len(candidates) > 0:
  288. candidates.sort(key=lambda x: x[0])
  289. total_subject_object_dis += candidates[0][1]
  290. with_caption_subject.add(j)
  291. return ret, total_subject_object_dis
  292. def get_imgs(self, page_no: int): # @许瑞
  293. records, _ = self.__tie_up_category_by_distance(page_no, 3, 4)
  294. return [
  295. {
  296. "bbox": record["all"],
  297. "img_body_bbox": record["subject_body"],
  298. "img_caption_bbox": record.get("object_body", None),
  299. }
  300. for record in records
  301. ]
  302. def get_tables(
  303. self, page_no: int
  304. ) -> list: # 3个坐标, caption, table主体,table-note
  305. with_captions, _ = self.__tie_up_category_by_distance(page_no, 5, 6)
  306. with_footnotes, _ = self.__tie_up_category_by_distance(page_no, 5, 7)
  307. ret = []
  308. N, M = len(with_captions), len(with_footnotes)
  309. assert N == M
  310. for i in range(N):
  311. record = {
  312. "table_caption_bbox": with_captions[i].get("object_body", None),
  313. "table_body_bbox": with_captions[i]["subject_body"],
  314. "table_footnote_bbox": with_footnotes[i].get("object_body", None),
  315. }
  316. x0 = min(with_captions[i]["all"][0], with_footnotes[i]["all"][0])
  317. y0 = min(with_captions[i]["all"][1], with_footnotes[i]["all"][1])
  318. x1 = max(with_captions[i]["all"][2], with_footnotes[i]["all"][2])
  319. y1 = max(with_captions[i]["all"][3], with_footnotes[i]["all"][3])
  320. record["bbox"] = [x0, y0, x1, y1]
  321. ret.append(record)
  322. return ret
  323. def get_equations(self, page_no: int) -> list: # 有坐标,也有字
  324. inline_equations = self.__get_blocks_by_type(
  325. ModelBlockTypeEnum.EMBEDDING.value, page_no, ["latex"]
  326. )
  327. interline_equations = self.__get_blocks_by_type(
  328. ModelBlockTypeEnum.ISOLATED.value, page_no, ["latex"]
  329. )
  330. interline_equations_blocks = self.__get_blocks_by_type(
  331. ModelBlockTypeEnum.ISOLATE_FORMULA.value, page_no
  332. )
  333. return inline_equations, interline_equations, interline_equations_blocks
  334. def get_discarded(self, page_no: int) -> list: # 自研模型,只有坐标
  335. blocks = self.__get_blocks_by_type(ModelBlockTypeEnum.ABANDON.value, page_no)
  336. return blocks
  337. def get_text_blocks(self, page_no: int) -> list: # 自研模型搞的,只有坐标,没有字
  338. blocks = self.__get_blocks_by_type(ModelBlockTypeEnum.PLAIN_TEXT.value, page_no)
  339. return blocks
  340. def get_title_blocks(self, page_no: int) -> list: # 自研模型,只有坐标,没字
  341. blocks = self.__get_blocks_by_type(ModelBlockTypeEnum.TITLE.value, page_no)
  342. return blocks
  343. def get_ocr_text(self, page_no: int) -> list: # paddle 搞的,有字也有坐标
  344. text_spans = []
  345. model_page_info = self.__model_list[page_no]
  346. layout_dets = model_page_info["layout_dets"]
  347. for layout_det in layout_dets:
  348. if layout_det["category_id"] == "15":
  349. span = {
  350. "bbox": layout_det["bbox"],
  351. "content": layout_det["text"],
  352. }
  353. text_spans.append(span)
  354. return text_spans
  355. def get_all_spans(self, page_no: int) -> list:
  356. all_spans = []
  357. model_page_info = self.__model_list[page_no]
  358. layout_dets = model_page_info["layout_dets"]
  359. allow_category_id_list = [3, 5, 13, 14, 15]
  360. """当成span拼接的"""
  361. # 3: 'image', # 图片
  362. # 5: 'table', # 表格
  363. # 13: 'inline_equation', # 行内公式
  364. # 14: 'interline_equation', # 行间公式
  365. # 15: 'text', # ocr识别文本
  366. for layout_det in layout_dets:
  367. category_id = layout_det["category_id"]
  368. if category_id in allow_category_id_list:
  369. span = {"bbox": layout_det["bbox"]}
  370. if category_id == 3:
  371. span["type"] = ContentType.Image
  372. elif category_id == 5:
  373. span["type"] = ContentType.Table
  374. elif category_id == 13:
  375. span["content"] = layout_det["latex"]
  376. span["type"] = ContentType.InlineEquation
  377. elif category_id == 14:
  378. span["content"] = layout_det["latex"]
  379. span["type"] = ContentType.InterlineEquation
  380. elif category_id == 15:
  381. span["content"] = layout_det["text"]
  382. span["type"] = ContentType.Text
  383. all_spans.append(span)
  384. return all_spans
  385. def get_page_size(self, page_no: int): # 获取页面宽高
  386. # 获取当前页的page对象
  387. page = self.__docs[page_no]
  388. # 获取当前页的宽高
  389. page_w = page.rect.width
  390. page_h = page.rect.height
  391. return page_w, page_h
  392. def __get_blocks_by_type(
  393. self, type: int, page_no: int, extra_col: list[str] = []
  394. ) -> list:
  395. blocks = []
  396. for page_dict in self.__model_list:
  397. layout_dets = page_dict.get("layout_dets", [])
  398. page_info = page_dict.get("page_info", {})
  399. page_number = page_info.get("page_no", -1)
  400. if page_no != page_number:
  401. continue
  402. for item in layout_dets:
  403. category_id = item.get("category_id", -1)
  404. bbox = item.get("bbox", None)
  405. if category_id == type:
  406. block = {"bbox": bbox}
  407. for col in extra_col:
  408. block[col] = item.get(col, None)
  409. blocks.append(block)
  410. return blocks
  411. if __name__ == "__main__":
  412. drw = DiskReaderWriter(r"D:/project/20231108code-clean")
  413. if 0:
  414. pdf_file_path = r"linshixuqiu\19983-00.pdf"
  415. model_file_path = r"linshixuqiu\19983-00_new.json"
  416. pdf_bytes = drw.read(pdf_file_path, AbsReaderWriter.MODE_BIN)
  417. model_json_txt = drw.read(model_file_path, AbsReaderWriter.MODE_TXT)
  418. model_list = json.loads(model_json_txt)
  419. write_path = r"D:\project\20231108code-clean\linshixuqiu\19983-00"
  420. img_bucket_path = "imgs"
  421. img_writer = DiskReaderWriter(join_path(write_path, img_bucket_path))
  422. pdf_docs = fitz.open("pdf", pdf_bytes)
  423. magic_model = MagicModel(model_list, pdf_docs)
  424. if 1:
  425. model_list = json.loads(
  426. drw.read("/opt/data/pdf/20240418/j.chroma.2009.03.042.json")
  427. )
  428. pdf_bytes = drw.read(
  429. "/opt/data/pdf/20240418/j.chroma.2009.03.042.pdf", AbsReaderWriter.MODE_BIN
  430. )
  431. pdf_docs = fitz.open("pdf", pdf_bytes)
  432. magic_model = MagicModel(model_list, pdf_docs)
  433. for i in range(7):
  434. print(magic_model.get_imgs(i))