pdf_extract_kit.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. from loguru import logger
  2. import os
  3. import time
  4. from pathlib import Path
  5. import shutil
  6. from magic_pdf.libs.Constants import *
  7. from magic_pdf.libs.clean_memory import clean_memory
  8. from magic_pdf.model.model_list import AtomicModel
  9. os.environ['NO_ALBUMENTATIONS_UPDATE'] = '1' # 禁止albumentations检查更新
  10. os.environ['YOLO_VERBOSE'] = 'False' # disable yolo logger
  11. try:
  12. import cv2
  13. import yaml
  14. import argparse
  15. import numpy as np
  16. import torch
  17. import torchtext
  18. if torchtext.__version__ >= "0.18.0":
  19. torchtext.disable_torchtext_deprecation_warning()
  20. from PIL import Image
  21. from torchvision import transforms
  22. from torch.utils.data import Dataset, DataLoader
  23. from ultralytics import YOLO
  24. from unimernet.common.config import Config
  25. import unimernet.tasks as tasks
  26. from unimernet.processors import load_processor
  27. from doclayout_yolo import YOLOv10
  28. except ImportError as e:
  29. logger.exception(e)
  30. logger.error(
  31. 'Required dependency not installed, please install by \n'
  32. '"pip install magic-pdf[full] --extra-index-url https://myhloli.github.io/wheels/"')
  33. exit(1)
  34. from magic_pdf.model.pek_sub_modules.layoutlmv3.model_init import Layoutlmv3_Predictor
  35. from magic_pdf.model.pek_sub_modules.post_process import latex_rm_whitespace
  36. from magic_pdf.model.pek_sub_modules.self_modify import ModifiedPaddleOCR
  37. # from magic_pdf.model.pek_sub_modules.structeqtable.StructTableModel import StructTableModel
  38. from magic_pdf.model.ppTableModel import ppTableModel
  39. def table_model_init(table_model_type, model_path, max_time, _device_='cpu'):
  40. if table_model_type == MODEL_NAME.STRUCT_EQTABLE:
  41. # table_model = StructTableModel(model_path, max_time=max_time, device=_device_)
  42. logger.error("StructEqTable is under upgrade, the current version does not support it.")
  43. exit(1)
  44. elif table_model_type == MODEL_NAME.TABLE_MASTER:
  45. config = {
  46. "model_dir": model_path,
  47. "device": _device_
  48. }
  49. table_model = ppTableModel(config)
  50. else:
  51. logger.error("table model type not allow")
  52. exit(1)
  53. return table_model
  54. def mfd_model_init(weight):
  55. mfd_model = YOLO(weight)
  56. return mfd_model
  57. def mfr_model_init(weight_dir, cfg_path, _device_='cpu'):
  58. args = argparse.Namespace(cfg_path=cfg_path, options=None)
  59. cfg = Config(args)
  60. cfg.config.model.pretrained = os.path.join(weight_dir, "pytorch_model.pth")
  61. cfg.config.model.model_config.model_name = weight_dir
  62. cfg.config.model.tokenizer_config.path = weight_dir
  63. task = tasks.setup_task(cfg)
  64. model = task.build_model(cfg)
  65. model.to(_device_)
  66. model.eval()
  67. vis_processor = load_processor('formula_image_eval', cfg.config.datasets.formula_rec_eval.vis_processor.eval)
  68. mfr_transform = transforms.Compose([vis_processor, ])
  69. return [model, mfr_transform]
  70. def layout_model_init(weight, config_file, device):
  71. model = Layoutlmv3_Predictor(weight, config_file, device)
  72. return model
  73. def doclayout_yolo_model_init(weight):
  74. model = YOLOv10(weight)
  75. return model
  76. def ocr_model_init(show_log: bool = False, det_db_box_thresh=0.3, lang=None, use_dilation=True, det_db_unclip_ratio=1.8):
  77. if lang is not None:
  78. model = ModifiedPaddleOCR(show_log=show_log, det_db_box_thresh=det_db_box_thresh, lang=lang, use_dilation=use_dilation, det_db_unclip_ratio=det_db_unclip_ratio)
  79. else:
  80. model = ModifiedPaddleOCR(show_log=show_log, det_db_box_thresh=det_db_box_thresh, use_dilation=use_dilation, det_db_unclip_ratio=det_db_unclip_ratio)
  81. return model
  82. class MathDataset(Dataset):
  83. def __init__(self, image_paths, transform=None):
  84. self.image_paths = image_paths
  85. self.transform = transform
  86. def __len__(self):
  87. return len(self.image_paths)
  88. def __getitem__(self, idx):
  89. # if not pil image, then convert to pil image
  90. if isinstance(self.image_paths[idx], str):
  91. raw_image = Image.open(self.image_paths[idx])
  92. else:
  93. raw_image = self.image_paths[idx]
  94. if self.transform:
  95. image = self.transform(raw_image)
  96. return image
  97. class AtomModelSingleton:
  98. _instance = None
  99. _models = {}
  100. def __new__(cls, *args, **kwargs):
  101. if cls._instance is None:
  102. cls._instance = super().__new__(cls)
  103. return cls._instance
  104. def get_atom_model(self, atom_model_name: str, **kwargs):
  105. lang = kwargs.get("lang", None)
  106. layout_model_name = kwargs.get("layout_model_name", None)
  107. key = (atom_model_name, layout_model_name, lang)
  108. if key not in self._models:
  109. self._models[key] = atom_model_init(model_name=atom_model_name, **kwargs)
  110. return self._models[key]
  111. def atom_model_init(model_name: str, **kwargs):
  112. if model_name == AtomicModel.Layout:
  113. if kwargs.get("layout_model_name") == MODEL_NAME.LAYOUTLMv3:
  114. atom_model = layout_model_init(
  115. kwargs.get("layout_weights"),
  116. kwargs.get("layout_config_file"),
  117. kwargs.get("device")
  118. )
  119. elif kwargs.get("layout_model_name") == MODEL_NAME.DocLayout_YOLO:
  120. atom_model = doclayout_yolo_model_init(
  121. kwargs.get("doclayout_yolo_weights"),
  122. )
  123. elif model_name == AtomicModel.MFD:
  124. atom_model = mfd_model_init(
  125. kwargs.get("mfd_weights")
  126. )
  127. elif model_name == AtomicModel.MFR:
  128. atom_model = mfr_model_init(
  129. kwargs.get("mfr_weight_dir"),
  130. kwargs.get("mfr_cfg_path"),
  131. kwargs.get("device")
  132. )
  133. elif model_name == AtomicModel.OCR:
  134. atom_model = ocr_model_init(
  135. kwargs.get("ocr_show_log"),
  136. kwargs.get("det_db_box_thresh"),
  137. kwargs.get("lang")
  138. )
  139. elif model_name == AtomicModel.Table:
  140. atom_model = table_model_init(
  141. kwargs.get("table_model_name"),
  142. kwargs.get("table_model_path"),
  143. kwargs.get("table_max_time"),
  144. kwargs.get("device")
  145. )
  146. else:
  147. logger.error("model name not allow")
  148. exit(1)
  149. return atom_model
  150. # Unified crop img logic
  151. def crop_img(input_res, input_pil_img, crop_paste_x=0, crop_paste_y=0):
  152. crop_xmin, crop_ymin = int(input_res['poly'][0]), int(input_res['poly'][1])
  153. crop_xmax, crop_ymax = int(input_res['poly'][4]), int(input_res['poly'][5])
  154. # Create a white background with an additional width and height of 50
  155. crop_new_width = crop_xmax - crop_xmin + crop_paste_x * 2
  156. crop_new_height = crop_ymax - crop_ymin + crop_paste_y * 2
  157. return_image = Image.new('RGB', (crop_new_width, crop_new_height), 'white')
  158. # Crop image
  159. crop_box = (crop_xmin, crop_ymin, crop_xmax, crop_ymax)
  160. cropped_img = input_pil_img.crop(crop_box)
  161. return_image.paste(cropped_img, (crop_paste_x, crop_paste_y))
  162. return_list = [crop_paste_x, crop_paste_y, crop_xmin, crop_ymin, crop_xmax, crop_ymax, crop_new_width, crop_new_height]
  163. return return_image, return_list
  164. class CustomPEKModel:
  165. def __init__(self, ocr: bool = False, show_log: bool = False, **kwargs):
  166. """
  167. ======== model init ========
  168. """
  169. # 获取当前文件(即 pdf_extract_kit.py)的绝对路径
  170. current_file_path = os.path.abspath(__file__)
  171. # 获取当前文件所在的目录(model)
  172. current_dir = os.path.dirname(current_file_path)
  173. # 上一级目录(magic_pdf)
  174. root_dir = os.path.dirname(current_dir)
  175. # model_config目录
  176. model_config_dir = os.path.join(root_dir, 'resources', 'model_config')
  177. # 构建 model_configs.yaml 文件的完整路径
  178. config_path = os.path.join(model_config_dir, 'model_configs.yaml')
  179. with open(config_path, "r", encoding='utf-8') as f:
  180. self.configs = yaml.load(f, Loader=yaml.FullLoader)
  181. # 初始化解析配置
  182. # layout config
  183. self.layout_config = kwargs.get("layout_config")
  184. self.layout_model_name = self.layout_config.get("model", MODEL_NAME.DocLayout_YOLO)
  185. # formula config
  186. self.formula_config = kwargs.get("formula_config")
  187. self.mfd_model_name = self.formula_config.get("mfd_model", MODEL_NAME.YOLO_V8_MFD)
  188. self.mfr_model_name = self.formula_config.get("mfr_model", MODEL_NAME.UniMerNet_v2_Small)
  189. self.apply_formula = self.formula_config.get("enable", True)
  190. # table config
  191. self.table_config = kwargs.get("table_config")
  192. self.apply_table = self.table_config.get("enable", False)
  193. self.table_max_time = self.table_config.get("max_time", TABLE_MAX_TIME_VALUE)
  194. self.table_model_name = self.table_config.get("model", MODEL_NAME.TABLE_MASTER)
  195. # ocr config
  196. self.apply_ocr = ocr
  197. self.lang = kwargs.get("lang", None)
  198. logger.info(
  199. "DocAnalysis init, this may take some times, layout_model: {}, apply_formula: {}, apply_ocr: {}, "
  200. "apply_table: {}, table_model: {}, lang: {}".format(
  201. self.layout_model_name, self.apply_formula, self.apply_ocr, self.apply_table, self.table_model_name, self.lang
  202. )
  203. )
  204. # 初始化解析方案
  205. self.device = kwargs.get("device", "cpu")
  206. logger.info("using device: {}".format(self.device))
  207. models_dir = kwargs.get("models_dir", os.path.join(root_dir, "resources", "models"))
  208. logger.info("using models_dir: {}".format(models_dir))
  209. atom_model_manager = AtomModelSingleton()
  210. # 初始化公式识别
  211. if self.apply_formula:
  212. # 初始化公式检测模型
  213. self.mfd_model = atom_model_manager.get_atom_model(
  214. atom_model_name=AtomicModel.MFD,
  215. mfd_weights=str(os.path.join(models_dir, self.configs["weights"][self.mfd_model_name]))
  216. )
  217. # 初始化公式解析模型
  218. mfr_weight_dir = str(os.path.join(models_dir, self.configs["weights"][self.mfr_model_name]))
  219. mfr_cfg_path = str(os.path.join(model_config_dir, "UniMERNet", "demo.yaml"))
  220. self.mfr_model, self.mfr_transform = atom_model_manager.get_atom_model(
  221. atom_model_name=AtomicModel.MFR,
  222. mfr_weight_dir=mfr_weight_dir,
  223. mfr_cfg_path=mfr_cfg_path,
  224. device=self.device
  225. )
  226. # 初始化layout模型
  227. if self.layout_model_name == MODEL_NAME.LAYOUTLMv3:
  228. self.layout_model = atom_model_manager.get_atom_model(
  229. atom_model_name=AtomicModel.Layout,
  230. layout_model_name=MODEL_NAME.LAYOUTLMv3,
  231. layout_weights=str(os.path.join(models_dir, self.configs['weights'][self.layout_model_name])),
  232. layout_config_file=str(os.path.join(model_config_dir, "layoutlmv3", "layoutlmv3_base_inference.yaml")),
  233. device=self.device
  234. )
  235. elif self.layout_model_name == MODEL_NAME.DocLayout_YOLO:
  236. self.layout_model = atom_model_manager.get_atom_model(
  237. atom_model_name=AtomicModel.Layout,
  238. layout_model_name=MODEL_NAME.DocLayout_YOLO,
  239. doclayout_yolo_weights=str(os.path.join(models_dir, self.configs['weights'][self.layout_model_name]))
  240. )
  241. # 初始化ocr
  242. if self.apply_ocr:
  243. # self.ocr_model = ModifiedPaddleOCR(show_log=show_log, det_db_box_thresh=0.3)
  244. self.ocr_model = atom_model_manager.get_atom_model(
  245. atom_model_name=AtomicModel.OCR,
  246. ocr_show_log=show_log,
  247. det_db_box_thresh=0.3,
  248. lang=self.lang
  249. )
  250. # init table model
  251. if self.apply_table:
  252. table_model_dir = self.configs["weights"][self.table_model_name]
  253. self.table_model = atom_model_manager.get_atom_model(
  254. atom_model_name=AtomicModel.Table,
  255. table_model_name=self.table_model_name,
  256. table_model_path=str(os.path.join(models_dir, table_model_dir)),
  257. table_max_time=self.table_max_time,
  258. device=self.device
  259. )
  260. home_directory = Path.home()
  261. det_source = os.path.join(models_dir, table_model_dir, DETECT_MODEL_DIR)
  262. rec_source = os.path.join(models_dir, table_model_dir, REC_MODEL_DIR)
  263. det_dest_dir = os.path.join(home_directory, PP_DET_DIRECTORY)
  264. rec_dest_dir = os.path.join(home_directory, PP_REC_DIRECTORY)
  265. if not os.path.exists(det_dest_dir):
  266. shutil.copytree(det_source, det_dest_dir)
  267. if not os.path.exists(rec_dest_dir):
  268. shutil.copytree(rec_source, rec_dest_dir)
  269. logger.info('DocAnalysis init done!')
  270. def __call__(self, image):
  271. page_start = time.time()
  272. latex_filling_list = []
  273. mf_image_list = []
  274. # layout检测
  275. layout_start = time.time()
  276. if self.layout_model_name == MODEL_NAME.LAYOUTLMv3:
  277. # layoutlmv3
  278. layout_res = self.layout_model(image, ignore_catids=[])
  279. elif self.layout_model_name == MODEL_NAME.DocLayout_YOLO:
  280. # doclayout_yolo
  281. layout_res = []
  282. doclayout_yolo_res = self.layout_model.predict(image, imgsz=1024, conf=0.25, iou=0.45, verbose=True, device=self.device)[0]
  283. for xyxy, conf, cla in zip(doclayout_yolo_res.boxes.xyxy.cpu(), doclayout_yolo_res.boxes.conf.cpu(), doclayout_yolo_res.boxes.cls.cpu()):
  284. xmin, ymin, xmax, ymax = [int(p.item()) for p in xyxy]
  285. new_item = {
  286. 'category_id': int(cla.item()),
  287. 'poly': [xmin, ymin, xmax, ymin, xmax, ymax, xmin, ymax],
  288. 'score': round(float(conf.item()), 3),
  289. }
  290. layout_res.append(new_item)
  291. layout_cost = round(time.time() - layout_start, 2)
  292. logger.info(f"layout detection time: {layout_cost}")
  293. pil_img = Image.fromarray(image)
  294. if self.apply_formula:
  295. # 公式检测
  296. mfd_start = time.time()
  297. mfd_res = self.mfd_model.predict(image, imgsz=1888, conf=0.25, iou=0.45, verbose=True, device=self.device)[0]
  298. logger.info(f"mfd time: {round(time.time() - mfd_start, 2)}")
  299. for xyxy, conf, cla in zip(mfd_res.boxes.xyxy.cpu(), mfd_res.boxes.conf.cpu(), mfd_res.boxes.cls.cpu()):
  300. xmin, ymin, xmax, ymax = [int(p.item()) for p in xyxy]
  301. new_item = {
  302. 'category_id': 13 + int(cla.item()),
  303. 'poly': [xmin, ymin, xmax, ymin, xmax, ymax, xmin, ymax],
  304. 'score': round(float(conf.item()), 2),
  305. 'latex': '',
  306. }
  307. layout_res.append(new_item)
  308. latex_filling_list.append(new_item)
  309. bbox_img = pil_img.crop((xmin, ymin, xmax, ymax))
  310. mf_image_list.append(bbox_img)
  311. # 公式识别
  312. mfr_start = time.time()
  313. dataset = MathDataset(mf_image_list, transform=self.mfr_transform)
  314. dataloader = DataLoader(dataset, batch_size=64, num_workers=0)
  315. mfr_res = []
  316. for mf_img in dataloader:
  317. mf_img = mf_img.to(self.device)
  318. with torch.no_grad():
  319. output = self.mfr_model.generate({'image': mf_img})
  320. mfr_res.extend(output['pred_str'])
  321. for res, latex in zip(latex_filling_list, mfr_res):
  322. res['latex'] = latex_rm_whitespace(latex)
  323. mfr_cost = round(time.time() - mfr_start, 2)
  324. logger.info(f"formula nums: {len(mf_image_list)}, mfr time: {mfr_cost}")
  325. # Select regions for OCR / formula regions / table regions
  326. ocr_res_list = []
  327. table_res_list = []
  328. single_page_mfdetrec_res = []
  329. for res in layout_res:
  330. if int(res['category_id']) in [13, 14]:
  331. single_page_mfdetrec_res.append({
  332. "bbox": [int(res['poly'][0]), int(res['poly'][1]),
  333. int(res['poly'][4]), int(res['poly'][5])],
  334. })
  335. elif int(res['category_id']) in [0, 1, 2, 4, 6, 7]:
  336. ocr_res_list.append(res)
  337. elif int(res['category_id']) in [5]:
  338. table_res_list.append(res)
  339. if torch.cuda.is_available() and self.device != 'cpu':
  340. properties = torch.cuda.get_device_properties(self.device)
  341. total_memory = properties.total_memory / (1024 ** 3) # 将字节转换为 GB
  342. if total_memory <= 10:
  343. gc_start = time.time()
  344. clean_memory()
  345. gc_time = round(time.time() - gc_start, 2)
  346. logger.info(f"gc time: {gc_time}")
  347. # ocr识别
  348. if self.apply_ocr:
  349. ocr_start = time.time()
  350. # Process each area that requires OCR processing
  351. for res in ocr_res_list:
  352. new_image, useful_list = crop_img(res, pil_img, crop_paste_x=50, crop_paste_y=50)
  353. paste_x, paste_y, xmin, ymin, xmax, ymax, new_width, new_height = useful_list
  354. # Adjust the coordinates of the formula area
  355. adjusted_mfdetrec_res = []
  356. for mf_res in single_page_mfdetrec_res:
  357. mf_xmin, mf_ymin, mf_xmax, mf_ymax = mf_res["bbox"]
  358. # Adjust the coordinates of the formula area to the coordinates relative to the cropping area
  359. x0 = mf_xmin - xmin + paste_x
  360. y0 = mf_ymin - ymin + paste_y
  361. x1 = mf_xmax - xmin + paste_x
  362. y1 = mf_ymax - ymin + paste_y
  363. # Filter formula blocks outside the graph
  364. if any([x1 < 0, y1 < 0]) or any([x0 > new_width, y0 > new_height]):
  365. continue
  366. else:
  367. adjusted_mfdetrec_res.append({
  368. "bbox": [x0, y0, x1, y1],
  369. })
  370. # OCR recognition
  371. new_image = cv2.cvtColor(np.asarray(new_image), cv2.COLOR_RGB2BGR)
  372. ocr_res = self.ocr_model.ocr(new_image, mfd_res=adjusted_mfdetrec_res)[0]
  373. # Integration results
  374. if ocr_res:
  375. for box_ocr_res in ocr_res:
  376. p1, p2, p3, p4 = box_ocr_res[0]
  377. text, score = box_ocr_res[1]
  378. # Convert the coordinates back to the original coordinate system
  379. p1 = [p1[0] - paste_x + xmin, p1[1] - paste_y + ymin]
  380. p2 = [p2[0] - paste_x + xmin, p2[1] - paste_y + ymin]
  381. p3 = [p3[0] - paste_x + xmin, p3[1] - paste_y + ymin]
  382. p4 = [p4[0] - paste_x + xmin, p4[1] - paste_y + ymin]
  383. layout_res.append({
  384. 'category_id': 15,
  385. 'poly': p1 + p2 + p3 + p4,
  386. 'score': round(score, 2),
  387. 'text': text,
  388. })
  389. ocr_cost = round(time.time() - ocr_start, 2)
  390. logger.info(f"ocr time: {ocr_cost}")
  391. # 表格识别 table recognition
  392. if self.apply_table:
  393. table_start = time.time()
  394. for res in table_res_list:
  395. new_image, _ = crop_img(res, pil_img)
  396. single_table_start_time = time.time()
  397. # logger.info("------------------table recognition processing begins-----------------")
  398. latex_code = None
  399. html_code = None
  400. if self.table_model_name == MODEL_NAME.STRUCT_EQTABLE:
  401. with torch.no_grad():
  402. latex_code = self.table_model.image2latex(new_image)[0]
  403. else:
  404. html_code = self.table_model.img2html(new_image)
  405. run_time = time.time() - single_table_start_time
  406. # logger.info(f"------------table recognition processing ends within {run_time}s-----")
  407. if run_time > self.table_max_time:
  408. logger.warning(f"------------table recognition processing exceeds max time {self.table_max_time}s----------")
  409. # 判断是否返回正常
  410. if latex_code:
  411. expected_ending = latex_code.strip().endswith('end{tabular}') or latex_code.strip().endswith(
  412. 'end{table}')
  413. if expected_ending:
  414. res["latex"] = latex_code
  415. else:
  416. logger.warning(f"table recognition processing fails, not found expected LaTeX table end")
  417. elif html_code:
  418. res["html"] = html_code
  419. else:
  420. logger.warning(f"table recognition processing fails, not get latex or html return")
  421. logger.info(f"table time: {round(time.time() - table_start, 2)}")
  422. logger.info(f"-----page total time: {round(time.time() - page_start, 2)}-----")
  423. return layout_res