pdf_extract_kit.py 20 KB

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