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: enhance batch analysis with inline formula masking and debug image output
myhloli620e5ca1cd12
diff --git a/mineru/backend/pipeline/batch_analyze.py b/mineru/backend/pipeline/batch_analyze.pyindex 3d4af93f..1b4c8085 100644--- a/mineru/backend/pipeline/batch_analyze.py+++ b/mineru/backend/pipeline/batch_analyze.py@@ -1,5 +1,6 @@import base64import html+import osimport cv2from loguru import logger@@ -14,7 +15,11 @@ from ...model.table.rec.unet_table.utils_table_recover import (plot_html_table,sorted_ocr_boxes as sorted_table_boxes,)-from ...utils.config_reader import get_formula_enable, get_table_enable+from ...utils.config_reader import (+ get_formula_enable,+ get_ocr_det_mask_inline_formula_enable,+ get_table_enable,+)from ...utils.bbox_utils import normalize_to_int_bboxfrom ...utils.model_utils import crop_img, get_res_list_from_layout_res, clean_vramfrom ...utils.ocr_utils import merge_det_boxes, update_det_boxes, sorted_boxes@@ -27,15 +32,28 @@ OCR_DET_BASE_BATCH_SIZE = 16TABLE_ORI_CLS_BATCH_SIZE = 16TABLE_Wired_Wireless_CLS_BATCH_SIZE = 16TABLE_RICH_IMAGE_LABELS = {"image", "chart", "seal"}+PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", ".."))+TABLE_OCR_DET_DEBUG_DIR = os.path.join(PROJECT_ROOT, "output_images", "table_ocr_det_debug")class BatchAnalyze:- def __init__(self, model_manager, batch_ratio: int, formula_enable, table_enable, enable_ocr_det_batch: bool = True):+ def __init__(+ self,+ model_manager,+ batch_ratio: int,+ formula_enable,+ table_enable,+ enable_ocr_det_batch: bool = True,+ mask_inline_formula_for_ocr_det: bool = True,+ ):self.batch_ratio = batch_ratioself.formula_enable = get_formula_enable(formula_enable)self.table_enable = get_table_enable(table_enable)self.model_manager = model_managerself.enable_ocr_det_batch = enable_ocr_det_batch+ self.mask_inline_formula_for_ocr_det = (+ get_ocr_det_mask_inline_formula_enable(mask_inline_formula_for_ocr_det)+ )@staticmethoddef _normalize_bbox(box) -> list[int] | None:@@ -108,6 +126,70 @@ class BatchAnalyze:img_base64 = base64.b64encode(encoded.tobytes()).decode("utf-8")return f'<img src="data:image/jpg;base64,{img_base64}">'+ @staticmethod+ def _apply_mask_boxes_to_image(+ bgr_image: np.ndarray,+ mask_boxes: list[dict] | None,+ ) -> np.ndarray:+ if not mask_boxes:+ return bgr_image++ masked_image = bgr_image.copy()+ image_h, image_w = masked_image.shape[:2]+ for mask_box in mask_boxes:+ bbox = mask_box.get("bbox")+ if bbox is None:+ continue++ int_bbox = normalize_to_int_bbox(bbox, image_size=(image_h, image_w))+ if int_bbox is None:+ continue++ x0, y0, x1, y1 = int_bbox+ masked_image[y0:y1, x0:x1] = 255++ return masked_image++ def _get_masked_det_image(+ self,+ bgr_image: np.ndarray,+ mask_boxes: list[dict] | None,+ ) -> np.ndarray:+ if not self.mask_inline_formula_for_ocr_det:+ return bgr_image+ return self._apply_mask_boxes_to_image(bgr_image, mask_boxes)++ @staticmethod+ def _dump_table_det_debug_images(+ table_id: int,+ original_bgr_image: np.ndarray,+ masked_bgr_image: np.ndarray,+ dt_boxes_final: list,+ ) -> None:+ os.makedirs(TABLE_OCR_DET_DEBUG_DIR, exist_ok=True)++ original_path = os.path.join(+ TABLE_OCR_DET_DEBUG_DIR,+ f"table_{table_id:04d}_orig.png",+ )+ masked_path = os.path.join(+ TABLE_OCR_DET_DEBUG_DIR,+ f"table_{table_id:04d}_masked.png",+ )+ det_boxes_path = os.path.join(+ TABLE_OCR_DET_DEBUG_DIR,+ f"table_{table_id:04d}_det_boxes.png",+ )++ cv2.imwrite(original_path, original_bgr_image)+ cv2.imwrite(masked_path, masked_bgr_image)++ det_boxes_image = original_bgr_image.copy()+ for dt_box in dt_boxes_final or []:+ points = np.asarray(dt_box, dtype=np.int32).reshape((-1, 1, 2))+ cv2.polylines(det_boxes_image, [points], isClosed=True, color=(0, 0, 255), thickness=2)+ cv2.imwrite(det_boxes_path, det_boxes_image)+def _collect_table_rich_items(self, table_res_dict: dict) -> list[dict]:rich_items = []table_bbox = table_res_dict["table_res"]["bbox"]@@ -335,6 +417,7 @@ class BatchAnalyze:# 表格识别 table recognitionif self.table_enable:+ os.makedirs(TABLE_OCR_DET_DEBUG_DIR, exist_ok=True)# 图片旋转批量处理img_orientation_cls_model = atom_model_manager.get_atom_model(@@ -370,10 +453,15 @@ class BatchAnalyze:table_res_dict["table_rich_items"] = self._collect_table_rich_items(table_res_dict)- table_res_dict["table_mask_boxes"] = [+ table_res_dict["table_det_mask_boxes"] = [{"bbox": item["bbox"]}for item in table_res_dict["table_rich_items"]]+ table_res_dict["table_formula_mask_boxes"] = [+ {"bbox": item["bbox"]}+ for item in table_res_dict["table_rich_items"]+ if item.get("type") == "formula"+ ]# OCR det 过程,顺序执行rec_img_lang_group = defaultdict(list)@@ -387,15 +475,25 @@ class BatchAnalyze:tqdm(table_res_list_all_page, desc="Table-ocr det")):bgr_image = cv2.cvtColor(table_res_dict["table_img"], cv2.COLOR_RGB2BGR)- ocr_result = det_ocr_engine.ocr(bgr_image, rec=False)[0]+ det_image = self._apply_mask_boxes_to_image(+ bgr_image,+ table_res_dict.get("table_det_mask_boxes") or [],+ )+ ocr_result = det_ocr_engine.ocr(det_image, rec=False)[0]dt_boxes_sorted = sorted_boxes(np.asarray(ocr_result)) if ocr_result else []dt_boxes_merged = merge_det_boxes(dt_boxes_sorted) if dt_boxes_sorted else []- table_mask_boxes = table_res_dict.get("table_mask_boxes") or []+ table_formula_mask_boxes = (+ table_res_dict.get("table_formula_mask_boxes") or []+ )dt_boxes_final = (- update_det_boxes(dt_boxes_merged, table_mask_boxes)- if dt_boxes_merged and table_mask_boxes+ update_det_boxes(dt_boxes_merged, table_formula_mask_boxes)+ if dt_boxes_merged and table_formula_mask_boxeselse dt_boxes_merged)++ # debug 输出检测结果和调试信息+ # self._dump_table_det_debug_images(index, bgr_image, det_image, dt_boxes_final)+# 构造需要 OCR 识别的图片字典,包括cropped_img, dt_box, table_id,并按照语言进行分组for dt_box in dt_boxes_final:rec_img_lang_group[table_res_dict["lang"]].append(@@ -537,9 +635,18 @@ class BatchAnalyze:# BGR转换bgr_image = cv2.cvtColor(new_image, cv2.COLOR_RGB2BGR)+ det_image = self._get_masked_det_image(+ bgr_image,+ adjusted_mfdetrec_res,+ )all_cropped_images_info.append((- bgr_image, useful_list, ocr_res_list_dict, res, adjusted_mfdetrec_res, _lang+ bgr_image,+ det_image,+ useful_list,+ ocr_res_list_dict,+ adjusted_mfdetrec_res,+ _lang,))# 按语言分组@@ -568,7 +675,7 @@ class BatchAnalyze:resolution_groups = defaultdict(list)for crop_info in lang_crop_list:- cropped_img = crop_info[0]+ cropped_img = crop_info[1]h, w = cropped_img.shape[:2]# 直接计算目标尺寸并用作分组键target_h = ((h + RESOLUTION_GROUP_STRIDE - 1) // RESOLUTION_GROUP_STRIDE) * RESOLUTION_GROUP_STRIDE@@ -581,7 +688,7 @@ class BatchAnalyze:# 对所有图像进行padding到统一尺寸batch_images = []for crop_info in group_crops:- img = crop_info[0]+ img = crop_info[1]h, w = img.shape[:2]# 创建目标尺寸的白色背景padded_img = np.ones((target_h, target_w, 3), dtype=np.uint8) * 255@@ -594,7 +701,14 @@ class BatchAnalyze:# 处理批处理结果for crop_info, (dt_boxes, _) in zip(group_crops, batch_results):- bgr_image, useful_list, ocr_res_list_dict, res, adjusted_mfdetrec_res, _lang = crop_info+ (+ bgr_image,+ _det_image,+ useful_list,+ ocr_res_list_dict,+ adjusted_mfdetrec_res,+ _lang,+ ) = crop_infoif dt_boxes is not None and len(dt_boxes) > 0:# 处理检测框@@ -638,8 +752,12 @@ class BatchAnalyze:)# OCR-detbgr_image = cv2.cvtColor(new_image, cv2.COLOR_RGB2BGR)+ det_image = self._get_masked_det_image(+ bgr_image,+ adjusted_mfdetrec_res,+ )ocr_res = ocr_model.ocr(- bgr_image, mfd_res=adjusted_mfdetrec_res, rec=False+ det_image, mfd_res=adjusted_mfdetrec_res, rec=False)[0]# Integration resultsdiff --git a/mineru/model/layout/pp_doclayoutv2.py b/mineru/model/layout/pp_doclayoutv2.pyindex 90245454..46906dfc 100644--- a/mineru/model/layout/pp_doclayoutv2.py+++ b/mineru/model/layout/pp_doclayoutv2.py@@ -24,6 +24,8 @@ from transformers.models.rt_detr.configuration_rt_detr import RTDetrConfigfrom transformers.models.rt_detr.modeling_rt_detr import RTDetrForObjectDetection, RTDetrModel, RTDetrPreTrainedModelfrom transformers.utils import ModelOutput+from mineru.utils.bbox_utils import normalize_to_int_bbox+DEFAULT_IMAGE_SIZE = (800, 800)DEFAULT_RESCALE_FACTOR = 1.0 / 255.0@@ -989,16 +991,8 @@ class PPDocLayoutV2LayoutModel:return str(self.config.id2label.get(label_id, self.config.id2label.get(str(label_id), label_id)))@staticmethod- def _clip_bbox(box: Sequence[float], image_size: Tuple[int, int]) -> Optional[List[float]]:- height, width = image_size- xmin, ymin, xmax, ymax = [float(v) for v in box]- xmin = max(0.0, min(float(width), xmin))- xmax = max(0.0, min(float(width), xmax))- ymin = max(0.0, min(float(height), ymin))- ymax = max(0.0, min(float(height), ymax))- if xmax <= xmin or ymax <= ymin:- return None- return [round(xmin, 4), round(ymin, 4), round(xmax, 4), round(ymax, 4)]+ def _clip_bbox(box: Sequence[float], image_size: Tuple[int, int]) -> Optional[List[int]]:+ return normalize_to_int_bbox(box, image_size=image_size)def _parse_prediction(self, result: Dict[str, torch.Tensor], image_size: Tuple[int, int]) -> List[Dict]:layout_res = []@@ -1100,14 +1094,14 @@ class PPDocLayoutV2LayoutModel:box["cls_id"] = cls_id@staticmethod- def _union_bbox(box1: Sequence[float], box2: Sequence[float]) -> List[float]:+ def _union_bbox(box1: Sequence[float], box2: Sequence[float]) -> List[int]:x1_min, y1_min, x1_max, y1_max = [float(v) for v in box1]x2_min, y2_min, x2_max, y2_max = [float(v) for v in box2]return [- round(min(x1_min, x2_min), 4),- round(min(y1_min, y2_min), 4),- round(max(x1_max, x2_max), 4),- round(max(y1_max, y2_max), 4),+ math.floor(min(x1_min, x2_min)),+ math.floor(min(y1_min, y2_min)),+ math.ceil(max(x1_max, x2_max)),+ math.ceil(max(y1_max, y2_max)),]@staticmethod@@ -1422,7 +1416,7 @@ if __name__ == "__main__":os.path.join(auto_download_and_get_model_root_path(ModelPath.pp_doclayout_v2), ModelPath.pp_doclayout_v2))- args.image = "/Users/myhloli/pdf/png/table_image.png"+ args.image = "/Users/myhloli/pdf/png/table_image3.png"model = PPDocLayoutV2LayoutModel(weight=args.model,diff --git a/mineru/utils/bbox_utils.py b/mineru/utils/bbox_utils.pynew file mode 100644index 00000000..be790582--- /dev/null+++ b/mineru/utils/bbox_utils.py@@ -0,0 +1,50 @@+import math++import numpy as np+++def normalize_to_int_bbox(box, image_size: tuple[int, int] | None = None) -> list[int] | None:+ if box is None:+ return None++ arr = np.asarray(box, dtype=np.float64)+ if arr.size == 0:+ return None++ if arr.ndim == 2 and arr.shape[-1] == 2:+ xs = arr[:, 0]+ ys = arr[:, 1]+ xmin = float(np.min(xs))+ ymin = float(np.min(ys))+ xmax = float(np.max(xs))+ ymax = float(np.max(ys))+ else:+ flat = arr.reshape(-1)+ if flat.size == 4:+ xmin, ymin, xmax, ymax = [float(v) for v in flat]+ elif flat.size >= 8:+ xs = flat[0::2]+ ys = flat[1::2]+ xmin = float(np.min(xs))+ ymin = float(np.min(ys))+ xmax = float(np.max(xs))+ ymax = float(np.max(ys))+ else:+ return None++ xmin = math.floor(xmin)+ ymin = math.floor(ymin)+ xmax = math.ceil(xmax)+ ymax = math.ceil(ymax)++ if image_size is not None:+ height, width = image_size+ xmin = max(0, min(int(width), xmin))+ ymin = max(0, min(int(height), ymin))+ xmax = max(0, min(int(width), xmax))+ ymax = max(0, min(int(height), ymax))++ if xmax <= xmin or ymax <= ymin:+ return None++ return [int(xmin), int(ymin), int(xmax), int(ymax)]diff --git a/mineru/utils/config_reader.py b/mineru/utils/config_reader.pyindex 39404cf1..0594345c 100644--- a/mineru/utils/config_reader.py+++ b/mineru/utils/config_reader.py@@ -119,6 +119,12 @@ def get_table_enable(table_enable):return table_enable+def get_ocr_det_mask_inline_formula_enable(enable):+ enable_env = os.getenv('MINERU_OCR_DET_MASK_INLINE_FORMULA_ENABLE')+ enable = enable if enable_env is None else enable_env.lower() == 'true'+ return enable++def get_latex_delimiter_config():config = read_config()if config is None:@@ -150,4 +156,4 @@ def get_local_models_dir():models_dir = config.get('models-dir')if models_dir is None:logger.warning(f"'models-dir' not found in {CONFIG_FILE_NAME}, use None as default")- return models_dir\ No newline at end of file+ return models_dir