pdf_extract_kit.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. import os
  2. import cv2
  3. import yaml
  4. import time
  5. import argparse
  6. import numpy as np
  7. import torch
  8. from loguru import logger
  9. from paddleocr import draw_ocr
  10. from PIL import Image
  11. from torchvision import transforms
  12. from torch.utils.data import Dataset, DataLoader
  13. from ultralytics import YOLO
  14. from unimernet.common.config import Config
  15. import unimernet.tasks as tasks
  16. from unimernet.processors import load_processor
  17. from magic_pdf.model.pek_sub_modules.layoutlmv3.model_init import Layoutlmv3_Predictor
  18. from magic_pdf.model.pek_sub_modules.post_process import get_croped_image, latex_rm_whitespace
  19. from magic_pdf.model.pek_sub_modules.self_modify import ModifiedPaddleOCR
  20. def mfd_model_init(weight):
  21. mfd_model = YOLO(weight)
  22. return mfd_model
  23. def mfr_model_init(weight_dir, cfg_path, _device_='cpu'):
  24. args = argparse.Namespace(cfg_path=cfg_path, options=None)
  25. cfg = Config(args)
  26. cfg.config.model.pretrained = os.path.join(weight_dir, "pytorch_model.bin")
  27. cfg.config.model.model_config.model_name = weight_dir
  28. cfg.config.model.tokenizer_config.path = weight_dir
  29. task = tasks.setup_task(cfg)
  30. model = task.build_model(cfg)
  31. model = model.to(_device_)
  32. vis_processor = load_processor('formula_image_eval', cfg.config.datasets.formula_rec_eval.vis_processor.eval)
  33. return model, vis_processor
  34. def layout_model_init(weight, config_file, device):
  35. model = Layoutlmv3_Predictor(weight, config_file, device)
  36. return model
  37. class MathDataset(Dataset):
  38. def __init__(self, image_paths, transform=None):
  39. self.image_paths = image_paths
  40. self.transform = transform
  41. def __len__(self):
  42. return len(self.image_paths)
  43. def __getitem__(self, idx):
  44. # if not pil image, then convert to pil image
  45. if isinstance(self.image_paths[idx], str):
  46. raw_image = Image.open(self.image_paths[idx])
  47. else:
  48. raw_image = self.image_paths[idx]
  49. if self.transform:
  50. image = self.transform(raw_image)
  51. return image
  52. class CustomPEKModel:
  53. def __init__(self, ocr: bool = False, show_log: bool = False, **kwargs):
  54. """
  55. ======== model init ========
  56. """
  57. # 获取当前文件(即 pdf_extract_kit.py)的绝对路径
  58. current_file_path = os.path.abspath(__file__)
  59. # 获取当前文件所在的目录(model)
  60. current_dir = os.path.dirname(current_file_path)
  61. # 上一级目录(magic_pdf)
  62. root_dir = os.path.dirname(current_dir)
  63. # model_config目录
  64. model_config_dir = os.path.join(root_dir, 'resources', 'model_config')
  65. # 构建 model_configs.yaml 文件的完整路径
  66. config_path = os.path.join(model_config_dir, 'model_configs.yaml')
  67. with open(config_path, "r") as f:
  68. self.configs = yaml.load(f, Loader=yaml.FullLoader)
  69. # 初始化解析配置
  70. self.apply_layout = kwargs.get("apply_layout", self.configs["config"]["layout"])
  71. self.apply_formula = kwargs.get("apply_formula", self.configs["config"]["formula"])
  72. self.apply_ocr = ocr
  73. logger.info(
  74. "DocAnalysis init, this may take some times. apply_layout: {}, apply_formula: {}, apply_ocr: {}".format(
  75. self.apply_layout, self.apply_formula, self.apply_ocr
  76. )
  77. )
  78. assert self.apply_layout, "DocAnalysis must contain layout model."
  79. # 初始化解析方案
  80. self.device = kwargs.get("device", self.configs["config"]["device"])
  81. logger.info("using device: {}".format(self.device))
  82. models_dir = kwargs.get("models_dir", os.path.join(root_dir, "resources", "models"))
  83. # 初始化公式识别
  84. if self.apply_formula:
  85. # 初始化公式检测模型
  86. self.mfd_model = mfd_model_init(str(os.path.join(models_dir, self.configs["weights"]["mfd"])))
  87. # 初始化公式解析模型
  88. mfr_weight_dir = str(os.path.join(models_dir, self.configs["weights"]["mfr"]))
  89. mfr_cfg_path = str(os.path.join(model_config_dir, "UniMERNet", "demo.yaml"))
  90. self.mfr_model, mfr_vis_processors = mfr_model_init(mfr_weight_dir, mfr_cfg_path, _device_=self.device)
  91. self.mfr_transform = transforms.Compose([mfr_vis_processors, ])
  92. # 初始化layout模型
  93. self.layout_model = Layoutlmv3_Predictor(
  94. str(os.path.join(models_dir, self.configs['weights']['layout'])),
  95. str(os.path.join(model_config_dir, "layoutlmv3", "layoutlmv3_base_inference.yaml")),
  96. device=self.device
  97. )
  98. # 初始化ocr
  99. if self.apply_ocr:
  100. self.ocr_model = ModifiedPaddleOCR(show_log=show_log)
  101. logger.info('DocAnalysis init done!')
  102. def __call__(self, image):
  103. latex_filling_list = []
  104. mf_image_list = []
  105. # layout检测
  106. layout_start = time.time()
  107. layout_res = self.layout_model(image, ignore_catids=[])
  108. layout_cost = round(time.time() - layout_start, 2)
  109. logger.info(f"layout detection cost: {layout_cost}")
  110. # 公式检测
  111. mfd_res = self.mfd_model.predict(image, imgsz=1888, conf=0.25, iou=0.45, verbose=True)[0]
  112. for xyxy, conf, cla in zip(mfd_res.boxes.xyxy.cpu(), mfd_res.boxes.conf.cpu(), mfd_res.boxes.cls.cpu()):
  113. xmin, ymin, xmax, ymax = [int(p.item()) for p in xyxy]
  114. new_item = {
  115. 'category_id': 13 + int(cla.item()),
  116. 'poly': [xmin, ymin, xmax, ymin, xmax, ymax, xmin, ymax],
  117. 'score': round(float(conf.item()), 2),
  118. 'latex': '',
  119. }
  120. layout_res.append(new_item)
  121. latex_filling_list.append(new_item)
  122. bbox_img = get_croped_image(Image.fromarray(image), [xmin, ymin, xmax, ymax])
  123. mf_image_list.append(bbox_img)
  124. # 公式识别
  125. mfr_start = time.time()
  126. dataset = MathDataset(mf_image_list, transform=self.mfr_transform)
  127. dataloader = DataLoader(dataset, batch_size=64, num_workers=0)
  128. mfr_res = []
  129. for mf_img in dataloader:
  130. mf_img = mf_img.to(self.device)
  131. output = self.mfr_model.generate({'image': mf_img})
  132. mfr_res.extend(output['pred_str'])
  133. for res, latex in zip(latex_filling_list, mfr_res):
  134. res['latex'] = latex_rm_whitespace(latex)
  135. mfr_cost = round(time.time() - mfr_start, 2)
  136. logger.info(f"formula nums: {len(mf_image_list)}, mfr time: {mfr_cost}")
  137. # ocr识别
  138. if self.apply_ocr:
  139. ocr_start = time.time()
  140. pil_img = Image.fromarray(image)
  141. single_page_mfdetrec_res = []
  142. for res in layout_res:
  143. if int(res['category_id']) in [13, 14]:
  144. xmin, ymin = int(res['poly'][0]), int(res['poly'][1])
  145. xmax, ymax = int(res['poly'][4]), int(res['poly'][5])
  146. single_page_mfdetrec_res.append({
  147. "bbox": [xmin, ymin, xmax, ymax],
  148. })
  149. for res in layout_res:
  150. if int(res['category_id']) in [0, 1, 2, 4, 6, 7]: # 需要进行ocr的类别
  151. xmin, ymin = int(res['poly'][0]), int(res['poly'][1])
  152. xmax, ymax = int(res['poly'][4]), int(res['poly'][5])
  153. crop_box = (xmin, ymin, xmax, ymax)
  154. cropped_img = Image.new('RGB', pil_img.size, 'white')
  155. cropped_img.paste(pil_img.crop(crop_box), crop_box)
  156. cropped_img = cv2.cvtColor(np.asarray(cropped_img), cv2.COLOR_RGB2BGR)
  157. ocr_res = self.ocr_model.ocr(cropped_img, mfd_res=single_page_mfdetrec_res)[0]
  158. if ocr_res:
  159. for box_ocr_res in ocr_res:
  160. p1, p2, p3, p4 = box_ocr_res[0]
  161. text, score = box_ocr_res[1]
  162. layout_res.append({
  163. 'category_id': 15,
  164. 'poly': p1 + p2 + p3 + p4,
  165. 'score': round(score, 2),
  166. 'text': text,
  167. })
  168. ocr_cost = round(time.time() - ocr_start, 2)
  169. logger.info(f"ocr cost: {ocr_cost}")
  170. return layout_res