pdf_extract_kit.py 20 KB

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