pdf_extract_kit.py 8.4 KB

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