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: add light/full model stack with ONNX backends
jinzhenj433f808c0a48
diff --git a/mineru/backend/local_model_runtime.py b/mineru/backend/local_model_runtime.pyindex 0618d60c..be0ca6ee 100644--- a/mineru/backend/local_model_runtime.py+++ b/mineru/backend/local_model_runtime.py@@ -6,19 +6,21 @@ from __future__ import annotationsimport osimport threadingfrom collections.abc import Callable-from typing import Any+from typing import TYPE_CHECKING, Any-import torchfrom loguru import logger-from ..model.layout.pp_doclayoutv2 import PPDocLayoutV2LayoutModel-from ..model.mfr.unimernet.Unimernet import UnimernetModel-from ..model.ocr.pytorch_paddle import PytorchPaddleOCRfrom ..model.table.cls.mineru_table_ori_cls import MineruTableOrientationClsModelfrom ..model.table.cls.paddle_table_cls import PaddleTableClsModelfrom ..model.table.rec.slanet_plus.main import PaddleTableModelfrom ..model.table.rec.unet_table.main import UnetTableModel++if TYPE_CHECKING:+ from ..model.layout.pp_doclayoutv2 import PPDocLayoutV2LayoutModel+ from ..model.mfr.unimernet.Unimernet import UnimernetModel+ from ..model.ocr.pytorch_paddle import PytorchPaddleOCRfrom ..utils.config_reader import get_device+from ..utils.config_reader import get_model_stackfrom ..utils.model_registry import PDF_EXTRACT_KIT, ModelPathfrom ..utils.ocr_language import normalize_ocr_model_lang@@ -126,12 +128,18 @@ def wireless_table_model_init(lang: str | None = None) -> PaddleTableModel:return table_model-def mfr_model_init(weight_dir: str, device: str | torch.device = "cpu") -> UnimernetModel:+def mfr_model_init(weight_dir: str, device: str = "cpu") -> "UnimernetModel":+ from ..model.mfr.unimernet.Unimernet import UnimernetModel+return UnimernetModel(weight_dir, device)-def pp_doclayout_v2_model_init(weight: str, device: str | torch.device = "cpu") -> PPDocLayoutV2LayoutModel:+def pp_doclayout_v2_model_init(weight: str, device: str = "cpu") -> "PPDocLayoutV2LayoutModel":+ from ..model.layout.pp_doclayoutv2 import PPDocLayoutV2LayoutModel+if str(device).startswith("npu"):+ import torch+device = torch.device(device)model = PPDocLayoutV2LayoutModel(weight, device)return model@@ -142,7 +150,9 @@ def ocr_model_init(lang: str | None = None,det_db_unclip_ratio: float = 1.5,enable_merge_det_boxes: bool = True,-) -> PytorchPaddleOCR:+) -> "PytorchPaddleOCR":+ from ..model.ocr.pytorch_paddle import PytorchPaddleOCR+ocr_kwargs = {"lang": normalize_ocr_model_lang(lang),"det_db_box_thresh": det_db_box_thresh,@@ -192,18 +202,52 @@ class AtomModelSingleton:def atom_model_init(model_name: str, **kwargs: Any) -> Any:+ stack = get_model_stack()atom_model = Noneif model_name == AtomicModel.Layout:- atom_model = pp_doclayout_v2_model_init(kwargs.get("pp_doclayout_v2_weights"), kwargs.get("device"))+ if stack == "light":+ from ..model.layout.pp_doclayout_v2_onnx import PPDocLayoutV2LayoutModelONNX+ from ..utils.model_registry import PP_DOCLAYOUT_V2_ONNX++ atom_model = PPDocLayoutV2LayoutModelONNX(+ weight=str(PP_DOCLAYOUT_V2_ONNX.onnx.ensure()),+ device=kwargs.get("device", "cpu"),+ )+ else:+ atom_model = pp_doclayout_v2_model_init(kwargs.get("pp_doclayout_v2_weights"), kwargs.get("device"))elif model_name == AtomicModel.MFR:- atom_model = mfr_model_init(kwargs.get("mfr_weight_dir"), kwargs.get("device"))+ if stack == "light":+ from ..model.mfr.pp_formulanet_plus_m_onnx import PPFormulaNetPlusMONNX+ from ..utils.model_registry import PP_FORMULANET_PLUS_M_ONNX++ atom_model = PPFormulaNetPlusMONNX(+ model_path=str(PP_FORMULANET_PLUS_M_ONNX.onnx.ensure()),+ config_path=str(PP_FORMULANET_PLUS_M_ONNX.config.ensure()),+ device=kwargs.get("device", "cpu"),+ )+ else:+ atom_model = mfr_model_init(kwargs.get("mfr_weight_dir"), kwargs.get("device"))elif model_name == AtomicModel.OCR:- atom_model = ocr_model_init(- kwargs.get("det_db_box_thresh", 0.5),- kwargs.get("lang"),- kwargs.get("det_db_unclip_ratio", 1.5),- kwargs.get("enable_merge_det_boxes", True),- )+ if stack == "light":+ from ..model.ocr.pp_ocr_v6_onnx import PPOCRv6ONNX+ from ..utils.model_registry import PP_OCR_V6_SMALL_DET_ONNX, PP_OCR_V6_SMALL_REC_ONNX++ atom_model = PPOCRv6ONNX(+ det_model_path=str(PP_OCR_V6_SMALL_DET_ONNX.onnx.ensure()),+ rec_model_path=str(PP_OCR_V6_SMALL_REC_ONNX.onnx.ensure()),+ dict_path=str(PP_OCR_V6_SMALL_REC_ONNX.config.ensure()),+ device=kwargs.get("device", "cpu"),+ det_db_box_thresh=kwargs.get("det_db_box_thresh", 0.5),+ det_db_unclip_ratio=kwargs.get("det_db_unclip_ratio", 1.5),+ enable_merge_det_boxes=kwargs.get("enable_merge_det_boxes", True),+ )+ else:+ atom_model = ocr_model_init(+ kwargs.get("det_db_box_thresh", 0.5),+ kwargs.get("lang"),+ kwargs.get("det_db_unclip_ratio", 1.5),+ kwargs.get("enable_merge_det_boxes", True),+ )elif model_name == AtomicModel.WirelessTable:atom_model = wireless_table_model_init(kwargs.get("lang"),@@ -254,8 +298,11 @@ class HybridLocalModelContextSingleton:def ocr_det_batch_setting() -> bool:- import torch as _torch- from packaging import version+ try:+ import torch as _torch+ from packaging import version+ except ImportError:+ return Truedevice_type = os.getenv("MINERU_LMDEPLOY_DEVICE", "")if device_type.lower() in ["corex"]:@@ -315,7 +362,7 @@ class HybridLocalModelContext:det_db_box_thresh: float = 0.5,det_db_unclip_ratio: float = 1.5,enable_merge_det_boxes: bool = True,- ) -> PytorchPaddleOCR:+ ) -> "PytorchPaddleOCR":"""获取 OCR 原子模型,默认使用当前 Hybrid 本地上下文语言并复用 singleton 缓存。"""return self.atom_model_manager.get_atom_model(atom_model_name=AtomicModel.OCR,@@ -325,7 +372,7 @@ class HybridLocalModelContext:enable_merge_det_boxes=enable_merge_det_boxes,)- def get_layout_model(self) -> PPDocLayoutV2LayoutModel:+ def get_layout_model(self) -> "PPDocLayoutV2LayoutModel":"""获取 Layout 原子模型,供 Hybrid 本地 layout、标题拆分和公式框检测复用。"""return self.atom_model_manager.get_atom_model(atom_model_name=AtomicModel.Layout,@@ -333,7 +380,7 @@ class HybridLocalModelContext:device=self.device,)- def get_mfr_model(self) -> UnimernetModel:+ def get_mfr_model(self) -> "UnimernetModel":"""获取公式识别原子模型,统一复用当前公式模型配置和设备。"""mfr_model_path = _resolve_mfr_model_path()return self.atom_model_manager.get_atom_model(diff --git a/mineru/config.py b/mineru/config.pyindex 87634c01..b08fd33b 100644--- a/mineru/config.py+++ b/mineru/config.py@@ -356,6 +356,7 @@ class ManagedParseServerConfig(BaseModel):class ModelConfig(BaseModel):base_dir: str = _default_path("models")source: str = "auto"+ stack: str = "auto" # "auto" | "light" | "full"class DoclibConfig(BaseModel):diff --git a/mineru/model/layout/pp_doclayout_v2_base.py b/mineru/model/layout/pp_doclayout_v2_base.pynew file mode 100644index 00000000..a42d4135--- /dev/null+++ b/mineru/model/layout/pp_doclayout_v2_base.py@@ -0,0 +1,787 @@+# Copyright (c) Opendatalab. All rights reserved.+"""PP-DocLayoutV2 的后处理与可视化逻辑(与推理引擎无关)。++本模块只依赖 numpy / cv2 / PIL,不依赖 torch / transformers,+供 transformers 版(`pp_doclayoutv2.py`)和 ONNX 版(`pp_doclayout_v2_onnx.py`)+共同复用,保证两个后端的输出后处理完全一致。+"""++from __future__ import annotations++import colorsys+import hashlib+import json+import math+import os+from typing import Dict, List, Optional, Sequence, Tuple, Union++import numpy as np+from PIL import Image, ImageDraw, ImageFont++from ...utils.bbox_utils import normalize_to_int_bbox++DEFAULT_IMAGE_SIZE = (800, 800)+DEFAULT_RESCALE_FACTOR = 1.0 / 255.0++PP_DOCLAYOUT_V2_LABELS = [+ "abstract", # 0 论文摘要+ "algorithm", # 1 算法+ "aside_text", # 2 页边注文本,通常位于页面边缘,提供补充信息或注释,与主内容相关但不直接包含在内+ "chart", # 3 图表,通常包含数据可视化元素,如柱状图、折线图、饼图等,用于展示数据关系和趋势+ "content", # 4 只在大的目录块中出现,其他地方未见+ "display_formula", # 5 独立展示的公式,通常占据整行或多行,具有较大字体和清晰的布局,以突出其重要性和可读性+ "doc_title", # 6 文章标题,一篇文章的主标题+ "figure_title", # 7 image/chart/table的caption+ "footer", # 8 页脚文本+ "footer_image", # 9 页脚图片+ "footnote", # 10 page footnote,通常位于页面底部,提供对正文中特定内容的补充说明、引用来源或其他相关信息+ "formula_number", # 11 公式编号,通常与display_formula配合使用,标识独立展示的公式在文档中的位置和顺序,便于引用和索引+ "header", # 12 页眉文本+ "header_image", # 13 页眉图片+ "image", # 14 图片+ "inline_formula", # 15 行内公式+ "number", # 16 页码+ "paragraph_title", # 17 段落标题,有别与文章标题+ "reference", # 18 参考文献,list外框+ "reference_content", # 19 参考文献内容,list item+ "seal", # 20 印章+ "table", # 21 表格+ "text", # 22 一般文本+ "vertical_text", # 23 竖排文本+ "vision_footnote", # 24 image/chart/table的footnote+]++PP_DOCLAYOUT_V2_LABEL_TO_ID = {label: index for index, label in enumerate(PP_DOCLAYOUT_V2_LABELS)}++# Per-class confidence threshold used before reading-order decoding.+DEFAULT_CLASS_THRESHOLDS = [+ 0.5, # 0 abstract+ 0.5, # 1 algorithm+ 0.5, # 2 aside_text+ 0.5, # 3 chart+ 0.5, # 4 content+ 0.4, # 5 display_formula+ 0.4, # 6 doc_title+ 0.5, # 7 figure_title+ 0.5, # 8 footer+ 0.5, # 9 footer_image+ 0.5, # 10 footnote+ 0.5, # 11 formula_number+ 0.5, # 12 header+ 0.5, # 13 header_image+ 0.5, # 14 image+ 0.4, # 15 inline_formula+ 0.5, # 16 number+ 0.4, # 17 paragraph_title+ 0.5, # 18 reference+ 0.5, # 19 reference_content+ 0.45, # 20 seal+ 0.5, # 21 table+ 0.4, # 22 text+ 0.4, # 23 vertical_text+ 0.5, # 24 vision_footnote+]++# Reading-order head class remap used by the original upstream model.+DEFAULT_CLASS_ORDER = [+ 4, # 0 abstract+ 2, # 1 algorithm+ 14, # 2 aside_text+ 1, # 3 chart+ 5, # 4 content+ 7, # 5 display_formula+ 8, # 6 doc_title+ 6, # 7 figure_title+ 11, # 8 footer+ 11, # 9 footer+ 9, # 10 footnote+ 13, # 11 formula_number+ 10, # 12 header+ 10, # 13 header_image+ 1, # 14 image+ 2, # 15 inline_formula+ 3, # 16 number+ 0, # 17 paragraph_title+ 2, # 18 reference+ 2, # 19 reference_content+ 12, # 20 seal+ 1, # 21 table+ 2, # 22 text+ 15, # 23 vertical_text+ 6, # 24 vision_footnote+]+++def load_preprocess_config(model_dir: str) -> Dict:+ config_path = os.path.join(model_dir, "preprocessor_config.json")+ if not os.path.exists(config_path):+ return {}+ with open(config_path, "r", encoding="utf-8") as f:+ return json.load(f)+++def label_to_color(label: str) -> Tuple[int, int, int]:+ digest = hashlib.md5(label.encode("utf-8")).digest()+ hue = digest[0] / 255.0+ saturation = 0.65 + (digest[1] / 255.0) * 0.2+ value = 0.85 + (digest[2] / 255.0) * 0.1+ r, g, b = colorsys.hsv_to_rgb(hue, saturation, value)+ return int(r * 255), int(g * 255), int(b * 255)+++class PPDocLayoutV2PostProcessor:+ """PP-DocLayoutV2 检测结果的后处理逻辑。++ 所有方法都是纯 numpy/Python 实现,不依赖 torch/transformers。+ 子类只需提供 ``conf`` / ``use_paddlex_filter_boxes`` 等实例属性,+ 并实现 ``predict`` / ``batch_predict`` 即可。+ """++ HEADER_FOOTER_BOUNDARY_EXEMPT_LABELS = {"aside_text", "footnote", "number"}+ VISUAL_BODY_LABELS = {"image", "chart", "table", "seal"}+ PAGE_REGION_LABELS = {+ "header",+ "header_image",+ "footer",+ "footer_image",+ "footnote",+ "number",+ "aside_text",+ }++ # ------------------------------------------------------------------+ # bbox 几何计算+ # ------------------------------------------------------------------+ @staticmethod+ def _clip_bbox(box: Sequence[float], image_size: Tuple[int, int]) -> Optional[List[int]]:+ return normalize_to_int_bbox(box, image_size=image_size)++ @staticmethod+ def _calculate_bbox_area(box: Sequence[float]) -> float:+ xmin, ymin, xmax, ymax = [float(v) for v in box]+ return max(0.0, xmax - xmin) * max(0.0, ymax - ymin)++ @classmethod+ def _calculate_intersection_area(cls, box1: Sequence[float], box2: Sequence[float]) -> float:+ 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]+ inter_xmin = max(x1_min, x2_min)+ inter_ymin = max(y1_min, y2_min)+ inter_xmax = min(x1_max, x2_max)+ inter_ymax = min(y1_max, y2_max)+ return cls._calculate_bbox_area((inter_xmin, inter_ymin, inter_xmax, inter_ymax))++ @classmethod+ def _calculate_overlap_ratio(cls, box1: Sequence[float], box2: Sequence[float]) -> float:+ inter_area = cls._calculate_intersection_area(box1, box2)+ ref_area = min(cls._calculate_bbox_area(box1), cls._calculate_bbox_area(box2))+ if ref_area <= 0.0:+ return 0.0+ return inter_area / ref_area++ @classmethod+ def _calculate_iou(cls, box1: Sequence[float], box2: Sequence[float]) -> float:+ inter_area = cls._calculate_intersection_area(box1, box2)+ union_area = cls._calculate_bbox_area(box1) + cls._calculate_bbox_area(box2) - inter_area+ if union_area <= 0.0:+ return 0.0+ return inter_area / union_area++ @classmethod+ def _calculate_cover_ratio(cls, box1: Sequence[float], box2: Sequence[float]) -> float:+ box1_area = cls._calculate_bbox_area(box1)+ if box1_area <= 0.0:+ return 0.0+ return cls._calculate_intersection_area(box1, box2) / box1_area++ @staticmethod+ def _calculate_x_overlap_ratio(box1: Sequence[float], box2: Sequence[float]) -> float:+ """计算两个 bbox 在横向上的重叠比例,用于判断是否属于同一栏。"""+ box1_xmin, _, box1_xmax, _ = [float(v) for v in box1]+ box2_xmin, _, box2_xmax, _ = [float(v) for v in box2]+ box1_width = max(0.0, box1_xmax - box1_xmin)+ box2_width = max(0.0, box2_xmax - box2_xmin)+ ref_width = min(box1_width, box2_width)+ if ref_width <= 0.0:+ return 0.0+ overlap_width = max(0.0, min(box1_xmax, box2_xmax) - max(box1_xmin, box2_xmin))+ return overlap_width / ref_width++ @staticmethod+ def _calculate_x_cover_ratio(anchor_box: Sequence[float], candidate_box: Sequence[float]) -> float:+ """计算 anchor 在横向上覆盖 candidate 的比例。"""+ anchor_xmin, _, anchor_xmax, _ = [float(v) for v in anchor_box]+ candidate_xmin, _, candidate_xmax, _ = [float(v) for v in candidate_box]+ candidate_width = max(0.0, candidate_xmax - candidate_xmin)+ if candidate_width <= 0.0:+ return 0.0+ overlap_width = max(+ 0.0,+ min(anchor_xmax, candidate_xmax) - max(anchor_xmin, candidate_xmin),+ )+ return overlap_width / candidate_width++ @classmethod+ def _is_footer_x_scope(+ cls,+ anchor_box: Dict,+ candidate_box: Dict,+ image_size: Optional[Tuple[int, int]],+ full_width_threshold: float = 0.7,+ x_overlap_threshold: float = 0.3,+ ) -> bool:+ """判断候选块是否在页脚文本锚点的横向作用范围内。"""+ anchor_bbox = anchor_box.get("bbox")+ candidate_bbox = candidate_box.get("bbox")+ if not anchor_bbox or not candidate_bbox:+ return False++ if image_size is not None and len(image_size) >= 2:+ page_width = float(image_size[1])+ anchor_width = max(0.0, float(anchor_bbox[2]) - float(anchor_bbox[0]))+ if page_width > 0.0 and anchor_width / page_width >= full_width_threshold:+ return True++ return cls._calculate_x_overlap_ratio(anchor_bbox, candidate_bbox) >= x_overlap_threshold++ @classmethod+ def _is_covered_by_footnote(+ cls,+ footnote_box: Dict,+ candidate_box: Dict,+ x_cover_threshold: float = 0.7,+ ) -> bool:+ """判断候选块是否位于 footnote 区域内或其下方,并被其横向覆盖。"""+ footnote_bbox = footnote_box.get("bbox")+ candidate_bbox = candidate_box.get("bbox")+ if not footnote_bbox or not candidate_bbox:+ return False+ if candidate_bbox[1] < footnote_bbox[1]:+ return False+ return cls._calculate_x_cover_ratio(footnote_bbox, candidate_bbox) >= x_cover_threshold++ # ------------------------------------------------------------------+ # box 类型判断+ # ------------------------------------------------------------------+ @classmethod+ def _is_header_footer_boundary_candidate(cls, box: Dict, anchor_labels: set[str]) -> bool:+ """判断普通块是否可被页眉/页脚/页码边界规则改标。"""+ label = box.get("label")+ if label in cls.HEADER_FOOTER_BOUNDARY_EXEMPT_LABELS:+ return False+ return label not in anchor_labels++ @classmethod+ def _is_footnote_relabel_candidate(cls, box: Dict) -> bool:+ """排除页眉、页脚、页码、页边注等非正文区域块,保留正文内容块。"""+ return box.get("label") not in cls.PAGE_REGION_LABELS++ @staticmethod+ def _is_reference_box(box: Dict) -> bool:+ return box.get("label") == "reference" or int(box.get("cls_id", -1)) == 18++ @staticmethod+ def _is_display_formula_box(box: Dict) -> bool:+ return box.get("label") == "display_formula" or int(box.get("cls_id", -1)) == 5++ @staticmethod+ def _is_inline_formula_box(box: Dict) -> bool:+ return box.get("label") == "inline_formula" or int(box.get("cls_id", -1)) == 15++ @staticmethod+ def _is_formula_box(box: Dict) -> bool:+ return PPDocLayoutV2PostProcessor._is_display_formula_box(box) or PPDocLayoutV2PostProcessor._is_inline_formula_box(box)++ @staticmethod+ def _is_formula_number_box(box: Dict) -> bool:+ return box.get("label") == "formula_number" or int(box.get("cls_id", -1)) == 11++ # ------------------------------------------------------------------+ # label 修改+ # ------------------------------------------------------------------+ @staticmethod+ def _set_box_label(box: Dict, label: str) -> None:+ """统一同步设置 layout 检测框的标签名和类别编号。"""+ if label not in PP_DOCLAYOUT_V2_LABEL_TO_ID:+ raise ValueError(f"Unsupported PP-DocLayoutV2 label: {label}")+ box["label"] = label+ box["cls_id"] = PP_DOCLAYOUT_V2_LABEL_TO_ID[label]++ @staticmethod+ def _set_formula_label(box: Dict, label: str) -> None:+ if label not in {"inline_formula", "display_formula"}:+ raise ValueError(f"Unsupported formula label: {label}")+ PPDocLayoutV2PostProcessor._set_box_label(box, label)++ @staticmethod+ def _set_header_footer_label(box: Dict, label: str) -> None:+ """同步设置页眉/页脚相关标签及其类别编号。"""+ if label not in {"footer", "footer_image", "header", "header_image"}:+ raise ValueError(f"Unsupported header/footer label: {label}")+ PPDocLayoutV2PostProcessor._set_box_label(box, label)++ @staticmethod+ def _set_footnote_label(box: Dict) -> None:+ """同步设置 page footnote 标签及其类别编号。"""+ PPDocLayoutV2PostProcessor._set_box_label(box, "footnote")++ def _label_id_to_label_name(self, label_id: int) -> str:+ if 0 <= label_id < len(PP_DOCLAYOUT_V2_LABELS):+ return PP_DOCLAYOUT_V2_LABELS[label_id]+ # 兜底:调用方可能传入了非预设 id,这里返回字符串形式。+ return str(label_id)++ # ------------------------------------------------------------------+ # 后处理主流程+ # ------------------------------------------------------------------+ @classmethod+ def _filter_internal_visual_caption_boxes(+ cls,+ boxes: List[Dict],+ cover_threshold: float = 0.8,+ ) -> List[Dict]:+ """过滤落在图、表、印章等视觉主体内部的 figure_title。++ 这类块通常是图内的 (a)/(b) 标号,不应作为外部 caption 参与后续视觉分组。+ """+ visual_boxes = [box for box in boxes if box.get("label") in cls.VISUAL_BODY_LABELS]+ if not visual_boxes:+ return boxes++ filtered_boxes = []+ for box in boxes:+ if box.get("label") != "figure_title":+ filtered_boxes.append(box)+ continue++ caption_bbox = box.get("bbox")+ if not caption_bbox or len(caption_bbox) < 4:+ filtered_boxes.append(box)+ continue++ caption_center_x = (float(caption_bbox[0]) + float(caption_bbox[2])) / 2+ caption_center_y = (float(caption_bbox[1]) + float(caption_bbox[3])) / 2+ is_internal_caption = False+ for visual_box in visual_boxes:+ visual_bbox = visual_box.get("bbox")+ if not visual_bbox or len(visual_bbox) < 4:+ continue++ visual_xmin, visual_ymin, visual_xmax, visual_ymax = [float(v) for v in visual_bbox]+ if not (visual_xmin <= caption_center_x <= visual_xmax and visual_ymin <= caption_center_y <= visual_ymax):+ continue++ if cls._calculate_cover_ratio(caption_bbox, visual_bbox) >= cover_threshold:+ is_internal_caption = True+ break++ if not is_internal_caption:+ filtered_boxes.append(box)++ return filtered_boxes++ @classmethod+ def _reclassify_header_footer_by_page_half(+ cls,+ boxes: List[Dict],+ image_size: Optional[Tuple[int, int]],+ ) -> List[Dict]:+ """按页面上下半区重新校正页眉/页脚锚点,避免跨半页误触发边界规则。"""+ if image_size is None:+ return boxes++ page_height = float(image_size[0])+ if page_height <= 0:+ return boxes++ page_middle = page_height * 0.5+ upper_half_labels = {+ "footer": "header",+ "footer_image": "header_image",+ }+ lower_half_labels = {+ "header": "footer",+ "header_image": "footer_image",+ }+ for box in boxes:+ bbox = box.get("bbox")+ if not bbox or len(bbox) < 4:+ continue+ label = box.get("label")+ y_mid = (float(bbox[1]) + float(bbox[3])) / 2+ if y_mid < page_middle and label in upper_half_labels:+ cls._set_header_footer_label(box, upper_half_labels[label])+ elif y_mid >= page_middle and label in lower_half_labels:+ cls._set_header_footer_label(box, lower_half_labels[label])++ return boxes++ @staticmethod+ 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 [+ 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+ def _renumber_indices(boxes: List[Dict]) -> List[Dict]:+ for index, box in enumerate(boxes, start=1):+ box["index"] = index+ return boxes++ @classmethod+ def _deduplicate_boxes_by_iou(+ cls,+ boxes: List[Dict],+ iou_threshold: float = 0.9,+ ) -> List[Dict]:+ if len(boxes) <= 1:+ return boxes++ sorted_candidates = sorted(+ enumerate(boxes),+ key=lambda item: (-float(item[1].get("score", 0.0)), item[0]),+ )+ suppressed_indexes = set()+ kept_indexes = []++ for candidate_pos, (current_index, current_box) in enumerate(sorted_candidates):+ if current_index in suppressed_indexes:+ continue+ kept_indexes.append(current_index)+ for other_index, other_box in sorted_candidates[candidate_pos + 1 :]:+ if other_index in suppressed_indexes:+ continue+ if cls._calculate_iou(current_box["bbox"], other_box["bbox"]) > iou_threshold:+ suppressed_indexes.add(other_index)++ kept_indexes.sort()+ return [boxes[index] for index in kept_indexes]++ @classmethod+ def _merge_nested_formula_boxes(+ cls,+ boxes: List[Dict],+ overlap_threshold: float = 0.7,+ ) -> List[Dict]:+ if len(boxes) <= 1:+ return boxes++ changed = True+ while changed:+ changed = False+ formula_indexes = [index for index, box in enumerate(boxes) if cls._is_formula_box(box)]+ for formula_pos, left_index in enumerate(formula_indexes):+ for right_index in formula_indexes[formula_pos + 1 :]:+ left_box = boxes[left_index]+ right_box = boxes[right_index]+ if cls._calculate_overlap_ratio(left_box["bbox"], right_box["bbox"]) < overlap_threshold:+ continue++ left_area = cls._calculate_bbox_area(left_box["bbox"])+ right_area = cls._calculate_bbox_area(right_box["bbox"])+ if left_area > right_area:+ keep_index, drop_index = left_index, right_index+ elif right_area > left_area:+ keep_index, drop_index = right_index, left_index+ else:+ left_score = float(left_box.get("score", 0.0))+ right_score = float(right_box.get("score", 0.0))+ keep_index, drop_index = (+ (left_index, right_index) if left_score >= right_score else (right_index, left_index)+ )++ keep_box = boxes[keep_index]+ drop_box = boxes[drop_index]+ keep_box["bbox"] = cls._union_bbox(keep_box["bbox"], drop_box["bbox"])+ keep_box["score"] = round(+ max(float(keep_box.get("score", 0.0)), float(drop_box.get("score", 0.0))),+ 4,+ )+ del boxes[drop_index]+ changed = True+ break+ if changed:+ break++ return boxes++ @classmethod+ def _relabel_formula_boxes(+ cls,+ boxes: List[Dict],+ overlap_threshold: float = 0.7,+ ) -> List[Dict]:+ parent_candidates = [+ box+ for box in boxes+ if (not cls._is_formula_box(box) and not cls._is_formula_number_box(box) and not cls._is_reference_box(box))+ ]++ for box in boxes:+ if not cls._is_formula_box(box):+ continue+ target_label = "display_formula"+ for parent_box in parent_candidates:+ if cls._calculate_cover_ratio(box["bbox"], parent_box["bbox"]) >= overlap_threshold:+ target_label = "inline_formula"+ break+ cls._set_formula_label(box, target_label)++ return boxes++ @classmethod+ def _relabel_header_footer_boundary_blocks(+ cls,+ boxes: List[Dict],+ image_size: Optional[Tuple[int, int]] = None,+ ) -> List[Dict]:+ """按视觉坐标用页眉/页脚锚点修正边界区域的普通块标签。"""+ if len(boxes) <= 1:+ return boxes++ header_labels = {"header", "header_image"}+ footer_labels = {"footer", "footer_image"}+ ordered_boxes = sorted(boxes, key=lambda box: box["index"])+ ordered_boxes = cls._reclassify_header_footer_by_page_half(+ ordered_boxes,+ image_size=image_size,+ )+ boundary_anchor_ids = {+ id(box) for box in ordered_boxes if box.get("label") in header_labels or box.get("label") in footer_labels+ }++ header_anchor = max(+ (box for box in ordered_boxes if box.get("label") in header_labels),+ key=lambda box: (box["bbox"][3], box["index"]),+ default=None,+ )+ footer_anchor = min(+ (box for box in ordered_boxes if box.get("label") in footer_labels),+ key=lambda box: (box["bbox"][1], box["index"]),+ default=None,+ )++ # 先按最后一个页眉锚点的下边界修正,后续页脚修正可覆盖重叠区间。+ if header_anchor is not None:+ header_boundary = header_anchor["bbox"][3]+ for box in ordered_boxes:+ if not cls._is_header_footer_boundary_candidate(box, header_labels):+ continue+ if box["bbox"][3] <= header_boundary:+ cls._set_box_label(box, "header")++ footnote_anchors = [box for box in ordered_boxes if box.get("label") == "footnote"]+ if footnote_anchors:+ for box in ordered_boxes:+ if not cls._is_footnote_relabel_candidate(box):+ continue+ for footnote_anchor in footnote_anchors:+ if cls._is_covered_by_footnote(footnote_anchor, box):+ cls._set_footnote_label(box)+ break++ if footer_anchor is not None:+ footer_boundary = footer_anchor["bbox"][1]+ for box in ordered_boxes:+ if not cls._is_header_footer_boundary_candidate(box, footer_labels):+ continue+ if box["bbox"][1] >= footer_boundary and cls._is_footer_x_scope(footer_anchor, box, image_size):+ cls._set_box_label(box, "footer")++ if image_size is None:+ return ordered_boxes++ page_height = float(image_size[0])+ if page_height <= 0:+ return ordered_boxes++ top_boundary = page_height * 0.3+ bottom_boundary = page_height * 0.7+ top_numbers = []+ bottom_numbers = []+ for box in ordered_boxes:+ if box.get("label") != "number":+ continue+ y_mid = (float(box["bbox"][1]) + float(box["bbox"][3])) / 2+ if y_mid <= top_boundary:+ top_numbers.append(box)+ elif y_mid >= bottom_boundary:+ bottom_numbers.append(box)++ top_number_anchor = max(+ top_numbers,+ key=lambda box: (box["bbox"][3], box["index"]),+ default=None,+ )+ bottom_number_anchor = min(+ bottom_numbers,+ key=lambda box: (box["bbox"][1], box["index"]),+ default=None,+ )++ # number 自身不改标签,仅用上下 30% 区域中的 number 作为辅助分割线。+ if top_number_anchor is not None:+ header_boundary = top_number_anchor["bbox"][1]+ for box in ordered_boxes:+ if id(box) in boundary_anchor_ids or not cls._is_header_footer_boundary_candidate(box, set()):+ continue+ if box["bbox"][3] <= header_boundary:+ cls._set_box_label(box, "header")++ if bottom_number_anchor is not None:+ footer_boundary = bottom_number_anchor["bbox"][3]+ for box in ordered_boxes:+ if id(box) in boundary_anchor_ids or not cls._is_header_footer_boundary_candidate(box, set()):+ continue+ if box["bbox"][1] >= footer_boundary:+ cls._set_box_label(box, "footer")++ return ordered_boxes++ @classmethod+ def _apply_layout_post_process(+ cls,+ boxes: List[Dict],+ image_size: Optional[Tuple[int, int]] = None,+ ) -> List[Dict]:+ processed_boxes = [{**box, "bbox": list(box["bbox"])} for box in boxes]+ processed_boxes = cls._deduplicate_boxes_by_iou(processed_boxes, iou_threshold=0.9)+ processed_boxes = cls._merge_nested_formula_boxes(processed_boxes, overlap_threshold=0.7)+ processed_boxes = cls._relabel_formula_boxes(processed_boxes, overlap_threshold=0.7)+ processed_boxes = cls._relabel_header_footer_boundary_blocks(+ processed_boxes,+ image_size=image_size,+ )+ processed_boxes = cls._filter_internal_visual_caption_boxes(+ processed_boxes,+ cover_threshold=0.8,+ )+ return cls._renumber_indices(processed_boxes)++ @classmethod+ def _apply_paddlex_filter_boxes(+ cls,+ boxes: List[Dict],+ drop_inline_formula: bool = True,+ ) -> List[Dict]:+ filtered_boxes = [dict(box) for box in boxes if not cls._is_reference_box(box)]+ dropped_indexes = set()++ for i in range(len(filtered_boxes)):+ if i in dropped_indexes:+ continue+ x1, y1, x2, y2 = filtered_boxes[i]["bbox"]+ width = float(x2) - float(x1)+ height = float(y2) - float(y1)+ if (width < 6.0 or height < 6.0) and (drop_inline_formula or not cls._is_inline_formula_box(filtered_boxes[i])):+ dropped_indexes.add(i)+ continue++ for j in range(i + 1, len(filtered_boxes)):+ if i in dropped_indexes or j in dropped_indexes:+ continue++ if not drop_inline_formula and (+ cls._is_inline_formula_box(filtered_boxes[i]) or cls._is_inline_formula_box(filtered_boxes[j])+ ):+ continue++ overlap_ratio = cls._calculate_overlap_ratio(+ filtered_boxes[i]["bbox"],+ filtered_boxes[j]["bbox"],+ )+ if drop_inline_formula and (+ cls._is_inline_formula_box(filtered_boxes[i]) or cls._is_inline_formula_box(filtered_boxes[j])+ ):+ if overlap_ratio > 0.5:+ if cls._is_inline_formula_box(filtered_boxes[i]):+ dropped_indexes.add(i)+ if cls._is_inline_formula_box(filtered_boxes[j]):+ dropped_indexes.add(j)+ continue++ if overlap_ratio > 0.7:+ box_area_i = cls._calculate_bbox_area(filtered_boxes[i]["bbox"])+ box_area_j = cls._calculate_bbox_area(filtered_boxes[j]["bbox"])+ labels = {filtered_boxes[i]["label"], filtered_boxes[j]["label"]}+ if labels & {"image", "table", "seal", "chart"} and len(labels) > 1:+ if "table" not in labels or labels <= {"table", "image", "seal", "chart"}:+ continue+ if box_area_i >= box_area_j:+ dropped_indexes.add(j)+ else:+ dropped_indexes.add(i)++ kept_boxes = [box for index, box in enumerate(filtered_boxes) if index not in dropped_indexes]+ return cls._renumber_indices(kept_boxes)++ # ------------------------------------------------------------------+ # 可视化+ # ------------------------------------------------------------------+ def visualize(+ self,+ image: Union[np.ndarray, Image.Image],+ results: List[Dict],+ ) -> Image.Image:+ """在图像上绘制检测结果,返回 PIL.Image。"""+ if isinstance(image, Image.Image):+ pil_image = image.convert("RGB").copy()+ elif isinstance(image, np.ndarray):+ pil_image = Image.fromarray(image).convert("RGB").copy()+ else:+ raise TypeError(f"Unsupported image type: {type(image)}")++ draw = ImageDraw.Draw(pil_image)+ font = ImageFont.load_default()+ for res in sorted(+ results,+ key=lambda item: (item.get("index", 10**9), item.get("bbox", [0, 0, 0, 0])[1]),+ ):+ xmin, ymin, xmax, ymax = res["bbox"]+ color = label_to_color(res["label"])+ draw.rectangle([xmin, ymin, xmax, ymax], outline=color, width=3)++ text = f"{res['index']}: {res['label']} {res['score']:.2f}"+ text_top = int(round(ymin))+ text_bbox = draw.textbbox((0, 0), text, font=font)+ text_width = text_bbox[2] - text_bbox[0]+ text_height = text_bbox[3] - text_bbox[1]+ pad = 3++ if text_top - text_height - pad * 2 >= 0:+ text_bg_top = text_top - text_height - pad * 2+ else:+ text_bg_top = text_top+ text_bg_bottom = text_bg_top + text_height + pad * 2+ text_bg_right = int(round(xmax))+ text_bg_left = text_bg_right - text_width - pad * 2++ draw.rectangle(+ [text_bg_left, text_bg_top, text_bg_right, text_bg_bottom],+ fill=color,+ )+ draw.text(+ (text_bg_left + pad, text_bg_top + pad),+ text,+ fill="white",+ font=font,+ )+ return pil_image+++__all__ = [+ "DEFAULT_CLASS_ORDER",+ "DEFAULT_CLASS_THRESHOLDS",+ "DEFAULT_IMAGE_SIZE",+ "DEFAULT_RESCALE_FACTOR",+ "PP_DOCLAYOUT_V2_LABEL_TO_ID",+ "PP_DOCLAYOUT_V2_LABELS",+ "PPDocLayoutV2PostProcessor",+ "label_to_color",+ "load_preprocess_config",+]diff --git a/mineru/model/layout/pp_doclayout_v2_onnx.py b/mineru/model/layout/pp_doclayout_v2_onnx.pynew file mode 100644index 00000000..0af3bb40--- /dev/null+++ b/mineru/model/layout/pp_doclayout_v2_onnx.py@@ -0,0 +1,253 @@+# Copyright (c) Opendatalab. All rights reserved.+"""ONNX 后端的 PP-DocLayoutV2 推理封装。++与 ``PPDocLayoutV2LayoutModel``(transformers/torch 后端)公开接口完全一致,+内部用 onnxruntime 推理 PaddlePaddle 官方发布的 ``PP-DocLayoutV2_onnx`` 模型。++后处理逻辑(去重、合并公式框、重标 header/footer、阅读顺序排序等)直接复用+基类 ``PPDocLayoutV2PostProcessor``,保证两个后端的输出结构一致。+"""++from __future__ import annotations++from pathlib import Path+from typing import Dict, List, Optional, Sequence, Tuple, Union++import cv2+import numpy as np+import onnxruntime as ort+from loguru import logger+from PIL import Image+from tqdm import tqdm++from .pp_doclayout_v2_base import PP_DOCLAYOUT_V2_LABELS, PPDocLayoutV2PostProcessor++__all__ = ["PPDocLayoutV2LayoutModelONNX"]++# PaddlePaddle 官方 PP-DocLayoutV2_onnx 的输入尺寸(与 inference.yml 一致)。+_INPUT_SIZE = (800, 800)+++def _build_providers(device: Optional[str]) -> list[tuple[str, dict[str, object]]]:+ """根据 device 选择 onnxruntime providers。"""+ norm = (device or "cpu").lower().split(":", 1)[0]+ if norm == "cuda":+ return [+ ("CUDAExecutionProvider", {"device_id": 0, "arena_extend_strategy": "kSameAsRequested"}),+ ("CPUExecutionProvider", {"arena_extend_strategy": "kSameAsRequested"}),+ ]+ return [("CPUExecutionProvider", {"arena_extend_strategy": "kSameAsRequested"})]+++class PPDocLayoutV2LayoutModelONNX(PPDocLayoutV2PostProcessor):+ """PP-DocLayoutV2 的 ONNX 推理封装。++ 与 ``PPDocLayoutV2LayoutModel`` 的 ``predict`` / ``batch_predict`` / ``visualize``+ 接口完全一致,返回的 box dict 结构也一致(cls_id / label / score / bbox / index)。++ 差异:+ - 构造函数接收 onnx 文件路径(单个 ``.onnx``),而非 HF 模型目录+ - 不依赖 transformers / torch,仅用 onnxruntime + numpy + cv2+ - 预处理固定为 800x800 BICUBIC + /255(与 PaddlePaddle 官方 inference.yml 一致)+ - 阅读顺序直接来自 ONNX 输出的第 6/7 列(lexsort),无需 reading_order head+ """++ def __init__(+ self,+ weight: str,+ device: Optional[str] = "cpu",+ imgsz: Tuple[int, int] = _INPUT_SIZE,+ conf: float = 0.45,+ use_paddlex_filter_boxes: bool = True,+ intra_op_num_threads: int = 0,+ ) -> None:+ self.device = device or "cpu"+ self.conf = conf+ self.use_paddlex_filter_boxes = use_paddlex_filter_boxes+ self.model_path = str(weight)+ self.imgsz = imgsz+ self.rescale_factor = 1.0 / 255.0++ opts = ort.SessionOptions()+ opts.log_severity_level = 3+ opts.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL+ if intra_op_num_threads > 0:+ opts.intra_op_num_threads = intra_op_num_threads+ self.session = ort.InferenceSession(+ self.model_path,+ sess_options=opts,+ providers=_build_providers(self.device),+ )++ self._input_names = [i.name for i in self.session.get_inputs()]+ self._output_name = self.session.get_outputs()[0].name+ logger.debug(+ "PPDocLayoutV2LayoutModelONNX loaded: {} (inputs={}, outputs={})",+ Path(self.model_path).name,+ self._input_names,+ [o.name for o in self.session.get_outputs()],+ )++ def _preprocess_single_image(self, image: Union[np.ndarray, Image.Image]) -> Tuple[np.ndarray, Tuple[int, int]]:+ """Resize 到 800x800 (BICUBIC) + /255,返回 CHW float32 ndarray。"""+ if isinstance(image, Image.Image):+ pil_image = image.convert("RGB")+ target_size = pil_image.size[1], pil_image.size[0]+ arr = np.array(pil_image, dtype=np.uint8)+ elif isinstance(image, np.ndarray):+ arr = image+ if arr.ndim == 3 and arr.shape[2] == 3:+ arr = cv2.cvtColor(arr, cv2.COLOR_BGR2RGB)+ target_size = arr.shape[0], arr.shape[1]+ else:+ raise TypeError(f"Unsupported image type for PP-DocLayoutV2 ONNX: {type(image)}")++ resized = cv2.resize(arr, (self.imgsz[1], self.imgsz[0]), interpolation=cv2.INTER_LINEAR)+ norm = resized.astype(np.float32) * self.rescale_factor+ chw = norm.transpose(2, 0, 1)+ return chw, target_size++ def _run_session(self, pixel_values: np.ndarray, target_sizes: Sequence[Tuple[int, int]]) -> List[Dict[str, np.ndarray]]:+ """跑一次 ONNX 推理,解析输出为内部 prediction dict。++ PaddlePaddle 官方 PP-DocLayoutV2_onnx 输出 [N, 8]:+ [class_id, score, x1, y1, x2, y2, order_key_a, order_key_b]+ 其中 order_key_a/b 是阅读顺序 key,用 lexsort((-col7, col6)) 排序。+ 坐标已由模型内部按 scale_factor 还原到原图尺度。+ """+ feed: Dict[str, np.ndarray] = {}+ if "image" in self._input_names:+ feed["image"] = pixel_values+ if "scale_factor" in self._input_names:+ feed["scale_factor"] = np.array(+ [[self.imgsz[0] / ts[0], self.imgsz[1] / ts[1]] for ts in target_sizes],+ dtype=np.float32,+ )+ if "im_shape" in self._input_names:+ feed["im_shape"] = np.array([[self.imgsz[0], self.imgsz[1]]] * len(target_sizes), dtype=np.float32)+ else:+ feed[self._input_names[0]] = pixel_values++ preds = self.session.run(None, feed)[0]+ if preds.ndim == 3:+ preds = preds[0]++ batch_predictions: List[Dict[str, np.ndarray]] = []+ for sample_idx, target_size in enumerate(target_sizes):+ sample = preds if preds.ndim == 2 else preds[sample_idx]+ scores = sample[:, 1]+ keep = scores >= self.conf+ sample = sample[keep]++ if sample.shape[1] >= 8:+ order_idx = np.lexsort((-sample[:, 7], sample[:, 6]))+ sample = sample[order_idx]++ batch_predictions.append(+ {+ "scores": sample[:, 1],+ "labels": sample[:, 0].astype(np.int64),+ "boxes": sample[:, 2:6],+ }+ )+ return batch_predictions++ def _parse_prediction(self, result: Dict[str, np.ndarray], image_size: Tuple[int, int]) -> List[Dict]:+ """把 ndarray prediction 转成 box dict 列表(结构与 torch 版一致)。"""+ layout_res: List[Dict] = []+ for index, (score, label_id, box) in enumerate(+ zip(result["scores"], result["labels"], result["boxes"]),+ start=1,+ ):+ bbox = self._clip_bbox(box.tolist(), image_size=image_size)+ if bbox is None:+ continue+ cls_id = int(label_id)+ layout_res.append(+ {+ "cls_id": cls_id,+ "label": (PP_DOCLAYOUT_V2_LABELS[cls_id] if 0 <= cls_id < len(PP_DOCLAYOUT_V2_LABELS) else str(cls_id)),+ "score": round(float(score), 4),+ "bbox": bbox,+ "index": index,+ }+ )+ return layout_res++ def predict(+ self,+ image: Union[np.ndarray, Image.Image],+ use_paddlex_filter_boxes: Optional[bool] = None,+ ) -> List[Dict]:+ return self.batch_predict(+ [image],+ batch_size=1,+ use_paddlex_filter_boxes=use_paddlex_filter_boxes,+ )[0]++ def batch_predict(+ self,+ images: List[Union[np.ndarray, Image.Image]],+ batch_size: int = 1,+ use_paddlex_filter_boxes: Optional[bool] = None,+ ) -> List[List[Dict]]:+ if not images:+ return []++ use_filter = self.use_paddlex_filter_boxes if use_paddlex_filter_boxes is None else use_paddlex_filter_boxes+ results: List[List[Dict]] = []+ with tqdm(total=len(images), desc="Layout Predict") as pbar:+ for start in range(0, len(images), batch_size):+ batch_images = images[start : start + batch_size]+ pixel_values_list: List[np.ndarray] = []+ target_sizes: List[Tuple[int, int]] = []+ for image in batch_images:+ chw, target_size = self._preprocess_single_image(image)+ pixel_values_list.append(chw)+ target_sizes.append(target_size)++ batch_tensor = np.stack(pixel_values_list, axis=0).astype(np.float32)+ predictions = self._run_session(batch_tensor, target_sizes)+ for prediction, image_size in zip(predictions, target_sizes):+ layout_res = self._parse_prediction(prediction, image_size)+ if use_filter:+ layout_res = self._apply_paddlex_filter_boxes(layout_res, drop_inline_formula=False)+ layout_res = self._apply_layout_post_process(layout_res, image_size=image_size)+ results.append(layout_res)+ pbar.update(len(batch_images))+ return results+++if __name__ == "__main__":+ import argparse++ parser = argparse.ArgumentParser(description="PP-DocLayoutV2 ONNX local inference smoke test")+ parser.add_argument("image", nargs="?", help="Path to an input image.")+ parser.add_argument("--model", default=None, help="Path to inference.onnx.")+ parser.add_argument("--device", default=None, help="cpu / cuda / mps.")+ parser.add_argument("--output", default=None, help="Save visualization to this path.")+ args = parser.parse_args()++ if args.model is None:+ from ...utils.model_registry import PP_DOCLAYOUT_V2_ONNX++ args.model = str(PP_DOCLAYOUT_V2_ONNX.onnx.ensure())++ if args.device is None:+ from ...utils.config_reader import get_device++ args.device = get_device()++ model = PPDocLayoutV2LayoutModelONNX(weight=args.model, device=args.device)+ print(f"model loaded on {model.device}")++ if args.image:+ with Image.open(args.image) as img:+ results = model.predict(img)+ print(f"detected {len(results)} regions")+ for r in results:+ print(f" [{r['index']}] {r['label']:<20} score={r['score']:.2f} bbox={r['bbox']}")+ if args.output:+ vis = model.visualize(img, results)+ vis.save(args.output)+ print(f"visualization saved to {args.output}")diff --git a/mineru/model/layout/pp_doclayoutv2.py b/mineru/model/layout/pp_doclayoutv2.pyindex 52e433c1..4ca9d72d 100644--- a/mineru/model/layout/pp_doclayoutv2.py+++ b/mineru/model/layout/pp_doclayoutv2.py@@ -1,21 +1,17 @@# Copyright (c) Opendatalab. All rights reserved.import argparse-import colorsys-import hashlibimport jsonimport math-import osfrom dataclasses import dataclassfrom typing import Dict, List, Optional, Sequence, Tuple, Unionimport numpy as np-from PIL import Image, ImageDraw, ImageFont-from torch import nn-from tqdm import tqdm+import torchimport torchvision.transforms.v2.functional as tvF+from PIL import Image+from torch import nnfrom torchvision.transforms import InterpolationMode--import torch+from tqdm import tqdmfrom transformers import AutoConfigfrom transformers.activations import ACT2FNfrom transformers.configuration_utils import PretrainedConfig@@ -25,98 +21,17 @@ 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--PP_DOCLAYOUT_V2_LABELS = [- "abstract", # 0 论文摘要- "algorithm", # 1 算法- "aside_text", # 2 页边注文本,通常位于页面边缘,提供补充信息或注释,与主内容相关但不直接包含在内- "chart", # 3 图表,通常包含数据可视化元素,如柱状图、折线图、饼图等,用于展示数据关系和趋势- "content", # 4 只在大的目录块中出现,其他地方未见- "display_formula", # 5 独立展示的公式,通常占据整行或多行,具有较大字体和清晰的布局,以突出其重要性和可读性- "doc_title", # 6 文章标题,一篇文章的主标题- "figure_title", # 7 image/chart/table的caption- "footer", # 8 页脚文本- "footer_image", # 9 页脚图片- "footnote", # 10 page footnote,通常位于页面底部,提供对正文中特定内容的补充说明、引用来源或其他相关信息- "formula_number", # 11 公式编号,通常与display_formula配合使用,标识独立展示的公式在文档中的位置和顺序,便于引用和索引- "header", # 12 页眉文本- "header_image", # 13 页眉图片- "image", # 14 图片- "inline_formula", # 15 行内公式- "number", # 16 页码- "paragraph_title", # 17 段落标题,有别与文章标题- "reference", # 18 参考文献,list外框- "reference_content", # 19 参考文献内容,list item- "seal", # 20 印章- "table", # 21 表格- "text", # 22 一般文本- "vertical_text", # 23 竖排文本- "vision_footnote", # 24 image/chart/table的footnote-]--PP_DOCLAYOUT_V2_LABEL_TO_ID = {label: index for index, label in enumerate(PP_DOCLAYOUT_V2_LABELS)}--# Per-class confidence threshold used before reading-order decoding.-DEFAULT_CLASS_THRESHOLDS = [- 0.5, # 0 abstract- 0.5, # 1 algorithm- 0.5, # 2 aside_text- 0.5, # 3 chart- 0.5, # 4 content- 0.4, # 5 display_formula- 0.4, # 6 doc_title- 0.5, # 7 figure_title- 0.5, # 8 footer- 0.5, # 9 footer_image- 0.5, # 10 footnote- 0.5, # 11 formula_number- 0.5, # 12 header- 0.5, # 13 header_image- 0.5, # 14 image- 0.4, # 15 inline_formula- 0.5, # 16 number- 0.4, # 17 paragraph_title- 0.5, # 18 reference- 0.5, # 19 reference_content- 0.45, # 20 seal- 0.5, # 21 table- 0.4, # 22 text- 0.4, # 23 vertical_text- 0.5, # 24 vision_footnote-]--# Reading-order head class remap used by the original upstream model.-DEFAULT_CLASS_ORDER = [- 4, # 0 abstract- 2, # 1 algorithm- 14, # 2 aside_text- 1, # 3 chart- 5, # 4 content- 7, # 5 display_formula- 8, # 6 doc_title- 6, # 7 figure_title- 11, # 8 footer- 11, # 9 footer- 9, # 10 footnote- 13, # 11 formula_number- 10, # 12 header- 10, # 13 header_image- 1, # 14 image- 2, # 15 inline_formula- 3, # 16 number- 0, # 17 paragraph_title- 2, # 18 reference- 2, # 19 reference_content- 12, # 20 seal- 1, # 21 table- 2, # 22 text- 15, # 23 vertical_text- 6, # 24 vision_footnote-]+from .pp_doclayout_v2_base import (+ DEFAULT_CLASS_ORDER,+ DEFAULT_CLASS_THRESHOLDS,+ DEFAULT_IMAGE_SIZE,+ DEFAULT_RESCALE_FACTOR,+ PP_DOCLAYOUT_V2_LABEL_TO_ID,+ PP_DOCLAYOUT_V2_LABELS,+ PPDocLayoutV2PostProcessor,+ label_to_color,+ load_preprocess_config,+)def _build_default_backbone_config():@@ -142,9 +57,7 @@ def _create_bidirectional_mask(if attention_mask.ndim == 4:return attention_maskif attention_mask.ndim != 2:- raise ValueError(- f"PP-DocLayoutV2 reading-order mask must be 2D or 4D, got shape {tuple(attention_mask.shape)}"- )+ raise ValueError(f"PP-DocLayoutV2 reading-order mask must be 2D or 4D, got shape {tuple(attention_mask.shape)}")embeds = encoder_hidden_states if encoder_hidden_states is not None else inputs_embedsbatch_size, query_length = inputs_embeds.shape[:2]@@ -165,23 +78,6 @@ def _create_bidirectional_mask()-def _load_preprocess_config(model_dir: str) -> Dict:- config_path = os.path.join(model_dir, "preprocessor_config.json")- if not os.path.exists(config_path):- return {}- with open(config_path, "r", encoding="utf-8") as f:- return json.load(f)---def _label_to_color(label: str) -> Tuple[int, int, int]:- digest = hashlib.md5(label.encode("utf-8")).digest()- hue = digest[0] / 255.0- saturation = 0.65 + (digest[1] / 255.0) * 0.2- value = 0.85 + (digest[2] / 255.0) * 0.1- r, g, b = colorsys.hsv_to_rgb(hue, saturation, value)- return int(r * 255), int(g * 255), int(b * 255)--@dataclassclass PPDocLayoutV2ForObjectDetectionOutput(ModelOutput):logits: torch.FloatTensor | None = None@@ -355,9 +251,7 @@ class PPDocLayoutV2PositionRelationEmbedding(nn.Module):base = config.relation_bias_thetadim = config.relation_bias_embed_dimhalf_dim = dim // 2- inv_freq = 1.0 / (- base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / half_dim)- )+ inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / half_dim))return inv_freq, 1.0def box_relative_encoding(@@ -423,19 +317,13 @@ class PPDocLayoutV2ReadingOrderSelfAttention(nn.Module):):batch_size, _, _ = hidden_states.shapequery_layer = (- self.query(hidden_states)- .view(batch_size, -1, self.num_attention_heads, self.attention_head_size)- .transpose(1, 2)+ self.query(hidden_states).view(batch_size, -1, self.num_attention_heads, self.attention_head_size).transpose(1, 2))key_layer = (- self.key(hidden_states)- .view(batch_size, -1, self.num_attention_heads, self.attention_head_size)- .transpose(1, 2)+ self.key(hidden_states).view(batch_size, -1, self.num_attention_heads, self.attention_head_size).transpose(1, 2))value_layer = (- self.value(hidden_states)- .view(batch_size, -1, self.num_attention_heads, self.attention_head_size)- .transpose(1, 2)+ self.value(hidden_states).view(batch_size, -1, self.num_attention_heads, self.attention_head_size).transpose(1, 2))attention_scores = torch.matmul(query_layer / (self.attention_head_size**0.5), key_layer.transpose(-1, -2))@@ -588,8 +476,7 @@ class PPDocLayoutV2ReadingOrderEncoder(nn.Module):max_exact = num_buckets // 2is_small = relative_position < max_exactval_if_large = max_exact + (- torch.log(relative_position.float() / max_exact) / math.log(max_distance / max_exact)- * (num_buckets - max_exact)+ torch.log(relative_position.float() / max_exact) / math.log(max_distance / max_exact) * (num_buckets - max_exact)).to(torch.long)val_if_large = torch.min(val_if_large, torch.full_like(val_if_large, num_buckets - 1))return ret + torch.where(is_small, relative_position, val_if_large)@@ -741,12 +628,7 @@ class PPDocLayoutV2ReadingOrder(PPDocLayoutV2PreTrainedModel):batch_size, seq_len = mask.shapenum_pred = mask.sum(dim=1)- input_ids = torch.full(- (batch_size, seq_len + 2),- self.config.pad_token_id,- dtype=torch.long,- device=device,- )+ input_ids = torch.full((batch_size, seq_len + 2), self.config.pad_token_id, dtype=torch.long, device=device)input_ids[:, 0] = self.config.start_token_idpred_col_idx = torch.arange(seq_len + 2, device=device).unsqueeze(0)pred_mask = (pred_col_idx >= 1) & (pred_col_idx <= num_pred.unsqueeze(1))@@ -895,19 +777,7 @@ class PPDocLayoutV2ForObjectDetection(RTDetrForObjectDetection):return result if use_return_dict else result.to_tuple()-class PPDocLayoutV2LayoutModel:- HEADER_FOOTER_BOUNDARY_EXEMPT_LABELS = {"aside_text", "footnote", "number"}- VISUAL_BODY_LABELS = {"image", "chart", "table", "seal"}- PAGE_REGION_LABELS = {- "header",- "header_image",- "footer",- "footer_image",- "footnote",- "number",- "aside_text",- }-+class PPDocLayoutV2LayoutModel(PPDocLayoutV2PostProcessor):def __init__(self,weight: str,@@ -920,7 +790,7 @@ class PPDocLayoutV2LayoutModel:self.conf = confself.use_paddlex_filter_boxes = use_paddlex_filter_boxesself.model_dir = weight- self.preprocess_config = _load_preprocess_config(self.model_dir)+ self.preprocess_config = load_preprocess_config(self.model_dir)size = self.preprocess_config.get("size", {})self.imgsz = (int(size.get("width", imgsz[0])),@@ -936,14 +806,12 @@ class PPDocLayoutV2LayoutModel:def _get_order_seqs(order_logits: torch.Tensor) -> torch.Tensor:order_scores = torch.sigmoid(order_logits)batch_size, sequence_length, _ = order_scores.shape- order_votes = order_scores.triu(diagonal=1).sum(dim=1) + (- 1.0 - order_scores.transpose(1, 2)- ).tril(diagonal=-1).sum(dim=1)+ order_votes = order_scores.triu(diagonal=1).sum(dim=1) + (1.0 - order_scores.transpose(1, 2)).tril(diagonal=-1).sum(+ dim=1+ )order_pointers = torch.argsort(order_votes, dim=1)order_seq = torch.empty_like(order_pointers)- ranks = torch.arange(sequence_length, device=order_pointers.device, dtype=order_pointers.dtype).expand(- batch_size, -1- )+ ranks = torch.arange(sequence_length, device=order_pointers.device, dtype=order_pointers.dtype).expand(batch_size, -1)order_seq.scatter_(1, order_pointers, ranks)return order_seq@@ -1008,15 +876,6 @@ class PPDocLayoutV2LayoutModel:)return results- def _label_id_to_label_name(self, label_id: int) -> str:- if 0 <= label_id < len(PP_DOCLAYOUT_V2_LABELS):- return PP_DOCLAYOUT_V2_LABELS[label_id]- 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[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 = []for index, (score, label_id, box, _order_seq) in enumerate(@@ -1044,591 +903,6 @@ class PPDocLayoutV2LayoutModel:)return layout_res- @staticmethod- def _calculate_bbox_area(box: Sequence[float]) -> float:- xmin, ymin, xmax, ymax = [float(v) for v in box]- return max(0.0, xmax - xmin) * max(0.0, ymax - ymin)-- @classmethod- def _calculate_intersection_area(cls, box1: Sequence[float], box2: Sequence[float]) -> float:- 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]- inter_xmin = max(x1_min, x2_min)- inter_ymin = max(y1_min, y2_min)- inter_xmax = min(x1_max, x2_max)- inter_ymax = min(y1_max, y2_max)- return cls._calculate_bbox_area((inter_xmin, inter_ymin, inter_xmax, inter_ymax))-- @classmethod- def _calculate_overlap_ratio(cls, box1: Sequence[float], box2: Sequence[float]) -> float:- inter_area = cls._calculate_intersection_area(box1, box2)- ref_area = min(cls._calculate_bbox_area(box1), cls._calculate_bbox_area(box2))- if ref_area <= 0.0:- return 0.0- return inter_area / ref_area-- @classmethod- def _calculate_iou(cls, box1: Sequence[float], box2: Sequence[float]) -> float:- inter_area = cls._calculate_intersection_area(box1, box2)- union_area = cls._calculate_bbox_area(box1) + cls._calculate_bbox_area(box2) - inter_area- if union_area <= 0.0:- return 0.0- return inter_area / union_area-- @classmethod- def _calculate_cover_ratio(cls, box1: Sequence[float], box2: Sequence[float]) -> float:- box1_area = cls._calculate_bbox_area(box1)- if box1_area <= 0.0:- return 0.0- return cls._calculate_intersection_area(box1, box2) / box1_area-- @staticmethod- def _calculate_x_overlap_ratio(box1: Sequence[float], box2: Sequence[float]) -> float:- """计算两个 bbox 在横向上的重叠比例,用于判断是否属于同一栏。"""- box1_xmin, _, box1_xmax, _ = [float(v) for v in box1]- box2_xmin, _, box2_xmax, _ = [float(v) for v in box2]- box1_width = max(0.0, box1_xmax - box1_xmin)- box2_width = max(0.0, box2_xmax - box2_xmin)- ref_width = min(box1_width, box2_width)- if ref_width <= 0.0:- return 0.0- overlap_width = max(0.0, min(box1_xmax, box2_xmax) - max(box1_xmin, box2_xmin))- return overlap_width / ref_width-- @staticmethod- def _calculate_x_cover_ratio(anchor_box: Sequence[float], candidate_box: Sequence[float]) -> float:- """计算 anchor 在横向上覆盖 candidate 的比例。"""- anchor_xmin, _, anchor_xmax, _ = [float(v) for v in anchor_box]- candidate_xmin, _, candidate_xmax, _ = [float(v) for v in candidate_box]- candidate_width = max(0.0, candidate_xmax - candidate_xmin)- if candidate_width <= 0.0:- return 0.0- overlap_width = max(- 0.0,- min(anchor_xmax, candidate_xmax) - max(anchor_xmin, candidate_xmin),- )- return overlap_width / candidate_width-- @classmethod- def _is_footer_x_scope(- cls,- anchor_box: Dict,- candidate_box: Dict,- image_size: Optional[Tuple[int, int]],- full_width_threshold: float = 0.7,- x_overlap_threshold: float = 0.3,- ) -> bool:- """判断候选块是否在页脚文本锚点的横向作用范围内。"""- anchor_bbox = anchor_box.get("bbox")- candidate_bbox = candidate_box.get("bbox")- if not anchor_bbox or not candidate_bbox:- return False-- if image_size is not None and len(image_size) >= 2:- page_width = float(image_size[1])- anchor_width = max(0.0, float(anchor_bbox[2]) - float(anchor_bbox[0]))- if page_width > 0.0 and anchor_width / page_width >= full_width_threshold:- return True-- return cls._calculate_x_overlap_ratio(anchor_bbox, candidate_bbox) >= x_overlap_threshold-- @classmethod- def _is_covered_by_footnote(- cls,- footnote_box: Dict,- candidate_box: Dict,- x_cover_threshold: float = 0.7,- ) -> bool:- """判断候选块是否位于 footnote 区域内或其下方,并被其横向覆盖。"""- footnote_bbox = footnote_box.get("bbox")- candidate_bbox = candidate_box.get("bbox")- if not footnote_bbox or not candidate_bbox:- return False- if candidate_bbox[1] < footnote_bbox[1]:- return False- return cls._calculate_x_cover_ratio(footnote_bbox, candidate_bbox) >= x_cover_threshold-- @classmethod- def _is_header_footer_boundary_candidate(cls, box: Dict, anchor_labels: set[str]) -> bool:- """判断普通块是否可被页眉/页脚/页码边界规则改标。"""- label = box.get("label")- if label in cls.HEADER_FOOTER_BOUNDARY_EXEMPT_LABELS:- return False- return label not in anchor_labels-- @classmethod- def _is_footnote_relabel_candidate(cls, box: Dict) -> bool:- """排除页眉、页脚、页码、页边注等非正文区域块,保留正文内容块。"""- return box.get("label") not in cls.PAGE_REGION_LABELS-- @staticmethod- def _is_reference_box(box: Dict) -> bool:- return box.get("label") == "reference" or int(box.get("cls_id", -1)) == 18-- @staticmethod- def _is_display_formula_box(box: Dict) -> bool:- return box.get("label") == "display_formula" or int(box.get("cls_id", -1)) == 5-- @staticmethod- def _is_inline_formula_box(box: Dict) -> bool:- return box.get("label") == "inline_formula" or int(box.get("cls_id", -1)) == 15-- @staticmethod- def _is_formula_box(box: Dict) -> bool:- return (- PPDocLayoutV2LayoutModel._is_display_formula_box(box)- or PPDocLayoutV2LayoutModel._is_inline_formula_box(box)- )-- @staticmethod- def _is_formula_number_box(box: Dict) -> bool:- return box.get("label") == "formula_number" or int(box.get("cls_id", -1)) == 11-- @staticmethod- def _set_box_label(box: Dict, label: str) -> None:- """统一同步设置 layout 检测框的标签名和类别编号。"""- if label not in PP_DOCLAYOUT_V2_LABEL_TO_ID:- raise ValueError(f"Unsupported PP-DocLayoutV2 label: {label}")- box["label"] = label- box["cls_id"] = PP_DOCLAYOUT_V2_LABEL_TO_ID[label]-- @staticmethod- def _set_formula_label(box: Dict, label: str) -> None:- if label not in {"inline_formula", "display_formula"}:- raise ValueError(f"Unsupported formula label: {label}")- PPDocLayoutV2LayoutModel._set_box_label(box, label)-- @staticmethod- def _set_header_footer_label(box: Dict, label: str) -> None:- """同步设置页眉/页脚相关标签及其类别编号。"""- if label not in {"footer", "footer_image", "header", "header_image"}:- raise ValueError(f"Unsupported header/footer label: {label}")- PPDocLayoutV2LayoutModel._set_box_label(box, label)-- @staticmethod- def _set_footnote_label(box: Dict) -> None:- """同步设置 page footnote 标签及其类别编号。"""- PPDocLayoutV2LayoutModel._set_box_label(box, "footnote")-- @classmethod- def _filter_internal_visual_caption_boxes(- cls,- boxes: List[Dict],- cover_threshold: float = 0.8,- ) -> List[Dict]:- """过滤落在图、表、印章等视觉主体内部的 figure_title。-- 这类块通常是图内的 (a)/(b) 标号,不应作为外部 caption 参与后续视觉分组。- """- visual_boxes = [box for box in boxes if box.get("label") in cls.VISUAL_BODY_LABELS]- if not visual_boxes:- return boxes-- filtered_boxes = []- for box in boxes:- if box.get("label") != "figure_title":- filtered_boxes.append(box)- continue-- caption_bbox = box.get("bbox")- if not caption_bbox or len(caption_bbox) < 4:- filtered_boxes.append(box)- continue-- caption_center_x = (float(caption_bbox[0]) + float(caption_bbox[2])) / 2- caption_center_y = (float(caption_bbox[1]) + float(caption_bbox[3])) / 2- is_internal_caption = False- for visual_box in visual_boxes:- visual_bbox = visual_box.get("bbox")- if not visual_bbox or len(visual_bbox) < 4:- continue-- visual_xmin, visual_ymin, visual_xmax, visual_ymax = [float(v) for v in visual_bbox]- if not (- visual_xmin <= caption_center_x <= visual_xmax- and visual_ymin <= caption_center_y <= visual_ymax- ):- continue-- if cls._calculate_cover_ratio(caption_bbox, visual_bbox) >= cover_threshold:- is_internal_caption = True- break-- if not is_internal_caption:- filtered_boxes.append(box)-- return filtered_boxes-- @classmethod- def _reclassify_header_footer_by_page_half(- cls,- boxes: List[Dict],- image_size: Optional[Tuple[int, int]],- ) -> List[Dict]:- """按页面上下半区重新校正页眉/页脚锚点,避免跨半页误触发边界规则。"""- if image_size is None:- return boxes-- page_height = float(image_size[0])- if page_height <= 0:- return boxes-- page_middle = page_height * 0.5- upper_half_labels = {- "footer": "header",- "footer_image": "header_image",- }- lower_half_labels = {- "header": "footer",- "header_image": "footer_image",- }- for box in boxes:- bbox = box.get("bbox")- if not bbox or len(bbox) < 4:- continue- label = box.get("label")- y_mid = (float(bbox[1]) + float(bbox[3])) / 2- if y_mid < page_middle and label in upper_half_labels:- cls._set_header_footer_label(box, upper_half_labels[label])- elif y_mid >= page_middle and label in lower_half_labels:- cls._set_header_footer_label(box, lower_half_labels[label])-- return boxes-- @staticmethod- 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 [- 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- def _renumber_indices(boxes: List[Dict]) -> List[Dict]:- for index, box in enumerate(boxes, start=1):- box["index"] = index- return boxes-- @classmethod- def _deduplicate_boxes_by_iou(- cls,- boxes: List[Dict],- iou_threshold: float = 0.9,- ) -> List[Dict]:- if len(boxes) <= 1:- return boxes-- sorted_candidates = sorted(- enumerate(boxes),- key=lambda item: (-float(item[1].get("score", 0.0)), item[0]),- )- suppressed_indexes = set()- kept_indexes = []-- for candidate_pos, (current_index, current_box) in enumerate(sorted_candidates):- if current_index in suppressed_indexes:- continue- kept_indexes.append(current_index)- for other_index, other_box in sorted_candidates[candidate_pos + 1 :]:- if other_index in suppressed_indexes:- continue- if cls._calculate_iou(current_box["bbox"], other_box["bbox"]) > iou_threshold:- suppressed_indexes.add(other_index)-- kept_indexes.sort()- return [boxes[index] for index in kept_indexes]-- @classmethod- def _merge_nested_formula_boxes(- cls,- boxes: List[Dict],- overlap_threshold: float = 0.7,- ) -> List[Dict]:- if len(boxes) <= 1:- return boxes-- changed = True- while changed:- changed = False- formula_indexes = [index for index, box in enumerate(boxes) if cls._is_formula_box(box)]- for formula_pos, left_index in enumerate(formula_indexes):- for right_index in formula_indexes[formula_pos + 1 :]:- left_box = boxes[left_index]- right_box = boxes[right_index]- if cls._calculate_overlap_ratio(left_box["bbox"], right_box["bbox"]) < overlap_threshold:- continue-- left_area = cls._calculate_bbox_area(left_box["bbox"])- right_area = cls._calculate_bbox_area(right_box["bbox"])- if left_area > right_area:- keep_index, drop_index = left_index, right_index- elif right_area > left_area:- keep_index, drop_index = right_index, left_index- else:- left_score = float(left_box.get("score", 0.0))- right_score = float(right_box.get("score", 0.0))- keep_index, drop_index = (- (left_index, right_index)- if left_score >= right_score- else (right_index, left_index)- )-- keep_box = boxes[keep_index]- drop_box = boxes[drop_index]- keep_box["bbox"] = cls._union_bbox(keep_box["bbox"], drop_box["bbox"])- keep_box["score"] = round(- max(float(keep_box.get("score", 0.0)), float(drop_box.get("score", 0.0))),- 4,- )- del boxes[drop_index]- changed = True- break- if changed:- break-- return boxes-- @classmethod- def _relabel_formula_boxes(- cls,- boxes: List[Dict],- overlap_threshold: float = 0.7,- ) -> List[Dict]:- parent_candidates = [- box- for box in boxes- if (- not cls._is_formula_box(box)- and not cls._is_formula_number_box(box)- and not cls._is_reference_box(box)- )- ]-- for box in boxes:- if not cls._is_formula_box(box):- continue- target_label = "display_formula"- for parent_box in parent_candidates:- if cls._calculate_cover_ratio(box["bbox"], parent_box["bbox"]) >= overlap_threshold:- target_label = "inline_formula"- break- cls._set_formula_label(box, target_label)-- return boxes-- @classmethod- def _relabel_header_footer_boundary_blocks(- cls,- boxes: List[Dict],- image_size: Optional[Tuple[int, int]] = None,- ) -> List[Dict]:- """按视觉坐标用页眉/页脚锚点修正边界区域的普通块标签。"""- if len(boxes) <= 1:- return boxes-- header_labels = {"header", "header_image"}- footer_labels = {"footer", "footer_image"}- ordered_boxes = sorted(boxes, key=lambda box: box["index"])- ordered_boxes = cls._reclassify_header_footer_by_page_half(- ordered_boxes,- image_size=image_size,- )- boundary_anchor_ids = {- id(box)- for box in ordered_boxes- if box.get("label") in header_labels or box.get("label") in footer_labels- }-- header_anchor = max(- (box for box in ordered_boxes if box.get("label") in header_labels),- key=lambda box: (box["bbox"][3], box["index"]),- default=None,- )- footer_anchor = min(- (box for box in ordered_boxes if box.get("label") in footer_labels),- key=lambda box: (box["bbox"][1], box["index"]),- default=None,- )-- # 先按最后一个页眉锚点的下边界修正,后续页脚修正可覆盖重叠区间。- if header_anchor is not None:- header_boundary = header_anchor["bbox"][3]- for box in ordered_boxes:- if not cls._is_header_footer_boundary_candidate(box, header_labels):- continue- if box["bbox"][3] <= header_boundary:- cls._set_box_label(box, "header")-- footnote_anchors = [box for box in ordered_boxes if box.get("label") == "footnote"]- if footnote_anchors:- for box in ordered_boxes:- if not cls._is_footnote_relabel_candidate(box):- continue- for footnote_anchor in footnote_anchors:- if cls._is_covered_by_footnote(footnote_anchor, box):- cls._set_footnote_label(box)- break-- if footer_anchor is not None:- footer_boundary = footer_anchor["bbox"][1]- for box in ordered_boxes:- if not cls._is_header_footer_boundary_candidate(box, footer_labels):- continue- if (- box["bbox"][1] >= footer_boundary- and cls._is_footer_x_scope(footer_anchor, box, image_size)- ):- cls._set_box_label(box, "footer")-- if image_size is None:- return ordered_boxes-- page_height = float(image_size[0])- if page_height <= 0:- return ordered_boxes-- top_boundary = page_height * 0.3- bottom_boundary = page_height * 0.7- top_numbers = []- bottom_numbers = []- for box in ordered_boxes:- if box.get("label") != "number":- continue- y_mid = (float(box["bbox"][1]) + float(box["bbox"][3])) / 2- if y_mid <= top_boundary:- top_numbers.append(box)- elif y_mid >= bottom_boundary:- bottom_numbers.append(box)-- top_number_anchor = max(- top_numbers,- key=lambda box: (box["bbox"][3], box["index"]),- default=None,- )- bottom_number_anchor = min(- bottom_numbers,- key=lambda box: (box["bbox"][1], box["index"]),- default=None,- )-- # number 自身不改标签,仅用上下 30% 区域中的 number 作为辅助分割线。- if top_number_anchor is not None:- header_boundary = top_number_anchor["bbox"][1]- for box in ordered_boxes:- if (- id(box) in boundary_anchor_ids- or not cls._is_header_footer_boundary_candidate(box, set())- ):- continue- if box["bbox"][3] <= header_boundary:- cls._set_box_label(box, "header")-- if bottom_number_anchor is not None:- footer_boundary = bottom_number_anchor["bbox"][3]- for box in ordered_boxes:- if (- id(box) in boundary_anchor_ids- or not cls._is_header_footer_boundary_candidate(box, set())- ):- continue- if box["bbox"][1] >= footer_boundary:- cls._set_box_label(box, "footer")-- return ordered_boxes-- @classmethod- def _apply_layout_post_process(- cls,- boxes: List[Dict],- image_size: Optional[Tuple[int, int]] = None,- ) -> List[Dict]:- processed_boxes = [{**box, "bbox": list(box["bbox"])} for box in boxes]- processed_boxes = cls._deduplicate_boxes_by_iou(processed_boxes, iou_threshold=0.9)- processed_boxes = cls._merge_nested_formula_boxes(processed_boxes, overlap_threshold=0.7)- processed_boxes = cls._relabel_formula_boxes(processed_boxes, overlap_threshold=0.7)- processed_boxes = cls._relabel_header_footer_boundary_blocks(- processed_boxes,- image_size=image_size,- )- processed_boxes = cls._filter_internal_visual_caption_boxes(- processed_boxes,- cover_threshold=0.8,- )- return cls._renumber_indices(processed_boxes)-- @classmethod- def _apply_paddlex_filter_boxes(- cls,- boxes: List[Dict],- drop_inline_formula: bool = True,- ) -> List[Dict]:- filtered_boxes = [dict(box) for box in boxes if not cls._is_reference_box(box)]- dropped_indexes = set()-- for i in range(len(filtered_boxes)):- if i in dropped_indexes:- continue- x1, y1, x2, y2 = filtered_boxes[i]["bbox"]- width = float(x2) - float(x1)- height = float(y2) - float(y1)- if (- (width < 6.0 or height < 6.0)- and (drop_inline_formula or not cls._is_inline_formula_box(filtered_boxes[i]))- ):- dropped_indexes.add(i)- continue-- for j in range(i + 1, len(filtered_boxes)):- if i in dropped_indexes or j in dropped_indexes:- continue-- if (- not drop_inline_formula- and (- cls._is_inline_formula_box(filtered_boxes[i])- or cls._is_inline_formula_box(filtered_boxes[j])- )- ):- continue-- overlap_ratio = cls._calculate_overlap_ratio(- filtered_boxes[i]["bbox"],- filtered_boxes[j]["bbox"],- )- if (- drop_inline_formula- and (- cls._is_inline_formula_box(filtered_boxes[i])- or cls._is_inline_formula_box(filtered_boxes[j])- )- ):- if overlap_ratio > 0.5:- if cls._is_inline_formula_box(filtered_boxes[i]):- dropped_indexes.add(i)- if cls._is_inline_formula_box(filtered_boxes[j]):- dropped_indexes.add(j)- continue-- if overlap_ratio > 0.7:- box_area_i = cls._calculate_bbox_area(filtered_boxes[i]["bbox"])- box_area_j = cls._calculate_bbox_area(filtered_boxes[j]["bbox"])- labels = {filtered_boxes[i]["label"], filtered_boxes[j]["label"]}- if labels & {"image", "table", "seal", "chart"} and len(labels) > 1:- if "table" not in labels or labels <= {"table", "image", "seal", "chart"}:- continue- if box_area_i >= box_area_j:- dropped_indexes.add(j)- else:- dropped_indexes.add(i)-- kept_boxes = [- box for index, box in enumerate(filtered_boxes) if index not in dropped_indexes- ]- return cls._renumber_indices(kept_boxes)-def predict(self,image: Union[np.ndarray, Image.Image],@@ -1650,9 +924,7 @@ class PPDocLayoutV2LayoutModel:return []use_paddlex_filter_boxes = (- self.use_paddlex_filter_boxes- if use_paddlex_filter_boxes is None- else use_paddlex_filter_boxes+ self.use_paddlex_filter_boxes if use_paddlex_filter_boxes is None else use_paddlex_filter_boxes)results: List[List[Dict]] = []with torch.no_grad():@@ -1678,55 +950,21 @@ class PPDocLayoutV2LayoutModel:pbar.update(len(batch_images))return results- def visualize(- self,- image: Union[np.ndarray, Image.Image],- results: List[Dict],- ) -> Image.Image:- if isinstance(image, np.ndarray):- image = Image.fromarray(image)- image = image.convert("RGB").copy()- draw = ImageDraw.Draw(image)- font = ImageFont.load_default()- for res in sorted(results, key=lambda item: (item.get("index", 10**9), item.get("bbox", [0, 0, 0, 0])[1])):- xmin, ymin, xmax, ymax = res["bbox"]- color = _label_to_color(res["label"])- draw.rectangle([xmin, ymin, xmax, ymax], outline=color, width=3)-- text = f"{res['index']}: {res['label']} {res['score']:.2f}"- text_top = int(round(ymin))- text_bbox = draw.textbbox((0, 0), text, font=font)- text_width = text_bbox[2] - text_bbox[0]- text_height = text_bbox[3] - text_bbox[1]- pad = 3-- if text_top - text_height - pad * 2 >= 0:- text_bg_top = text_top - text_height - pad * 2- else:- text_bg_top = text_top- text_bg_bottom = text_bg_top + text_height + pad * 2- text_bg_right = int(round(xmax))- text_bg_left = text_bg_right - text_width - pad * 2-- draw.rectangle(- [text_bg_left, text_bg_top, text_bg_right, text_bg_bottom],- fill=color,- )- draw.text(- (text_bg_left + pad, text_bg_top + pad),- text,- fill="white",- font=font,- )- return image-__all__ = [+ "DEFAULT_CLASS_ORDER",+ "DEFAULT_CLASS_THRESHOLDS",+ "DEFAULT_IMAGE_SIZE",+ "DEFAULT_RESCALE_FACTOR",+ "PP_DOCLAYOUT_V2_LABELS",+ "PP_DOCLAYOUT_V2_LABEL_TO_ID","PPDocLayoutV2Config","PPDocLayoutV2ForObjectDetection","PPDocLayoutV2LayoutModel","PPDocLayoutV2ReadingOrder","PPDocLayoutV2ReadingOrderConfig",+ "label_to_color",+ "load_preprocess_config",]@@ -1741,6 +979,7 @@ if __name__ == "__main__":if args.device is None:from mineru.utils.config_reader import get_device+args.device = get_device()if args.model is None:diff --git a/mineru/model/mfr/post_process.py b/mineru/model/mfr/post_process.pynew file mode 100644index 00000000..f740419d--- /dev/null+++ b/mineru/model/mfr/post_process.py@@ -0,0 +1,59 @@+# Copyright (c) Opendatalab. All rights reserved.+"""公式识别后处理的公共逻辑。++从 ``pp_formulanet_plus_m/processors.py`` 的 ``UniMERNetDecode`` 类中提取,+供 torch 版和 ONNX 版共同复用,避免代码重复。+"""+from __future__ import annotations++import re++from ftfy import fix_text++from .utils import (+ fix_latex_environments,+ fix_latex_left_right,+ remove_unsupported_commands,+ remove_up_commands,+)++_CHINESE_TEXT_WRAPPING_PATTERN = re.compile(r"\\text\s*{\s*([^}]*?[一-鿿]+[^}]*?)\s*}")+++def remove_chinese_text_wrapping(formula: str) -> str:+ """去掉中文文字外的 ``\\text{}`` 包裹。++ 与 ``UniMERNetDecode.remove_chinese_text_wrapping`` 行为一致。+ """+ replaced = _CHINESE_TEXT_WRAPPING_PATTERN.sub(lambda m: m.group(1), formula)+ return replaced.replace('"', "")+++def fix_latex(text: str) -> str:+ """修复 LaTeX 格式。++ 与 ``UniMERNetDecode.fix_latex`` 行为一致:+ 1. 平衡 ``\\left`` / ``\\right``+ 2. 补全 ``\\begin{}`` / ``\\end{}``+ 3. 移除 ``\\up`` 前缀+ 4. 移除不支持的命令+ """+ text = fix_latex_left_right(text, fix_delimiter=False)+ text = fix_latex_environments(text)+ text = remove_up_commands(text)+ text = remove_unsupported_commands(text)+ return text+++def post_process_formula(text: str) -> str:+ """公式文本的完整后处理流程。++ 与 ``UniMERNetDecode.post_process`` 行为一致:+ 1. 去掉中文 ``\\text{}`` 包裹+ 2. ftfy 修复 Unicode+ 3. 修复 LaTeX 格式+ """+ text = remove_chinese_text_wrapping(text)+ text = fix_text(text)+ text = fix_latex(text)+ return textdiff --git a/mineru/model/mfr/pp_formulanet_plus_m/processors.py b/mineru/model/mfr/pp_formulanet_plus_m/processors.pyindex 452d7049..e574519c 100644--- a/mineru/model/mfr/pp_formulanet_plus_m/processors.py+++ b/mineru/model/mfr/pp_formulanet_plus_m/processors.py@@ -8,12 +8,10 @@ import refrom PIL import Image, ImageOpsfrom typing import List, Optional, Tuple, Union, Dict, Any-from loguru import loggerfrom tokenizers import AddedTokenfrom tokenizers import Tokenizer as TokenizerFast-from mineru.model.mfr.utils import fix_latex_left_right, fix_latex_environments, remove_up_commands, \- remove_unsupported_commands+from mineru.model.mfr.post_process import post_process_formulaclass UniMERNetImgDecode(object):@@ -541,7 +539,7 @@ class UniMERNetDecode(object):generated_text.append(self.tokenizer.decode(tok_id, skip_special_tokens=True))- generated_text = [self.post_process(text) for text in generated_text]+ generated_text = [post_process_formula(text) for text in generated_text]return generated_textdef normalize(self, s: str) -> str:@@ -586,49 +584,6 @@ class UniMERNetDecode(object):breakreturn s.replace("XXXXXXX", " ")- def remove_chinese_text_wrapping(self, formula):- pattern = re.compile(r"\\text\s*{\s*([^}]*?[\u4e00-\u9fff]+[^}]*?)\s*}")-- def replacer(match):- return match.group(1)-- replaced_formula = pattern.sub(replacer, formula)- return replaced_formula.replace('"', "")-- def post_process(self, text: str) -> str:- """Post-processes a string by fixing text and normalizing it.-- Args:- text (str): String to post-process.-- Returns:- str: Post-processed string.- """- from ftfy import fix_text-- text = self.remove_chinese_text_wrapping(text)- text = fix_text(text)- # logger.debug(f"Text after ftfy fix: {text}")- text = self.fix_latex(text)- # logger.debug(f"Text after LaTeX fix: {text}")- return text-- def fix_latex(self, text: str) -> str:- """Fixes LaTeX formatting in a string.-- Args:- text (str): String to fix.-- Returns:- str: Fixed string.- """- text = fix_latex_left_right(text, fix_delimiter=False)- text = fix_latex_environments(text)- text = remove_up_commands(text)- text = remove_unsupported_commands(text)- # text = self.normalize(text)- return text-def __call__(self,preds: np.ndarray,diff --git a/mineru/model/mfr/pp_formulanet_plus_m_onnx.py b/mineru/model/mfr/pp_formulanet_plus_m_onnx.pynew file mode 100644index 00000000..93f099e3--- /dev/null+++ b/mineru/model/mfr/pp_formulanet_plus_m_onnx.py@@ -0,0 +1,319 @@+# Copyright (c) Opendatalab. All rights reserved.+"""ONNX 后端的 PP-FormulaNet-Plus-M 推理封装。++与 ``UnimernetModel``(torch/transformers 后端)公开接口完全一致,+内部用 onnxruntime 推理 RapidDoc 转出的 PP-FormulaNet_plus-M ONNX 模型。++ONNX 模型输出 token IDs(int64),不是 logits——自回归循环已 bake 进计算图,+一次前向推理即可得到完整 LaTeX token 序列。++预处理/后处理参数与 RapidDoc ``inference.yml`` 一致。+"""+from __future__ import annotations++import json+import math+from pathlib import Path+from typing import Any, List, Optional, Tuple++import cv2+import numpy as np+import onnxruntime as ort+import yaml+from loguru import logger+from PIL import Image, ImageOps+from tqdm import tqdm++from .post_process import post_process_formula++__all__ = ["PPFormulaNetPlusMONNX"]++# 预处理常量(与 inference.yml 一致)+_INPUT_SIZE = (384, 384)+_MEAN = np.array([0.7931, 0.7931, 0.7931], dtype=np.float32).reshape(1, 1, 3)+_STD = np.array([0.1738, 0.1738, 0.1738], dtype=np.float32).reshape(1, 1, 3)++# tokenizer 特殊 token IDs+_BOS_TOKEN_ID = 0+_PAD_TOKEN_ID = 1+_EOS_TOKEN_ID = 2+++def _build_providers(device: str) -> list[tuple[str, dict[str, Any]]]:+ norm = (device or "cpu").lower().split(":", 1)[0]+ if norm == "cuda":+ return [+ ("CUDAExecutionProvider", {"device_id": 0, "arena_extend_strategy": "kSameAsRequested"}),+ ("CPUExecutionProvider", {"arena_extend_strategy": "kSameAsRequested"}),+ ]+ return [("CPUExecutionProvider", {"arena_extend_strategy": "kSameAsRequested"})]+++class PPFormulaNetPlusMONNX:+ """PP-FormulaNet-Plus-M 的 ONNX 推理封装。++ 与 ``UnimernetModel`` 的 ``predict`` / ``batch_predict`` 接口完全一致。++ 差异:+ - 构造函数接收 onnx 文件路径 + yml 配置路径,而非 HF 模型目录+ - 不依赖 torch / transformers,仅用 onnxruntime + numpy + cv2+ - 模型输出 token IDs(非 logits),自回归循环已 bake 进 ONNX 图+ """++ def __init__(+ self,+ model_path: str,+ config_path: str,+ device: str = "cpu",+ intra_op_num_threads: int = 0,+ ) -> None:+ self.device = device or "cpu"++ opts = ort.SessionOptions()+ opts.log_severity_level = 3+ opts.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL+ if intra_op_num_threads > 0:+ opts.intra_op_num_threads = intra_op_num_threads+ self.session = ort.InferenceSession(+ model_path,+ sess_options=opts,+ providers=_build_providers(self.device),+ )+ self.input_name = self.session.get_inputs()[0].name++ # 从 yml 加载 tokenizer+ with open(config_path, encoding="utf-8") as f:+ yml = yaml.safe_load(f)+ char_dict = yml["PostProcess"]["character_dict"]++ from tokenizers import Tokenizer as TokenizerFast++ fast_str = json.dumps(char_dict["fast_tokenizer_file"])+ self.tokenizer = TokenizerFast.from_buffer(fast_str.encode("utf-8"))++ logger.debug(+ "PPFormulaNetPlusMONNX loaded: {} (config={})",+ Path(model_path).name,+ Path(config_path).name,+ )++ # ------------------------------------------------------------------+ # bbox 工具(与 UnimernetModel._normalize_bbox 一致)+ # ------------------------------------------------------------------+ @staticmethod+ def _normalize_bbox(bbox: Any, image: np.ndarray) -> Optional[Tuple[int, int, int, int]]:+ if bbox is None:+ return None+ xmin, ymin, xmax, ymax = [float(v) for v in bbox]+ xmin = math.floor(xmin)+ ymin = math.floor(ymin)+ xmax = math.ceil(xmax)+ ymax = math.ceil(ymax)+ height, width = image.shape[:2]+ xmin = max(0, min(width, xmin))+ xmax = max(0, min(width, xmax))+ ymin = max(0, min(height, ymin))+ ymax = max(0, min(height, ymax))+ if xmax <= xmin or ymax <= ymin:+ return None+ return xmin, ymin, xmax, ymax++ @staticmethod+ def _item_to_bbox(item: dict, image: np.ndarray) -> Optional[Tuple[int, int, int, int]]:+ return PPFormulaNetPlusMONNX._normalize_bbox(item.get("bbox"), image)++ def _build_formula_items(+ self, mfd_res: list, image: np.ndarray, interline_enable: bool = True+ ) -> Tuple[List[dict], List[Tuple[dict, Tuple[int, int, int, int]]]]:+ formula_list = []+ crop_targets = []++ for item in mfd_res or []:+ if not isinstance(item, dict):+ continue+ label = item.get("label")+ if label not in ["inline_formula", "display_formula"]:+ continue+ if not interline_enable and label == "display_formula":+ continue++ new_item = dict(item)+ new_item.setdefault("latex", "")+ formula_list.append(new_item)++ bbox = self._item_to_bbox(new_item, image)+ if bbox is not None:+ crop_targets.append((new_item, bbox))++ return formula_list, crop_targets++ # ------------------------------------------------------------------+ # 预处理(与 RapidDoc PPPreProcess 一致)+ # ------------------------------------------------------------------+ @staticmethod+ def _crop_margin(pil_img: Image.Image) -> Image.Image:+ data = np.array(pil_img.convert("L"))+ max_val, min_val = data.max(), data.min()+ if max_val == min_val:+ return pil_img+ data = (data - min_val) / (max_val - min_val) * 255+ gray = 255 * (data < 200).astype(np.uint8)+ coords = cv2.findNonZero(gray)+ if coords is None:+ return pil_img+ a, b, w, h = cv2.boundingRect(coords)+ return pil_img.crop((a, b, w + a, h + b))++ @staticmethod+ def _img_decode(img: np.ndarray) -> Optional[np.ndarray]:+ pil = Image.fromarray(img).convert("RGB")+ pil = PPFormulaNetPlusMONNX._crop_margin(pil)+ if pil.height == 0 or pil.width == 0:+ return None++ # resize: shortest edge to min(input_size), thumbnail to max+ size = min(_INPUT_SIZE)+ if pil.height <= pil.width:+ new_w = int(size * pil.width / pil.height)+ pil = pil.resize((new_w, size), resample=Image.BILINEAR)+ else:+ new_h = int(size * pil.height / pil.width)+ pil = pil.resize((size, new_h), resample=Image.BILINEAR)+ pil.thumbnail((_INPUT_SIZE[1], _INPUT_SIZE[0]))++ delta_w = _INPUT_SIZE[1] - pil.width+ delta_h = _INPUT_SIZE[0] - pil.height+ padding = (delta_w // 2, delta_h // 2, delta_w - delta_w // 2, delta_h - delta_h // 2)+ return np.array(ImageOps.expand(pil, padding))++ @staticmethod+ def _transform(img: np.ndarray) -> np.ndarray:+ img = (img.astype(np.float32) / 255.0 - _MEAN) / _STD+ gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)+ squeezed = np.squeeze(gray)+ return cv2.merge([squeezed, squeezed, squeezed])++ @staticmethod+ def _format_image(img: np.ndarray) -> np.ndarray:+ im_h, im_w = img.shape[:2]+ divide_h = math.ceil(im_h / 16) * 16+ divide_w = math.ceil(im_w / 16) * 16+ img = img[:, :, 0]+ img = np.pad(img, ((0, divide_h - im_h), (0, divide_w - im_w)), constant_values=(1, 1))+ img = img[:, :, np.newaxis].transpose(2, 0, 1)+ return img[np.newaxis, :]++ @classmethod+ def _preprocess(cls, img: np.ndarray) -> Optional[np.ndarray]:+ decoded = cls._img_decode(img)+ if decoded is None:+ return None+ return cls._format_image(cls._transform(decoded))++ # ------------------------------------------------------------------+ # 后处理(tokenizer decode)+ # ------------------------------------------------------------------+ def _decode_tokens(self, token_ids: np.ndarray) -> str:+ if token_ids.ndim == 2:+ ids = [int(x) for x in token_ids[0].tolist()]+ else:+ ids = [int(x) for x in token_ids.tolist()]++ # 截断到 eos token+ for i, tid in enumerate(ids):+ if tid == _EOS_TOKEN_ID:+ ids = ids[: i + 1]+ break++ raw_text = self.tokenizer.decode(ids, skip_special_tokens=True)+ return post_process_formula(raw_text)++ # ------------------------------------------------------------------+ # 推理+ # ------------------------------------------------------------------+ def _infer_batch(self, crops: List[np.ndarray]) -> List[str]:+ """对一批裁剪图做推理,返回 LaTeX 字符串列表。"""+ if not crops:+ return []++ results: List[str] = [""] * len(crops)+ valid_indices: List[int] = []+ valid_inputs: List[np.ndarray] = []++ for i, crop in enumerate(crops):+ inp = self._preprocess(crop)+ if inp is not None:+ valid_indices.append(i)+ valid_inputs.append(inp)++ if not valid_inputs:+ return results++ with tqdm(total=len(valid_inputs), desc="MFR Predict") as pbar:+ for i, inp in enumerate(valid_inputs):+ preds = self.session.run(None, {self.input_name: inp.astype(np.float32)})[0]+ latex = self._decode_tokens(preds)+ results[valid_indices[i]] = latex+ pbar.update(1)++ return results++ # ------------------------------------------------------------------+ # 公开接口(与 UnimernetModel 一致)+ # ------------------------------------------------------------------+ def predict(+ self,+ mfd_res: list,+ image: np.ndarray,+ 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,+ ) -> 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: List[List[dict]] = []+ all_crops: List[np.ndarray] = []+ crop_to_formula: List[Tuple[int, int]] = [] # (page_idx, formula_idx_in_page)++ for page_idx, (mfd_res, image) in enumerate(zip(images_mfd_res, images)):+ formula_list, crop_targets = self._build_formula_items(+ mfd_res,+ image,+ interline_enable=interline_enable,+ )++ for formula_idx, (formula_item, (xmin, ymin, xmax, ymax)) in enumerate(crop_targets):+ bbox_img = image[ymin:ymax, xmin:xmax]+ all_crops.append(bbox_img)+ crop_to_formula.append((page_idx, len(images_formula_list), formula_idx))++ images_formula_list.append(formula_list)++ if not all_crops:+ return images_formula_list++ # 批量推理+ latex_results = self._infer_batch(all_crops)++ # 回填 latex+ for (page_idx, _, formula_idx), latex in zip(crop_to_formula, latex_results):+ images_formula_list[page_idx][formula_idx]["latex"] = latex++ return images_formula_listdiff --git a/mineru/model/ocr/pp_ocr_v6_onnx.py b/mineru/model/ocr/pp_ocr_v6_onnx.pynew file mode 100644index 00000000..f1e0fbd6--- /dev/null+++ b/mineru/model/ocr/pp_ocr_v6_onnx.py@@ -0,0 +1,671 @@+# Copyright (c) Opendatalab. All rights reserved.+"""ONNX 后端的 PP-OCRv6 推理封装。++与 ``PytorchPaddleOCR``(torch 后端)公开接口一致,+内部用 onnxruntime 推理 PaddlePaddle 官方发布的 PP-OCRv6 ONNX 模型。++限制:+- 仅支持 ch 语系(中英日 + 拉丁系 50 语言),不支持多语种切换+- 不支持 seal 模式+- 不支持角度分类(use_angle_cls)++预处理/后处理参数与 PaddlePaddle 官方 ``inference.yml`` 一似。+"""+from __future__ import annotations++import copy+import math+import time+import warnings+from pathlib import Path+from typing import Any, List, Optional, Tuple, Union++import cv2+import numpy as np+import onnxruntime as ort+import pyclipper+from loguru import logger+from shapely.geometry import Polygon+from tqdm import tqdm++from ...utils.ocr_utils import (+ check_img,+ get_rotate_crop_image_for_text_rec,+ merge_det_boxes,+ preprocess_image,+ sorted_boxes,+ update_det_boxes,+)++__all__ = ["PPOCRv6ONNX"]+++# ------------------------------------------------------------------+# 共享工具+# ------------------------------------------------------------------+def _build_providers(device: str) -> list[tuple[str, dict[str, Any]]]:+ norm = (device or "cpu").lower().split(":", 1)[0]+ if norm == "cuda":+ return [+ ("CUDAExecutionProvider", {"device_id": 0, "arena_extend_strategy": "kSameAsRequested"}),+ ("CPUExecutionProvider", {"arena_extend_strategy": "kSameAsRequested"}),+ ]+ return [("CPUExecutionProvider", {"arena_extend_strategy": "kSameAsRequested"})]+++def _load_character_dict(dict_path: str) -> List[str]:+ """加载字符表,支持 txt 文件或 inference.yml 格式。"""+ if dict_path.endswith(".yml") or dict_path.endswith(".yaml"):+ import yaml++ with open(dict_path, encoding="utf-8") as f:+ yml = yaml.safe_load(f)+ chars = yml.get("PostProcess", {}).get("character_dict", [])+ if not isinstance(chars, list):+ raise ValueError(f"character_dict in {dict_path} is not a list")+ return chars+ # txt 文件:每行一个字符+ return [+ line.decode("utf-8").strip("\n").strip("\r\n")+ for line in Path(dict_path).read_bytes().splitlines()+ ]+++def _make_session(model_path: str, device: str, intra_op_num_threads: int = 0) -> ort.InferenceSession:+ opts = ort.SessionOptions()+ opts.log_severity_level = 3+ opts.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL+ if intra_op_num_threads > 0:+ opts.intra_op_num_threads = intra_op_num_threads+ return ort.InferenceSession(+ model_path,+ sess_options=opts,+ providers=_build_providers(device),+ )+++# ------------------------------------------------------------------+# 文本检测器(det)+# ------------------------------------------------------------------+class TextDetectorONNX:+ """PP-OCRv6 det 的 ONNX 推理封装。++ 预处理: DetResize (limit_side_len=960, limit_type='max') + Normalize (ImageNet) + ToCHW+ 后处理: DBPostProcess (thresh/box_thresh/unclip_ratio) + filter+ """++ def __init__(+ self,+ model_path: str,+ device: str = "cpu",+ limit_side_len: int = 960,+ limit_type: str = "max",+ max_side_limit: int = 4000,+ thresh: float = 0.3,+ box_thresh: float = 0.5,+ unclip_ratio: float = 1.5,+ max_candidates: int = 1000,+ use_dilation: bool = True,+ intra_op_num_threads: int = 0,+ ) -> None:+ self.session = _make_session(model_path, device, intra_op_num_threads)+ self.input_name = self.session.get_inputs()[0].name++ self.limit_side_len = limit_side_len+ self.limit_type = limit_type+ self.max_side_limit = max_side_limit+ self.thresh = thresh+ self.box_thresh = box_thresh+ self.unclip_ratio = unclip_ratio+ self.max_candidates = max_candidates+ self.min_size = 3+ self.score_mode = "fast"+ self.use_dilation = use_dilation+ self.dilation_kernel = np.array([[1, 1], [1, 1]]) if use_dilation else None++ # ---- 预处理 ----+ def _resize_image(self, img: np.ndarray) -> Tuple[Optional[np.ndarray], Optional[Tuple[float, float]]]:+ """与 DetResizeForTest.resize_image_type0 一致。"""+ h, w = img.shape[:2]++ if self.limit_type == "max":+ if max(h, w) > self.limit_side_len:+ ratio = float(self.limit_side_len) / max(h, w)+ else:+ ratio = 1.0+ elif self.limit_type == "min":+ if min(h, w) < self.limit_side_len:+ ratio = float(self.limit_side_len) / min(h, w)+ else:+ ratio = 1.0+ else:+ ratio = 1.0++ resize_h = int(h * ratio)+ resize_w = int(w * ratio)++ if max(resize_h, resize_w) > self.max_side_limit:+ ratio = float(self.max_side_limit) / max(resize_h, resize_w)+ resize_h = int(resize_h * ratio)+ resize_w = int(resize_w * ratio)++ resize_h = max(int(round(resize_h / 32) * 32), 32)+ resize_w = max(int(round(resize_w / 32) * 32), 32)++ if resize_w <= 0 or resize_h <= 0:+ return None, None++ resized = cv2.resize(img, (resize_w, resize_h))+ ratio_h = resize_h / float(h)+ ratio_w = resize_w / float(w)+ return resized, (ratio_h, ratio_w)++ def _preprocess(self, img: np.ndarray) -> Optional[Tuple[np.ndarray, np.ndarray]]:+ """返回 (chw_float32, shape_list) 或 None。"""+ resized, ratios = self._resize_image(img)+ if resized is None:+ return None++ mean = np.array([0.485, 0.456, 0.406], dtype=np.float32)+ std = np.array([0.229, 0.224, 0.225], dtype=np.float32)+ norm = (resized.astype(np.float32) / 255.0 - mean) / std+ chw = norm.transpose(2, 0, 1)[np.newaxis, ...].astype(np.float32)++ src_h, src_w = img.shape[:2]+ ratio_h, ratio_w = ratios+ shape_list = np.array([[src_h, src_w, ratio_h, ratio_w]], dtype=np.float32)+ return chw, shape_list++ # ---- 后处理(DBPostProcess)----+ @staticmethod+ def _get_mini_boxes(contour: np.ndarray) -> Tuple[np.ndarray, float]:+ rect = cv2.minAreaRect(contour)+ points = sorted(cv2.boxPoints(rect), key=lambda x: x[0])+ idx_1, idx_4 = (0, 1) if points[1][1] > points[0][1] else (1, 0)+ idx_2, idx_3 = (2, 3) if points[3][1] > points[2][1] else (3, 2)+ box = np.array([points[idx_1], points[idx_2], points[idx_3], points[idx_4]])+ return box, min(rect[1])++ @staticmethod+ def _box_score_fast(bitmap: np.ndarray, box: np.ndarray) -> float:+ h, w = bitmap.shape[:2]+ xmin = int(np.clip(np.floor(box[:, 0].min()), 0, w - 1))+ xmax = int(np.clip(np.ceil(box[:, 0].max()), 0, w - 1))+ ymin = int(np.clip(np.floor(box[:, 1].min()), 0, h - 1))+ ymax = int(np.clip(np.ceil(box[:, 1].max()), 0, h - 1))+ mask = np.zeros((ymax - ymin + 1, xmax - xmin + 1), dtype=np.uint8)+ b = box.copy()+ b[:, 0] -= xmin+ b[:, 1] -= ymin+ cv2.fillPoly(mask, b.reshape(1, -1, 2).astype(np.int32), 1)+ return float(cv2.mean(bitmap[ymin : ymax + 1, xmin : xmax + 1], mask)[0])++ def _unclip(self, box: np.ndarray) -> np.ndarray:+ poly = Polygon(box)+ if not poly.is_valid or poly.area == 0:+ return box+ distance = poly.area * self.unclip_ratio / poly.length+ offset = pyclipper.PyclipperOffset()+ offset.AddPath(box.tolist(), pyclipper.JT_ROUND, pyclipper.ET_CLOSEDPOLYGON)+ expanded = np.array(offset.Execute(distance))+ return expanded++ def _boxes_from_bitmap(+ self, pred: np.ndarray, bitmap: np.ndarray, dest_width: int, dest_height: int+ ) -> Tuple[np.ndarray, List[float]]:+ height, width = bitmap.shape+ outs = cv2.findContours((bitmap * 255).astype(np.uint8), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)+ contours = outs[0] if len(outs) == 2 else outs[1]+ contours = contours[: self.max_candidates]++ boxes: List[np.ndarray] = []+ scores: List[float] = []+ for c in contours:+ points, sside = self._get_mini_boxes(c)+ if sside < self.min_size:+ continue+ score = self._box_score_fast(pred, points)+ if self.box_thresh > score:+ continue+ box = self._unclip(points)+ if len(box) == 0:+ continue+ box, sside = self._get_mini_boxes(box.reshape(-1, 1, 2))+ if sside < self.min_size + 2:+ continue+ box[:, 0] = np.clip(np.round(box[:, 0] / width * dest_width), 0, dest_width)+ box[:, 1] = np.clip(np.round(box[:, 1] / height * dest_height), 0, dest_height)+ boxes.append(box.astype(np.int16))+ scores.append(score)+ if not boxes:+ return np.zeros((0, 4, 2), dtype=np.int16), []+ return np.array(boxes), scores++ def _postprocess(self, pred: np.ndarray, shape_list: np.ndarray) -> np.ndarray:+ """DB 后处理 + 过滤,返回 [N, 4, 2] int16。"""+ seg = pred[0, 0, :, :] # [H, W]+ bitmap = seg > self.thresh+ if self.dilation_kernel is not None:+ bitmap = cv2.dilate(np.array(bitmap).astype(np.uint8), self.dilation_kernel)++ src_h, src_w = int(shape_list[0]), int(shape_list[1])+ boxes, _ = self._boxes_from_bitmap(seg, bitmap, src_w, src_h)+ return self._filter_det_res(boxes, (src_h, src_w))++ @staticmethod+ def _order_points_clockwise(pts: np.ndarray) -> np.ndarray:+ x_sorted = pts[np.argsort(pts[:, 0]), :]+ left_most = x_sorted[:2, :]+ right_most = x_sorted[2:, :]+ left_most = left_most[np.argsort(left_most[:, 1]), :]+ (tl, bl) = left_most+ right_most = right_most[np.argsort(right_most[:, 1]), :]+ (tr, br) = right_most+ return np.array([tl, tr, br, bl], dtype="float32")++ def _filter_det_res(self, dt_boxes: np.ndarray, image_shape: Tuple[int, int]) -> np.ndarray:+ img_height, img_width = image_shape+ dt_boxes_new: List[np.ndarray] = []+ for box in dt_boxes:+ box = self._order_points_clockwise(box)+ box = np.clip(box, 0, [img_width - 1, img_height - 1]).astype(np.int16)+ rect_width = int(np.linalg.norm(box[0] - box[1]))+ rect_height = int(np.linalg.norm(box[0] - box[3]))+ if rect_width <= 3 or rect_height <= 3:+ continue+ dt_boxes_new.append(box)+ if not dt_boxes_new:+ return np.zeros((0, 4, 2), dtype=np.int16)+ return np.array(dt_boxes_new)++ # ---- 推理 ----+ def __call__(self, img: np.ndarray) -> Tuple[Optional[np.ndarray], float]:+ t0 = time.perf_counter()+ preprocessed = self._preprocess(img)+ if preprocessed is None:+ return None, 0.0+ chw, shape_list = preprocessed+ pred = self.session.run(None, {self.input_name: chw})[0]+ dt_boxes = self._postprocess(pred, shape_list[0])+ return dt_boxes, time.perf_counter() - t0++ def batch_predict(+ self,+ img_list: List[np.ndarray],+ max_batch_size: int = 8,+ tqdm_enable: bool = False,+ tqdm_desc: str = "OCR-det Predict",+ tqdm_progress_bar: Optional[Any] = None,+ ) -> List[Tuple[Optional[np.ndarray], float]]:+ if not img_list:+ return []++ pbar = tqdm_progress_bar+ should_close = False+ if pbar is None:+ pbar = tqdm(total=len(img_list), desc=tqdm_desc, disable=not tqdm_enable)+ should_close = True++ results: List[Tuple[Optional[np.ndarray], float]] = [(None, 0.0)] * len(img_list)+ try:+ for i, img in enumerate(img_list):+ dt_boxes, elapse = self(img)+ results[i] = (dt_boxes, elapse)+ pbar.update(1)+ finally:+ if should_close:+ pbar.close()+ return results+++# ------------------------------------------------------------------+# 文本识别器(rec)+# ------------------------------------------------------------------+class TextRecognizerONNX:+ """PP-OCRv6 rec 的 ONNX 推理封装。++ 预处理: RecResizeImg (动态宽度, imgH=48) + Normalize (/127.5 - 1) + padding+ 后处理: CTC 解码+ """++ def __init__(+ self,+ model_path: str,+ dict_path: str,+ device: str = "cpu",+ rec_image_shape: Tuple[int, int, int] = (3, 48, 320),+ rec_batch_num: int = 6,+ drop_score: float = 0.5,+ intra_op_num_threads: int = 0,+ ) -> None:+ self.session = _make_session(model_path, device, intra_op_num_threads)+ self.input_name = self.session.get_inputs()[0].name++ self.img_c, self.img_h, self.img_w = rec_image_shape+ self.rec_batch_num = rec_batch_num+ self.drop_score = drop_score++ # 字符表: ["blank"] + dict_chars + [" "]+ # dict_path 可以是 txt 文件(每行一个字符)或 inference.yml(含 character_dict 列表)+ chars = _load_character_dict(dict_path)+ self.character = ["blank"] + chars + [" "]++ def _resize_norm_img(self, img: np.ndarray, max_wh_ratio: float) -> np.ndarray:+ img_c, img_h, img_w = self.img_c, self.img_h, self.img_w+ max_wh_ratio = max(max_wh_ratio, img_w / img_h)+ img_w = int(img_h * max_wh_ratio)++ h, w = img.shape[:2]+ ratio = w / float(h)+ resized_w = min(img_w, int(max(math.ceil(img_h * ratio), 1)))++ resized = cv2.resize(img, (resized_w, img_h))+ norm = resized.astype(np.float32).transpose(2, 0, 1) / 127.5 - 1.0+ padded = np.zeros((img_c, img_h, img_w), dtype=np.float32)+ padded[:, :, :resized_w] = norm+ return padded++ def _decode(self, pred: np.ndarray) -> Tuple[str, float]:+ """CTC 解码单个 prediction。"""+ idx = pred.argmax(axis=1)+ prob = pred.max(axis=1)+ # collapse consecutive duplicates+ selection = np.ones(len(idx), dtype=bool)+ selection[1:] = idx[1:] != idx[:-1]+ # remove blank (index 0)+ selection &= idx != 0+ chars = [self.character[i] for i in idx[selection]]+ text = "".join(chars)+ conf = float(prob[selection].mean()) if selection.any() else 0.0+ return text, conf++ def __call__(+ self,+ img_list: List[np.ndarray],+ tqdm_enable: bool = False,+ tqdm_desc: str = "OCR-rec Predict",+ tqdm_progress_bar: Optional[Any] = None,+ ) -> Tuple[List[Tuple[str, float]], float]:+ if not img_list:+ return [], 0.0++ t0 = time.perf_counter()+ img_num = len(img_list)++ # 按宽高比排序(加速 batch 内 padding 效率)+ width_list = [img.shape[1] / float(img.shape[0]) for img in img_list]+ indices = np.argsort(np.array(width_list))++ rec_res: List[Tuple[str, float]] = [("", 0.0)] * img_num++ pbar = tqdm_progress_bar+ should_close = False+ if pbar is None:+ pbar = tqdm(total=img_num, desc=tqdm_desc, disable=not tqdm_enable)+ should_close = True++ try:+ batch_num = self.rec_batch_num+ for beg in range(0, img_num, batch_num):+ end = min(img_num, beg + batch_num)+ batch_indices = indices[beg:end]+ max_wh_ratio = width_list[batch_indices[-1]]++ norm_img_batch = []+ for idx in batch_indices:+ norm_img = self._resize_norm_img(img_list[idx], max_wh_ratio)+ norm_img_batch.append(norm_img[np.newaxis, ...])+ batch_tensor = np.concatenate(norm_img_batch, axis=0).astype(np.float32)++ preds = self.session.run(None, {self.input_name: batch_tensor})[0]+ # preds shape: [B, T, C]++ for i, idx in enumerate(batch_indices):+ text, conf = self._decode(preds[i])+ rec_res[idx] = (text, conf)+ pbar.update(end - beg)+ finally:+ if should_close:+ pbar.close()++ return rec_res, time.perf_counter() - t0+++# ------------------------------------------------------------------+# 组合类:PPOCRv6ONNX+# ------------------------------------------------------------------+class PPOCRv6ONNX:+ """PP-OCRv6 的 ONNX 推理封装。++ 与 ``PytorchPaddleOCR`` 的 ``ocr()`` 接口兼容。+ 不支持 seal 模式和多语种切换。+ """++ def __init__(+ self,+ det_model_path: str,+ rec_model_path: str,+ dict_path: str,+ device: str = "cpu",+ det_db_box_thresh: float = 0.5,+ det_db_unclip_ratio: float = 1.5,+ enable_merge_det_boxes: bool = True,+ drop_score: float = 0.5,+ rec_batch_num: int = 6,+ intra_op_num_threads: int = 0,+ ) -> None:+ self.text_detector = TextDetectorONNX(+ model_path=det_model_path,+ device=device,+ box_thresh=det_db_box_thresh,+ unclip_ratio=det_db_unclip_ratio,+ intra_op_num_threads=intra_op_num_threads,+ )+ self.text_recognizer = TextRecognizerONNX(+ model_path=rec_model_path,+ dict_path=dict_path,+ device=device,+ rec_batch_num=rec_batch_num,+ drop_score=drop_score,+ intra_op_num_threads=intra_op_num_threads,+ )+ self.drop_score = drop_score+ self.is_seal = False+ self.enable_merge_det_boxes = enable_merge_det_boxes+ self.lang = "ch"++ logger.debug(+ "PPOCRv6ONNX loaded: det={}, rec={}",+ Path(det_model_path).name,+ Path(rec_model_path).name,+ )++ def ocr(+ self,+ img: Union[np.ndarray, List[np.ndarray], str, bytes],+ det: bool = True,+ rec: bool = True,+ mfd_res: Optional[List[dict]] = None,+ tqdm_enable: bool = False,+ tqdm_desc: str = "OCR-rec Predict",+ tqdm_progress_bar: Optional[Any] = None,+ ) -> List[Optional[List]]:+ assert isinstance(img, (np.ndarray, list, str, bytes))+ if isinstance(img, list) and det:+ logger.error("When input a list of images, det must be false")+ return [None]++ img = check_img(img)+ imgs = [img]++ with warnings.catch_warnings():+ warnings.simplefilter("ignore", category=RuntimeWarning)++ if det and rec:+ # 完整 OCR:det + crop + rec+ ocr_res: List[Optional[List]] = []+ for img in imgs:+ img = preprocess_image(img)+ dt_boxes, rec_res = self._det_rec(img, mfd_res)+ if (dt_boxes is None or len(dt_boxes) == 0) and not rec_res:+ ocr_res.append(None)+ continue+ tmp_res = [[box.tolist(), res] for box, res in zip(dt_boxes, rec_res)]+ ocr_res.append(tmp_res)+ return ocr_res++ elif det and not rec:+ # 仅检测+ ocr_res: List[Optional[List]] = []+ for img in imgs:+ img = preprocess_image(img)+ dt_boxes, _elapse = self.text_detector(img)+ if dt_boxes is None:+ ocr_res.append(None)+ continue+ dt_boxes = sorted_boxes(dt_boxes)+ if self.enable_merge_det_boxes:+ dt_boxes = merge_det_boxes(dt_boxes)+ if mfd_res:+ dt_boxes = update_det_boxes(dt_boxes, mfd_res)+ tmp_res = [box.tolist() for box in dt_boxes]+ ocr_res.append(tmp_res)+ return ocr_res++ elif not det and rec:+ # 仅识别+ ocr_res: List[Optional[List]] = []+ for img in imgs:+ if not isinstance(img, list):+ img = preprocess_image(img)+ img = [img]+ rec_res, _elapse = self.text_recognizer(+ img,+ tqdm_enable=tqdm_enable,+ tqdm_desc=tqdm_desc,+ tqdm_progress_bar=tqdm_progress_bar,+ )+ ocr_res.append(rec_res)+ return ocr_res++ return [None]++ def _det_rec(+ self, img: np.ndarray, mfd_res: Optional[List[dict]] = None+ ) -> Tuple[np.ndarray, List[Tuple[str, float]]]:+ """det + crop + rec 的完整流程。"""+ ori_im = img+ dt_boxes, _elapse = self.text_detector(img)+ if dt_boxes is None or len(dt_boxes) == 0:+ return np.array([]), []++ dt_boxes = sorted_boxes(dt_boxes)+ if self.enable_merge_det_boxes:+ dt_boxes = merge_det_boxes(dt_boxes)+ if mfd_res:+ dt_boxes = update_det_boxes(dt_boxes, mfd_res)++ img_crop_list: List[np.ndarray] = []+ for bno in range(len(dt_boxes)):+ tmp_box = copy.deepcopy(dt_boxes[bno])+ img_crop = get_rotate_crop_image_for_text_rec(ori_im, tmp_box)+ if img_crop is not None:+ img_crop_list.append(img_crop)++ if not img_crop_list:+ return np.array([]), []++ rec_res, _elapse = self.text_recognizer(img_crop_list)++ filter_boxes, filter_rec_res = [], []+ for box, rec_result in zip(dt_boxes, rec_res):+ _text, score = rec_result+ if score >= self.drop_score:+ filter_boxes.append(box)+ filter_rec_res.append(rec_result)++ if not filter_boxes:+ return np.array([]), []+ return np.array(filter_boxes), filter_rec_res++ def __call__(self, img: np.ndarray, mfd_res: Optional[List[dict]] = None):+ """便捷调用,等价于 ocr(img, det=True, rec=True)。"""+ if img is None:+ return None, None+ boxes, rec_res = self._det_rec(img, mfd_res)+ if len(boxes) == 0:+ return None, None+ return boxes, rec_res+++if __name__ == "__main__":+ import argparse+ import json+ import os++ parser = argparse.ArgumentParser(description="PP-OCRv6 ONNX local inference smoke test")+ parser.add_argument("image", help="Path to an input image.")+ parser.add_argument("--det", default=None, help="Path to det inference.onnx.")+ parser.add_argument("--rec", default=None, help="Path to rec inference.onnx.")+ parser.add_argument("--dict", default=None, help="Path to character dict file.")+ parser.add_argument("--device", default="cpu", help="cpu / cuda.")+ parser.add_argument("--output", default=None, help="Save result JSON to this path.")+ args = parser.parse_args()++ # 默认从 model_registry 获取路径+ if args.det is None or args.rec is None:+ from ...utils.model_registry import PP_OCR_V6_SMALL_DET_ONNX, PP_OCR_V6_SMALL_REC_ONNX++ if args.det is None:+ args.det = str(PP_OCR_V6_SMALL_DET_ONNX.onnx.ensure())+ if args.rec is None:+ args.rec = str(PP_OCR_V6_SMALL_REC_ONNX.onnx.ensure())+ if args.dict is None:+ # rec 的 dict 内嵌在 inference.yml 里,但我们直接用 ModelScope 下载的 dict+ # 从 rec 的 model_registry config path 读取+ from ...utils.model_registry import PP_OCR_V6_SMALL_REC_ONNX++ rec_dir = PP_OCR_V6_SMALL_REC_ONNX.onnx.local_path().parent+ # 尝试从 inference.yml 提取 dict,或使用内置的+ args.dict = str(rec_dir / "inference.yml")++ print(f"det: {args.det}")+ print(f"rec: {args.rec}")+ print(f"dict: {args.dict}")++ # 对于 dict,我们需要从 inference.yml 提取 character_dict+ # 但更简单的方式是直接用 RapidOCR 下载的 dict 文件+ # 这里先用一个 fallback+ if not os.path.exists(args.dict) or args.dict.endswith(".yml"):+ # 尝试使用 rec onnx 内嵌的 dict(从 inference.yml 解析)+ import yaml++ with open(args.dict, encoding="utf-8") as f:+ yml = yaml.safe_load(f)+ chars = yml.get("PostProcess", {}).get("character_dict", [])+ # 写入临时 dict 文件+ tmp_dict = "/tmp/ppocrv6_dict.txt"+ with open(tmp_dict, "w", encoding="utf-8") as f:+ for c in chars:+ f.write(c + "\n")+ args.dict = tmp_dict+ print(f"extracted dict to: {args.dict} ({len(chars)} chars)")++ model = PPOCRv6ONNX(+ det_model_path=args.det,+ rec_model_path=args.rec,+ dict_path=args.dict,+ device=args.device,+ )++ img = cv2.imread(args.image)+ results = model.ocr(img)+ print(f"\ndetected {len(results[0] or [])} text lines")+ for item in results[0] or []:+ box, (text, score) = item+ print(f" conf={score:.2f} {text[:80]}")++ if args.output:+ with open(args.output, "w", encoding="utf-8") as f:+ json.dump(results, f, ensure_ascii=False, indent=2)+ print(f"\nresult saved to {args.output}")diff --git a/mineru/parser/tier.py b/mineru/parser/tier.pyindex 27bc04b9..c59983db 100644--- a/mineru/parser/tier.py+++ b/mineru/parser/tier.py@@ -40,9 +40,6 @@ __all__ = [PARSER_BACKENDS = SUPPORTED_BACKENDS_BASIC_REQUIRED_MODULES = [- "ftfy",- "shapely",- "pyclipper","six","torch","torchvision",@@ -211,6 +208,11 @@ def runtime_options_for_tier(def required_modules_for_tier(tier: DeploymentTier) -> list[str]:if tier not in DEPLOYMENT_TIERS:raise ValueError(f"Unsupported deployment tier '{tier}'. Supported tiers: {', '.join(DEPLOYMENT_TIERS)}")+ from ..utils.config_reader import get_model_stack++ stack = get_model_stack()+ if stack == "light":+ return []if tier == "basic":return list(_BASIC_REQUIRED_MODULES)platform_modules = list(_STANDARD_REQUIRED_MODULES_BY_PLATFORM.get(sys.platform, []))diff --git a/mineru/utils/config_reader.py b/mineru/utils/config_reader.pyindex 3b37668a..6b333f05 100644--- a/mineru/utils/config_reader.py+++ b/mineru/utils/config_reader.py@@ -77,6 +77,23 @@ def get_device() -> str:return "cpu"+def get_model_stack() -> str:+ """返回模型推理技术栈:``"light"`` 或 ``"full"``。++ 优先读取 ``config.model.stack``(支持环境变量 ``MINERU_MODEL_STACK``)。+ 当值为 ``"auto"`` 时,根据 ``get_device()`` 的结果自动选择:+ device 为 ``"cpu"`` 时用 ``"light"``(onnxruntime / llama.cpp),否则用 ``"full"``(PyTorch / transformers)。+ """+ from ..config import config++ stack = config.model.stack+ if stack in ("light", "full"):+ return stack+ # auto: cpu → light, 其他 → full+ device = get_device()+ return "light" if device == "cpu" else "full"++def get_ocr_det_mask_inline_formula_enable(enable: bool) -> bool:enable_env = os.getenv("MINERU_OCR_DET_MASK_INLINE_FORMULA_ENABLE")enable = enable if enable_env is None else enable_env.lower() == "true"diff --git a/mineru/utils/model_utils.py b/mineru/utils/model_utils.pyindex 4d3797eb..90ec5cc6 100644--- a/mineru/utils/model_utils.py+++ b/mineru/utils/model_utils.py@@ -14,8 +14,9 @@ from ..types import BBox, IntBBoxtry:import torchimport torch_npu+ _TORCH_AVAILABLE = Trueexcept ImportError:- pass+ _TORCH_AVAILABLE = FalseTEXT_REGION_LABELS = {"abstract",@@ -193,6 +194,9 @@ def get_res_list_from_layout_res(def clean_memory(device: str = "cuda") -> None:+ if not _TORCH_AVAILABLE:+ gc.collect()+ returnif str(device).startswith("cuda"):if torch.cuda.is_available(): # type: ignoretorch.cuda.empty_cache() # type: ignore@@ -244,6 +248,8 @@ def get_vram(device: str) -> int:# 环境变量未配置或配置错误,根据device自动获取total_memory = 1+ if not _TORCH_AVAILABLE:+ return total_memoryif torch.cuda.is_available() and str(device).startswith("cuda"): # type: ignoretotal_memory = round(torch.cuda.get_device_properties(device).total_memory / (1024**3)) # type: ignore # 将字节转换为 GBelif str(device).startswith("npu"):diff --git a/pyproject.toml b/pyproject.tomlindex e42040a0..c82cd755 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -70,6 +70,9 @@ dependencies = ["rich>=13.0.0","jieba>=0.42.1","onnxruntime>=1.17.0",+ "ftfy>=6.3.1,<7",+ "shapely>=2.0.7,<3",+ "pyclipper>=1.3.0,<2",][project.optional-dependencies]@@ -85,9 +88,6 @@ test = ["tomli; python_version < '3.11'",]basic = [- "ftfy>=6.3.1,<7",- "shapely>=2.0.7,<3",- "pyclipper>=1.3.0,<2","six>=1.17.0,<2","torch>=2.6.0,<3","torchvision",diff --git a/tests/unittest/test_doclib_app_startup.py b/tests/unittest/test_doclib_app_startup.pyindex 6c9e222b..bfa42644 100644--- a/tests/unittest/test_doclib_app_startup.py+++ b/tests/unittest/test_doclib_app_startup.py@@ -72,15 +72,21 @@ def test_basic_extra_includes_preflight_runtime_dependencies() -> None:basic_dependencies = pyproject["project"]["optional-dependencies"]["basic"]dependency_names = {dependency.split(">", 1)[0].split("=", 1)[0].lower() for dependency in basic_dependencies}module_to_distribution = {- "ftfy": "ftfy",- "pyclipper": "pyclipper",- "shapely": "shapely","six": "six","torch": "torch","torchvision": "torchvision","transformers": "transformers",}+ # light backend 跳过所有模块检查,只验证 full backend 的依赖完整性+ import os+ os.environ["MINERU_MODEL_STACK"] = "full"+ import mineru.config as cfg+ import importlib+ importlib.reload(cfg)+ cfg._loaded_config = cfg._load_effective_config()+ cfg.config = cfg._loaded_config.config+missing = [module_namefor module_name in parser_tier.required_modules_for_tier("basic")diff --git a/tests/unittest/test_parser_api_contract.py b/tests/unittest/test_parser_api_contract.pyindex 4a244437..f96a8125 100644--- a/tests/unittest/test_parser_api_contract.py+++ b/tests/unittest/test_parser_api_contract.py@@ -2822,13 +2822,11 @@ def test_api_server_preflights_basic_tier_dependencies(monkeypatch: pytest.Monkereturn object()monkeypatch.setattr(importlib, "import_module", fake_import_module)+ monkeypatch.setenv("MINERU_MODEL_STACK", "full")create_app(upload_dir=str(tmp_path), tier="basic")assert imported_modules == [- "ftfy",- "shapely",- "pyclipper","six","torch","torchvision",@@ -2846,13 +2844,11 @@ def test_api_server_preflights_standard_tier_dependencies_for_platform(monkeypatmonkeypatch.setattr(importlib, "import_module", fake_import_module)monkeypatch.setattr(parser_tier.sys, "platform", "darwin")monkeypatch.setattr(parser_tier.platform, "machine", lambda: "arm64")+ monkeypatch.setenv("MINERU_MODEL_STACK", "full")create_app(upload_dir=str(tmp_path), tier="standard")assert imported_modules == [- "ftfy",- "shapely",- "pyclipper","six","torch","torchvision",@@ -2875,13 +2871,11 @@ def test_api_server_preflights_standard_tier_dependencies_skip_mlx_on_intel_macomonkeypatch.setattr(importlib, "import_module", fake_import_module)monkeypatch.setattr(parser_tier.sys, "platform", "darwin")monkeypatch.setattr(parser_tier.platform, "machine", lambda: "x86_64")+ monkeypatch.setenv("MINERU_MODEL_STACK", "full")create_app(upload_dir=str(tmp_path), tier="standard")assert imported_modules == [- "ftfy",- "shapely",- "pyclipper","six","torch","torchvision",