pdf_extract_kit.py 21 KB

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