pdf_extract_kit.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. from loguru import logger
  2. import os
  3. import time
  4. os.environ['NO_ALBUMENTATIONS_UPDATE'] = '1' # 禁止albumentations检查更新
  5. try:
  6. import cv2
  7. import yaml
  8. import argparse
  9. import numpy as np
  10. import torch
  11. import torchtext
  12. if torchtext.__version__ >= "0.18.0":
  13. torchtext.disable_torchtext_deprecation_warning()
  14. from PIL import Image
  15. from torchvision import transforms
  16. from torch.utils.data import Dataset, DataLoader
  17. from ultralytics import YOLO
  18. from unimernet.common.config import Config
  19. import unimernet.tasks as tasks
  20. from unimernet.processors import load_processor
  21. except ImportError as e:
  22. logger.exception(e)
  23. logger.error(
  24. 'Required dependency not installed, please install by \n'
  25. '"pip install magic-pdf[full] detectron2 --extra-index-url https://myhloli.github.io/wheels/"')
  26. exit(1)
  27. from magic_pdf.model.pek_sub_modules.layoutlmv3.model_init import Layoutlmv3_Predictor
  28. from magic_pdf.model.pek_sub_modules.post_process import get_croped_image, latex_rm_whitespace
  29. from magic_pdf.model.pek_sub_modules.self_modify import ModifiedPaddleOCR
  30. from magic_pdf.model.pek_sub_modules.structeqtable.StructTableModel import StructTableModel
  31. def table_model_init(model_path, max_time=400, _device_='cpu'):
  32. table_model = StructTableModel(model_path, max_time=max_time, device=_device_)
  33. return table_model
  34. def mfd_model_init(weight):
  35. mfd_model = YOLO(weight)
  36. return mfd_model
  37. def mfr_model_init(weight_dir, cfg_path, _device_='cpu'):
  38. args = argparse.Namespace(cfg_path=cfg_path, options=None)
  39. cfg = Config(args)
  40. cfg.config.model.pretrained = os.path.join(weight_dir, "pytorch_model.bin")
  41. cfg.config.model.model_config.model_name = weight_dir
  42. cfg.config.model.tokenizer_config.path = weight_dir
  43. task = tasks.setup_task(cfg)
  44. model = task.build_model(cfg)
  45. model = model.to(_device_)
  46. vis_processor = load_processor('formula_image_eval', cfg.config.datasets.formula_rec_eval.vis_processor.eval)
  47. return model, vis_processor
  48. def layout_model_init(weight, config_file, device):
  49. model = Layoutlmv3_Predictor(weight, config_file, device)
  50. return model
  51. class MathDataset(Dataset):
  52. def __init__(self, image_paths, transform=None):
  53. self.image_paths = image_paths
  54. self.transform = transform
  55. def __len__(self):
  56. return len(self.image_paths)
  57. def __getitem__(self, idx):
  58. # if not pil image, then convert to pil image
  59. if isinstance(self.image_paths[idx], str):
  60. raw_image = Image.open(self.image_paths[idx])
  61. else:
  62. raw_image = self.image_paths[idx]
  63. if self.transform:
  64. image = self.transform(raw_image)
  65. return image
  66. class CustomPEKModel:
  67. def __init__(self, ocr: bool = False, show_log: bool = False, **kwargs):
  68. """
  69. ======== model init ========
  70. """
  71. # 获取当前文件(即 pdf_extract_kit.py)的绝对路径
  72. current_file_path = os.path.abspath(__file__)
  73. # 获取当前文件所在的目录(model)
  74. current_dir = os.path.dirname(current_file_path)
  75. # 上一级目录(magic_pdf)
  76. root_dir = os.path.dirname(current_dir)
  77. # model_config目录
  78. model_config_dir = os.path.join(root_dir, 'resources', 'model_config')
  79. # 构建 model_configs.yaml 文件的完整路径
  80. config_path = os.path.join(model_config_dir, 'model_configs.yaml')
  81. with open(config_path, "r", encoding='utf-8') as f:
  82. self.configs = yaml.load(f, Loader=yaml.FullLoader)
  83. # 初始化解析配置
  84. self.apply_layout = kwargs.get("apply_layout", self.configs["config"]["layout"])
  85. self.apply_formula = kwargs.get("apply_formula", self.configs["config"]["formula"])
  86. self.table_config = kwargs.get("table_config", self.configs["config"]["table_config"])
  87. self.apply_table = self.table_config.get("is_table_recog_enable", False)
  88. self.apply_ocr = ocr
  89. logger.info(
  90. "DocAnalysis init, this may take some times. apply_layout: {}, apply_formula: {}, apply_ocr: {}, apply_table: {}".format(
  91. self.apply_layout, self.apply_formula, self.apply_ocr, self.apply_table
  92. )
  93. )
  94. assert self.apply_layout, "DocAnalysis must contain layout model."
  95. # 初始化解析方案
  96. self.device = kwargs.get("device", self.configs["config"]["device"])
  97. logger.info("using device: {}".format(self.device))
  98. models_dir = kwargs.get("models_dir", os.path.join(root_dir, "resources", "models"))
  99. logger.info("using models_dir: {}".format(models_dir))
  100. # 初始化公式识别
  101. if self.apply_formula:
  102. # 初始化公式检测模型
  103. self.mfd_model = mfd_model_init(str(os.path.join(models_dir, self.configs["weights"]["mfd"])))
  104. # 初始化公式解析模型
  105. mfr_weight_dir = str(os.path.join(models_dir, self.configs["weights"]["mfr"]))
  106. mfr_cfg_path = str(os.path.join(model_config_dir, "UniMERNet", "demo.yaml"))
  107. self.mfr_model, mfr_vis_processors = mfr_model_init(mfr_weight_dir, mfr_cfg_path, _device_=self.device)
  108. self.mfr_transform = transforms.Compose([mfr_vis_processors, ])
  109. # 初始化layout模型
  110. self.layout_model = Layoutlmv3_Predictor(
  111. str(os.path.join(models_dir, self.configs['weights']['layout'])),
  112. str(os.path.join(model_config_dir, "layoutlmv3", "layoutlmv3_base_inference.yaml")),
  113. device=self.device
  114. )
  115. # 初始化ocr
  116. if self.apply_ocr:
  117. self.ocr_model = ModifiedPaddleOCR(show_log=show_log)
  118. # init structeqtable
  119. if self.apply_table:
  120. max_time = self.table_config.get("max_time", 400)
  121. self.table_model = table_model_init(str(os.path.join(models_dir, self.configs["weights"]["table"])),
  122. max_time=max_time, _device_=self.device)
  123. logger.info('DocAnalysis init done!')
  124. def __call__(self, image):
  125. latex_filling_list = []
  126. mf_image_list = []
  127. # layout检测
  128. layout_start = time.time()
  129. layout_res = self.layout_model(image, ignore_catids=[])
  130. layout_cost = round(time.time() - layout_start, 2)
  131. logger.info(f"layout detection cost: {layout_cost}")
  132. if self.apply_formula:
  133. # 公式检测
  134. mfd_res = self.mfd_model.predict(image, imgsz=1888, conf=0.25, iou=0.45, verbose=True)[0]
  135. for xyxy, conf, cla in zip(mfd_res.boxes.xyxy.cpu(), mfd_res.boxes.conf.cpu(), mfd_res.boxes.cls.cpu()):
  136. xmin, ymin, xmax, ymax = [int(p.item()) for p in xyxy]
  137. new_item = {
  138. 'category_id': 13 + int(cla.item()),
  139. 'poly': [xmin, ymin, xmax, ymin, xmax, ymax, xmin, ymax],
  140. 'score': round(float(conf.item()), 2),
  141. 'latex': '',
  142. }
  143. layout_res.append(new_item)
  144. latex_filling_list.append(new_item)
  145. bbox_img = get_croped_image(Image.fromarray(image), [xmin, ymin, xmax, ymax])
  146. mf_image_list.append(bbox_img)
  147. # 公式识别
  148. mfr_start = time.time()
  149. dataset = MathDataset(mf_image_list, transform=self.mfr_transform)
  150. dataloader = DataLoader(dataset, batch_size=64, num_workers=0)
  151. mfr_res = []
  152. for mf_img in dataloader:
  153. mf_img = mf_img.to(self.device)
  154. output = self.mfr_model.generate({'image': mf_img})
  155. mfr_res.extend(output['pred_str'])
  156. for res, latex in zip(latex_filling_list, mfr_res):
  157. res['latex'] = latex_rm_whitespace(latex)
  158. mfr_cost = round(time.time() - mfr_start, 2)
  159. logger.info(f"formula nums: {len(mf_image_list)}, mfr time: {mfr_cost}")
  160. # ocr识别
  161. if self.apply_ocr:
  162. ocr_start = time.time()
  163. pil_img = Image.fromarray(image)
  164. # 筛选出需要OCR的区域和公式区域
  165. ocr_res_list = []
  166. single_page_mfdetrec_res = []
  167. for res in layout_res:
  168. if int(res['category_id']) in [13, 14]:
  169. single_page_mfdetrec_res.append({
  170. "bbox": [int(res['poly'][0]), int(res['poly'][1]),
  171. int(res['poly'][4]), int(res['poly'][5])],
  172. })
  173. elif int(res['category_id']) in [0, 1, 2, 4, 6, 7]:
  174. ocr_res_list.append(res)
  175. # 对每一个需OCR处理的区域进行处理
  176. for res in ocr_res_list:
  177. xmin, ymin = int(res['poly'][0]), int(res['poly'][1])
  178. xmax, ymax = int(res['poly'][4]), int(res['poly'][5])
  179. paste_x = 50
  180. paste_y = 50
  181. # 创建一个宽高各多50的白色背景
  182. new_width = xmax - xmin + paste_x * 2
  183. new_height = ymax - ymin + paste_y * 2
  184. new_image = Image.new('RGB', (new_width, new_height), 'white')
  185. # 裁剪图像
  186. crop_box = (xmin, ymin, xmax, ymax)
  187. cropped_img = pil_img.crop(crop_box)
  188. new_image.paste(cropped_img, (paste_x, paste_y))
  189. # 调整公式区域坐标
  190. adjusted_mfdetrec_res = []
  191. for mf_res in single_page_mfdetrec_res:
  192. mf_xmin, mf_ymin, mf_xmax, mf_ymax = mf_res["bbox"]
  193. # 将公式区域坐标调整为相对于裁剪区域的坐标
  194. x0 = mf_xmin - xmin + paste_x
  195. y0 = mf_ymin - ymin + paste_y
  196. x1 = mf_xmax - xmin + paste_x
  197. y1 = mf_ymax - ymin + paste_y
  198. # 过滤在图外的公式块
  199. if any([x1 < 0, y1 < 0]) or any([x0 > new_width, y0 > new_height]):
  200. continue
  201. else:
  202. adjusted_mfdetrec_res.append({
  203. "bbox": [x0, y0, x1, y1],
  204. })
  205. # OCR识别
  206. new_image = cv2.cvtColor(np.asarray(new_image), cv2.COLOR_RGB2BGR)
  207. ocr_res = self.ocr_model.ocr(new_image, mfd_res=adjusted_mfdetrec_res)[0]
  208. # 整合结果
  209. if ocr_res:
  210. for box_ocr_res in ocr_res:
  211. p1, p2, p3, p4 = box_ocr_res[0]
  212. text, score = box_ocr_res[1]
  213. # 将坐标转换回原图坐标系
  214. p1 = [p1[0] - paste_x + xmin, p1[1] - paste_y + ymin]
  215. p2 = [p2[0] - paste_x + xmin, p2[1] - paste_y + ymin]
  216. p3 = [p3[0] - paste_x + xmin, p3[1] - paste_y + ymin]
  217. p4 = [p4[0] - paste_x + xmin, p4[1] - paste_y + ymin]
  218. layout_res.append({
  219. 'category_id': 15,
  220. 'poly': p1 + p2 + p3 + p4,
  221. 'score': round(score, 2),
  222. 'text': text,
  223. })
  224. ocr_cost = round(time.time() - ocr_start, 2)
  225. logger.info(f"ocr cost: {ocr_cost}")
  226. # 表格识别 table recognition
  227. if self.apply_table:
  228. pil_img = Image.fromarray(image)
  229. for layout in layout_res:
  230. if layout.get("category_id", -1) == 5:
  231. poly = layout["poly"]
  232. xmin, ymin = int(poly[0]), int(poly[1])
  233. xmax, ymax = int(poly[4]), int(poly[5])
  234. paste_x = 50
  235. paste_y = 50
  236. # 创建一个宽高各多50的白色背景 create a whiteboard with 50 larger width and length
  237. new_width = xmax - xmin + paste_x * 2
  238. new_height = ymax - ymin + paste_y * 2
  239. new_image = Image.new('RGB', (new_width, new_height), 'white')
  240. # 裁剪图像 crop image
  241. crop_box = (xmin, ymin, xmax, ymax)
  242. cropped_img = pil_img.crop(crop_box)
  243. new_image.paste(cropped_img, (paste_x, paste_y))
  244. start_time = time.time()
  245. logger.info("------------------table recognition processing begins-----------------")
  246. latex_code = self.table_model.image2latex(new_image)[0]
  247. end_time = time.time()
  248. run_time = end_time - start_time
  249. logger.info(f"------------table recognition processing ends within {run_time}s-----")
  250. layout["latex"] = latex_code
  251. return layout_res