pdf_extract_kit.py 19 KB

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