pdf_extract_kit.py 18 KB

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