pdf_extract_kit.py 19 KB

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