pdf_extract_kit.py 8.4 KB

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