pdf_extract_kit.py 21 KB

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