pdf_extract_kit.py 22 KB

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