pdf_extract_kit.py 14 KB

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