pdf_extract_kit.py 18 KB

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