magic_model.py 25 KB

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