pdf_extract_kit.py 18 KB

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