magic_model.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885
  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 _is_in, bbox_relative_pos, bbox_distance
  12. from magic_pdf.libs.ModelBlockTypeEnum import ModelBlockTypeEnum
  13. class MagicModel:
  14. """
  15. 每个函数没有得到元素的时候返回空list
  16. """
  17. def __fix_axis(self):
  18. need_remove_list = []
  19. for model_page_info in self.__model_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. x0, y0, _, _, x1, y1, _, _ = layout_det["poly"]
  27. bbox = [
  28. int(x0 / horizontal_scale_ratio),
  29. int(y0 / vertical_scale_ratio),
  30. int(x1 / horizontal_scale_ratio),
  31. int(y1 / vertical_scale_ratio),
  32. ]
  33. layout_det["bbox"] = bbox
  34. # 删除高度或者宽度为0的spans
  35. if bbox[2] - bbox[0] == 0 or bbox[3] - bbox[1] == 0:
  36. need_remove_list.append(layout_det)
  37. for need_remove in need_remove_list:
  38. layout_dets.remove(need_remove)
  39. def __init__(self, model_list: list, docs: fitz.Document):
  40. self.__model_list = model_list
  41. self.__docs = docs
  42. self.__fix_axis()
  43. def __reduct_overlap(self, bboxes):
  44. N = len(bboxes)
  45. keep = [True] * N
  46. for i in range(N):
  47. for j in range(N):
  48. if i == j:
  49. continue
  50. if _is_in(bboxes[i], bboxes[j]):
  51. keep[i] = False
  52. return [bboxes[i] for i in range(N) if keep[i]]
  53. def __tie_up_category_by_distance(
  54. self, page_no, subject_category_id, object_category_id
  55. ):
  56. """
  57. 假定每个 subject 最多有一个 object (可以有多个相邻的 object 合并为单个 object),每个 object 只能属于一个 subject
  58. """
  59. ret = []
  60. MAX_DIS_OF_POINT = 10**9 + 7
  61. subjects = self.__reduct_overlap(
  62. list(
  63. map(
  64. lambda x: x["bbox"],
  65. filter(
  66. lambda x: x["category_id"] == subject_category_id,
  67. self.__model_list[page_no]["layout_dets"],
  68. ),
  69. )
  70. )
  71. )
  72. objects = self.__reduct_overlap(
  73. list(
  74. map(
  75. lambda x: x["bbox"],
  76. filter(
  77. lambda x: x["category_id"] == object_category_id,
  78. self.__model_list[page_no]["layout_dets"],
  79. ),
  80. )
  81. )
  82. )
  83. subject_object_relation_map = {}
  84. subjects.sort(key=lambda x: x[0] ** 2 + x[1] ** 2) # get the distance !
  85. all_bboxes = []
  86. for v in subjects:
  87. all_bboxes.append({"category_id": subject_category_id, "bbox": v})
  88. for v in objects:
  89. all_bboxes.append({"category_id": object_category_id, "bbox": v})
  90. N = len(all_bboxes)
  91. dis = [[MAX_DIS_OF_POINT] * N for _ in range(N)]
  92. for i in range(N):
  93. for j in range(i):
  94. if (
  95. all_bboxes[i]["category_id"] == subject_category_id
  96. and all_bboxes[j]["category_id"] == subject_category_id
  97. ):
  98. continue
  99. dis[i][j] = bbox_distance(all_bboxes[i]["bbox"], all_bboxes[j]["bbox"])
  100. dis[j][i] = dis[i][j]
  101. used = set()
  102. for i in range(N):
  103. # 求第 i 个 subject 所关联的 object
  104. if all_bboxes[i]["category_id"] != subject_category_id:
  105. continue
  106. seen = set()
  107. candidates = []
  108. arr = []
  109. for j in range(N):
  110. pos_flag_count = sum(
  111. list(
  112. map(
  113. lambda x: 1 if x else 0,
  114. bbox_relative_pos(
  115. all_bboxes[i]["bbox"], all_bboxes[j]["bbox"]
  116. ),
  117. )
  118. )
  119. )
  120. if pos_flag_count > 1:
  121. continue
  122. if (
  123. all_bboxes[j]["category_id"] != object_category_id
  124. or j in used
  125. or dis[i][j] == MAX_DIS_OF_POINT
  126. ):
  127. continue
  128. arr.append((dis[i][j], j))
  129. arr.sort(key=lambda x: x[0])
  130. if len(arr) > 0:
  131. candidates.append(arr[0][1])
  132. seen.add(arr[0][1])
  133. # 已经获取初始种子
  134. for j in set(candidates):
  135. tmp = []
  136. for k in range(i + 1, N):
  137. pos_flag_count = sum(
  138. list(
  139. map(
  140. lambda x: 1 if x else 0,
  141. bbox_relative_pos(
  142. all_bboxes[j]["bbox"], all_bboxes[k]["bbox"]
  143. ),
  144. )
  145. )
  146. )
  147. if pos_flag_count > 1:
  148. continue
  149. if (
  150. all_bboxes[k]["category_id"] != object_category_id
  151. or k in used
  152. or k in seen
  153. or dis[j][k] == MAX_DIS_OF_POINT
  154. ):
  155. continue
  156. is_nearest = True
  157. for l in range(i + 1, N):
  158. if l in (j, k) or l in used or l in seen:
  159. continue
  160. if not float_gt(dis[l][k], dis[j][k]):
  161. is_nearest = False
  162. break
  163. if is_nearest:
  164. tmp.append(k)
  165. seen.add(k)
  166. candidates = tmp
  167. if len(candidates) == 0:
  168. break
  169. # 已经获取到某个 figure 下所有的最靠近的 captions,以及最靠近这些 captions 的 captions 。
  170. # 先扩一下 bbox,
  171. x0s = [all_bboxes[idx]["bbox"][0] for idx in seen] + [
  172. all_bboxes[i]["bbox"][0]
  173. ]
  174. y0s = [all_bboxes[idx]["bbox"][1] for idx in seen] + [
  175. all_bboxes[i]["bbox"][1]
  176. ]
  177. x1s = [all_bboxes[idx]["bbox"][2] for idx in seen] + [
  178. all_bboxes[i]["bbox"][2]
  179. ]
  180. y1s = [all_bboxes[idx]["bbox"][3] for idx in seen] + [
  181. all_bboxes[i]["bbox"][3]
  182. ]
  183. ox0, oy0, ox1, oy1 = min(x0s), min(y0s), max(x1s), max(y1s)
  184. ix0, iy0, ix1, iy1 = all_bboxes[i]["bbox"]
  185. # 分成了 4 个截取空间,需要计算落在每个截取空间下 objects 合并后占据的矩形面积
  186. caption_poses = [
  187. [ox0, oy0, ix0, oy1],
  188. [ox0, oy0, ox1, iy0],
  189. [ox0, iy1, ox1, oy1],
  190. [ix1, oy0, ox1, oy1],
  191. ]
  192. caption_areas = []
  193. for bbox in caption_poses:
  194. embed_arr = []
  195. for idx in seen:
  196. if _is_in(all_bboxes[idx]["bbox"], bbox):
  197. embed_arr.append(idx)
  198. if len(embed_arr) > 0:
  199. embed_x0 = min([all_bboxes[idx]["bbox"][0] for idx in embed_arr])
  200. embed_y0 = min([all_bboxes[idx]["bbox"][1] for idx in embed_arr])
  201. embed_x1 = max([all_bboxes[idx]["bbox"][2] for idx in embed_arr])
  202. embed_y1 = max([all_bboxes[idx]["bbox"][3] for idx in embed_arr])
  203. caption_areas.append(
  204. int(abs(embed_x1 - embed_x0) * abs(embed_y1 - embed_y0))
  205. )
  206. else:
  207. caption_areas.append(0)
  208. subject_object_relation_map[i] = []
  209. if max(caption_areas) > 0:
  210. max_area_idx = caption_areas.index(max(caption_areas))
  211. caption_bbox = caption_poses[max_area_idx]
  212. for j in seen:
  213. if _is_in(all_bboxes[j]["bbox"], caption_bbox):
  214. used.add(j)
  215. subject_object_relation_map[i].append(j)
  216. for i in sorted(subject_object_relation_map.keys()):
  217. result = {
  218. "subject_body": all_bboxes[i]["bbox"],
  219. "all": all_bboxes[i]["bbox"],
  220. }
  221. if len(subject_object_relation_map[i]) > 0:
  222. x0 = min(
  223. [all_bboxes[j]["bbox"][0] for j in subject_object_relation_map[i]]
  224. )
  225. y0 = min(
  226. [all_bboxes[j]["bbox"][1] for j in subject_object_relation_map[i]]
  227. )
  228. x1 = max(
  229. [all_bboxes[j]["bbox"][2] for j in subject_object_relation_map[i]]
  230. )
  231. y1 = max(
  232. [all_bboxes[j]["bbox"][3] for j in subject_object_relation_map[i]]
  233. )
  234. result["object_body"] = [x0, y0, x1, y1]
  235. result["all"] = [
  236. min(x0, all_bboxes[i]["bbox"][0]),
  237. min(y0, all_bboxes[i]["bbox"][1]),
  238. max(x1, all_bboxes[i]["bbox"][2]),
  239. max(y1, all_bboxes[i]["bbox"][3]),
  240. ]
  241. ret.append(result)
  242. total_subject_object_dis = 0
  243. # 计算已经配对的 distance 距离
  244. for i in subject_object_relation_map.keys():
  245. for j in subject_object_relation_map[i]:
  246. total_subject_object_dis += bbox_distance(
  247. all_bboxes[i]["bbox"], all_bboxes[j]["bbox"]
  248. )
  249. # 计算未匹配的 subject 和 object 的距离(非精确版)
  250. with_caption_subject = set(
  251. [
  252. key
  253. for key in subject_object_relation_map.keys()
  254. if len(subject_object_relation_map[i]) > 0
  255. ]
  256. )
  257. for i in range(N):
  258. if all_bboxes[i]["category_id"] != object_category_id or i in used:
  259. continue
  260. candidates = []
  261. for j in range(N):
  262. if (
  263. all_bboxes[j]["category_id"] != subject_category_id
  264. or j in with_caption_subject
  265. ):
  266. continue
  267. candidates.append((dis[i][j], j))
  268. if len(candidates) > 0:
  269. candidates.sort(key=lambda x: x[0])
  270. total_subject_object_dis += candidates[0][1]
  271. with_caption_subject.add(j)
  272. return ret, total_subject_object_dis
  273. def get_imgs(self, page_no: int): # @许瑞
  274. records, _ = self.__tie_up_category_by_distance(page_no, 3, 4)
  275. return [
  276. {
  277. "bbox": record["all"],
  278. "img_body_bbox": record["subject_body"],
  279. "img_caption_bbox": record.get("object_body", None),
  280. }
  281. for record in records
  282. ]
  283. def get_tables(
  284. self, page_no: int
  285. ) -> list: # 3个坐标, caption, table主体,table-note
  286. with_captions, _ = self.__tie_up_category_by_distance(page_no, 5, 6)
  287. with_footnotes, _ = self.__tie_up_category_by_distance(page_no, 5, 7)
  288. ret = []
  289. N, M = len(with_captions), len(with_footnotes)
  290. assert N == M
  291. for i in range(N):
  292. record = {
  293. "table_caption_bbox": with_captions[i].get("object_body", None),
  294. "table_body_bbox": with_captions[i]["subject_body"],
  295. "table_footnote_bbox": with_footnotes[i].get("object_body", None),
  296. }
  297. x0 = min(with_captions[i]["all"][0], with_footnotes[i]["all"][0])
  298. y0 = min(with_captions[i]["all"][1], with_footnotes[i]["all"][1])
  299. x1 = max(with_captions[i]["all"][2], with_footnotes[i]["all"][2])
  300. y1 = max(with_captions[i]["all"][3], with_footnotes[i]["all"][3])
  301. record["bbox"] = [x0, y0, x1, y1]
  302. ret.append(record)
  303. return ret
  304. def get_equations(self, page_no: int) -> list: # 有坐标,也有字
  305. inline_equations = self.__get_blocks_by_type(ModelBlockTypeEnum.EMBEDDING.value, page_no, ["latex"])
  306. interline_equations = self.__get_blocks_by_type(ModelBlockTypeEnum.ISOLATED.value, page_no, ["latex"])
  307. interline_equations_blocks = self.__get_blocks_by_type(ModelBlockTypeEnum.ISOLATE_FORMULA.value, page_no)
  308. return inline_equations, interline_equations, interline_equations_blocks
  309. def get_discarded(self, page_no: int) -> list: # 自研模型,只有坐标
  310. blocks = self.__get_blocks_by_type(ModelBlockTypeEnum.ABANDON.value, page_no)
  311. return blocks
  312. def get_text_blocks(self, page_no: int) -> list: # 自研模型搞的,只有坐标,没有字
  313. blocks = self.__get_blocks_by_type(ModelBlockTypeEnum.PLAIN_TEXT.value, page_no)
  314. return blocks
  315. def get_title_blocks(self, page_no: int) -> list: # 自研模型,只有坐标,没字
  316. blocks = self.__get_blocks_by_type(ModelBlockTypeEnum.TITLE.value, page_no)
  317. return blocks
  318. def get_ocr_text(self, page_no: int) -> list: # paddle 搞的,有字也有坐标
  319. text_spans = []
  320. model_page_info = self.__model_list[page_no]
  321. layout_dets = model_page_info["layout_dets"]
  322. for layout_det in layout_dets:
  323. if layout_det["category_id"] == "15":
  324. span = {
  325. "bbox": layout_det['bbox'],
  326. "content": layout_det["text"],
  327. }
  328. text_spans.append(span)
  329. return text_spans
  330. def get_all_spans(self, page_no: int) -> list:
  331. all_spans = []
  332. model_page_info = self.__model_list[page_no]
  333. layout_dets = model_page_info["layout_dets"]
  334. allow_category_id_list = [3, 5, 13, 14, 15]
  335. """当成span拼接的"""
  336. # 3: 'image', # 图片
  337. # 4: 'table', # 表格
  338. # 13: 'inline_equation', # 行内公式
  339. # 14: 'interline_equation', # 行间公式
  340. # 15: 'text', # ocr识别文本
  341. for layout_det in layout_dets:
  342. category_id = layout_det["category_id"]
  343. if category_id in allow_category_id_list:
  344. span = {
  345. "bbox": layout_det['bbox']
  346. }
  347. if category_id == 3:
  348. span["type"] = ContentType.Image
  349. elif category_id == 5:
  350. span["type"] = ContentType.Table
  351. elif category_id == 13:
  352. span["content"] = layout_det["latex"]
  353. span["type"] = ContentType.InlineEquation
  354. elif category_id == 14:
  355. span["content"] = layout_det["latex"]
  356. span["type"] = ContentType.InterlineEquation
  357. elif category_id == 15:
  358. span["content"] = layout_det["text"]
  359. span["type"] = ContentType.Text
  360. all_spans.append(span)
  361. return all_spans
  362. def get_page_size(self, page_no: int): # 获取页面宽高
  363. # 获取当前页的page对象
  364. page = self.__docs[page_no]
  365. # 获取当前页的宽高
  366. page_w = page.rect.width
  367. page_h = page.rect.height
  368. return page_w, page_h
  369. def __get_blocks_by_type(self, types: list, page_no: int, extra_col: list[str] = []) -> list:
  370. blocks = []
  371. for page_dict in self.__model_list:
  372. layout_dets = page_dict.get("layout_dets", [])
  373. page_info = page_dict.get("page_info", {})
  374. page_number = page_info.get("page_no", -1)
  375. if page_no != page_number:
  376. continue
  377. for item in layout_dets:
  378. category_id = item.get("category_id", -1)
  379. bbox = item.get("bbox", None)
  380. if category_id in types:
  381. block = {
  382. "bbox": bbox
  383. }
  384. for col in extra_col:
  385. block[col] = item.get(col, None)
  386. blocks.append(block)
  387. return blocks
  388. if __name__ == "__main__":
  389. drw = DiskReaderWriter(r"D:/project/20231108code-clean")
  390. if 0:
  391. pdf_file_path = r"linshixuqiu\19983-00.pdf"
  392. model_file_path = r"linshixuqiu\19983-00_new.json"
  393. pdf_bytes = drw.read(pdf_file_path, AbsReaderWriter.MODE_BIN)
  394. model_json_txt = drw.read(model_file_path, AbsReaderWriter.MODE_TXT)
  395. model_list = json.loads(model_json_txt)
  396. write_path = r"D:\project\20231108code-clean\linshixuqiu\19983-00"
  397. img_bucket_path = "imgs"
  398. img_writer = DiskReaderWriter(join_path(write_path, img_bucket_path))
  399. pdf_docs = fitz.open("pdf", pdf_bytes)
  400. magic_model = MagicModel(model_list, pdf_docs)
  401. if 1:
  402. model_list = json.loads(
  403. drw.read("/opt/data/pdf/20240418/j.chroma.2009.03.042.json")
  404. )
  405. pdf_bytes = drw.read(
  406. "/opt/data/pdf/20240418/j.chroma.2009.03.042.pdf", AbsReaderWriter.MODE_BIN
  407. )
  408. pdf_docs = fitz.open("pdf", pdf_bytes)
  409. magic_model = MagicModel(model_list, pdf_docs)
  410. for i in range(7):
  411. print(magic_model.get_imgs(i))
  412. def __reduct_overlap(self, bboxes):
  413. N = len(bboxes)
  414. keep = [True] * N
  415. for i in range(N):
  416. for j in range(N):
  417. if i == j:
  418. continue
  419. if _is_in(bboxes[i], bboxes[j]):
  420. keep[i] = False
  421. return [bboxes[i] for i in range(N) if keep[i]]
  422. def __tie_up_category_by_distance(
  423. self, page_no, subject_category_id, object_category_id
  424. ):
  425. """
  426. 假定每个 subject 最多有一个 object (可以有多个相邻的 object 合并为单个 object),每个 object 只能属于一个 subject
  427. """
  428. ret = []
  429. MAX_DIS_OF_POINT = 10**9 + 7
  430. subjects = self.__reduct_overlap(
  431. list(
  432. map(
  433. lambda x: x["bbox"],
  434. filter(
  435. lambda x: x["category_id"] == subject_category_id,
  436. self.__model_list[page_no]["layout_dets"],
  437. ),
  438. )
  439. )
  440. )
  441. objects = self.__reduct_overlap(
  442. list(
  443. map(
  444. lambda x: x["bbox"],
  445. filter(
  446. lambda x: x["category_id"] == object_category_id,
  447. self.__model_list[page_no]["layout_dets"],
  448. ),
  449. )
  450. )
  451. )
  452. subject_object_relation_map = {}
  453. subjects.sort(key=lambda x: x[0] ** 2 + x[1] ** 2) # get the distance !
  454. all_bboxes = []
  455. for v in subjects:
  456. all_bboxes.append({"category_id": subject_category_id, "bbox": v})
  457. for v in objects:
  458. all_bboxes.append({"category_id": object_category_id, "bbox": v})
  459. N = len(all_bboxes)
  460. dis = [[MAX_DIS_OF_POINT] * N for _ in range(N)]
  461. for i in range(N):
  462. for j in range(i):
  463. if (
  464. all_bboxes[i]["category_id"] == subject_category_id
  465. and all_bboxes[j]["category_id"] == subject_category_id
  466. ):
  467. continue
  468. dis[i][j] = bbox_distance(all_bboxes[i]["bbox"], all_bboxes[j]["bbox"])
  469. dis[j][i] = dis[i][j]
  470. used = set()
  471. for i in range(N):
  472. # 求第 i 个 subject 所关联的 object
  473. if all_bboxes[i]["category_id"] != subject_category_id:
  474. continue
  475. seen = set()
  476. candidates = []
  477. arr = []
  478. for j in range(N):
  479. pos_flag_count = sum(
  480. list(
  481. map(
  482. lambda x: 1 if x else 0,
  483. bbox_relative_pos(
  484. all_bboxes[i]["bbox"], all_bboxes[j]["bbox"]
  485. ),
  486. )
  487. )
  488. )
  489. if pos_flag_count > 1:
  490. continue
  491. if (
  492. all_bboxes[j]["category_id"] != object_category_id
  493. or j in used
  494. or dis[i][j] == MAX_DIS_OF_POINT
  495. ):
  496. continue
  497. arr.append((dis[i][j], j))
  498. arr.sort(key=lambda x: x[0])
  499. if len(arr) > 0:
  500. candidates.append(arr[0][1])
  501. seen.add(arr[0][1])
  502. # 已经获取初始种子
  503. for j in set(candidates):
  504. tmp = []
  505. for k in range(i + 1, N):
  506. pos_flag_count = sum(
  507. list(
  508. map(
  509. lambda x: 1 if x else 0,
  510. bbox_relative_pos(
  511. all_bboxes[j]["bbox"], all_bboxes[k]["bbox"]
  512. ),
  513. )
  514. )
  515. )
  516. if pos_flag_count > 1:
  517. continue
  518. if (
  519. all_bboxes[k]["category_id"] != object_category_id
  520. or k in used
  521. or k in seen
  522. or dis[j][k] == MAX_DIS_OF_POINT
  523. ):
  524. continue
  525. is_nearest = True
  526. for l in range(i + 1, N):
  527. if l in (j, k) or l in used or l in seen:
  528. continue
  529. if not float_gt(dis[l][k], dis[j][k]):
  530. is_nearest = False
  531. break
  532. if is_nearest:
  533. tmp.append(k)
  534. seen.add(k)
  535. candidates = tmp
  536. if len(candidates) == 0:
  537. break
  538. # 已经获取到某个 figure 下所有的最靠近的 captions,以及最靠近这些 captions 的 captions 。
  539. # 先扩一下 bbox,
  540. x0s = [all_bboxes[idx]["bbox"][0] for idx in seen] + [
  541. all_bboxes[i]["bbox"][0]
  542. ]
  543. y0s = [all_bboxes[idx]["bbox"][1] for idx in seen] + [
  544. all_bboxes[i]["bbox"][1]
  545. ]
  546. x1s = [all_bboxes[idx]["bbox"][2] for idx in seen] + [
  547. all_bboxes[i]["bbox"][2]
  548. ]
  549. y1s = [all_bboxes[idx]["bbox"][3] for idx in seen] + [
  550. all_bboxes[i]["bbox"][3]
  551. ]
  552. ox0, oy0, ox1, oy1 = min(x0s), min(y0s), max(x1s), max(y1s)
  553. ix0, iy0, ix1, iy1 = all_bboxes[i]["bbox"]
  554. # 分成了 4 个截取空间,需要计算落在每个截取空间下 objects 合并后占据的矩形面积
  555. caption_poses = [
  556. [ox0, oy0, ix0, oy1],
  557. [ox0, oy0, ox1, iy0],
  558. [ox0, iy1, ox1, oy1],
  559. [ix1, oy0, ox1, oy1],
  560. ]
  561. caption_areas = []
  562. for bbox in caption_poses:
  563. embed_arr = []
  564. for idx in seen:
  565. if _is_in(all_bboxes[idx]["bbox"], bbox):
  566. embed_arr.append(idx)
  567. if len(embed_arr) > 0:
  568. embed_x0 = min([all_bboxes[idx]["bbox"][0] for idx in embed_arr])
  569. embed_y0 = min([all_bboxes[idx]["bbox"][1] for idx in embed_arr])
  570. embed_x1 = max([all_bboxes[idx]["bbox"][2] for idx in embed_arr])
  571. embed_y1 = max([all_bboxes[idx]["bbox"][3] for idx in embed_arr])
  572. caption_areas.append(
  573. int(abs(embed_x1 - embed_x0) * abs(embed_y1 - embed_y0))
  574. )
  575. else:
  576. caption_areas.append(0)
  577. subject_object_relation_map[i] = []
  578. if max(caption_areas) > 0:
  579. max_area_idx = caption_areas.index(max(caption_areas))
  580. caption_bbox = caption_poses[max_area_idx]
  581. for j in seen:
  582. if _is_in(all_bboxes[j]["bbox"], caption_bbox):
  583. used.add(j)
  584. subject_object_relation_map[i].append(j)
  585. for i in sorted(subject_object_relation_map.keys()):
  586. result = {
  587. "subject_body": all_bboxes[i]["bbox"],
  588. "all": all_bboxes[i]["bbox"],
  589. }
  590. if len(subject_object_relation_map[i]) > 0:
  591. x0 = min(
  592. [all_bboxes[j]["bbox"][0] for j in subject_object_relation_map[i]]
  593. )
  594. y0 = min(
  595. [all_bboxes[j]["bbox"][1] for j in subject_object_relation_map[i]]
  596. )
  597. x1 = max(
  598. [all_bboxes[j]["bbox"][2] for j in subject_object_relation_map[i]]
  599. )
  600. y1 = max(
  601. [all_bboxes[j]["bbox"][3] for j in subject_object_relation_map[i]]
  602. )
  603. result["object_body"] = [x0, y0, x1, y1]
  604. result["all"] = [
  605. min(x0, all_bboxes[i]["bbox"][0]),
  606. min(y0, all_bboxes[i]["bbox"][1]),
  607. max(x1, all_bboxes[i]["bbox"][2]),
  608. max(y1, all_bboxes[i]["bbox"][3]),
  609. ]
  610. ret.append(result)
  611. total_subject_object_dis = 0
  612. # 计算已经配对的 distance 距离
  613. for i in subject_object_relation_map.keys():
  614. for j in subject_object_relation_map[i]:
  615. total_subject_object_dis += bbox_distance(
  616. all_bboxes[i]["bbox"], all_bboxes[j]["bbox"]
  617. )
  618. # 计算未匹配的 subject 和 object 的距离(非精确版)
  619. with_caption_subject = set(
  620. [
  621. key
  622. for key in subject_object_relation_map.keys()
  623. if len(subject_object_relation_map[i]) > 0
  624. ]
  625. )
  626. for i in range(N):
  627. if all_bboxes[i]["category_id"] != object_category_id or i in used:
  628. continue
  629. candidates = []
  630. for j in range(N):
  631. if (
  632. all_bboxes[j]["category_id"] != subject_category_id
  633. or j in with_caption_subject
  634. ):
  635. continue
  636. candidates.append((dis[i][j], j))
  637. if len(candidates) > 0:
  638. candidates.sort(key=lambda x: x[0])
  639. total_subject_object_dis += candidates[0][1]
  640. with_caption_subject.add(j)
  641. return ret, total_subject_object_dis
  642. def get_imgs(self, page_no: int): # @许瑞
  643. records, _ = self.__tie_up_category_by_distance(page_no, 3, 4)
  644. return [
  645. {
  646. "bbox": record["all"],
  647. "img_body_bbox": record["subject_body"],
  648. "img_caption_bbox": record.get("object_body", None),
  649. }
  650. for record in records
  651. ]
  652. def get_tables(
  653. self, page_no: int
  654. ) -> list: # 3个坐标, caption, table主体,table-note
  655. with_captions, _ = self.__tie_up_category_by_distance(page_no, 5, 6)
  656. with_footnotes, _ = self.__tie_up_category_by_distance(page_no, 5, 7)
  657. ret = []
  658. N, M = len(with_captions), len(with_footnotes)
  659. assert N == M
  660. for i in range(N):
  661. record = {
  662. "table_caption_bbox": with_captions[i].get("object_body", None),
  663. "table_body_bbox": with_captions[i]["subject_body"],
  664. "table_footnote_bbox": with_footnotes[i].get("object_body", None),
  665. }
  666. x0 = min(with_captions[i]["all"][0], with_footnotes[i]["all"][0])
  667. y0 = min(with_captions[i]["all"][1], with_footnotes[i]["all"][1])
  668. x1 = max(with_captions[i]["all"][2], with_footnotes[i]["all"][2])
  669. y1 = max(with_captions[i]["all"][3], with_footnotes[i]["all"][3])
  670. record["bbox"] = [x0, y0, x1, y1]
  671. ret.append(record)
  672. return ret
  673. def get_equations(self, page_no: int) -> list: # 有坐标,也有字
  674. inline_equations = self.__get_blocks_by_type(ModelBlockTypeEnum.EMBEDDING.value, page_no, ["latex"])
  675. interline_equations = self.__get_blocks_by_type(ModelBlockTypeEnum.ISOLATED.value, page_no, ["latex"])
  676. interline_equations_blocks = self.__get_blocks_by_type(ModelBlockTypeEnum.ISOLATE_FORMULA.value, page_no)
  677. return inline_equations, interline_equations, interline_equations_blocks
  678. def get_discarded(self, page_no: int) -> list: # 自研模型,只有坐标
  679. blocks = self.__get_blocks_by_type(ModelBlockTypeEnum.ABANDON.value, page_no)
  680. return blocks
  681. def get_text_blocks(self, page_no: int) -> list: # 自研模型搞的,只有坐标,没有字
  682. blocks = self.__get_blocks_by_type(ModelBlockTypeEnum.PLAIN_TEXT.value, page_no)
  683. return blocks
  684. def get_title_blocks(self, page_no: int) -> list: # 自研模型,只有坐标,没字
  685. blocks = self.__get_blocks_by_type(ModelBlockTypeEnum.TITLE.value, page_no)
  686. return blocks
  687. def get_ocr_text(self, page_no: int) -> list: # paddle 搞的,有字也有坐标
  688. text_spans = []
  689. model_page_info = self.__model_list[page_no]
  690. layout_dets = model_page_info["layout_dets"]
  691. for layout_det in layout_dets:
  692. if layout_det["category_id"] == "15":
  693. span = {
  694. "bbox": layout_det['bbox'],
  695. "content": layout_det["text"],
  696. }
  697. text_spans.append(span)
  698. return text_spans
  699. def get_all_spans(self, page_no: int) -> list:
  700. all_spans = []
  701. model_page_info = self.__model_list[page_no]
  702. layout_dets = model_page_info["layout_dets"]
  703. allow_category_id_list = [3, 5, 13, 14, 15]
  704. """当成span拼接的"""
  705. # 3: 'image', # 图片
  706. # 4: 'table', # 表格
  707. # 13: 'inline_equation', # 行内公式
  708. # 14: 'interline_equation', # 行间公式
  709. # 15: 'text', # ocr识别文本
  710. for layout_det in layout_dets:
  711. category_id = layout_det["category_id"]
  712. if category_id in allow_category_id_list:
  713. span = {
  714. "bbox": layout_det['bbox']
  715. }
  716. if category_id == 3:
  717. span["type"] = ContentType.Image
  718. elif category_id == 5:
  719. span["type"] = ContentType.Table
  720. elif category_id == 13:
  721. span["content"] = layout_det["latex"]
  722. span["type"] = ContentType.InlineEquation
  723. elif category_id == 14:
  724. span["content"] = layout_det["latex"]
  725. span["type"] = ContentType.InterlineEquation
  726. elif category_id == 15:
  727. span["content"] = layout_det["text"]
  728. span["type"] = ContentType.Text
  729. all_spans.append(span)
  730. return all_spans
  731. def get_page_size(self, page_no: int): # 获取页面宽高
  732. # 获取当前页的page对象
  733. page = self.__docs[page_no]
  734. # 获取当前页的宽高
  735. page_w = page.rect.width
  736. page_h = page.rect.height
  737. return page_w, page_h
  738. def __get_blocks_by_type(self, types: list, page_no: int, extra_col: list[str] = []) -> list:
  739. blocks = []
  740. for page_dict in self.__model_list:
  741. layout_dets = page_dict.get("layout_dets", [])
  742. page_info = page_dict.get("page_info", {})
  743. page_number = page_info.get("page_no", -1)
  744. if page_no != page_number:
  745. continue
  746. for item in layout_dets:
  747. category_id = item.get("category_id", -1)
  748. bbox = item.get("bbox", None)
  749. if category_id in types:
  750. block = {
  751. "bbox": bbox
  752. }
  753. for col in extra_col:
  754. block[col] = item.get(col, None)
  755. blocks.append(block)
  756. return blocks
  757. if __name__ == "__main__":
  758. drw = DiskReaderWriter(r"D:/project/20231108code-clean")
  759. if 0:
  760. pdf_file_path = r"linshixuqiu\19983-00.pdf"
  761. model_file_path = r"linshixuqiu\19983-00_new.json"
  762. pdf_bytes = drw.read(pdf_file_path, AbsReaderWriter.MODE_BIN)
  763. model_json_txt = drw.read(model_file_path, AbsReaderWriter.MODE_TXT)
  764. model_list = json.loads(model_json_txt)
  765. write_path = r"D:\project\20231108code-clean\linshixuqiu\19983-00"
  766. img_bucket_path = "imgs"
  767. img_writer = DiskReaderWriter(join_path(write_path, img_bucket_path))
  768. pdf_docs = fitz.open("pdf", pdf_bytes)
  769. magic_model = MagicModel(model_list, pdf_docs)
  770. if 1:
  771. model_list = json.loads(
  772. drw.read("/opt/data/pdf/20240418/j.chroma.2009.03.042.json")
  773. )
  774. pdf_bytes = drw.read(
  775. "/opt/data/pdf/20240418/j.chroma.2009.03.042.pdf", AbsReaderWriter.MODE_BIN
  776. )
  777. pdf_docs = fitz.open("pdf", pdf_bytes)
  778. magic_model = MagicModel(model_list, pdf_docs)
  779. for i in range(7):
  780. print(magic_model.get_imgs(i))