Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.
Python ai4sciencedocument-analysisdocxextract-datalayout-analysisocrparserpdfpdf-converterpdf-extractor-llmpdf-extractor-pretrainpdf-extractor-ragpdf-parserpptxpythonxlsx
feat: refactor prediction methods to streamline batch processing and enhance error handling
myhlolicbbabcb347dd
diff --git a/mineru/model/mfr/pp_formulanet_plus_m/predict_formula.py b/mineru/model/mfr/pp_formulanet_plus_m/predict_formula.pyindex 6582d4ba..62613d87 100644--- a/mineru/model/mfr/pp_formulanet_plus_m/predict_formula.py+++ b/mineru/model/mfr/pp_formulanet_plus_m/predict_formula.py@@ -1,19 +1,21 @@import mathimport os-import torch-import yamlfrom pathlib import Path+import torch+import yamlfrom loguru import loggerfrom tqdm import tqdm-from mineru.model.utils.tools.infer import pytorchocr_utility+from mineru.model.utils.pytorchocr.base_ocr_v20 import BaseOCRV20+from mineru.model.utils.tools.infer import pytorchocr_utility+from .processors import (- UniMERNetImgDecode,- UniMERNetTestTransform,LatexImageFormat,ToBatch,UniMERNetDecode,+ UniMERNetImgDecode,+ UniMERNetTestTransform,)@@ -33,7 +35,7 @@ class FormulaRecognizer(BaseOCRV20):"pytorchocr","utils","resources",- "pp_formulanet_arch_config.yaml"+ "pp_formulanet_arch_config.yaml",)self.infer_yaml_path = os.path.join(weight_dir,@@ -112,28 +114,19 @@ class FormulaRecognizer(BaseOCRV20):return formula_list, crop_targets- def predict(self, img_list, batch_size: int = 64):- # Reduce batch size by 50% to avoid potential memory issues during inference.- batch_size = max(1, int(0.5 * batch_size))- batch_imgs = self.pre_tfs["UniMERNetImgDecode"](imgs=img_list)- batch_imgs = self.pre_tfs["UniMERNetTestTransform"](imgs=batch_imgs)- batch_imgs = self.pre_tfs["LatexImageFormat"](imgs=batch_imgs)- inp = self.pre_tfs["ToBatch"](imgs=batch_imgs)- inp = torch.from_numpy(inp[0])- inp = inp.to(self.device)- rec_formula = []- with torch.no_grad():- with tqdm(total=len(inp), desc="MFR Predict") as pbar:- for index in range(0, len(inp), batch_size):- batch_data = inp[index: index + batch_size]- # with torch.amp.autocast(device_type=self.device.type):- # batch_preds = [self.net(batch_data)]- batch_preds = [self.net(batch_data)]- batch_preds = [p.reshape([-1]) for p in batch_preds[0]]- batch_preds = [bp.cpu().numpy() for bp in batch_preds]- rec_formula += self.post_op(batch_preds)- pbar.update(len(batch_preds))- return rec_formula+ def predict(+ self,+ mfd_res,+ image,+ batch_size: int = 64,+ interline_enable: bool = True,+ ) -> list:+ return self.batch_predict(+ [mfd_res],+ [image],+ batch_size=batch_size,+ interline_enable=interline_enable,+ )[0]def batch_predict(self,@@ -142,15 +135,18 @@ class FormulaRecognizer(BaseOCRV20):batch_size: int = 64,interline_enable: bool = True,) -> list:+ if not images_mfd_res:+ return []++ if len(images_mfd_res) != len(images):+ raise ValueError("images_mfd_res and images must have the same length.")+images_formula_list = []mf_image_list = []backfill_list = []image_info = [] # Store (area, original_index, image) tuples- # Collect images with their original indices- for image_index in range(len(images_mfd_res)):- mfd_res = images_mfd_res[image_index]- image = images[image_index]+ for mfd_res, image in zip(images_mfd_res, images):formula_list, crop_targets = self._build_formula_items(mfd_res, image, interline_enable=interline_enable)@@ -166,24 +162,36 @@ class FormulaRecognizer(BaseOCRV20):images_formula_list.append(formula_list)- # Stable sort by area- image_info.sort(key=lambda x: x[0]) # sort by area+ if not image_info:+ return images_formula_list++ image_info.sort(key=lambda x: x[0])sorted_indices = [x[1] for x in image_info]sorted_images = [x[2] for x in image_info]-- # Create mapping for resultsindex_mapping = {new_idx: old_idx for new_idx, old_idx in enumerate(sorted_indices)}- if len(sorted_images) > 0:- # 进行预测- batch_size = min(batch_size, max(1, 2 ** (len(sorted_images).bit_length() - 1))) if sorted_images else 1- rec_formula = self.predict(sorted_images, batch_size)- else:- rec_formula = []+ batch_size = min(batch_size, max(1, 2 ** (len(sorted_images).bit_length() - 1)))+ batch_size = max(1, int(0.5 * batch_size))++ batch_imgs = self.pre_tfs["UniMERNetImgDecode"](imgs=sorted_images)+ batch_imgs = self.pre_tfs["UniMERNetTestTransform"](imgs=batch_imgs)+ batch_imgs = self.pre_tfs["LatexImageFormat"](imgs=batch_imgs)+ inp = self.pre_tfs["ToBatch"](imgs=batch_imgs)+ inp = torch.from_numpy(inp[0]).to(self.device)++ rec_formula = []+ with torch.no_grad():+ with tqdm(total=len(inp), desc="MFR Predict") as pbar:+ for index in range(0, len(inp), batch_size):+ batch_data = inp[index : index + batch_size]+ batch_preds = [self.net(batch_data)]+ batch_preds = [p.reshape([-1]) for p in batch_preds[0]]+ batch_preds = [bp.cpu().numpy() for bp in batch_preds]+ rec_formula += self.post_op(batch_preds)+ pbar.update(len(batch_data))- # Restore original orderunsorted_results = [""] * len(rec_formula)for new_idx, latex in enumerate(rec_formula):original_idx = index_mapping[new_idx]diff --git a/mineru/model/mfr/unimernet/Unimernet.py b/mineru/model/mfr/unimernet/Unimernet.pyindex 386b3c54..b7fc9974 100644--- a/mineru/model/mfr/unimernet/Unimernet.py+++ b/mineru/model/mfr/unimernet/Unimernet.py@@ -23,6 +23,7 @@ class MathDataset(Dataset):class UnimernetModel(object):def __init__(self, weight_dir, _device_="cpu"):from .unimernet_hf import UnimernetModel+if _device_.startswith("mps") or _device_.startswith("npu") or _device_.startswith("musa"):self.model = UnimernetModel.from_pretrained(weight_dir, attn_implementation="eager")else:@@ -79,48 +80,39 @@ class UnimernetModel(object):return formula_list, crop_targets- def predict(self, mfd_res, image):- formula_list, crop_targets = self._build_formula_items(- mfd_res, image, interline_enable=True- )- mf_image_list = []-- for _, (xmin, ymin, xmax, ymax) in crop_targets:- bbox_img = image[ymin:ymax, xmin:xmax]- mf_image_list.append(bbox_img)-- if not mf_image_list:- return formula_list-- dataset = MathDataset(mf_image_list, transform=self.model.transform)- dataloader = DataLoader(dataset, batch_size=32, num_workers=0)- mfr_res = []- for mf_img in dataloader:- mf_img = mf_img.to(dtype=self.model.dtype)- mf_img = mf_img.to(self.device)- with torch.no_grad():- output = self.model.generate({"image": mf_img})- mfr_res.extend(output["fixed_str"])- for (res, _), latex in zip(crop_targets, mfr_res):- res["latex"] = latex- return formula_list+ def predict(+ self,+ mfd_res,+ image,+ batch_size: int = 64,+ interline_enable: bool = True,+ ) -> list:+ return self.batch_predict(+ [mfd_res],+ [image],+ batch_size=batch_size,+ interline_enable=interline_enable,+ )[0]def batch_predict(- self,- images_mfd_res: list,- images: list,- batch_size: int = 64,- interline_enable: bool = True,+ self,+ images_mfd_res: list,+ images: list,+ batch_size: int = 64,+ interline_enable: bool = True,) -> list:+ if not images_mfd_res:+ return []++ if len(images_mfd_res) != len(images):+ raise ValueError("images_mfd_res and images must have the same length.")+images_formula_list = []mf_image_list = []backfill_list = []image_info = [] # Store (area, original_index, image) tuples- # Collect images with their original indices- for image_index in range(len(images_mfd_res)):- mfd_res = images_mfd_res[image_index]- image = images[image_index]+ for mfd_res, image in zip(images_mfd_res, images):formula_list, crop_targets = self._build_formula_items(mfd_res, image, interline_enable=interline_enable)@@ -136,45 +128,33 @@ class UnimernetModel(object):images_formula_list.append(formula_list)- # Stable sort by area- image_info.sort(key=lambda x: x[0]) # sort by area+ if not image_info:+ return images_formula_list++ image_info.sort(key=lambda x: x[0])sorted_indices = [x[1] for x in image_info]sorted_images = [x[2] for x in image_info]-- # Create mapping for resultsindex_mapping = {new_idx: old_idx for new_idx, old_idx in enumerate(sorted_indices)}- # Create dataset with sorted imagesdataset = MathDataset(sorted_images, transform=self.model.transform)-- # 如果batch_size > len(sorted_images),则设置为不超过len(sorted_images)的2的幂- batch_size = min(batch_size, max(1, 2 ** (len(sorted_images).bit_length() - 1))) if sorted_images else 1-+ batch_size = min(batch_size, max(1, 2 ** (len(sorted_images).bit_length() - 1)))dataloader = DataLoader(dataset, batch_size=batch_size, num_workers=0)- # Process batches and store resultsmfr_res = []- # for mf_img in dataloader:-with tqdm(total=len(sorted_images), desc="MFR Predict") as pbar:- for index, mf_img in enumerate(dataloader):+ for mf_img in dataloader:mf_img = mf_img.to(dtype=self.model.dtype)mf_img = mf_img.to(self.device)with torch.no_grad():output = self.model.generate({"image": mf_img}, batch_size=batch_size)mfr_res.extend(output["fixed_str"])+ pbar.update(len(mf_img))- # 更新进度条,每次增加batch_size,但要注意最后一个batch可能不足batch_size- current_batch_size = min(batch_size, len(sorted_images) - index * batch_size)- pbar.update(current_batch_size)-- # Restore original orderunsorted_results = [""] * len(mfr_res)for new_idx, latex in enumerate(mfr_res):original_idx = index_mapping[new_idx]unsorted_results[original_idx] = latex- # Fill results backfor res, latex in zip(backfill_list, unsorted_results):res["latex"] = latex