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 new modules for PDF analysis and document processing, including content cleaning and table merging
myhloli677241e1b398
diff --git a/mineru/backend/analysis/__init__.py b/mineru/backend/analysis/__init__.pynew file mode 100644index 00000000..04cbaa22--- /dev/null+++ b/mineru/backend/analysis/__init__.py@@ -0,0 +1,2 @@+# Copyright (c) Opendatalab. All rights reserved.+"""文档 model-list 生产层。"""diff --git a/mineru/backend/analysis/contracts.py b/mineru/backend/analysis/contracts.pynew file mode 100644index 00000000..263d610f--- /dev/null+++ b/mineru/backend/analysis/contracts.py@@ -0,0 +1,21 @@+# Copyright (c) Opendatalab. All rights reserved.+"""文档分析分支汇合前使用的内部结果契约。"""++from __future__ import annotations++from dataclasses import dataclass+from typing import Any, Literal, TypeAlias++AnalyzeEffort: TypeAlias = Literal["flash", "low", "medium", "high", "xhigh"]+ParseMode: TypeAlias = Literal["auto", "txt", "ocr"]+OfficeSuffix: TypeAlias = Literal["docx", "pptx", "xlsx"]+++@dataclass(slots=True)+class AnalysisResult:+ """封装 model-list 及分析分支最终采用的元数据和计时结果。"""++ model_list: list[list[dict[str, Any]]]+ effort: AnalyzeEffort+ parse_mode: ParseMode+ elapsed: floatdiff --git a/mineru/backend/analysis/office.py b/mineru/backend/analysis/office.pynew file mode 100644index 00000000..4f1de08d--- /dev/null+++ b/mineru/backend/analysis/office.py@@ -0,0 +1,31 @@+# Copyright (c) Opendatalab. All rights reserved.+"""Office 文档 model-list 生产入口。"""++from __future__ import annotations++import time+from io import BytesIO++from mineru.model.flash import DocxModel, PptxModel, XlsxModel++from .contracts import AnalysisResult, OfficeSuffix++_OFFICE_MODEL_MAP = {+ "docx": DocxModel,+ "pptx": PptxModel,+ "xlsx": XlsxModel,+}+++def analyze_office(file_bytes: bytes, file_suffix: OfficeSuffix) -> AnalysisResult:+ """调用对应 Flash Office 模型并精确统计 predict 阶段耗时。"""+ office_model = _OFFICE_MODEL_MAP[file_suffix]()+ infer_started_at = time.perf_counter()+ model_list = office_model.predict(BytesIO(file_bytes))+ infer_elapsed = time.perf_counter() - infer_started_at+ return AnalysisResult(+ model_list=model_list,+ effort="flash",+ parse_mode="txt",+ elapsed=infer_elapsed,+ )diff --git a/mineru/backend/utils/__init__.py b/mineru/backend/analysis/pdf/__init__.pysimilarity index 63%rename from mineru/backend/utils/__init__.pyrename to mineru/backend/analysis/pdf/__init__.pyindex 1e17167c..916f622e 100644--- a/mineru/backend/utils/__init__.py+++ b/mineru/backend/analysis/pdf/__init__.py@@ -1 +1,2 @@# Copyright (c) Opendatalab. All rights reserved.+"""PDF 分析流水线。"""diff --git a/mineru/backend/analysis/pdf/constants.py b/mineru/backend/analysis/pdf/constants.pynew file mode 100644index 00000000..d79712df--- /dev/null+++ b/mineru/backend/analysis/pdf/constants.py@@ -0,0 +1,143 @@+# Copyright (c) Opendatalab. All rights reserved.+"""PDF 分析各领域阶段共享的阈值、类型集合与映射。"""++from __future__ import annotations++import re++from mineru.types import RAW_ALGORITHM, RAW_CAPTION, RAW_FOOTNOTE, RAW_PHONETIC, BlockType++LAYOUT_BASE_BATCH_SIZE = 1+MFR_BASE_BATCH_SIZE = 16+OCR_DET_BASE_BATCH_SIZE = 8+LAYOUT_TITLE_SPLIT_OVERLAP_THRESHOLD = 0.8+IMAGE_BLOCK_CONTAINMENT_THRESHOLD = 0.8+IMAGE_BLOCK_LAYOUT_COVERAGE_THRESHOLD = 0.9+IMAGE_BLOCK_LAYOUT_MIN_VISUAL_COUNT = 2+BATCH_RATIO = 2+TABLE_TEXT_LINE_OVERLAP_THRESHOLD = 0.5+TABLE_TEXT_ORIENTATION_MIN_VALID_LINES = 3+TABLE_TEXT_ORIENTATION_MIN_DOMINANCE_RATIO = 0.6+TABLE_TEXT_ORIENTATION_ANGLES = frozenset({0, 90, 180, 270})+_VLM_UNCLASSIFIED_TITLE_TYPE = "title"++TITLE_BLOCK_TYPES = {+ _VLM_UNCLASSIFIED_TITLE_TYPE,+ BlockType.DOC_TITLE,+ BlockType.PARAGRAPH_TITLE,+}+CODE_CONTENT_BLOCK_TYPES = {BlockType.CODE, RAW_ALGORITHM}+LINE_METADATA_BLOCK_TYPES = {+ BlockType.TEXT,+ BlockType.DOC_TITLE,+ BlockType.PARAGRAPH_TITLE,+ RAW_CAPTION,+ RAW_FOOTNOTE,+}+NATURAL_LANGUAGE_CONTENT_BLOCK_TYPES = {+ BlockType.TEXT,+ BlockType.DOC_TITLE,+ BlockType.PARAGRAPH_TITLE,+ BlockType.ASIDE_TEXT,+ BlockType.HEADER,+ BlockType.FOOTER,+ BlockType.PAGE_NUMBER,+ BlockType.PAGE_FOOTNOTE,+ BlockType.REF_TEXT,+ BlockType.LIST,+ BlockType.INDEX,+ RAW_CAPTION,+ RAW_FOOTNOTE,+}+VLM_VISUAL_ANNOTATION_TYPE_MAP = {+ BlockType.TABLE_CAPTION: RAW_CAPTION,+ BlockType.IMAGE_CAPTION: RAW_CAPTION,+ BlockType.CODE_CAPTION: RAW_CAPTION,+ BlockType.TABLE_FOOTNOTE: RAW_FOOTNOTE,+ BlockType.IMAGE_FOOTNOTE: RAW_FOOTNOTE,+}+VLM_MODEL_LIST_FIELDS = frozenset({"type", "bbox", "content", "angle", "score", "sub_type", "cell_merge"})+MODEL_JSON_VISUAL_BLOCK_TYPES = {+ BlockType.IMAGE,+ BlockType.CHART,+ BlockType.TABLE,+ BlockType.EQUATION,+}+LOCAL_LAYOUT_IMAGE_BLOCK_BODY_TYPES = {BlockType.IMAGE, BlockType.CHART}+LOCAL_LAYOUT_IMAGE_BLOCK_AREA_TYPES = {+ *LOCAL_LAYOUT_IMAGE_BLOCK_BODY_TYPES,+ BlockType.IMAGE_CAPTION,+ RAW_CAPTION,+ BlockType.IMAGE_FOOTNOTE,+ RAW_FOOTNOTE,+}+_INLINE_FORMULA_PATTERN = re.compile(r"\\\((.*?)\\\)")++VLM_LAYOUT_LABEL_MAP = {+ "abstract": BlockType.TEXT,+ "algorithm": BlockType.CODE,+ "aside_text": BlockType.ASIDE_TEXT,+ "chart": BlockType.CHART,+ "content": BlockType.INDEX,+ "display_formula": BlockType.EQUATION,+ "doc_title": BlockType.DOC_TITLE,+ "figure_title": RAW_CAPTION,+ "footer": BlockType.FOOTER,+ "footer_image": BlockType.FOOTER,+ "footnote": BlockType.PAGE_FOOTNOTE,+ "formula_number": BlockType.FORMULA_NUMBER,+ "header": BlockType.HEADER,+ "header_image": BlockType.HEADER,+ "image": BlockType.IMAGE,+ "number": BlockType.PAGE_NUMBER,+ "paragraph_title": BlockType.PARAGRAPH_TITLE,+ "reference_content": BlockType.REF_TEXT,+ "seal": BlockType.IMAGE,+ "table": BlockType.TABLE,+ "text": BlockType.TEXT,+ "vertical_text": BlockType.TEXT,+ "vision_footnote": RAW_FOOTNOTE,+}+PIPELINE_DET_TYPE = {+ BlockType.TEXT,+ BlockType.CODE,+ BlockType.ASIDE_TEXT,+ BlockType.INDEX,+ BlockType.DOC_TITLE,+ RAW_CAPTION,+ BlockType.FOOTER,+ BlockType.PAGE_FOOTNOTE,+ BlockType.HEADER,+ BlockType.PAGE_NUMBER,+ BlockType.PARAGRAPH_TITLE,+ BlockType.REF_TEXT,+ RAW_FOOTNOTE,+}+NOT_EXTRACT_TYPES = {+ BlockType.TEXT,+ _VLM_UNCLASSIFIED_TITLE_TYPE,+ BlockType.DOC_TITLE,+ BlockType.PARAGRAPH_TITLE,+ BlockType.HEADER,+ BlockType.FOOTER,+ BlockType.PAGE_NUMBER,+ BlockType.PAGE_FOOTNOTE,+ BlockType.REF_TEXT,+ BlockType.TABLE_CAPTION,+ BlockType.IMAGE_CAPTION,+ RAW_CAPTION,+ BlockType.TABLE_FOOTNOTE,+ BlockType.IMAGE_FOOTNOTE,+ RAW_FOOTNOTE,+ BlockType.CODE_CAPTION,+ RAW_PHONETIC,+}+VLM_TXT_DET_TYPE = NOT_EXTRACT_TYPES+VLM_OCR_DET_TYPE = {+ BlockType.TEXT,+ BlockType.DOC_TITLE,+ BlockType.PARAGRAPH_TITLE,+ RAW_CAPTION,+ RAW_FOOTNOTE,+}+_LOW_TXT_VISUAL_RUN_ANGLES = (0.0, 90.0, 180.0, 270.0)diff --git a/mineru/backend/analysis/pdf/formulas.py b/mineru/backend/analysis/pdf/formulas.pynew file mode 100644index 00000000..052815dc--- /dev/null+++ b/mineru/backend/analysis/pdf/formulas.py@@ -0,0 +1,236 @@+# Copyright (c) Opendatalab. All rights reserved.+"""PDF 公式识别输入、结果回填和公式编号规范化。"""++from __future__ import annotations++from typing import Any++import cv2+import numpy as np+from PIL import Image++from mineru.backend.local_model_runtime import HybridLocalModelContext+from mineru.utils.bbox_utils import normalize_to_int_bbox+from mineru.utils.ocr_utils import get_rotate_crop_image_for_text_rec++from ....types import BlockType+from mineru.utils.text_utils import full_to_half+from mineru.utils.text_utils import clean_isolated_formula++from .geometry import (+ _bbox_to_pixel_bbox,+ _medium_bbox_to_quad,+ _normalize_layout_bbox_to_unit,+ _normalize_medium_content,+ _normalize_page_size,+)+++def normalize_formula_tag_content(tag_content: str) -> str:+ """归一化公式编号文本,去掉全角字符和包裹括号后用于 \\tag{}。"""+ tag_content = full_to_half(str(tag_content or "").strip())+ if tag_content.startswith("("):+ tag_content = tag_content[1:].strip()+ if tag_content.endswith(")"):+ tag_content = tag_content[:-1].strip()+ return tag_content+++def normalize_formula_content_for_tag(formula_content: str) -> str:+ """归一化待合并编号的公式正文,去掉 VLM/Hybrid 可能携带的展示公式分隔符。"""+ return clean_isolated_formula(str(formula_content or ""))+++def build_tagged_formula_content(formula_content: str, tag_content: str) -> str | None:+ """将公式正文和编号文本合成为带 LaTeX tag 的纯公式内容。"""+ formula_content = normalize_formula_content_for_tag(formula_content)+ tag_content = normalize_formula_tag_content(tag_content)+ if not formula_content or not tag_content:+ return None+ return f"{formula_content}\\tag{{{tag_content}}}"+++def _is_hybrid_equation_block(block: dict[str, Any]) -> bool:+ """判断 raw Hybrid/VLM block 是否表示可合并编号的行间公式。"""+ return str(block.get("type") or "").lower() in {+ BlockType.EQUATION,+ "display_formula",+ }+++def _is_hybrid_formula_number_block(block: dict[str, Any]) -> bool:+ """判断 raw Hybrid/VLM block 是否表示公式编号。"""+ return str(block.get("type") or "").lower() == BlockType.FORMULA_NUMBER+++def _append_hybrid_formula_number_tag(equation_block: dict[str, Any], number_block: dict[str, Any]) -> None:+ """把 raw Hybrid/VLM 公式编号合并到相邻公式 block 的 content/latex 字段。"""+ target_key = "latex" if equation_block.get("latex") else "content"+ tagged_content = build_tagged_formula_content(+ str(equation_block.get(target_key) or ""),+ str(number_block.get("content") or number_block.get("text") or ""),+ )+ if tagged_content:+ equation_block[target_key] = tagged_content+++def optimize_hybrid_formula_number_blocks(page_model_list: list[dict[str, Any]]) -> list[dict[str, Any]]:+ """合并 Hybrid raw model list 中的 formula_number,并返回新的 block 列表。"""+ optimized_blocks: list[dict[str, Any]] = []+ blocks = list(page_model_list)+ for index, block in enumerate(blocks):+ if not _is_hybrid_formula_number_block(block):+ optimized_blocks.append(block)+ continue++ prev_block = blocks[index - 1] if index > 0 else None+ if prev_block and _is_hybrid_equation_block(prev_block):+ _append_hybrid_formula_number_tag(prev_block, block)+ continue++ next_block = blocks[index + 1] if index + 1 < len(blocks) else None+ next_next_block = blocks[index + 2] if index + 2 < len(blocks) else None+ if (+ next_block+ and _is_hybrid_equation_block(next_block)+ and (next_next_block is None or not _is_hybrid_formula_number_block(next_next_block))+ ):+ _append_hybrid_formula_number_tag(next_block, block)+ continue++ fallback_block = dict(block)+ fallback_block["type"] = BlockType.TEXT+ optimized_blocks.append(fallback_block)+ return optimized_blocks+++def _build_formula_inputs(images_layout_res: list[list[dict[str, Any]]]) -> list[list[dict[str, Any]]]:+ """构造完整 MFD/MFR 输入,保留全部行内和行间公式框。"""+ formula_inputs = []+ for layout_res in images_layout_res:+ page_formula_inputs = []+ for res in layout_res:+ label = res.get("label")+ if label not in ["inline_formula", "display_formula"]:+ continue+ bbox = res.get("bbox")+ if bbox is None or len(bbox) != 4:+ continue+ page_formula_inputs.append(+ {+ "label": label,+ "bbox": list(bbox),+ "score": float(res.get("score", 0.0)),+ # layout 只提供公式位置;未运行 MFR 的 high/xhigh OCR 必须保留空 LaTeX。+ "latex": "",+ }+ )+ formula_inputs.append(page_formula_inputs)+ return formula_inputs+++def _split_formula_results(+ images_formula_list: list[list[dict[str, Any]]],+) -> tuple[list[list[dict[str, Any]]], list[list[dict[str, Any]]]]:+ """按原始标签拆分 MFR 结果,避免行间公式进入 inline sidecar。"""+ inline_formula_list = []+ display_formula_list = []+ for page_formula_list in images_formula_list:+ inline_formula_list.append([formula for formula in page_formula_list if formula.get("label") == "inline_formula"])+ display_formula_list.append([formula for formula in page_formula_list if formula.get("label") == "display_formula"])+ return inline_formula_list, display_formula_list+++def _apply_medium_display_formula_results(+ model_list: list[list[dict[str, Any]]],+ display_formula_list: list[list[dict[str, Any]]],+ images_pil_list: list[Image.Image],+) -> None:+ """将 medium 行间公式 LaTeX 按页和 bbox 回填到对应 equation 块。"""+ for page_idx, (page_model_list, page_display_formula_list, page_image) in enumerate(+ zip(model_list, display_formula_list, images_pil_list)+ ):+ page_size = _normalize_page_size(page_image)+ equation_blocks_by_bbox: dict[tuple[float, ...], list[dict[str, Any]]] = {}+ for block in page_model_list:+ if block.get("type") != BlockType.EQUATION:+ continue+ block_bbox = block.get("bbox")+ if block_bbox is None or len(block_bbox) != 4:+ continue+ equation_blocks_by_bbox.setdefault(tuple(float(value) for value in block_bbox), []).append(block)++ for formula in page_display_formula_list:+ normalized_bbox = _normalize_layout_bbox_to_unit(formula.get("bbox"), page_size)+ if normalized_bbox is None:+ continue+ matched_blocks = equation_blocks_by_bbox.get(tuple(normalized_bbox), [])+ if len(matched_blocks) != 1:+ raise ValueError(+ "Hybrid medium display formula must match exactly one equation block: "+ f"page_idx={page_idx}, bbox={normalized_bbox}, matches={len(matched_blocks)}"+ )+ matched_blocks[0]["content"] = formula.get("latex", "")+++def _formula_item_to_pixel_bbox(item: dict[str, Any]) -> list[int] | None:+ """读取公式项的四点 bbox,并转换为后续裁图使用的整数坐标。"""+ bbox = item.get("bbox")+ if bbox is not None and len(bbox) == 4:+ return [int(float(v)) for v in bbox]+ return None+++def _apply_medium_formula_number_ocr(+ local_context: HybridLocalModelContext,+ model_list: list[list[dict[str, Any]]],+ np_images: list[np.ndarray],+) -> None:+ """对 medium formula_number 裁剪图执行 OCR-rec,并把编号文本回填到原始 layout 项。"""+ need_rec_items: list[dict[str, Any]] = []+ formula_number_crops: list[np.ndarray] = []+ for block_list, np_img in zip(model_list, np_images):+ image_h, image_w = np_img.shape[:2]+ bgr_image = cv2.cvtColor(np_img, cv2.COLOR_RGB2BGR)+ for block_item in block_list:+ if block_item.get("type") != BlockType.FORMULA_NUMBER:+ continue++ formula_number_bbox = normalize_to_int_bbox(+ _bbox_to_pixel_bbox(block_item.get("bbox"), (image_w, image_h)),+ image_size=(image_h, image_w),+ )+ if formula_number_bbox is None:+ continue++ # 使用 OCR rec 的标准旋转裁剪逻辑,保证 medium 编号裁图与正文 OCR-rec 输入一致。+ formula_number_crops.append(+ get_rotate_crop_image_for_text_rec(+ bgr_image,+ _medium_bbox_to_quad(formula_number_bbox).copy(),+ )+ )+ need_rec_items.append(block_item)++ if not formula_number_crops:+ return++ ocr_result_list = local_context.ocr_model.ocr(+ formula_number_crops,+ det=False,+ tqdm_enable=True,+ tqdm_desc="OCR-rec",+ )[0]+ if len(ocr_result_list) != len(need_rec_items):+ raise ValueError(+ "Hybrid medium formula number OCR rec result count mismatch: "+ f"ocr_result_list={len(ocr_result_list)}, need_rec_items={len(need_rec_items)}"+ )++ for block_item, ocr_result in zip(need_rec_items, ocr_result_list):+ if not ocr_result or len(ocr_result) < 2:+ continue+ ocr_text, _ = ocr_result+ normalized_text = _normalize_medium_content(ocr_text)+ if normalized_text:+ block_item["content"] = normalized_textdiff --git a/mineru/backend/analysis/pdf/geometry.py b/mineru/backend/analysis/pdf/geometry.pynew file mode 100644index 00000000..91134e27--- /dev/null+++ b/mineru/backend/analysis/pdf/geometry.py@@ -0,0 +1,202 @@+# Copyright (c) Opendatalab. All rights reserved.+"""PDF 页面坐标、方向和裁图使用的无状态几何原语。"""++from __future__ import annotations++import base64+from typing import Any++import cv2+import numpy as np+from loguru import logger++from mineru.types import BBox+from mineru.utils.bbox_utils import normalize_to_int_bbox+++def _normalize_page_size(page_image: Any) -> tuple[int, int]:+ """从PIL或numpy图像中读取页面宽高,供归一化bbox还原为像素bbox。"""+ if hasattr(page_image, "size"):+ return page_image.size++ height, width = page_image.shape[:2]+ return width, height+++def _bbox_to_pixel_bbox(bbox: BBox | None, page_size: tuple[int, int]) -> BBox | None:+ """将归一化或像素bbox统一成像素bbox,异常bbox返回None。"""+ if bbox is None or len(bbox) != 4:+ return None++ try:+ x0, y0, x1, y1 = [float(v) for v in bbox]+ except (TypeError, ValueError):+ return None++ width, height = page_size+ if all(0.0 <= value <= 1.0 for value in [x0, y0, x1, y1]):+ x0, y0, x1, y1 = x0 * width, y0 * height, x1 * width, y1 * height++ left, right = sorted([x0, x1])+ top, bottom = sorted([y0, y1])+ if right <= left or bottom <= top:+ return None+ return (left, top, right, bottom)+++def _normalize_layout_bbox_to_unit(bbox: BBox | None, page_size: tuple[int, int]) -> list[float] | None:+ """将 layout 像素 bbox 归一化为 VLM ContentBlock 需要的 0-1 坐标。"""+ pixel_bbox = _bbox_to_pixel_bbox(bbox, page_size)+ if pixel_bbox is None:+ return None++ page_width, page_height = page_size+ if page_width <= 0 or page_height <= 0:+ return None++ x0, y0, x1, y1 = pixel_bbox+ unit_bbox = [+ round(max(0.0, min(1.0, float(x0) / page_width)), 3),+ round(max(0.0, min(1.0, float(y0) / page_height)), 3),+ round(max(0.0, min(1.0, float(x1) / page_width)), 3),+ round(max(0.0, min(1.0, float(y1) / page_height)), 3),+ ]+ if unit_bbox[2] <= unit_bbox[0] or unit_bbox[3] <= unit_bbox[1]:+ return None+ return unit_bbox+++def _medium_bbox_to_quad(bbox: list[float] | tuple[float, ...]) -> np.ndarray:+ """将普通 bbox 转为表格模型 OCR token 使用的四点框。"""+ x0, y0, x1, y1 = [float(v) for v in bbox]+ return np.asarray([[x0, y0], [x1, y0], [x1, y1], [x0, y1]], dtype=np.float32)+++def _normalize_medium_content(value: Any) -> str:+ """将 medium 本地模型输出的文本字段规范成 Hybrid block 可消费的字符串。"""+ if isinstance(value, list):+ return "\n".join(str(item) for item in value if str(item).strip())+ if isinstance(value, str):+ return value.strip()+ return ""+++def _table_bbox_center(bbox: BBox) -> tuple[float, float]:+ """计算 bbox 中心点,用于判断图片或公式应归属哪个表格。"""+ return (float(bbox[0]) + float(bbox[2])) / 2.0, (float(bbox[1]) + float(bbox[3])) / 2.0+++def _normalize_visual_block_angle(angle: Any) -> int:+ """规范视觉块角度为 0/90/180/270,无法识别的角度按 0 处理。"""+ try:+ normalized_angle = int(float(angle or 0)) % 360+ except (TypeError, ValueError):+ logger.warning(f"Unsupported visual block angle: {angle}, using 0")+ return 0+ if normalized_angle not in {0, 90, 180, 270}:+ logger.warning(f"Unsupported visual block angle: {angle}, using 0")+ return 0+ return normalized_angle+++def _rotate_visual_block_image_to_upright(image: np.ndarray, angle: int) -> np.ndarray:+ """按 layout 视觉块角度把裁图旋转至正向,角度语义与方向分类模型保持一致。"""+ if angle == 270:+ return cv2.rotate(image, cv2.ROTATE_90_CLOCKWISE)+ if angle == 90:+ return cv2.rotate(image, cv2.ROTATE_90_COUNTERCLOCKWISE)+ if angle == 180:+ return cv2.rotate(image, cv2.ROTATE_180)+ return image+++def _rotate_medium_table_bbox(+ bbox: BBox,+ image_width: float,+ image_height: float,+ angle: int,+) -> BBox:+ """把原表格裁图中的 bbox 同步转换到旋转后裁图坐标系。"""+ x0, y0, x1, y1 = [float(value) for value in bbox]+ if angle == 270:+ # 顺时针旋转 90 度后,新 x 轴来自原 y 轴的反方向。+ return (image_height - y1, x0, image_height - y0, x1)+ if angle == 90:+ # 逆时针旋转 90 度后,新 y 轴来自原 x 轴的反方向。+ return (y0, image_width - x1, y1, image_width - x0)+ if angle == 180:+ return (image_width - x1, image_height - y1, image_width - x0, image_height - y0)+ return (x0, y0, x1, y1)+++def _get_medium_table_virtual_image_bbox(+ bbox: BBox,+ image_size: tuple[int, int],+ box_size: float = 10.0,+) -> BBox:+ """在图片中心生成小 OCR token 框,避免图片大框干扰单元格匹配。"""+ image_width, image_height = image_size+ center_x, center_y = _table_bbox_center(bbox)+ half_size = box_size / 2.0+ return (+ max(0.0, center_x - half_size),+ max(0.0, center_y - half_size),+ min(float(image_width), center_x + half_size),+ min(float(image_height), center_y + half_size),+ )+++def _encode_page_crop_as_jpeg_data_uri(+ np_image: np.ndarray,+ page_bbox: BBox,+ angle: int,+) -> str:+ """从页面原图按像素框裁剪,按视觉块方向回正后编码为 JPEG data URI。"""+ image_h, image_w = np_image.shape[:2]+ image_bbox = normalize_to_int_bbox(page_bbox, image_size=(image_h, image_w))+ if image_bbox is None:+ return ""+ x0, y0, x1, y1 = image_bbox+ crop_rgb = np_image[y0:y1, x0:x1].copy()+ if crop_rgb.size == 0:+ return ""++ crop_rgb = _rotate_visual_block_image_to_upright(crop_rgb, angle)+ crop_bgr = cv2.cvtColor(crop_rgb, cv2.COLOR_RGB2BGR)+ success, encoded = cv2.imencode(".jpg", crop_bgr)+ if not success:+ return ""+ return f"data:image/jpeg;base64,{base64.b64encode(encoded.tobytes()).decode('ascii')}"+++def _sidecar_bbox_to_page_bbox(+ bbox: BBox | None,+ page_size: tuple[float, float],+ render_scale: float,+) -> BBox | None:+ """将公式或 OCR sidecar bbox 转为 PDF point 坐标,供原生字符匹配和组行。"""+ if bbox is None or len(bbox) != 4 or render_scale <= 0:+ return None+ try:+ x0, y0, x1, y1 = [float(value) for value in bbox]+ except (TypeError, ValueError):+ return None++ page_width, page_height = page_size+ if page_width <= 0 or page_height <= 0:+ return None+ if all(0.0 <= value <= 1.0 for value in [x0, y0, x1, y1]):+ x0, y0, x1, y1 = x0 * page_width, y0 * page_height, x1 * page_width, y1 * page_height+ else:+ x0, y0, x1, y1 = (+ x0 / render_scale,+ y0 / render_scale,+ x1 / render_scale,+ y1 / render_scale,+ )++ left, right = sorted([max(0.0, min(page_width, x0)), max(0.0, min(page_width, x1))])+ top, bottom = sorted([max(0.0, min(page_height, y0)), max(0.0, min(page_height, y1))])+ if right <= left or bottom <= top:+ return None+ return (left, top, right, bottom)diff --git a/mineru/backend/analysis/pdf/layout.py b/mineru/backend/analysis/pdf/layout.pynew file mode 100644index 00000000..a1f3b182--- /dev/null+++ b/mineru/backend/analysis/pdf/layout.py@@ -0,0 +1,139 @@+# Copyright (c) Opendatalab. All rights reserved.+"""Layout、VLM 块转换和页面坐标归一化。"""++from __future__ import annotations++from collections.abc import Iterable, Mapping+from copy import deepcopy+from typing import Any++import numpy as np+from PIL import Image++from mineru.types import BBox, BlockType+from mineru.utils.bbox_utils import normalize_to_int_bbox+from mineru.utils.pdf_image_tools import get_crop_np_img++from .geometry import _normalize_layout_bbox_to_unit, _normalize_page_size+from .constants import (+ VLM_LAYOUT_LABEL_MAP,+ VLM_MODEL_LIST_FIELDS,+ VLM_VISUAL_ANNOTATION_TYPE_MAP,+)+++def _load_vlm_runtime() -> dict[str, Any]:+ """按需加载 VLM runtime 组件,确保只有 high/extra_high 路径触发 VLM 依赖。"""+ from mineru.model.vlm.runtime import (+ ModelSingleton,+ _get_model_async,+ _maybe_enable_serial_execution,+ aio_predictor_execution_guard,+ predictor_execution_guard,+ )++ return {+ "ModelSingleton": ModelSingleton,+ "_get_model_async": _get_model_async,+ "_maybe_enable_serial_execution": _maybe_enable_serial_execution,+ "aio_predictor_execution_guard": aio_predictor_execution_guard,+ "predictor_execution_guard": predictor_execution_guard,+ }+++def _layout_item_to_content_block(layout_item: dict[str, Any], page_size: tuple[int, int]) -> dict | None:+ """将本地 layout 小模型检测项转换为 mineru-vl-utils 的 ContentBlock。"""+ label = layout_item.get("label") or layout_item.get("type")++ block_type = VLM_LAYOUT_LABEL_MAP.get(str(label))+ if block_type is None:+ return None++ bbox = _normalize_layout_bbox_to_unit(layout_item.get("bbox"), page_size)+ if bbox is None:+ return None++ content_block = {+ "type": block_type,+ "bbox": bbox,+ "angle": layout_item.get("angle", 0),+ }++ if block_type == BlockType.IMAGE and label == "seal":+ content_block["sub_type"] = "seal"++ return content_block+++def _get_crop_table_img(+ np_img: np.ndarray,+ table_res_bbox: BBox,+ scale: float = 1,+) -> np.ndarray:+ """按指定缩放裁剪表格图,保持 medium 表格处理只使用当前文件窗口图像。"""+ bbox = normalize_to_int_bbox([float(v) / float(scale) for v in table_res_bbox])+ if bbox is None:+ return np_img[0:0, 0:0]+ return get_crop_np_img(bbox, np_img, scale=scale)+++def _collect_table_items(+ images_layout_res: list[list[dict[str, Any]]],+ np_images: list[np.ndarray],+) -> list[dict[str, Any]]:+ """收集各页有效表格检测项及其裁图,供方向分类阶段批量处理。"""+ table_items = []+ for page_idx, (layout_res, np_img) in enumerate(zip(images_layout_res, np_images)):+ for table_res in layout_res:+ if table_res.get("label") != "table":+ continue+ table_img = _get_crop_table_img(np_img=np_img, table_res_bbox=table_res["bbox"])+ if table_img.size == 0:+ continue+ table_items.append(+ {+ "table_img": table_img,+ "layout_item": table_res,+ "page_idx": page_idx,+ }+ )+ return table_items+++def _build_vl_style_layout_blocks(+ images_layout_res: list[list[dict[str, Any]]],+ images_pil_list: list[Image.Image],+) -> list[list[Any]]:+ """按页构造 Hybrid high 模式传给 VLM 的外部 layout blocks。"""+ blocks_list: list[list[Any]] = []+ for layout_res, image in zip(images_layout_res, images_pil_list):+ page_size = _normalize_page_size(image)+ page_blocks = []+ for layout_item in layout_res:+ content_block = _layout_item_to_content_block(layout_item, page_size)+ if content_block is not None:+ page_blocks.append(content_block)+ blocks_list.append(page_blocks)+ return blocks_list+++def _convert_vlm_results_to_model_list(+ vlm_results: Iterable[Iterable[Mapping[str, Any]]],+) -> list[list[dict[str, Any]]]:+ """将 VLM 结果投影为允许进入 Analyze 的字段,丢弃未采用的外部属性。"""+ return [+ [+ {field_name: deepcopy(value) for field_name, value in dict(block).items() if field_name in VLM_MODEL_LIST_FIELDS}+ for block in page_blocks+ ]+ for page_blocks in vlm_results+ ]+++def _normalize_xhigh_vlm_blocks(model_list: list[list[dict[str, Any]]]) -> None:+ """归一化 xhigh VLM 的视觉注释类型。"""+ for page_model_list in model_list:+ for block in page_model_list:+ normalized_type = VLM_VISUAL_ANNOTATION_TYPE_MAP.get(block.get("type"))+ if normalized_type is not None:+ block["type"] = normalized_typediff --git a/mineru/backend/analysis/pdf/normalization.py b/mineru/backend/analysis/pdf/normalization.pynew file mode 100644index 00000000..a6742645--- /dev/null+++ b/mineru/backend/analysis/pdf/normalization.py@@ -0,0 +1,150 @@+# Copyright (c) Opendatalab. All rights reserved.+"""标题拆分与 PDF model-list 的最终规范化。"""++from __future__ import annotations++import math+from typing import Any++from mineru.types import BBox, BlockType, RAW_PHONETIC+from mineru.utils.bbox_utils import calculate_overlap_area_2_minbox_area_ratio+from mineru.utils.text_utils import full_to_half_exclude_marks++from .constants import (+ LAYOUT_TITLE_SPLIT_OVERLAP_THRESHOLD,+ LINE_METADATA_BLOCK_TYPES,+ NATURAL_LANGUAGE_CONTENT_BLOCK_TYPES,+ _INLINE_FORMULA_PATTERN,+ _VLM_UNCLASSIFIED_TITLE_TYPE,+)+from .geometry import _bbox_to_pixel_bbox+++def _collect_layout_doc_title_bboxes(layout_res: list[dict[str, Any]], page_size: tuple[int, int]) -> list[BBox]:+ """只收集layout小模型输出的doc_title框,忽略paragraph_title等其他类型。"""+ doc_title_bboxes: list[BBox] = []+ for layout_item in layout_res or []:+ if layout_item.get("label") != BlockType.DOC_TITLE:+ continue+ bbox = _bbox_to_pixel_bbox(layout_item.get("bbox"), page_size)+ if bbox is not None:+ doc_title_bboxes.append(bbox)+ return doc_title_bboxes+++def _has_doc_title_overlap(title_bbox: BBox, doc_title_bboxes: list[BBox], overlap_threshold: float) -> bool:+ """判断VLM标题框是否与任一layout doc_title框达到最小框重叠阈值。"""+ return any(+ calculate_overlap_area_2_minbox_area_ratio(title_bbox, doc_title_bbox) >= overlap_threshold+ for doc_title_bbox in doc_title_bboxes+ )+++def _apply_layout_title_split(+ model_list: list[list[dict[str, Any]]],+ images_layout_res: list[list[dict[str, Any]]],+ page_sizes: list[tuple[int, int]],+ overlap_threshold: float = LAYOUT_TITLE_SPLIT_OVERLAP_THRESHOLD,+) -> None:+ """用layout doc_title框将VLM title拆分为doc_title和paragraph_title。"""+ for page_model_list, layout_res, page_size in zip(model_list, images_layout_res, page_sizes):+ doc_title_bboxes = _collect_layout_doc_title_bboxes(layout_res, page_size)+ for block in page_model_list:+ if block.get("type") != _VLM_UNCLASSIFIED_TITLE_TYPE:+ continue+ title_bbox = _bbox_to_pixel_bbox(block.get("bbox"), page_size)+ if title_bbox is None:+ continue+ if _has_doc_title_overlap(title_bbox, doc_title_bboxes, overlap_threshold):+ block["type"] = BlockType.DOC_TITLE+ else:+ block["type"] = BlockType.PARAGRAPH_TITLE+++def _is_valid_pdf_text_block(block: dict[str, Any]) -> bool:+ """检查 PDF 文本块是否同时具有非空正文和完整合法的归一化行框。"""++ content = block.get("content")+ if not isinstance(content, str) or not content.strip():+ return False++ lines = block.get("lines")+ if not isinstance(lines, list) or not lines:+ return False+ for line in lines:+ if not isinstance(line, dict):+ return False+ bbox = line.get("bbox")+ if not isinstance(bbox, (list, tuple)) or len(bbox) != 4:+ return False+ if any(+ not isinstance(value, (int, float)) or isinstance(value, bool) or not math.isfinite(float(value)) for value in bbox+ ):+ return False+ x0, y0, x1, y1 = [float(value) for value in bbox]+ if not all(0.0 <= value <= 1.0 for value in (x0, y0, x1, y1)) or x1 <= x0 or y1 <= y0:+ return False+ return True+++def _normalize_natural_language_content(content: str) -> str:+ """将自然语言中的全角字母和数字转为半角,同时原样保留行内公式片段。"""+ normalized_parts: list[str] = []+ cursor = 0+ formula_markers = (("\\(", "\\)"), ("<eq>", "</eq>"))++ while cursor < len(content):+ formula_starts = [+ (start, opening, closing) for opening, closing in formula_markers if (start := content.find(opening, cursor)) >= 0+ ]+ if not formula_starts:+ normalized_parts.append(full_to_half_exclude_marks(content[cursor:]))+ break++ formula_start, opening, closing = min(formula_starts, key=lambda item: item[0])+ normalized_parts.append(full_to_half_exclude_marks(content[cursor:formula_start]))+ formula_end = content.find(closing, formula_start + len(opening))+ if formula_end < 0:+ normalized_parts.append(content[formula_start:])+ break++ formula_end += len(closing)+ normalized_parts.append(content[formula_start:formula_end])+ cursor = formula_end++ return "".join(normalized_parts)+++def _normalize_pdf_model_list(model_list: list[list[dict[str, Any]]]) -> None:+ """清理 PDF block 元数据、规范公式,并过滤正文或行框无效的文本块。"""+ for page_idx, page_model_list in enumerate(model_list):+ for block_idx, block in enumerate(page_model_list):+ raw_type = block.get("type")+ if raw_type == RAW_PHONETIC:+ block["type"] = BlockType.TEXT+ elif raw_type == BlockType.EQUATION:+ equation_content = block.get("content")+ if isinstance(equation_content, str):+ if equation_content.startswith("\\["):+ equation_content = equation_content[2:]+ if equation_content.endswith("\\]"):+ equation_content = equation_content[:-2]+ block["content"] = equation_content.strip()+ elif raw_type == _VLM_UNCLASSIFIED_TITLE_TYPE:+ raise ValueError(f"Unclassified PDF title block: page_idx={page_idx}, block_idx={block_idx}")+ block.pop("angle", None)+ block.pop("score", None)+ content = block.get("content")+ if not isinstance(content, str):+ continue+ if block.get("type") in NATURAL_LANGUAGE_CONTENT_BLOCK_TYPES:+ content = _normalize_natural_language_content(content)+ block["content"] = _INLINE_FORMULA_PATTERN.sub(+ lambda match: f"<eq>{match.group(1)}</eq>",+ content,+ )+ page_model_list[:] = [+ block+ for block in page_model_list+ if block.get("type") not in LINE_METADATA_BLOCK_TYPES or _is_valid_pdf_text_block(block)+ ]diff --git a/mineru/backend/analysis/pdf/ocr.py b/mineru/backend/analysis/pdf/ocr.pynew file mode 100644index 00000000..792f4114--- /dev/null+++ b/mineru/backend/analysis/pdf/ocr.py@@ -0,0 +1,329 @@+# Copyright (c) Opendatalab. All rights reserved.+"""OCR 检测、识别、置信度过滤与印章 OCR。"""++from __future__ import annotations++from dataclasses import dataclass+from typing import Any, Literal++import cv2+import numpy as np+from tqdm import tqdm++from mineru.backend.local_model_runtime import HybridLocalModelContext+from mineru.types import BlockType+from mineru.utils.bbox_utils import normalize_to_int_bbox+from mineru.utils.model_utils import crop_img+from mineru.utils.ocr_utils import (+ OcrConfidence,+ get_adjusted_mfdetrec_res,+ get_ocr_result_list,+ mask_formula_regions_for_ocr_det,+ merge_det_boxes,+ sorted_boxes,+ update_det_boxes,+)++from .constants import (+ BATCH_RATIO,+ OCR_DET_BASE_BATCH_SIZE,+ PIPELINE_DET_TYPE,+ VLM_OCR_DET_TYPE,+ VLM_TXT_DET_TYPE,+)+from .geometry import _bbox_to_pixel_bbox, _normalize_medium_content+++@dataclass+class _OcrDetCrop:+ """保存一次 OCR det 裁剪的中间数据。"""++ bgr_image: Any+ useful_list: list[Any]+ adjusted_mfdetrec_res: list[Any]+ page_ocr_res_list: list[dict[str, Any]]+++def _build_ocr_det_type_and_mfr_enable(+ parse_mode: Literal["txt", "ocr"],+ effort: Literal["medium", "high", "xhigh"],+) -> tuple[set[str], bool]:+ """返回 OCR 检测块类型,以及是否需要执行小模型公式识别。"""+ if parse_mode not in ("txt", "ocr"):+ raise ValueError(f"Unsupported parse mode: {parse_mode}")+ if effort not in ("medium", "high", "xhigh"):+ raise ValueError(f"Unsupported analyze effort: {effort}")++ if effort == "medium":+ return PIPELINE_DET_TYPE, True+ if parse_mode == "txt":+ return VLM_TXT_DET_TYPE, True+ return VLM_OCR_DET_TYPE, False+++def _set_temp_pixel_bbox(res: dict[str, Any], pixel_bbox: list[int]) -> None:+ """临时切换为像素 bbox,便于复用已有裁剪逻辑。"""+ res["_normalized_bbox"] = list(res["bbox"])+ res["bbox"] = pixel_bbox+++def _restore_normalized_bbox(res: dict[str, Any]) -> None:+ """恢复归一化 bbox,避免 OCR det 过程污染 Hybrid 输出。"""+ normalized_bbox = res.pop("_normalized_bbox", None)+ if normalized_bbox is not None:+ res["bbox"] = normalized_bbox+++def _collect_ocr_det_crops(+ np_images: list[Any],+ model_list: list[list[dict[str, Any]]],+ mfd_res: list[Any],+ ocr_det_type: set[str],+) -> tuple[list[list[dict[str, Any]]], list[_OcrDetCrop]]:+ """收集 OCR det 需要处理的裁剪图,并为每页预建 sidecar 结果列表。"""+ ocr_res_list: list[list[dict[str, Any]]] = []+ crops: list[_OcrDetCrop] = []++ for np_image, page_mfd_res, page_results in zip(np_images, mfd_res, model_list):+ page_ocr_res_list: list[dict[str, Any]] = []+ ocr_res_list.append(page_ocr_res_list)+ img_height, img_width = np_image.shape[:2]+ for res in page_results:+ if res["type"] not in ocr_det_type:+ continue+ x0 = max(0, int(res["bbox"][0] * img_width))+ y0 = max(0, int(res["bbox"][1] * img_height))+ x1 = min(img_width, int(res["bbox"][2] * img_width))+ y1 = min(img_height, int(res["bbox"][3] * img_height))+ if x1 <= x0 or y1 <= y0:+ continue+ _set_temp_pixel_bbox(res, [x0, y0, x1, y1])+ try:+ new_image, useful_list = crop_img(res, np_image, crop_paste_x=50, crop_paste_y=50)+ finally:+ _restore_normalized_bbox(res)+ adjusted_mfdetrec_res = get_adjusted_mfdetrec_res(page_mfd_res, useful_list)+ bgr_image = cv2.cvtColor(new_image, cv2.COLOR_RGB2BGR) # type: ignore+ bgr_image = mask_formula_regions_for_ocr_det(bgr_image, adjusted_mfdetrec_res)+ crops.append(+ _OcrDetCrop(+ bgr_image=bgr_image,+ useful_list=useful_list,+ adjusted_mfdetrec_res=adjusted_mfdetrec_res,+ page_ocr_res_list=page_ocr_res_list,+ )+ )++ return ocr_res_list, crops+++def _normalize_batch_ocr_det_boxes(dt_boxes: Any, adjusted_mfdetrec_res: list[Any]) -> list[Any]:+ """对 batch OCR det 的检测框排序、合并,并按公式位置修正。"""+ if dt_boxes is None or len(dt_boxes) == 0:+ return []++ dt_boxes_sorted = sorted_boxes(dt_boxes)+ dt_boxes_merged = merge_det_boxes(dt_boxes_sorted) if dt_boxes_sorted else []+ if dt_boxes_merged and adjusted_mfdetrec_res:+ return update_det_boxes(dt_boxes_merged, adjusted_mfdetrec_res)+ return dt_boxes_merged+++def _append_ocr_det_result(+ crop: _OcrDetCrop,+ ocr_res: Any,+ need_rec_img: bool,+) -> None:+ """将 OCR det 原始框转换为 Hybrid ocr_text sidecar 并写回对应页。"""+ if not ocr_res:+ return+ ocr_result_list = get_ocr_result_list(+ ocr_res,+ crop.useful_list,+ need_rec_img,+ crop.bgr_image,+ )+ crop.page_ocr_res_list.extend(ocr_result_list)+++def _ocr_det(+ local_model_context: HybridLocalModelContext,+ np_images: list[np.ndarray],+ model_list: list[list[dict[str, Any]]],+ mfd_res: list[Any],+ need_rec_img: bool,+ ocr_det_type: set[str],+) -> list[list[dict[str, Any]]]:+ """执行 Hybrid OCR det sidecar 生成,按运行时配置选择单图或 batch 模式。"""+ ocr_res_list, crops = _collect_ocr_det_crops(np_images, model_list, mfd_res, ocr_det_type)++ if crops:+ batch_images = [crop.bgr_image for crop in crops]+ det_batch_size = min(len(batch_images), BATCH_RATIO * OCR_DET_BASE_BATCH_SIZE)+ batch_results = local_model_context.ocr_model.text_detector.batch_predict(+ batch_images,+ det_batch_size,+ tqdm_enable=True,+ tqdm_desc="OCR-det",+ )++ for crop, (dt_boxes, _) in zip(crops, batch_results):+ dt_boxes_final = _normalize_batch_ocr_det_boxes(dt_boxes, crop.adjusted_mfdetrec_res)+ if dt_boxes_final:+ ocr_res = [box.tolist() if hasattr(box, "tolist") else box for box in dt_boxes_final]+ _append_ocr_det_result(crop, ocr_res, need_rec_img)+ return ocr_res_list+++def _collect_ocr_rec_inputs(+ ocr_res_list: list[list[dict[str, Any]]],+) -> tuple[list[tuple[list[dict[str, Any]], dict[str, Any]]], list[Any]]:+ """收集需要 OCR rec 的裁剪图,同时从 sidecar 中移除临时图像对象。"""+ need_ocr_list = []+ img_crop_list = []+ for page_ocr_res_list in ocr_res_list:+ for ocr_res in page_ocr_res_list:+ if "np_img" in ocr_res:+ need_ocr_list.append((page_ocr_res_list, ocr_res))+ img_crop_list.append(ocr_res.pop("np_img"))+ return need_ocr_list, img_crop_list+++def _should_remove_low_confidence_ocr_text(ocr_text: str, ocr_score: float, ocr_res: dict[str, Any]) -> bool:+ """判断 OCR rec 结果是否应因低置信或竖排噪声被丢弃。"""+ if ocr_score < OcrConfidence.min_confidence:+ return True++ layout_res_bbox = ocr_res.get("bbox")+ if layout_res_bbox is None and ocr_res.get("poly") is not None:+ layout_res_bbox = [+ ocr_res["poly"][0],+ ocr_res["poly"][1],+ ocr_res["poly"][4],+ ocr_res["poly"][5],+ ]+ if layout_res_bbox is None:+ return True++ layout_res_width = layout_res_bbox[2] - layout_res_bbox[0]+ layout_res_height = layout_res_bbox[3] - layout_res_bbox[1]+ return (+ ocr_text+ in [+ "(204号",+ "(20",+ "(2",+ "(2号",+ "(20号",+ "号",+ "(204",+ "(cid:)",+ "(ci:)",+ "(cd:1)",+ "cd:)",+ "c)",+ "(cd:)",+ "c",+ "id:)",+ ":)",+ "√:)",+ "√i:)",+ "−i:)",+ "−:",+ "i:)",+ ]+ and ocr_score < 0.8+ and layout_res_width < layout_res_height+ )+++def _apply_ocr_rec_results(+ local_model_context: HybridLocalModelContext,+ ocr_res_list: list[list[dict[str, Any]]],+) -> None:+ """执行 OCR rec 并把文本写回 sidecar,结果数量异常时显式报错。"""+ need_ocr_list, img_crop_list = _collect_ocr_rec_inputs(ocr_res_list)+ if not img_crop_list:+ return++ ocr_result_list = local_model_context.ocr_model.ocr(+ img_crop_list,+ det=False,+ tqdm_enable=True,+ )[0]++ if len(ocr_result_list) != len(need_ocr_list):+ raise ValueError(+ f"Hybrid OCR rec result count mismatch: ocr_result_list={len(ocr_result_list)}, need_ocr_list={len(need_ocr_list)}"+ )++ items_to_remove = []+ for index, (page_ocr_res_list, need_ocr_res) in enumerate(need_ocr_list):+ ocr_text, ocr_score = ocr_result_list[index]+ need_ocr_res["text"] = ocr_text+ need_ocr_res["score"] = float(f"{ocr_score:.3f}")+ if _should_remove_low_confidence_ocr_text(ocr_text, ocr_score, need_ocr_res):+ items_to_remove.append((page_ocr_res_list, need_ocr_res))++ for page_ocr_res_list, need_ocr_res in items_to_remove:+ if need_ocr_res in page_ocr_res_list:+ page_ocr_res_list.remove(need_ocr_res)+++def _apply_seal_ocr(+ local_model_context: HybridLocalModelContext,+ model_list: list[list[dict[str, Any]]],+ np_images: list[np.ndarray],+) -> None:+ """对 medium/high 最终 seal block 逐张执行专用 OCR,并将多段文本按行写回 content。"""+ if len(model_list) != len(np_images):+ raise ValueError(f"Hybrid seal OCR page count mismatch: model_list={len(model_list)}, images={len(np_images)}")++ seal_tasks: list[tuple[dict[str, Any], np.ndarray]] = []+ for page_model_list, np_img in zip(model_list, np_images):+ image_h, image_w = np_img.shape[:2]+ for block_item in page_model_list:+ if block_item.get("type") != BlockType.IMAGE or block_item.get("sub_type") != "seal":+ continue++ seal_bbox = normalize_to_int_bbox(+ _bbox_to_pixel_bbox(block_item.get("bbox"), (image_w, image_h)),+ image_size=(image_h, image_w),+ )+ if seal_bbox is None:+ continue++ x0, y0, x1, y1 = seal_bbox+ seal_crop_rgb = np_img[y0:y1, x0:x1]+ if seal_crop_rgb.size == 0:+ continue++ seal_crop_bgr = cv2.cvtColor(seal_crop_rgb, cv2.COLOR_RGB2BGR)+ seal_tasks.append((block_item, seal_crop_bgr))++ if not seal_tasks:+ return++ seal_model = local_model_context.seal_model+ for block_item, seal_crop_bgr in tqdm(+ seal_tasks,+ total=len(seal_tasks),+ desc="OCR-seal",+ ):+ seal_ocr_results = seal_model.ocr(seal_crop_bgr)+ seal_ocr_result = seal_ocr_results[0] if seal_ocr_results else []++ seal_texts = []+ for seal_item in seal_ocr_result or []:+ if not isinstance(seal_item, (list, tuple)) or len(seal_item) != 2:+ continue+ rec_result = seal_item[1]+ if not isinstance(rec_result, (list, tuple)) or not rec_result:+ continue+ seal_text = _normalize_medium_content(rec_result[0])+ if seal_text:+ seal_texts.append(seal_text)++ seal_content = "\n".join(seal_texts)+ if seal_content:+ block_item["content"] = seal_contentdiff --git a/mineru/backend/analysis/pdf/pipeline.py b/mineru/backend/analysis/pdf/pipeline.pynew file mode 100644index 00000000..32c53885--- /dev/null+++ b/mineru/backend/analysis/pdf/pipeline.py@@ -0,0 +1,98 @@+# Copyright (c) Opendatalab. All rights reserved.+"""PDF 分析的文档级生命周期与领域阶段编排。"""++from __future__ import annotations++import os+import time+from typing import Any, Literal++from mineru.backend.analysis.contracts import AnalysisResult+from mineru.backend.local_model_runtime import HybridLocalModelContextSingleton+from mineru.utils.engine_utils import get_vlm_engine+from mineru.utils.model_utils import clean_memory+from mineru.utils.pdf_document import PDFDocument++from .layout import _load_vlm_runtime+from .normalization import _normalize_pdf_model_list+from .window import process_pdf_windows++os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1"++_SUPPORTED_PDF_EFFORTS = {"flash", "low", "medium", "high", "xhigh"}+++def analyze_pdf(+ file_bytes: bytes,+ effort: Literal["flash", "low", "medium", "high", "xhigh"] = "high",+ parse_mode: Literal["auto", "txt", "ocr"] = "auto",+ image_analysis: bool = True,+) -> AnalysisResult:+ """生产 PDF model-list,并返回最终路由元数据和精确推理耗时。"""+ document = PDFDocument(file_bytes)+ document_closed = False+ hybrid_model = None+ model_list: list[list[dict[str, Any]]] = []+ try:+ if parse_mode == "auto":+ parse_mode = document.classify()+ if parse_mode not in ["txt", "ocr"]:+ raise ValueError(f"parse_mode {parse_mode} is not supported")+ if effort not in _SUPPORTED_PDF_EFFORTS:+ raise ValueError(f"Unsupported analyze effort: {effort}")++ # Flash 只处理原生文本,OCR 文档继续复用 Hybrid low 流程。+ if effort == "flash" and parse_mode == "ocr":+ effort = "low"++ flash_txt_mode = effort == "flash" and parse_mode == "txt"+ vlm_predictor = None++ if not flash_txt_mode:+ hybrid_model_singleton = HybridLocalModelContextSingleton()+ hybrid_model = hybrid_model_singleton.get_model()++ if effort in ["high", "xhigh"]:+ vlm_runtime = _load_vlm_runtime()+ vlm_backend = get_vlm_engine(inference_engine="auto", is_async=False)+ vlm_predictor = vlm_runtime["ModelSingleton"]().get_model(+ backend=vlm_backend,+ model_path=None,+ server_url=None,+ )+ vlm_predictor = vlm_runtime["_maybe_enable_serial_execution"](vlm_predictor, vlm_backend)+ else:+ vlm_predictor = None++ infer_started_at = time.perf_counter()+ model_list = process_pdf_windows(+ file_bytes,+ document,+ effort=effort,+ parse_mode=parse_mode, # type: ignore[arg-type]+ image_analysis=image_analysis,+ flash_txt_mode=flash_txt_mode,+ hybrid_model=hybrid_model,+ vlm_predictor=vlm_predictor,+ )++ # 仅 PDF 模型结果需要统一清理块元数据并规范化行内公式。+ _normalize_pdf_model_list(model_list)+ infer_elapsed = time.perf_counter() - infer_started_at++ finally:+ try:+ if not document_closed:+ document.close()+ document_closed = True+ finally:+ # 无论窗口处理是否异常,都释放已初始化的 Hybrid 模型资源。+ if hybrid_model is not None:+ clean_memory(hybrid_model.device)++ return AnalysisResult(+ model_list=model_list,+ effort=effort,+ parse_mode=parse_mode,+ elapsed=infer_elapsed,+ )diff --git a/mineru/backend/analysis/pdf/tables.py b/mineru/backend/analysis/pdf/tables.pynew file mode 100644index 00000000..b7c33a95--- /dev/null+++ b/mineru/backend/analysis/pdf/tables.py@@ -0,0 +1,696 @@+# Copyright (c) Opendatalab. All rights reserved.+"""表格方向检测、Medium/Low 表格识别与文本投影。"""++from __future__ import annotations++import html+import math+from collections import Counter+from typing import Any, Literal++import cv2+import numpy as np+from loguru import logger++from mineru.backend.local_model_runtime import HybridLocalModelContext, run_ocr_inference+from mineru.model.model_types import AtomicModelName+from mineru.types import BBox, BlockType, ContentType+from mineru.utils.bbox_utils import (+ calculate_overlap_area_in_bbox1_area_ratio,+ normalize_to_int_bbox,+)+from mineru.utils.ocr_utils import mask_formula_regions_for_ocr_det+from mineru.utils.pdf_document import PDFPage, get_lines_from_chars+from mineru.utils.spatial_text import project_ocr_table_text, project_pdf_table_text++from .constants import (+ BATCH_RATIO,+ OCR_DET_BASE_BATCH_SIZE,+ TABLE_TEXT_LINE_OVERLAP_THRESHOLD,+ TABLE_TEXT_ORIENTATION_ANGLES,+ TABLE_TEXT_ORIENTATION_MIN_DOMINANCE_RATIO,+ TABLE_TEXT_ORIENTATION_MIN_VALID_LINES,+ _LOW_TXT_VISUAL_RUN_ANGLES,+)+from .geometry import (+ _bbox_to_pixel_bbox,+ _encode_page_crop_as_jpeg_data_uri,+ _get_medium_table_virtual_image_bbox,+ _medium_bbox_to_quad,+ _normalize_medium_content,+ _normalize_page_size,+ _normalize_visual_block_angle,+ _rotate_medium_table_bbox,+ _rotate_visual_block_image_to_upright,+ _sidecar_bbox_to_page_bbox,+ _table_bbox_center,+)+from .text.models import _AnalyzeSpan+from .text.native import __replace_ligatures, __replace_unicode, _is_supported_rotation+++def _apply_table_rotate_labels(+ table_items: list[dict[str, Any]],+ rotate_labels: list[str],+) -> None:+ """按分类输入顺序将表格旋转角写回原始 layout 检测项。"""+ if len(rotate_labels) != len(table_items):+ raise ValueError("Hybrid table orientation result count mismatch")+ for table_item, rotate_label in zip(table_items, rotate_labels):+ table_item["layout_item"]["angle"] = int(rotate_label or "0")+++def _build_pdf_text_visual_run_spans(pdf_page: PDFPage) -> list[_AnalyzeSpan]:+ """将 Low/TXT 原生粗行按 Flash 字符间隙拆成可独立分配的视觉 run。"""++ # 延迟导入避免 Hybrid 模块初始化时提前加载完整 Flash PDF 流水线。+ from mineru.model.flash.native_pdf.native_text import _build_native_line_items++ line_items = _build_native_line_items(+ get_lines_from_chars(pdf_page.get_chars()),+ tuple(float(value) for value in pdf_page.size),+ page_rotation=pdf_page.rotation,+ supported_angles=_LOW_TXT_VISUAL_RUN_ANGLES,+ )+ page_spans: list[_AnalyzeSpan] = []+ for line_item in line_items:+ content = __replace_ligatures(__replace_unicode(line_item.text)).strip()+ if not content:+ continue+ page_spans.append(+ _AnalyzeSpan(+ type=ContentType.TEXT,+ bbox=line_item.bbox,+ content=content,+ score=1.0,+ )+ )+ return page_spans+++def _detect_table_angle_from_pdf_lines(+ pdf_lines: list[dict[str, Any]],+ table_bbox: BBox,+) -> int | None:+ """统计表格框内标准方向文本行,满足强众数门槛时返回表格角度。"""+ angle_counts: Counter[int] = Counter()+ for pdf_line in pdf_lines:+ try:+ raw_bbox = pdf_line.get("bbox")+ line_bbox = getattr(raw_bbox, "bbox", raw_bbox)+ if line_bbox is None or len(line_bbox) != 4:+ continue+ x0, y0, x1, y1 = [float(value) for value in line_bbox]+ if x1 <= x0 or y1 <= y0:+ continue++ line_text = "".join(str(pdf_span.get("text", "") or "") for pdf_span in pdf_line.get("spans", [])).strip()+ if not line_text:+ continue++ rotation = float(pdf_line.get("rotation", 0.0) or 0.0)+ except (AttributeError, TypeError, ValueError):+ continue++ if (+ calculate_overlap_area_in_bbox1_area_ratio(+ (x0, y0, x1, y1),+ table_bbox,+ )+ <= TABLE_TEXT_LINE_OVERLAP_THRESHOLD+ ):+ continue+ if not _is_supported_rotation(rotation):+ continue++ angle = int(round(math.degrees(rotation))) % 360+ if angle in TABLE_TEXT_ORIENTATION_ANGLES:+ angle_counts[angle] += 1++ valid_line_count = sum(angle_counts.values())+ if valid_line_count < TABLE_TEXT_ORIENTATION_MIN_VALID_LINES:+ return None++ max_count = max(angle_counts.values())+ dominant_angles = [angle for angle, count in angle_counts.items() if count == max_count]+ if len(dominant_angles) != 1:+ return None+ if max_count / valid_line_count < TABLE_TEXT_ORIENTATION_MIN_DOMINANCE_RATIO:+ return None+ return dominant_angles[0]+++def _resolve_txt_table_orientations(+ table_items: list[dict[str, Any]],+ pdf_pages: list[PDFPage],+ images_list: list[dict[str, Any]],+) -> list[dict[str, Any]]:+ """优先用原生 PDF 文本行写回表格角度,并返回需要视觉兜底的表格。"""+ fallback_table_items: list[dict[str, Any]] = []+ page_lines_cache: dict[int, list[dict[str, Any]] | None] = {}++ for table_item in table_items:+ page_idx = table_item.get("page_idx")+ if not isinstance(page_idx, int) or page_idx < 0 or page_idx >= len(pdf_pages) or page_idx >= len(images_list):+ fallback_table_items.append(table_item)+ continue++ try:+ pdf_page = pdf_pages[page_idx]+ render_scale = float(images_list[page_idx].get("scale", 0) or 0)+ table_bbox = _sidecar_bbox_to_page_bbox(+ table_item["layout_item"].get("bbox"),+ tuple(float(value) for value in pdf_page.size),+ render_scale,+ )+ except Exception as exc:+ logger.warning(f"Hybrid txt table orientation falls back to visual model: page_idx={page_idx}, error={exc}")+ fallback_table_items.append(table_item)+ continue++ if table_bbox is None:+ fallback_table_items.append(table_item)+ continue++ if page_idx not in page_lines_cache:+ try:+ page_lines_cache[page_idx] = get_lines_from_chars(pdf_page.get_chars())+ except Exception as exc:+ logger.warning(f"Hybrid txt table orientation falls back to visual model: page_idx={page_idx}, error={exc}")+ page_lines_cache[page_idx] = None++ pdf_lines = page_lines_cache[page_idx]+ if pdf_lines is None:+ fallback_table_items.append(table_item)+ continue++ table_angle = _detect_table_angle_from_pdf_lines(pdf_lines, table_bbox)+ if table_angle is None:+ fallback_table_items.append(table_item)+ continue+ table_item["layout_item"]["angle"] = table_angle++ return fallback_table_items+++def _apply_table_orientations(+ table_items: list[dict[str, Any]],+ parse_mode: Literal["txt", "ocr"],+ pdf_pages: list[PDFPage],+ images_list: list[dict[str, Any]],+ hybrid_model: HybridLocalModelContext,+) -> None:+ """按解析模式写回表格角度,文本证据不足时批量调用视觉方向模型。"""+ if parse_mode == "txt":+ fallback_table_items = _resolve_txt_table_orientations(+ table_items,+ pdf_pages,+ images_list,+ )+ elif parse_mode == "ocr":+ fallback_table_items = table_items+ else:+ raise ValueError(f"Unsupported parse mode: {parse_mode}")++ if not fallback_table_items:+ return++ rotate_labels = hybrid_model.table_orientation_cls_model.batch_predict(+ fallback_table_items,+ det_batch_size=BATCH_RATIO * OCR_DET_BASE_BATCH_SIZE,+ tqdm_enable=True,+ )+ _apply_table_rotate_labels(fallback_table_items, rotate_labels)+++def _table_bbox_intersection(bbox1: BBox, bbox2: BBox) -> BBox | None:+ """计算两个 bbox 的有效交集,无重叠时返回 None。"""+ x0 = max(float(bbox1[0]), float(bbox2[0]))+ y0 = max(float(bbox1[1]), float(bbox2[1]))+ x1 = min(float(bbox1[2]), float(bbox2[2]))+ y1 = min(float(bbox1[3]), float(bbox2[3]))+ if x1 <= x0 or y1 <= y0:+ return None+ return (x0, y0, x1, y1)+++def _select_table_owner(+ item_bbox: BBox,+ table_entries: list[dict[str, Any]],+) -> dict[str, Any] | None:+ """为 low/medium 对象匹配所属表格,多表命中时选择交叠面积最大的表格。"""+ center_x, center_y = _table_bbox_center(item_bbox)+ candidates: list[tuple[float, dict[str, Any]]] = []+ for table_entry in table_entries:+ table_bbox = table_entry["table_bbox"]+ if not (+ float(table_bbox[0]) <= center_x <= float(table_bbox[2])+ and float(table_bbox[1]) <= center_y <= float(table_bbox[3])+ ):+ continue+ overlap_bbox = _table_bbox_intersection(item_bbox, table_bbox)+ if overlap_bbox is None:+ continue+ overlap_area = float(overlap_bbox[2] - overlap_bbox[0]) * float(overlap_bbox[3] - overlap_bbox[1])+ candidates.append((overlap_area, table_entry))++ if not candidates:+ return None+ return max(candidates, key=lambda item: item[0])[1]+++def _collect_medium_table_tasks(+ model_list: list[list[dict[str, Any]]],+ inline_formula_list: list[list[dict[str, Any]]],+ np_images: list[np.ndarray],+) -> list[dict[str, Any]]:+ """从当前窗口 model_list 收集表格任务,并提前消费表内图片和行内公式。"""+ table_tasks: list[dict[str, Any]] = []+ for page_idx, (page_model_list, page_inline_formulas, np_image) in enumerate(+ zip(model_list, inline_formula_list, np_images)+ ):+ image_h, image_w = np_image.shape[:2]+ page_size = (image_w, image_h)+ table_entries: list[dict[str, Any]] = []+ for block in page_model_list:+ if block.get("type") != BlockType.TABLE:+ continue+ pixel_bbox = _bbox_to_pixel_bbox(block.get("bbox"), page_size)+ table_bbox = normalize_to_int_bbox(pixel_bbox, image_size=(image_h, image_w))+ if table_bbox is None:+ continue+ x0, y0, x1, y1 = table_bbox+ table_crop = np_image[y0:y1, x0:x1].copy()+ if table_crop.size == 0:+ continue+ table_entries.append(+ {+ "table_block": block,+ "table_bbox": table_bbox,+ "table_crop": table_crop,+ "angle": _normalize_visual_block_angle(block.get("angle", 0)),+ "inline_objects": [],+ }+ )++ if not table_entries:+ continue++ consumed_image_ids: set[int] = set()+ consumed_formula_ids: set[int] = set()+ for block in page_model_list:+ if block.get("type") != BlockType.IMAGE:+ continue+ image_bbox = _bbox_to_pixel_bbox(block.get("bbox"), page_size)+ if image_bbox is None:+ continue+ owner = _select_table_owner(image_bbox, table_entries)+ if owner is None:+ continue+ owner["inline_objects"].append(+ {+ "kind": "image",+ "page_bbox": image_bbox,+ "score": float(block.get("score", 1.0) or 0.0),+ }+ )+ consumed_image_ids.add(id(block))++ for formula in page_inline_formulas:+ latex = _normalize_medium_content(formula.get("latex", ""))+ formula_bbox = _bbox_to_pixel_bbox(formula.get("bbox"), page_size)+ if formula_bbox is None:+ continue+ owner = _select_table_owner(formula_bbox, table_entries)+ if owner is None:+ continue+ owner["inline_objects"].append(+ {+ "kind": "formula",+ "page_bbox": formula_bbox,+ "latex": latex,+ "score": float(formula.get("score", 1.0) or 0.0),+ }+ )+ consumed_formula_ids.add(id(formula))++ # 匹配完成后立即删除原始对象;后续 OCR 或结构识别失败均不回滚。+ page_model_list[:] = [block for block in page_model_list if id(block) not in consumed_image_ids]+ page_inline_formulas[:] = [formula for formula in page_inline_formulas if id(formula) not in consumed_formula_ids]++ for table_entry in table_entries:+ table_bbox = table_entry["table_bbox"]+ table_crop = table_entry["table_crop"]+ angle = table_entry["angle"]+ crop_h, crop_w = table_crop.shape[:2]+ rotated_crop = _rotate_visual_block_image_to_upright(table_crop, angle)+ rotated_h, rotated_w = rotated_crop.shape[:2]+ prepared_objects: list[dict[str, Any]] = []+ for inline_object in table_entry["inline_objects"]:+ overlap_bbox = _table_bbox_intersection(inline_object["page_bbox"], table_bbox)+ if overlap_bbox is None:+ continue+ relative_bbox = (+ float(overlap_bbox[0]) - float(table_bbox[0]),+ float(overlap_bbox[1]) - float(table_bbox[1]),+ float(overlap_bbox[2]) - float(table_bbox[0]),+ float(overlap_bbox[3]) - float(table_bbox[1]),+ )+ rotated_bbox = _rotate_medium_table_bbox(relative_bbox, crop_w, crop_h, angle)+ if inline_object["kind"] == "formula":+ latex = inline_object["latex"]+ content = f"<eq>{html.escape(latex)}</eq>" if latex else ""+ token_bbox = rotated_bbox+ else:+ image_src = _encode_page_crop_as_jpeg_data_uri(np_image, inline_object["page_bbox"], angle)+ content = f'<img src="{image_src}"/>' if image_src else ""+ token_bbox = _get_medium_table_virtual_image_bbox(+ rotated_bbox,+ (rotated_w, rotated_h),+ )+ prepared_objects.append(+ {+ **inline_object,+ "mask_bbox": rotated_bbox,+ "token_bbox": token_bbox,+ "content": content,+ }+ )++ table_tasks.append(+ {+ "page_idx": page_idx,+ "table_block": table_entry["table_block"],+ "table_bbox": table_bbox,+ "angle": angle,+ "table_img": rotated_crop,+ "wired_table_img": rotated_crop,+ "ocr_result": [],+ "table_res": {},+ "inline_objects": prepared_objects,+ }+ )+ return table_tasks+++def _sort_medium_table_ocr_result(ocr_result: list[list[Any]]) -> None:+ """按 token 顶边和左边坐标排序,保证表格 OCR 输入顺序稳定。"""++ def sort_key(item: list[Any]) -> tuple[float, float]:+ """提取四点框的最小 y/x,兼容普通列表和 numpy 数组。"""+ box = np.asarray(item[0], dtype=np.float32).reshape(-1, 2)+ return float(np.min(box[:, 1])), float(np.min(box[:, 0]))++ ocr_result.sort(key=sort_key)+++def _prepare_medium_table_ocr_results(+ local_model_context: HybridLocalModelContext,+ table_tasks: list[dict[str, Any]],+) -> None:+ """遮盖表内图片和公式后逐表执行 OCR,并合并内联对象 token。"""+ table_ocr_model = None+ try:+ table_ocr_model = local_model_context.get_ocr_model(+ det_db_box_thresh=0.5,+ det_db_unclip_ratio=1.6,+ enable_merge_det_boxes=False,+ )+ except Exception as exc:+ logger.warning(f"Hybrid medium table OCR model initialization failed: {exc}")++ for table_task in table_tasks:+ ocr_result: list[list[Any]] = []+ bgr_image = cv2.cvtColor(table_task["table_img"], cv2.COLOR_RGB2BGR)+ mask_boxes = [{"bbox": item["mask_bbox"]} for item in table_task["inline_objects"]]+ masked_image = mask_formula_regions_for_ocr_det(bgr_image, mask_boxes)++ if table_ocr_model is not None:+ try:+ page_ocr_results = run_ocr_inference(table_ocr_model.ocr, masked_image)+ raw_ocr_result = page_ocr_results[0] if page_ocr_results else None+ for raw_item in raw_ocr_result or []:+ if not raw_item or len(raw_item) < 2:+ continue+ box, rec_result = raw_item[0], raw_item[1]+ if not rec_result or len(rec_result) < 2:+ continue+ text, score = rec_result[0], rec_result[1]+ normalized_text = _normalize_medium_content(text)+ if not normalized_text:+ continue+ ocr_result.append(+ [+ np.asarray(box, dtype=np.float32),+ html.escape(normalized_text),+ float(score or 0.0),+ ]+ )+ except Exception as exc:+ logger.warning(f"Hybrid medium table OCR failed: page_idx={table_task['page_idx']}, error={exc}")++ for inline_object in table_task["inline_objects"]:+ if not inline_object["content"]:+ continue+ ocr_result.append(+ [+ _medium_bbox_to_quad(inline_object["token_bbox"]),+ inline_object["content"],+ inline_object["score"],+ ]+ )+ _sort_medium_table_ocr_result(ocr_result)+ table_task["ocr_result"] = ocr_result+++def _trim_medium_table_html(html_code: Any) -> str:+ """从模型输出中截取核心 table HTML;未带外围标签时保留原字符串。"""+ if not isinstance(html_code, str):+ return ""+ stripped_html = html_code.strip()+ lower_html = stripped_html.lower()+ start_index = lower_html.find("<table")+ end_index = lower_html.rfind("</table>")+ if start_index >= 0 and end_index >= start_index:+ return stripped_html[start_index : end_index + len("</table>")]+ return stripped_html+++def _apply_medium_table_recognition(+ local_model_context: HybridLocalModelContext,+ model_list: list[list[dict[str, Any]]],+ inline_formula_list: list[list[dict[str, Any]]],+ np_images: list[np.ndarray],+) -> None:+ """基于 model_list 执行 medium 表格解析,采用分类 batch、无线 batch、有线单表调度。"""+ table_tasks = _collect_medium_table_tasks(model_list, inline_formula_list, np_images)+ if not table_tasks:+ return++ _prepare_medium_table_ocr_results(local_model_context, table_tasks)++ try:+ local_model_context.table_cls_model.batch_predict(table_tasks)+ except Exception as exc:+ # 分类失败不阻断无线模型,未获得分类结果的表格按 wireless-only 处理。+ logger.warning(f"Hybrid medium table classification failed: {exc}")++ try:+ local_model_context.wireless_table_model.batch_predict(table_tasks)+ except Exception as exc:+ logger.warning(f"Hybrid medium wireless table recognition failed: {exc}")++ for table_task in table_tasks:+ cls_label = table_task["table_res"].get("cls_label")+ try:+ cls_score = float(table_task["table_res"].get("cls_score", 0.0) or 0.0)+ except (TypeError, ValueError):+ cls_score = 0.0+ use_wired_model = cls_label == AtomicModelName.WiredTable or (+ cls_label == AtomicModelName.WirelessTable and cls_score < 0.9+ )+ if use_wired_model:+ try:+ wireless_html = table_task["table_res"].get("html", "") or ""+ wired_html = local_model_context.wired_table_model.predict(+ table_task["wired_table_img"],+ table_task["ocr_result"],+ wireless_html,+ )+ if wired_html is not None:+ table_task["table_res"]["html"] = wired_html+ except Exception as exc:+ logger.warning(f"Hybrid medium wired table recognition failed: page_idx={table_task['page_idx']}, error={exc}")++ html_code = _trim_medium_table_html(table_task["table_res"].get("html", ""))+ if html_code:+ table_task["table_block"]["content"] = html_code+++def _remove_low_table_inner_blocks(+ images_list: list[dict[str, Any]],+ model_list: list[list[dict[str, Any]]],+) -> None:+ """按表格中心点归属规则移除 low 表内图片、公式和公式编号块。"""+ inner_block_types = {+ BlockType.IMAGE,+ BlockType.EQUATION,+ BlockType.FORMULA_NUMBER,+ }+ for image_dict, page_model_list in zip(images_list, model_list):+ page_size = _normalize_page_size(image_dict["img_pil"])+ table_entries = []+ for block in page_model_list:+ if block.get("type") != BlockType.TABLE:+ continue+ table_bbox = _bbox_to_pixel_bbox(block.get("bbox"), page_size)+ if table_bbox is not None:+ table_entries.append({"table_bbox": table_bbox})++ if not table_entries:+ continue++ retained_blocks = []+ for block in page_model_list:+ if block.get("type") not in inner_block_types:+ retained_blocks.append(block)+ continue+ block_bbox = _bbox_to_pixel_bbox(block.get("bbox"), page_size)+ if block_bbox is None or _select_table_owner(block_bbox, table_entries) is None:+ retained_blocks.append(block)+ page_model_list[:] = retained_blocks+++def _fill_low_table_contents(+ images_list: list[dict[str, Any]],+ pdf_pages: list[PDFPage],+ model_list: list[list[dict[str, Any]]],+ parse_mode: Literal["txt", "ocr"],+ local_model_context: HybridLocalModelContext,+) -> None:+ """为 low 表格回填空间投影纯文本,单表失败时保留空内容并继续。"""+ table_entries: list[dict[str, Any]] = []+ for page_idx, page_model_list in enumerate(model_list):+ table_idx = 0+ for block in page_model_list:+ if block.get("type") != BlockType.TABLE:+ continue+ block["content"] = ""+ table_entries.append(+ {+ "page_idx": page_idx,+ "table_idx": table_idx,+ "block": block,+ }+ )+ table_idx += 1++ if not table_entries:+ return++ # 表格一旦认领内部对象便立即从 model_list 删除,后续文本回填失败也不恢复。+ _remove_low_table_inner_blocks(images_list, model_list)++ if parse_mode == "txt":+ page_chars_cache: dict[int, list[Any]] = {}+ for table_entry in table_entries:+ page_idx = table_entry["page_idx"]+ table_idx = table_entry["table_idx"]+ table_block = table_entry["block"]+ try:+ pdf_page = pdf_pages[page_idx]+ page_width, page_height = pdf_page.size+ table_bbox = _bbox_to_pixel_bbox(+ table_block.get("bbox"),+ (int(page_width), int(page_height)),+ )+ if table_bbox is None:+ raise ValueError("invalid table bbox")+ if page_idx not in page_chars_cache:+ page_chars_cache[page_idx] = pdf_page.get_chars()+ table_block["content"] = project_pdf_table_text(+ page_chars_cache[page_idx],+ table_bbox,+ table_block.get("angle", 0),+ )+ if not table_block["content"]:+ logger.warning(+ "Hybrid low table text is empty: "+ f"parse_mode={parse_mode}, page_idx={page_idx}, "+ f"table_idx={table_idx}, bbox={table_block.get('bbox')}"+ )+ except Exception as exc:+ logger.warning(+ "Hybrid low table text failed: "+ f"parse_mode={parse_mode}, page_idx={page_idx}, "+ f"table_idx={table_idx}, bbox={table_block.get('bbox')}, error={exc}"+ )+ return++ if parse_mode != "ocr":+ raise ValueError(f"Unsupported parse mode: {parse_mode}")++ try:+ table_ocr_model = local_model_context.get_ocr_model(+ det_db_box_thresh=0.5,+ det_db_unclip_ratio=1.6,+ enable_merge_det_boxes=False,+ )+ except Exception as exc:+ for table_entry in table_entries:+ logger.warning(+ "Hybrid low table text failed: "+ f"parse_mode={parse_mode}, page_idx={table_entry['page_idx']}, "+ f"table_idx={table_entry['table_idx']}, "+ f"bbox={table_entry['block'].get('bbox')}, "+ f"error=OCR model initialization failed: {exc}"+ )+ return++ page_image_cache: dict[int, np.ndarray] = {}+ for table_entry in table_entries:+ page_idx = table_entry["page_idx"]+ table_idx = table_entry["table_idx"]+ table_block = table_entry["block"]+ try:+ if page_idx not in page_image_cache:+ page_image_cache[page_idx] = np.asarray(images_list[page_idx]["img_pil"]).copy()+ np_image = page_image_cache[page_idx]+ image_height, image_width = np_image.shape[:2]+ pixel_bbox = _bbox_to_pixel_bbox(+ table_block.get("bbox"),+ (image_width, image_height),+ )+ table_bbox = normalize_to_int_bbox(+ pixel_bbox,+ image_size=(image_height, image_width),+ )+ if table_bbox is None:+ raise ValueError("invalid table bbox")+ x0, y0, x1, y1 = table_bbox+ table_crop = np_image[y0:y1, x0:x1].copy()+ if table_crop.size == 0:+ raise ValueError("empty table crop")++ angle = _normalize_visual_block_angle(table_block.get("angle", 0))+ rotated_crop = _rotate_visual_block_image_to_upright(table_crop, angle)+ bgr_crop = cv2.cvtColor(rotated_crop, cv2.COLOR_RGB2BGR)+ page_ocr_results = run_ocr_inference(table_ocr_model.ocr, bgr_crop)+ raw_ocr_result = page_ocr_results[0] if page_ocr_results else None+ rotated_height, rotated_width = rotated_crop.shape[:2]+ table_block["content"] = project_ocr_table_text(+ raw_ocr_result,+ (rotated_width, rotated_height),+ )+ if not table_block["content"]:+ logger.warning(+ "Hybrid low table text is empty: "+ f"parse_mode={parse_mode}, page_idx={page_idx}, "+ f"table_idx={table_idx}, bbox={table_block.get('bbox')}"+ )+ except Exception as exc:+ logger.warning(+ "Hybrid low table text failed: "+ f"parse_mode={parse_mode}, page_idx={page_idx}, "+ f"table_idx={table_idx}, bbox={table_block.get('bbox')}, error={exc}"+ )diff --git a/mineru/backend/analysis/pdf/text/__init__.py b/mineru/backend/analysis/pdf/text/__init__.pynew file mode 100644index 00000000..20d5832e--- /dev/null+++ b/mineru/backend/analysis/pdf/text/__init__.py@@ -0,0 +1,2 @@+# Copyright (c) Opendatalab. All rights reserved.+"""PDF 原生文本、OCR Span 和内容重建。"""diff --git a/mineru/backend/analysis/pdf/text/content.py b/mineru/backend/analysis/pdf/text/content.pynew file mode 100644index 00000000..93b96877--- /dev/null+++ b/mineru/backend/analysis/pdf/text/content.py@@ -0,0 +1,386 @@+# Copyright (c) Opendatalab. All rights reserved.+"""文本/公式 Span 构造、组行、post-OCR 与 block content 回填。"""++from __future__ import annotations++from typing import Any, Literal++import numpy as np+from PIL import Image++from mineru.backend.local_model_runtime import HybridLocalModelContext, run_ocr_inference+from mineru.types import BBox, BlockType, ContentType+from mineru.utils.language import detect_lang+from mineru.utils.ocr_utils import OcrConfidence, rotate_vertical_crop_if_needed+from mineru.utils.pdf_document import PDFPage, get_lines_from_chars+from mineru.utils.text_utils import resolve_text_line_boundary++from ..constants import (+ CODE_CONTENT_BLOCK_TYPES,+ LINE_METADATA_BLOCK_TYPES,+ TITLE_BLOCK_TYPES,+)+from ..geometry import _bbox_to_pixel_bbox, _sidecar_bbox_to_page_bbox+from .lines import group_spans_to_lines+from .models import _AnalyzeLine, _AnalyzeSpan+from .native import (+ SpanBlockMatcher,+ __replace_ligatures,+ __replace_unicode,+ _clear_post_ocr_fallback,+ _is_supported_rotation,+ _restore_post_ocr_fallback,+ txt_spans_extract,+)+++def _validate_text_formula_window_inputs(+ images_list: list[dict[str, Any]],+ pdf_pages: list[PDFPage],+ model_list: list[list[dict[str, Any]]],+ images_layout_res: list[list[dict[str, Any]]],+) -> None:+ """校验文本公式处理所需的窗口分页数据,避免 zip 静默截断。"""+ page_counts = {+ "images": len(images_list),+ "pdf_pages": len(pdf_pages),+ "model_list": len(model_list),+ "layout": len(images_layout_res),+ }+ if len(set(page_counts.values())) != 1:+ raise ValueError(f"Hybrid text/formula window page count mismatch: {page_counts}")++ for page_idx, image_dict in enumerate(images_list):+ if image_dict.get("img_pil") is None:+ raise ValueError(f"Hybrid text/formula window image is missing img_pil: page_idx={page_idx}")+ scale = float(image_dict.get("scale", 0) or 0)+ if scale <= 0:+ raise ValueError(f"Hybrid text/formula window image scale must be positive: page_idx={page_idx}")+++def _build_pdf_text_line_spans(pdf_page: PDFPage) -> list[_AnalyzeSpan]:+ """将标准方向的 pdftext line 转为私有 span,并复用现有字符清洗规则。"""+ page_spans: list[_AnalyzeSpan] = []+ for pdf_line in get_lines_from_chars(pdf_page.get_chars()):+ try:+ rotation = float(pdf_line.get("rotation", 0.0) or 0.0)+ except (TypeError, ValueError):+ continue+ if not _is_supported_rotation(rotation):+ continue++ raw_bbox = pdf_line.get("bbox")+ bbox = getattr(raw_bbox, "bbox", raw_bbox)+ try:+ if bbox is None or len(bbox) != 4:+ continue+ x0, y0, x1, y1 = [float(value) for value in bbox]+ except (TypeError, ValueError):+ continue+ if x1 <= x0 or y1 <= y0:+ continue++ content = "".join(str(pdf_span.get("text", "") or "") for pdf_span in pdf_line.get("spans", []))+ content = __replace_unicode(content)+ content = __replace_ligatures(content).strip()+ if not content:+ continue++ page_spans.append(+ _AnalyzeSpan(+ type=ContentType.TEXT,+ bbox=(x0, y0, x1, y1),+ content=content,+ score=1.0,+ )+ )+ return page_spans+++def _build_page_text_formula_spans(+ page_inline_formula_list: list[dict[str, Any]],+ page_ocr_res_list: list[dict[str, Any]],+ page_size: tuple[float, float],+ render_scale: float,+) -> list[_AnalyzeSpan]:+ """将当前页行内公式和 OCR 结果转换为私有 span,供正文与公式共同组行。"""+ page_spans: list[_AnalyzeSpan] = []+ for formula in page_inline_formula_list:+ bbox = _sidecar_bbox_to_page_bbox(formula.get("bbox"), page_size, render_scale)+ if bbox is None:+ continue+ page_spans.append(+ _AnalyzeSpan(+ type=ContentType.INLINE_EQUATION,+ bbox=bbox,+ content=str(formula.get("latex", "") or "").strip(),+ score=float(formula.get("score", 0.0) or 0.0),+ )+ )++ for ocr_res in page_ocr_res_list:+ bbox = _sidecar_bbox_to_page_bbox(ocr_res.get("bbox"), page_size, render_scale)+ if bbox is None:+ continue+ page_spans.append(+ _AnalyzeSpan(+ type=ContentType.TEXT,+ bbox=bbox,+ content=str(ocr_res.get("text", "") or ""),+ score=float(ocr_res.get("score", 0.0) or 0.0),+ )+ )+ return page_spans+++def _fill_native_pdf_text_spans(+ pdf_page: PDFPage,+ page_spans: list[_AnalyzeSpan],+ page_pil_image: Image.Image,+ render_scale: float,+ page_size: tuple[float, float],+) -> list[_AnalyzeSpan]:+ """复用原生 PDF 字符回填逻辑,并为内容不足的 span 准备后置 OCR 裁图。"""+ page_width, page_height = page_size+ virtual_block = (0, 0, page_width, page_height, None, None, None, BlockType.TEXT)+ return txt_spans_extract(+ pdf_page,+ page_spans,+ page_pil_image,+ render_scale,+ [virtual_block],+ [],+ )+++def _group_page_spans_by_block(+ page_model_list: list[dict[str, Any]],+ page_spans: list[_AnalyzeSpan],+ page_size: tuple[float, float],+ target_block_types: set[str],+) -> dict[int, list[_AnalyzeLine]]:+ """按 block 原始顺序消费 span,并使用现有文本修复逻辑形成真实行。"""+ span_matcher = SpanBlockMatcher(page_spans)+ block_lines: dict[int, list[_AnalyzeLine]] = {}+ for block_idx, block_item in enumerate(page_model_list):+ block_type = str(block_item.get("type") or block_item.get("label") or "")+ if block_type not in target_block_types:+ continue+ block_bbox = _bbox_to_pixel_bbox(block_item.get("bbox"), page_size)+ if block_bbox is None:+ block_lines[block_idx] = []+ continue++ block_lines[block_idx] = group_spans_to_lines(span_matcher.collect_for_block(block_bbox))+ return block_lines+++def _apply_window_post_ocr(+ local_model_context: HybridLocalModelContext,+ page_block_lines_list: list[dict[int, list[_AnalyzeLine]]],+) -> None:+ """在当前窗口内识别原生字符不足的 span,保持 finalize 后置 OCR 的回退语义。"""+ need_ocr_spans: list[_AnalyzeSpan] = []+ img_crop_list: list[np.ndarray] = []+ for block_lines in page_block_lines_list:+ for lines in block_lines.values():+ for line in lines:+ for span in line.spans:+ if span.image is None:+ continue+ need_ocr_spans.append(span)+ img_crop_list.append(rotate_vertical_crop_if_needed(span.image))+ span.image = None++ if not img_crop_list:+ return+ ocr_res_list = run_ocr_inference(+ local_model_context.ocr_model.ocr,+ img_crop_list,+ det=False,+ tqdm_enable=True,+ )[0]+ if len(ocr_res_list) != len(need_ocr_spans):+ raise ValueError(+ f"Hybrid post-OCR result count mismatch: ocr_res_list={len(ocr_res_list)}, need_ocr_spans={len(need_ocr_spans)}"+ )++ for span, ocr_res in zip(need_ocr_spans, ocr_res_list):+ ocr_text, ocr_score = ocr_res+ if ocr_score > OcrConfidence.min_confidence:+ span.content = ocr_text+ span.score = float(f"{ocr_score:.3f}")+ _clear_post_ocr_fallback(span)+ elif _restore_post_ocr_fallback(span):+ continue+ else:+ span.content = ""+ span.score = 0.0+++def _line_content_parts(line: _AnalyzeLine) -> list[tuple[str, str]]:+ """提取一行内可输出的文本与行内公式,公式统一包装为反斜杠圆括号格式。"""+ parts: list[tuple[str, str]] = []+ for span in line.spans:+ if span.type == ContentType.TEXT:+ content = str(span.content or "").strip()+ elif span.type == ContentType.INLINE_EQUATION:+ latex = str(span.content or "").strip()+ content = f"\\({latex}\\)" if latex else ""+ else:+ continue+ if content:+ parts.append((span.type, content))+ return parts+++def _lines_to_block_content(lines: list[_AnalyzeLine], block_type: str) -> str:+ """将真实行折叠为统一 block content,保留目录/代码换行并处理自然语言跨行连接。"""+ content_lines = [parts for line in lines if (parts := _line_content_parts(line))]+ if not content_lines:+ return ""++ rendered_lines = [" ".join(content for _, content in parts) for parts in content_lines]+ if block_type == BlockType.INDEX or block_type in CODE_CONTENT_BLOCK_TYPES:+ return "\n".join(rendered_lines).strip()++ text_for_language = "".join(+ content for parts in content_lines for span_type, content in parts if span_type == ContentType.TEXT+ )+ block_language = detect_lang(text_for_language)+ content_parts = [rendered_lines[0]]+ for line_idx in range(1, len(rendered_lines)):+ current_type, current_content = content_lines[line_idx][0]+ next_starts_with_lowercase = current_type == ContentType.TEXT and bool(current_content) and current_content[0].islower()+ content_parts[-1], separator = resolve_text_line_boundary(+ content_parts[-1],+ block_language=block_language,+ next_starts_with_lowercase=next_starts_with_lowercase,+ )+ content_parts.extend([separator, rendered_lines[line_idx]])+ return "".join(content_parts).strip()+++def _build_ocr_det_line_items(lines: list[_AnalyzeLine], page_size: tuple[float, float]) -> list[dict[str, Any]]:+ """将 Analyze 私有行转换为归一化行框。"""+ line_items = []+ for line in lines:+ normalized_bbox = _page_bbox_to_unit_bbox(line.bbox, page_size)+ if normalized_bbox is not None:+ line_items.append({"bbox": normalized_bbox})+ return line_items+++def _apply_block_content_and_line_metadata(+ page_model_list: list[dict[str, Any]],+ block_lines: dict[int, list[_AnalyzeLine]],+ page_size: tuple[float, float],+) -> None:+ """将组行结果回填到 block,并为正文、视觉标题和视觉脚注保存行框。"""+ for block_item in page_model_list:+ block_type = str(block_item.get("type") or block_item.get("label") or "")+ if block_type in LINE_METADATA_BLOCK_TYPES:+ block_item["lines"] = []+ else:+ block_item.pop("lines", None)++ for block_idx, lines in block_lines.items():+ block_item = page_model_list[block_idx]+ block_type = str(block_item.get("type") or block_item.get("label") or "")+ block_content = block_item.get("content")+ has_nonempty_content = bool(block_content.strip()) if isinstance(block_content, str) else bool(block_content)+ if not has_nonempty_content:+ block_item["content"] = _lines_to_block_content(lines, block_type)++ if block_type in LINE_METADATA_BLOCK_TYPES:+ block_item["lines"] = _build_ocr_det_line_items(lines, page_size)+++def _fill_window_block_content_and_lines(+ images_list: list[dict[str, Any]],+ pdf_pages: list[PDFPage],+ model_list: list[list[dict[str, Any]]],+ inline_formula_list: list[list[dict[str, Any]]],+ ocr_res_list: list[list[dict[str, Any]]],+ parse_mode: Literal["txt", "ocr"],+ ocr_det_type: set[str],+ local_model_context: HybridLocalModelContext,+) -> list[list[dict[str, Any]]]:+ """按页完成 span 回填与行级元数据构造,返回不含页面级 sidecar 的 model list。"""+ page_counts = {+ "images": len(images_list),+ "pdf_pages": len(pdf_pages),+ "model_list": len(model_list),+ "inline_formulas": len(inline_formula_list),+ "ocr_results": len(ocr_res_list),+ }+ if len(set(page_counts.values())) != 1:+ raise ValueError(f"Hybrid block content page count mismatch: {page_counts}")++ target_block_types = set(ocr_det_type) | TITLE_BLOCK_TYPES | {BlockType.TEXT}+ page_block_line_results: list[tuple[list[dict[str, Any]], dict[int, list[_AnalyzeLine]], tuple[float, float]]] = []+ for image_dict, pdf_page, page_model_list, page_inline_formula_list, page_ocr_res_list in zip(+ images_list,+ pdf_pages,+ model_list,+ inline_formula_list,+ ocr_res_list,+ ):+ page_pil_image = image_dict["img_pil"]+ render_scale = float(image_dict["scale"])+ page_size = tuple(float(value) for value in pdf_page.size)+ page_spans = _build_page_text_formula_spans(+ page_inline_formula_list,+ page_ocr_res_list,+ page_size,+ render_scale,+ )+ if parse_mode == "txt":+ page_spans = _fill_native_pdf_text_spans(+ pdf_page,+ page_spans,+ page_pil_image,+ render_scale,+ page_size,+ )++ block_lines = _group_page_spans_by_block(+ page_model_list,+ page_spans,+ page_size,+ target_block_types,+ )+ page_block_line_results.append((page_model_list, block_lines, page_size))++ if parse_mode == "txt":+ _apply_window_post_ocr(+ local_model_context,+ [block_lines for _, block_lines, _ in page_block_line_results],+ )++ for page_model_list, block_lines, page_size in page_block_line_results:+ _apply_block_content_and_line_metadata(+ page_model_list,+ block_lines,+ page_size,+ )+ return model_list+++def _page_bbox_to_unit_bbox(bbox: BBox, page_size: tuple[float, float]) -> list[float] | None:+ """将 PDF point bbox 转为页面级 0-1 坐标,并统一保留三位小数。"""+ page_width, page_height = page_size+ if page_width <= 0 or page_height <= 0 or len(bbox) != 4:+ return None+ x0, y0, x1, y1 = [float(value) for value in bbox]+ if x1 <= x0 or y1 <= y0:+ return None+ normalized_bbox = [+ round(max(0.0, min(1.0, x0 / page_width)), 3),+ round(max(0.0, min(1.0, y0 / page_height)), 3),+ round(max(0.0, min(1.0, x1 / page_width)), 3),+ round(max(0.0, min(1.0, y1 / page_height)), 3),+ ]+ if normalized_bbox[2] <= normalized_bbox[0] or normalized_bbox[3] <= normalized_bbox[1]:+ return None+ return normalized_bboxdiff --git a/mineru/backend/utils/span_block_fix.py b/mineru/backend/analysis/pdf/text/lines.pysimilarity index 74%rename from mineru/backend/utils/span_block_fix.pyrename to mineru/backend/analysis/pdf/text/lines.pyindex 037a3cbd..8170ef55 100644--- a/mineru/backend/utils/span_block_fix.py+++ b/mineru/backend/analysis/pdf/text/lines.py@@ -1,10 +1,34 @@# Copyright (c) Opendatalab. All rights reserved.+"""将 AnalyzeSpan 按横排或竖排规则聚合为 AnalyzeLine。"""+from __future__ import annotations-from ...types import ContentType-from ...utils.ocr_utils import _is_overlaps_x_exceeds_threshold, _is_overlaps_y_exceeds_threshold-from .analyze_draft import _AnalyzeLine, _AnalyzeSpan-from .span_orientation import is_vertical_text_block_by_spans+from .....types import ContentType+from .....utils.ocr_utils import _is_overlaps_x_exceeds_threshold, _is_overlaps_y_exceeds_threshold+from .models import _AnalyzeLine, _AnalyzeSpan++VERTICAL_SPAN_HEIGHT_TO_WIDTH_RATIO_THRESHOLD = 2+VERTICAL_SPAN_IN_BLOCK_THRESHOLD = 0.8+++def is_vertical_text_block_by_spans(spans: list[_AnalyzeSpan]) -> bool:+ """根据块内文本 span 的高宽比判断文本块是否更像竖排文本。"""+ valid_span_count = 0+ vertical_span_count = 0+ for span in spans:+ bbox = span.bbox+ if not bbox or len(bbox) < 4:+ continue+ span_width = bbox[2] - bbox[0]+ span_height = bbox[3] - bbox[1]+ if span_width <= 0 or span_height <= 0:+ continue+ valid_span_count += 1+ if span_height / span_width > VERTICAL_SPAN_HEIGHT_TO_WIDTH_RATIO_THRESHOLD:+ vertical_span_count += 1+ if valid_span_count == 0:+ return False+ return vertical_span_count / valid_span_count > VERTICAL_SPAN_IN_BLOCK_THRESHOLDdef group_spans_to_lines(spans: list[_AnalyzeSpan]) -> list[_AnalyzeLine]:@@ -14,9 +38,7 @@ def group_spans_to_lines(spans: list[_AnalyzeSpan]) -> list[_AnalyzeLine]:span.type = ContentType.INLINE_EQUATIONif is_vertical_text_block_by_spans(spans):- return vertical_line_sort_spans_from_top_to_bottom(- merge_spans_to_vertical_line(spans)- )+ return vertical_line_sort_spans_from_top_to_bottom(merge_spans_to_vertical_line(spans))return line_sort_spans_by_left_to_right(merge_spans_to_line(spans))diff --git a/mineru/backend/utils/analyze_draft.py b/mineru/backend/analysis/pdf/text/models.pysimilarity index 87%rename from mineru/backend/utils/analyze_draft.pyrename to mineru/backend/analysis/pdf/text/models.pyindex 3dbab96f..7ae00765 100644--- a/mineru/backend/utils/analyze_draft.py+++ b/mineru/backend/analysis/pdf/text/models.py@@ -1,10 +1,12 @@# Copyright (c) Opendatalab. All rights reserved.+"""PDF 分析阶段专用的轻量 Span 与 Line 中间对象。"""+from __future__ import annotationsfrom dataclasses import dataclass, fieldfrom typing import Any-from ...types import BBox+from .....types import BBox@dataclass(slots=True)diff --git a/mineru/backend/utils/span_pre_proc.py b/mineru/backend/analysis/pdf/text/native.pysimilarity index 92%rename from mineru/backend/utils/span_pre_proc.pyrename to mineru/backend/analysis/pdf/text/native.pyindex 42ba4aff..05aaa591 100644--- a/mineru/backend/utils/span_pre_proc.py+++ b/mineru/backend/analysis/pdf/text/native.py@@ -1,4 +1,6 @@# Copyright (c) Opendatalab. All rights reserved.+"""PDF 字符提取、Span 匹配和上下标内容重建。"""+from __future__ import annotationsimport collections@@ -12,12 +14,12 @@ import numpy as npfrom loguru import loggerfrom pdftext.schema import Char-from ...types import BBox, BlockType, ContentType-from ...utils.image_utils import calculate_contrast-from ...utils.pdf_document import PDFPage, get_lines_from_chars-from ...utils.pdf_image_tools import get_crop_img-from .boxbase import calculate_overlap_area_in_bbox1_area_ratio-from .analyze_draft import _AnalyzeSpan+from .....types import BBox, BlockType, ContentType+from .....utils.image_utils import calculate_contrast+from .....utils.pdf_document import PDFPage, get_lines_from_chars+from .....utils.pdf_image_tools import get_crop_img+from mineru.utils.bbox_utils import calculate_overlap_area_in_bbox1_area_ratio+from .models import _AnalyzeSpanMAX_NATIVE_TEXT_CHARS_PER_PAGE = 65535PRIVATE_USE_AREA_START = 0xE000@@ -32,11 +34,13 @@ POST_OCR_REASON_PRIVATE_USE_TEXT = "private_use_text"def __replace_ligatures(text: str) -> str:+ """将 PDF 字符流中的常见拉丁连字替换为普通字符序列。"""ligatures = {"fi": "fi", "fl": "fl", "ff": "ff", "ffi": "ffi", "ffl": "ffl", "ſt": "ft", "st": "st"}return re.sub("|".join(map(re.escape, ligatures.keys())), lambda m: ligatures[m.group()], text)def __replace_unicode(text: str) -> str:+ """清理 PDF 字符流中的换行和特殊控制字符。"""ligatures = {"\r\n": "","\u0002": "-",@@ -55,6 +59,7 @@ def txt_spans_extract(all_bboxes: list[tuple[Any, ...]],all_discarded_blocks: list[tuple[Any, ...]],) -> list[_AnalyzeSpan]:+ """从 PDF 原生字符中提取文本 Span,必要时准备后置 OCR 兜底。"""page_char_count = Nonetry:page_char_count = pdf_page.get_char_count()@@ -146,11 +151,7 @@ def _get_char_fill_key(char: Char) -> tuple[str, Any]:def _iter_line_chars(line: dict[str, Any]) -> list[Char]:"""按 pdftext line/span 结构展开字符,兼容缺少 chars 字段的异常 span。"""- return [- char- for span in line.get("spans", [])- for char in span.get("chars", [])- ]+ return [char for span in line.get("spans", []) for char in span.get("chars", [])]def _is_visible_standard_rotation_char(char: Char) -> bool:@@ -164,11 +165,7 @@ def _is_visible_standard_rotation_char(char: Char) -> bool:return Falsex0, y0, x1, y1 = [float(v) for v in bbox]- return (- x1 > x0- and y1 > y0- and _is_supported_rotation(float(char.get("rotation", 0)))- )+ return x1 > x0 and y1 > y0 and _is_supported_rotation(float(char.get("rotation", 0)))def _get_chars_for_span_fill(page_chars: list[Char] | dict[str, list[Char]]) -> list[Char]:@@ -178,22 +175,11 @@ def _get_chars_for_span_fill(page_chars: list[Char] | dict[str, list[Char]]) ->else:all_chars = page_chars- fill_char_keys = {- _get_char_fill_key(char)- for char in all_chars- if _is_supported_rotation(float(char.get("rotation", 0)))- }+ fill_char_keys = {_get_char_fill_key(char) for char in all_chars if _is_supported_rotation(float(char.get("rotation", 0)))}- rotated_chars = [- char- for char in all_chars- if not _is_supported_rotation(float(char.get("rotation", 0)))- ]+ rotated_chars = [char for char in all_chars if not _is_supported_rotation(float(char.get("rotation", 0)))]if not rotated_chars:- return [- char for char in all_chars- if _get_char_fill_key(char) in fill_char_keys- ]+ return [char for char in all_chars if _get_char_fill_key(char) in fill_char_keys]for line in get_lines_from_chars(all_chars):if not _is_supported_rotation(float(line.get("rotation", 0))):@@ -208,10 +194,7 @@ def _get_chars_for_span_fill(page_chars: list[Char] | dict[str, list[Char]]) ->if not _is_supported_rotation(float(char.get("rotation", 0))):fill_char_keys.add(_get_char_fill_key(char))- return [- char for char in all_chars- if _get_char_fill_key(char) in fill_char_keys- ]+ return [char for char in all_chars if _get_char_fill_key(char) in fill_char_keys]def _prepare_post_ocr_spans(@@ -220,6 +203,7 @@ def _prepare_post_ocr_spans(pil_img: Any,scale: float,) -> list[_AnalyzeSpan]:+ """为缺少原生文本的 Span 准备 OCR 裁图,并过滤低对比度无效区域。"""if len(need_ocr_spans) == 0:return spans@@ -246,6 +230,7 @@ class SpanBlockMatcher:"""按 block 顺序消费 span,并用 y 方向索引减少无效重叠计算。"""def __init__(self, spans: list[_AnalyzeSpan]) -> None:+ """复制待匹配 Span,并建立按纵向位置查询的网格索引。"""self.spans = list(spans)self.used_span_indices = set()self.grid_size = self._get_grid_size(self.spans)@@ -314,6 +299,7 @@ def fill_char_in_spans(all_chars: list[Char],median_span_height: float,) -> list[_AnalyzeSpan]:+ """将 PDF 字符分配到对应 Span,并返回仍需后置 OCR 的 Span。"""# 简单从上到下排一下序spans = sorted(spans, key=lambda x: x.bbox[1])@@ -460,10 +446,7 @@ def _should_fallback_to_post_ocr_for_private_use_text(signal: dict[str, float |if pua_count < PRIVATE_USE_TEXT_COUNT_THRESHOLD:return False- return (- signal["max_pua_run"] >= PRIVATE_USE_TEXT_RUN_THRESHOLD- or signal["pua_ratio"] >= PRIVATE_USE_TEXT_RATIO_THRESHOLD- )+ return signal["max_pua_run"] >= PRIVATE_USE_TEXT_RUN_THRESHOLD or signal["pua_ratio"] >= PRIVATE_USE_TEXT_RATIO_THRESHOLDdef _clear_post_ocr_fallback(span: _AnalyzeSpan) -> None:@@ -492,6 +475,7 @@ def calculate_char_in_span(char: str,span_height_ratio: float = Span_Height_Ratio,) -> bool:+ """根据字符中心、Span 中轴和边界标点规则判断字符是否属于 Span。"""char_center_x = (char_bbox[0] + char_bbox[2]) / 2char_center_y = (char_bbox[1] + char_bbox[3]) / 2span_center_y = (span_bbox[1] + span_bbox[3]) / 2@@ -551,9 +535,7 @@ def _is_valid_script_reference_char(char: Char, metrics: dict[str, float]) -> bodef _get_body_axis(chars: list[Char], char_metrics: list[dict[str, float]]) -> dict[str, float] | None:"""根据同一 span 内最大高度字符簇估计正文中心线和正文高度。"""- valid_metrics = [- metrics for char, metrics in zip(chars, char_metrics) if _is_valid_script_reference_char(char, metrics)- ]+ valid_metrics = [metrics for char, metrics in zip(chars, char_metrics) if _is_valid_script_reference_char(char, metrics)]if not valid_metrics:return None@@ -622,6 +604,7 @@ def _wrap_script_runs(role_text_parts: list[tuple[str, str]]) -> str:def chars_to_content(span: _AnalyzeSpan) -> None:+ """将 Span 内字符重建为文本,并合并连续的上标、下标片段。"""# 检查span中的char是否为空if len(span.metadata["chars"]) != 0:chars = span.metadata["chars"]diff --git a/mineru/backend/analysis/pdf/visuals.py b/mineru/backend/analysis/pdf/visuals.pynew file mode 100644index 00000000..97ae70d9--- /dev/null+++ b/mineru/backend/analysis/pdf/visuals.py@@ -0,0 +1,255 @@+# Copyright (c) Opendatalab. All rights reserved.+"""视觉块容器补全、方向归一化与页面裁图。"""++from __future__ import annotations++import math+from typing import Any++import numpy as np+from loguru import logger++from mineru.types import BBox, BlockType+from mineru.utils.bbox_utils import (+ calculate_overlap_area_2_minbox_area_ratio,+ calculate_overlap_area_in_bbox1_area_ratio,+)++from .constants import (+ IMAGE_BLOCK_CONTAINMENT_THRESHOLD,+ IMAGE_BLOCK_LAYOUT_COVERAGE_THRESHOLD,+ IMAGE_BLOCK_LAYOUT_MIN_VISUAL_COUNT,+ LOCAL_LAYOUT_IMAGE_BLOCK_AREA_TYPES,+ LOCAL_LAYOUT_IMAGE_BLOCK_BODY_TYPES,+ MODEL_JSON_VISUAL_BLOCK_TYPES,+)+from .geometry import (+ _bbox_to_pixel_bbox,+ _encode_page_crop_as_jpeg_data_uri,+ _normalize_page_size,+ _normalize_visual_block_angle,+)+++def _normalize_model_bbox_for_containment(raw_bbox: Any) -> BBox | None:+ """校验模型 block 的四点框,返回可用于面积包含判断的浮点坐标。"""+ try:+ if raw_bbox is None or len(raw_bbox) != 4:+ return None+ bbox = tuple(float(value) for value in raw_bbox)+ except (TypeError, ValueError):+ return None++ if not all(math.isfinite(value) for value in bbox):+ return None+ if bbox[2] <= bbox[0] or bbox[3] <= bbox[1]:+ return None+ return bbox+++def _collapse_image_blocks(+ page_model_list: list[dict[str, Any]],+ containment_threshold: float = IMAGE_BLOCK_CONTAINMENT_THRESHOLD,+) -> None:+ """将 image_block 折叠为单个图片,并删除面积上被其包裹的非容器子块。"""+ image_blocks = [block for block in page_model_list if block.get("type") == "image_block"]+ if not image_blocks:+ return++ image_block_ids = {id(block) for block in image_blocks}+ image_block_bboxes = [+ bbox for block in image_blocks if (bbox := _normalize_model_bbox_for_containment(block.get("bbox"))) is not None+ ]++ retained_blocks: list[dict[str, Any]] = []+ for block in page_model_list:+ if id(block) in image_block_ids:+ block["type"] = BlockType.IMAGE+ retained_blocks.append(block)+ continue++ block_bbox = _normalize_model_bbox_for_containment(block.get("bbox"))+ is_contained = block_bbox is not None and any(+ calculate_overlap_area_in_bbox1_area_ratio(block_bbox, image_block_bbox) >= containment_threshold+ for image_block_bbox in image_block_bboxes+ )+ if not is_contained:+ retained_blocks.append(block)++ page_model_list[:] = retained_blocks+++def _supplement_missing_image_block_containers(+ model_list: list[list[dict[str, Any]]],+ layout_blocks_list: list[list[dict[str, Any]]],+ containment_threshold: float = IMAGE_BLOCK_CONTAINMENT_THRESHOLD,+ coverage_threshold: float = IMAGE_BLOCK_LAYOUT_COVERAGE_THRESHOLD,+ min_visual_count: int = IMAGE_BLOCK_LAYOUT_MIN_VISUAL_COUNT,+) -> None:+ """用本地 layout 整图框为 xhigh 结果补充缺失的 image_block 容器。"""+ if len(model_list) != len(layout_blocks_list):+ raise ValueError(+ "Hybrid image-block fallback page count mismatch: "+ f"model_list={len(model_list)}, layout_blocks={len(layout_blocks_list)}"+ )++ for page_model_list, page_layout_blocks in zip(model_list, layout_blocks_list):+ existing_image_block_bboxes = [+ bbox+ for block in page_model_list+ if block.get("type") == "image_block"+ if (bbox := _normalize_model_bbox_for_containment(block.get("bbox"))) is not None+ ]++ existing_claimed_block_ids: set[int] = set()+ if existing_image_block_bboxes:+ for block in page_model_list:+ if block.get("type") == "image_block":+ continue+ block_bbox = _normalize_model_bbox_for_containment(block.get("bbox"))+ if block_bbox is not None and any(+ calculate_overlap_area_in_bbox1_area_ratio(block_bbox, image_block_bbox) >= containment_threshold+ for image_block_bbox in existing_image_block_bboxes+ ):+ existing_claimed_block_ids.add(id(block))++ candidates: list[tuple[int, float, int, int, dict[str, Any], set[int]]] = []+ for layout_order, layout_block in enumerate(page_layout_blocks):+ if layout_block.get("type") != BlockType.IMAGE or layout_block.get("sub_type") == "seal":+ continue++ layout_bbox = _normalize_model_bbox_for_containment(layout_block.get("bbox"))+ if layout_bbox is None:+ continue+ if any(+ calculate_overlap_area_2_minbox_area_ratio(layout_bbox, image_block_bbox) >= containment_threshold+ for image_block_bbox in existing_image_block_bboxes+ ):+ continue++ contained_blocks: list[tuple[int, dict[str, Any], BBox]] = []+ for block_index, block in enumerate(page_model_list):+ if block.get("type") == "image_block" or id(block) in existing_claimed_block_ids:+ continue+ block_bbox = _normalize_model_bbox_for_containment(block.get("bbox"))+ if block_bbox is None:+ continue+ if calculate_overlap_area_in_bbox1_area_ratio(block_bbox, layout_bbox) >= containment_threshold:+ contained_blocks.append((block_index, block, block_bbox))++ contained_visuals = [+ (block_index, block)+ for block_index, block, _ in contained_blocks+ if block.get("type") in LOCAL_LAYOUT_IMAGE_BLOCK_BODY_TYPES+ ]+ if len(contained_visuals) < min_visual_count:+ continue++ layout_area = (layout_bbox[2] - layout_bbox[0]) * (layout_bbox[3] - layout_bbox[1])+ contained_area = sum(+ (block_bbox[2] - block_bbox[0]) * (block_bbox[3] - block_bbox[1])+ for _, block, block_bbox in contained_blocks+ if block.get("type") in LOCAL_LAYOUT_IMAGE_BLOCK_AREA_TYPES+ )+ coverage_ratio = contained_area / layout_area+ if coverage_ratio < coverage_threshold and not math.isclose(+ coverage_ratio,+ coverage_threshold,+ rel_tol=0.0,+ abs_tol=1e-12,+ ):+ continue++ contained_block_ids = {id(block) for _, block, _ in contained_blocks}+ first_block_index = min(block_index for block_index, _, _ in contained_blocks)+ candidates.append(+ (+ -len(contained_visuals),+ layout_area,+ layout_order,+ first_block_index,+ layout_block,+ contained_block_ids,+ )+ )++ claimed_block_ids: set[int] = set()+ selected_containers: list[tuple[int, dict[str, Any]]] = []+ for _, _, _, first_block_index, layout_block, block_ids in sorted(candidates):+ if claimed_block_ids.intersection(block_ids):+ continue+ claimed_block_ids.update(block_ids)+ selected_containers.append(+ (+ first_block_index,+ {+ "type": "image_block",+ "bbox": list(layout_block["bbox"]),+ "angle": layout_block.get("angle", 0),+ "content": None,+ },+ )+ )++ for insert_index, image_block in sorted(selected_containers, reverse=True):+ page_model_list.insert(insert_index, image_block)+++def _attach_visual_block_images(+ model_list: list[list[dict[str, Any]]],+ images_list: list[dict[str, Any]],+ page_start_index: int = 0,+) -> None:+ """在窗口页图释放前,为最终 model_list 视觉块写入回正后的页面裁图。"""+ if len(model_list) != len(images_list):+ raise ValueError(f"Hybrid visual crop page count mismatch: model_list={len(model_list)}, images={len(images_list)}")++ for page_offset, (page_model_list, image_dict) in enumerate(zip(model_list, images_list)):+ _collapse_image_blocks(page_model_list)+ visual_blocks = [+ (block_idx, block)+ for block_idx, block in enumerate(page_model_list)+ if block.get("type") in MODEL_JSON_VISUAL_BLOCK_TYPES+ ]+ if not visual_blocks:+ continue++ page_index = page_start_index + page_offset+ page_pil_image = image_dict.get("img_pil")+ if page_pil_image is None:+ logger.warning(f"Skipping model visual block crops without page image: page={page_index}")+ continue++ converted_page_image = None+ try:+ if getattr(page_pil_image, "mode", None) == "RGB":+ page_rgb_image = page_pil_image+ else:+ converted_page_image = page_pil_image.convert("RGB")+ page_rgb_image = converted_page_image++ page_size = _normalize_page_size(page_rgb_image)+ np_image = np.asarray(page_rgb_image)+ for block_idx, block in visual_blocks:+ try:+ pixel_bbox = _bbox_to_pixel_bbox(block.get("bbox"), page_size)+ if pixel_bbox is None:+ raise ValueError("invalid bbox")+ angle = _normalize_visual_block_angle(block.get("angle", 0))+ image_base64 = _encode_page_crop_as_jpeg_data_uri(+ np_image,+ pixel_bbox,+ angle,+ )+ if not image_base64:+ raise ValueError("empty crop or JPEG encoding failure")+ block["image_base64"] = image_base64+ except Exception as exc:+ logger.warning(+ "Skipping invalid model visual block crop: "+ f"page={page_index}, block={block_idx}, type={block.get('type')}, "+ f"bbox={block.get('bbox')}, error={exc}"+ )+ finally:+ if converted_page_image is not None:+ converted_page_image.close()diff --git a/mineru/backend/analysis/pdf/window.py b/mineru/backend/analysis/pdf/window.pynew file mode 100644index 00000000..e79a76be--- /dev/null+++ b/mineru/backend/analysis/pdf/window.py@@ -0,0 +1,434 @@+# Copyright (c) Opendatalab. All rights reserved.+"""PDF 处理窗口、资源生命周期和窗口内阶段编排。"""++from __future__ import annotations++from dataclasses import dataclass+from typing import Any, Literal++import numpy as np+from loguru import logger++from mineru.backend.local_model_runtime import HybridLocalModelContext+from mineru.types import BlockType+from mineru.utils.config_reader import get_processing_window_size+from mineru.utils.pdf_document import PDFDocument, PDFPage+from mineru.utils.pdf_image_tools import load_images_from_pdf_bytes_range++from .constants import (+ BATCH_RATIO,+ LAYOUT_BASE_BATCH_SIZE,+ MFR_BASE_BATCH_SIZE,+ NOT_EXTRACT_TYPES,+ PIPELINE_DET_TYPE,+ TITLE_BLOCK_TYPES,+)+from .geometry import _normalize_page_size+from .layout import (+ _build_vl_style_layout_blocks,+ _collect_table_items,+ _convert_vlm_results_to_model_list,+ _normalize_xhigh_vlm_blocks,+)+from .normalization import _apply_layout_title_split+from .formulas import (+ _apply_medium_display_formula_results,+ _apply_medium_formula_number_ocr,+ _build_formula_inputs,+ _split_formula_results,+ optimize_hybrid_formula_number_blocks,+)+from .ocr import (+ _apply_ocr_rec_results,+ _build_ocr_det_type_and_mfr_enable,+ _ocr_det,+ _apply_seal_ocr,+)+from .tables import (+ _apply_medium_table_recognition,+ _build_pdf_text_visual_run_spans,+ _fill_low_table_contents,+ _apply_table_orientations,+)+from .visuals import (+ _attach_visual_block_images,+ _supplement_missing_image_block_containers,+)+from .text.content import (+ _apply_block_content_and_line_metadata,+ _fill_window_block_content_and_lines,+ _group_page_spans_by_block,+ _validate_text_formula_window_inputs,+)+++@dataclass(frozen=True)+class _ProcessingWindow:+ """记录单个 Hybrid 处理窗口的页码范围。"""++ index: int+ total: int+ start: int+ end: int+++def _build_processing_windows(page_count: int, configured_window_size: int) -> list[_ProcessingWindow]:+ """根据页数和配置窗口大小生成稳定的 Hybrid 分段处理计划。"""+ effective_window_size = min(page_count, configured_window_size) if page_count else 0+ if effective_window_size <= 0:+ return []++ total_windows = (page_count + effective_window_size - 1) // effective_window_size+ return [+ _ProcessingWindow(+ index=window_index,+ total=total_windows,+ start=window_start,+ end=min(page_count - 1, window_start + effective_window_size - 1),+ )+ for window_index, window_start in enumerate(range(0, page_count, effective_window_size))+ ]+++def _get_window_pdf_pages(pdf_doc: PDFDocument, window: _ProcessingWindow) -> list[PDFPage]:+ """按窗口闭区间获取对应的 PDFPage 对象,供窗口内后续处理复用。"""+ return [pdf_doc[page_idx] for page_idx in range(window.start, window.end + 1)]+++def _log_processing_window_plan(page_count: int, configured_window_size: int, total_windows: int) -> None:+ """输出 Hybrid 分段处理计划日志,避免同步和异步入口文案漂移。"""+ logger.info(+ f"Hybrid processing-window run. page_count={page_count}, "+ f"window_size={configured_window_size}, total_windows={total_windows}"+ )+++def _log_processing_window(window: _ProcessingWindow, page_count: int, image_count: int) -> None:+ """输出单个 Hybrid 处理窗口的页码范围日志。"""+ logger.info(+ f"Hybrid processing window {window.index + 1}/{window.total}: "+ f"pages {window.start + 1}-{window.end + 1}/{page_count} "+ f"({image_count} pages)"+ )+++def _close_images(images_list: list[dict[str, Any]]) -> None:+ """尽力关闭窗口内全部 PIL 图片,确保异常路径也能释放图像资源。"""+ for image_dict in images_list or []:+ pil_img = image_dict.get("img_pil")+ if pil_img is not None:+ try:+ pil_img.close()+ except Exception:+ pass+++def _process_low_text(+ images_list: list[dict[str, Any]],+ pdf_pages: list[PDFPage],+ model_list: list[list[dict[str, Any]]],+ parse_mode: Literal["txt", "ocr"],+ local_model_context: HybridLocalModelContext,+ images_layout_res: list[list[dict[str, Any]]],+) -> list[list[dict[str, Any]]]:+ """使用 pdftext line 或本地 OCR 为 low layout block 填充文本内容。"""+ _validate_text_formula_window_inputs(+ images_list,+ pdf_pages,+ model_list,+ images_layout_res,+ )++ if parse_mode == "txt":+ target_block_types = set(PIPELINE_DET_TYPE) | TITLE_BLOCK_TYPES | {BlockType.TEXT}+ for pdf_page, page_model_list in zip(pdf_pages, model_list):+ page_size = tuple(float(value) for value in pdf_page.size)+ block_lines = _group_page_spans_by_block(+ page_model_list,+ _build_pdf_text_visual_run_spans(pdf_page),+ page_size,+ target_block_types,+ )+ _apply_block_content_and_line_metadata(+ page_model_list,+ block_lines,+ page_size,+ )+ elif parse_mode == "ocr":+ images_pil_list = [image_dict["img_pil"] for image_dict in images_list]+ np_images = [np.asarray(pil_image).copy() for pil_image in images_pil_list]+ empty_formula_list: list[list[dict[str, Any]]] = [[] for _ in model_list]+ ocr_res_list = _ocr_det(+ local_model_context,+ np_images,+ model_list,+ empty_formula_list,+ True,+ PIPELINE_DET_TYPE,+ )+ _apply_ocr_rec_results(local_model_context, ocr_res_list)+ model_list = _fill_window_block_content_and_lines(+ images_list,+ pdf_pages,+ model_list,+ empty_formula_list,+ ocr_res_list,+ parse_mode,+ PIPELINE_DET_TYPE,+ local_model_context,+ )+ else:+ raise ValueError(f"Unsupported parse mode: {parse_mode}")++ _fill_low_table_contents(+ images_list,+ pdf_pages,+ model_list,+ parse_mode,+ local_model_context,+ )+ return model_list+++def _process_text_and_formulas(+ images_list: list[dict[str, Any]],+ pdf_pages: list[PDFPage],+ model_list: list[list[dict[str, Any]]],+ parse_mode: Literal["txt", "ocr"],+ effort: Literal["medium", "high", "xhigh"],+ local_model_context: HybridLocalModelContext,+ images_layout_res: list[list[dict[str, Any]]],+) -> list[list[dict[str, Any]]]:+ """在当前窗口内完成 OCR、公式、原生文本及 block 行信息回填。"""++ _validate_text_formula_window_inputs(+ images_list,+ pdf_pages,+ model_list,+ images_layout_res,+ )+ images_pil_list = [image_dict["img_pil"] for image_dict in images_list]++ # 遍历model_list,对文本块截图交由OCR识别+ # 根据 parse_mode 和 effort 决定需要ocr的文本块的类型以及只开det还是det+rec+ ocr_det_type, mfr_enable = _build_ocr_det_type_and_mfr_enable(+ parse_mode=parse_mode,+ effort=effort,+ )++ # 将PIL图片转换为numpy数组+ np_images = [np.asarray(pil_image).copy() for pil_image in images_pil_list]++ mfd_res = _build_formula_inputs(images_layout_res)+ images_formula_list = mfd_res+ interline_enable = effort == "medium"++ # medium 识别行内和行间公式;high/xhigh 的 txt 路径只识别行内公式。+ if mfr_enable:+ images_formula_list = local_model_context.mfr_model.batch_predict(+ mfd_res,+ np_images,+ batch_size=BATCH_RATIO * MFR_BASE_BATCH_SIZE,+ interline_enable=interline_enable,+ )++ inline_formula_list, display_formula_list = _split_formula_results(images_formula_list)+ if effort == "medium":+ # 表格解析必须早于正文行填充,确保表内图片和行内公式只由表格模型消费一次。+ _apply_medium_table_recognition(+ local_model_context,+ model_list,+ inline_formula_list,+ np_images,+ )+ # 将行间公式span回填入block+ _apply_medium_display_formula_results(+ model_list,+ display_formula_list,+ images_pil_list,+ )+ # 使用ocr识别行间公式标号+ _apply_medium_formula_number_ocr(+ local_model_context,+ model_list,+ np_images,+ )++ # 行间公式标号回填到block+ for page_model_list in model_list:+ page_model_list[:] = optimize_hybrid_formula_number_blocks(page_model_list)++ need_rec_img = parse_mode == "ocr" and effort == "medium"+ # vlm没有执行ocr,需要ocr_det+ ocr_res_list = _ocr_det(+ local_model_context,+ np_images,+ model_list,+ mfd_res,+ need_rec_img,+ ocr_det_type,+ )++ # 如果有rec_img则做ocr_rec+ if need_rec_img:+ _apply_ocr_rec_results(local_model_context, ocr_res_list)++ return _fill_window_block_content_and_lines(+ images_list,+ pdf_pages,+ model_list,+ inline_formula_list,+ ocr_res_list,+ parse_mode,+ ocr_det_type,+ local_model_context,+ )+++def process_pdf_windows(+ file_bytes: bytes,+ document: PDFDocument,+ *,+ effort: Literal["flash", "low", "medium", "high", "xhigh"],+ parse_mode: Literal["txt", "ocr"],+ image_analysis: bool,+ flash_txt_mode: bool,+ hybrid_model: HybridLocalModelContext | None,+ vlm_predictor: Any,+) -> list[list[dict[str, Any]]]:+ """按固定阶段处理全部 PDF 窗口并返回完整 model-list。"""+ page_count = document.page_count+ model_list: list[list[dict[str, Any]]] = []+ if flash_txt_mode:+ # Flash 先对整份 PDF 生成完整 model_list,不依赖页面渲染和处理窗口。+ from mineru.model.flash import PdfModel++ model_list = PdfModel().predict(document)++ configured_window_size = get_processing_window_size(default=64)+ windows = _build_processing_windows(page_count, configured_window_size)+ _log_processing_window_plan(page_count, configured_window_size, len(windows))++ for window in windows:+ window_pages = _get_window_pdf_pages(document, window)+ images_list = load_images_from_pdf_bytes_range(+ pdf_bytes=file_bytes,+ start_page_id=window.start,+ end_page_id=window.end,+ image_type="pil_img",+ )+ try:+ if len(window_pages) != len(images_list):+ raise ValueError("Hybrid processing window PDF page count does not match image count")+ images_pil_list = [image_dict["img_pil"] for image_dict in images_list]+ _log_processing_window(window, page_count, len(images_pil_list))++ if flash_txt_mode:+ # Flash 仅切割当前窗口的外层列表,用于页图释放前原地补充视觉块裁图。+ window_model_list = model_list[window.start : window.end + 1]+ else:+ np_images = [np.asarray(pil_image).copy() for pil_image in images_pil_list]+ images_layout_res = hybrid_model.layout_model.batch_predict(+ images_pil_list, batch_size=min(8, BATCH_RATIO * LAYOUT_BASE_BATCH_SIZE)+ )++ # 使用小模型layout时对layout的表格做旋转检测+ if effort in ["low", "medium", "high"]:+ table_items = _collect_table_items(images_layout_res, np_images)+ if table_items:+ _apply_table_orientations(+ table_items,+ parse_mode,+ window_pages,+ images_list,+ hybrid_model,+ )++ vl_style_layout_blocks = _build_vl_style_layout_blocks(images_layout_res, images_pil_list)++ if parse_mode == "txt":+ if effort in ["low", "medium"]:+ window_model_list = vl_style_layout_blocks+ elif effort == "high":+ window_model_list = vlm_predictor.batch_extract_with_layout(+ images=images_pil_list,+ blocks_list=vl_style_layout_blocks,+ not_extract_list=NOT_EXTRACT_TYPES,+ image_analysis=False,+ )+ elif effort == "xhigh":+ window_model_list = vlm_predictor.batch_two_step_extract(+ images=images_pil_list,+ not_extract_list=NOT_EXTRACT_TYPES,+ image_analysis=image_analysis,+ )+ else:+ raise ValueError(f"Unsupported analyze effort: {effort}")+ elif parse_mode == "ocr":+ if effort in ["low", "medium"]:+ window_model_list = vl_style_layout_blocks+ elif effort == "high":+ window_model_list = vlm_predictor.batch_extract_with_layout(+ images=images_pil_list,+ blocks_list=vl_style_layout_blocks,+ image_analysis=False,+ )+ elif effort == "xhigh":+ window_model_list = vlm_predictor.batch_two_step_extract(+ images=images_pil_list,+ image_analysis=image_analysis,+ )+ else:+ raise ValueError(f"Unsupported analyze effort: {effort}")+ else:+ raise ValueError(f"Unsupported parse mode: {parse_mode}")++ if effort in {"high", "xhigh"}:+ window_model_list = _convert_vlm_results_to_model_list(window_model_list)+ if effort == "xhigh":+ _normalize_xhigh_vlm_blocks(window_model_list)+ _apply_layout_title_split(+ window_model_list,+ images_layout_res,+ [_normalize_page_size(image) for image in images_pil_list],+ )++ if effort == "low":+ window_model_list = _process_low_text(+ images_list,+ window_pages,+ window_model_list,+ parse_mode,+ hybrid_model,+ images_layout_res,+ )+ else:+ window_model_list = _process_text_and_formulas(+ images_list,+ window_pages,+ window_model_list,+ parse_mode,+ effort,+ hybrid_model,+ images_layout_res,+ )++ if effort in {"medium", "high"}:+ _apply_seal_ocr(hybrid_model, window_model_list, np_images)+ elif effort == "xhigh":+ _supplement_missing_image_block_containers(+ window_model_list,+ vl_style_layout_blocks,+ )++ _attach_visual_block_images(+ window_model_list,+ images_list,+ page_start_index=window.start,+ )+ if not flash_txt_mode:+ model_list.extend(window_model_list)+ finally:+ _close_images(images_list)++ return model_listdiff --git a/mineru/backend/analyze.py b/mineru/backend/analyze.pyindex f1e2e9f1..77e780c1 100644--- a/mineru/backend/analyze.py+++ b/mineru/backend/analyze.py@@ -1,2593 +1,24 @@# Copyright (c) Opendatalab. All rights reserved.-import base64-import html-import math-import os-import re-import time-from collections import Counter-from collections.abc import Iterable, Mapping-from copy import deepcopy-from dataclasses import dataclass-from io import BytesIO-from typing import Any, Literal+"""统一 PDF 与 Office 文档分析的稳定公共门面。"""-import cv2-import numpy as np-from PIL import Image-from loguru import logger--from mineru.backend.model_list_to_midlle_json import model_list_to_pages-from mineru.version import __version__ as mineru_version-from mineru.backend.utils.table_text import project_ocr_table_text, project_pdf_table_text-from mineru.backend.local_model_runtime import (- AtomicModel,- HybridLocalModelContext,- HybridLocalModelContextSingleton,- run_ocr_inference,-)-from mineru.backend.utils.boxbase import (- calculate_overlap_area_2_minbox_area_ratio,- calculate_overlap_area_in_bbox1_area_ratio,-)-from mineru.backend.utils.char_utils import full_to_half_exclude_marks, resolve_text_line_boundary-from mineru.backend.utils.formula_number import optimize_hybrid_formula_number_blocks-from mineru.backend.utils.analyze_draft import _AnalyzeLine, _AnalyzeSpan-from mineru.backend.utils.span_block_fix import group_spans_to_lines-from mineru.backend.utils.raw_block_types import (- RAW_ALGORITHM,- RAW_CAPTION,- RAW_FOOTNOTE,- RAW_PHONETIC,-)-from mineru.backend.utils.span_pre_proc import (- SpanBlockMatcher,- __replace_ligatures,- __replace_unicode,- _clear_post_ocr_fallback,- _is_supported_rotation,- _restore_post_ocr_fallback,- txt_spans_extract,-)-from mineru.model.flash import DocxModel, PptxModel, XlsxModel-from mineru.utils.bbox_utils import normalize_to_int_bbox-from mineru.utils.engine_utils import get_vlm_engine-from mineru.utils.language import detect_lang-from mineru.utils.model_utils import clean_memory, crop_img-from mineru.utils.ocr_utils import (- OcrConfidence,- get_adjusted_mfdetrec_res,- get_ocr_result_list,- get_rotate_crop_image_for_text_rec,- mask_formula_regions_for_ocr_det,- merge_det_boxes,- rotate_vertical_crop_if_needed,- sorted_boxes,- update_det_boxes,-)-from mineru.utils.pdf_image_tools import load_images_from_pdf_bytes_range, get_crop_np_img-from tqdm import tqdm--from ..types import BBox, BlockType, ContentType, MiddleJson-from ..utils.config_reader import get_processing_window_size-from ..utils.pdf_document import PDFDocument, PDFPage, get_lines_from_chars---os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1" # 让mps可以fallback--LAYOUT_BASE_BATCH_SIZE = 1-MFR_BASE_BATCH_SIZE = 16-OCR_DET_BASE_BATCH_SIZE = 8-LAYOUT_TITLE_SPLIT_OVERLAP_THRESHOLD = 0.8-IMAGE_BLOCK_CONTAINMENT_THRESHOLD = 0.8-IMAGE_BLOCK_LAYOUT_COVERAGE_THRESHOLD = 0.9-IMAGE_BLOCK_LAYOUT_MIN_VISUAL_COUNT = 2-BATCH_RATIO = 2-TABLE_TEXT_LINE_OVERLAP_THRESHOLD = 0.5-TABLE_TEXT_ORIENTATION_MIN_VALID_LINES = 3-TABLE_TEXT_ORIENTATION_MIN_DOMINANCE_RATIO = 0.6-TABLE_TEXT_ORIENTATION_ANGLES = frozenset({0, 90, 180, 270})-_OFFICE_MODEL_MAP = {- "docx": DocxModel,- "pptx": PptxModel,- "xlsx": XlsxModel,-}-_SUPPORTED_FILE_SUFFIXES = {"pdf", *_OFFICE_MODEL_MAP}-_VLM_UNCLASSIFIED_TITLE_TYPE = "title"-TITLE_BLOCK_TYPES = {- _VLM_UNCLASSIFIED_TITLE_TYPE,- BlockType.DOC_TITLE,- BlockType.PARAGRAPH_TITLE,-}-CODE_CONTENT_BLOCK_TYPES = {- BlockType.CODE,- RAW_ALGORITHM,-}-LINE_METADATA_BLOCK_TYPES = {- BlockType.TEXT,- BlockType.DOC_TITLE,- BlockType.PARAGRAPH_TITLE,- RAW_CAPTION,- RAW_FOOTNOTE,-}-NATURAL_LANGUAGE_CONTENT_BLOCK_TYPES = {- BlockType.TEXT,- BlockType.DOC_TITLE,- BlockType.PARAGRAPH_TITLE,- BlockType.ASIDE_TEXT,- BlockType.HEADER,- BlockType.FOOTER,- BlockType.PAGE_NUMBER,- BlockType.PAGE_FOOTNOTE,- BlockType.REF_TEXT,- BlockType.LIST,- BlockType.INDEX,- RAW_CAPTION,- RAW_FOOTNOTE,-}-VLM_VISUAL_ANNOTATION_TYPE_MAP = {- BlockType.TABLE_CAPTION: RAW_CAPTION,- BlockType.IMAGE_CAPTION: RAW_CAPTION,- BlockType.CODE_CAPTION: RAW_CAPTION,- BlockType.TABLE_FOOTNOTE: RAW_FOOTNOTE,- BlockType.IMAGE_FOOTNOTE: RAW_FOOTNOTE,-}-VLM_MODEL_LIST_FIELDS = frozenset(- {"type", "bbox", "content", "angle", "score", "sub_type", "cell_merge"}-)-MODEL_JSON_VISUAL_BLOCK_TYPES = {- BlockType.IMAGE,- BlockType.CHART,- BlockType.TABLE,- BlockType.EQUATION,-}-LOCAL_LAYOUT_IMAGE_BLOCK_BODY_TYPES = {- BlockType.IMAGE,- BlockType.CHART,-}-LOCAL_LAYOUT_IMAGE_BLOCK_AREA_TYPES = {- *LOCAL_LAYOUT_IMAGE_BLOCK_BODY_TYPES,- BlockType.IMAGE_CAPTION,- RAW_CAPTION,- BlockType.IMAGE_FOOTNOTE,- RAW_FOOTNOTE,-}-_INLINE_FORMULA_PATTERN = re.compile(r"\\\((.*?)\\\)")--VLM_LAYOUT_LABEL_MAP = {- "abstract": BlockType.TEXT,- "algorithm": BlockType.CODE,- "aside_text": BlockType.ASIDE_TEXT,- "chart": BlockType.CHART,- "content": BlockType.INDEX,- "display_formula": BlockType.EQUATION,- "doc_title": BlockType.DOC_TITLE,- "figure_title": RAW_CAPTION,- "footer": BlockType.FOOTER,- "footer_image": BlockType.FOOTER,- "footnote": BlockType.PAGE_FOOTNOTE,- "formula_number": BlockType.FORMULA_NUMBER,- "header": BlockType.HEADER,- "header_image": BlockType.HEADER,- "image": BlockType.IMAGE,- "number": BlockType.PAGE_NUMBER,- "paragraph_title": BlockType.PARAGRAPH_TITLE,- "reference_content": BlockType.REF_TEXT,- "seal": BlockType.IMAGE,- "table": BlockType.TABLE,- "text": BlockType.TEXT,- "vertical_text": BlockType.TEXT,- "vision_footnote": RAW_FOOTNOTE,-}--PIPELINE_DET_TYPE = {- BlockType.TEXT,- BlockType.CODE,- BlockType.ASIDE_TEXT,- BlockType.INDEX,- BlockType.DOC_TITLE,- RAW_CAPTION,- BlockType.FOOTER,- BlockType.PAGE_FOOTNOTE,- BlockType.HEADER,- BlockType.PAGE_NUMBER,- BlockType.PARAGRAPH_TITLE,- BlockType.REF_TEXT,- RAW_FOOTNOTE,-}-NOT_EXTRACT_TYPES = {- BlockType.TEXT,- _VLM_UNCLASSIFIED_TITLE_TYPE,- BlockType.DOC_TITLE,- BlockType.PARAGRAPH_TITLE,- BlockType.HEADER,- BlockType.FOOTER,- BlockType.PAGE_NUMBER,- BlockType.PAGE_FOOTNOTE,- BlockType.REF_TEXT,- BlockType.TABLE_CAPTION,- BlockType.IMAGE_CAPTION,- RAW_CAPTION,- BlockType.TABLE_FOOTNOTE,- BlockType.IMAGE_FOOTNOTE,- RAW_FOOTNOTE,- BlockType.CODE_CAPTION,- RAW_PHONETIC,-}-VLM_TXT_DET_TYPE = NOT_EXTRACT_TYPES-VLM_OCR_DET_TYPE = {- BlockType.TEXT,- BlockType.DOC_TITLE,- BlockType.PARAGRAPH_TITLE,- RAW_CAPTION,- RAW_FOOTNOTE,-}-_LOW_TXT_VISUAL_RUN_ANGLES = (0.0, 90.0, 180.0, 270.0)---@dataclass-class _OcrDetCrop:- """保存一次 OCR det 裁剪的中间数据,避免用裸 tuple 传递阶段状态。"""-- bgr_image: Any- useful_list: list[Any]- adjusted_mfdetrec_res: list[Any]- page_ocr_res_list: list[dict[str, Any]]---def _load_vlm_runtime() -> dict[str, Any]:- """按需加载 VLM runtime 组件,确保只有 high/extra_high 路径触发 VLM 依赖。"""- from ..model.vlm.runtime import (- ModelSingleton,- _get_model_async,- _maybe_enable_serial_execution,- aio_predictor_execution_guard,- predictor_execution_guard,- )-- return {- "ModelSingleton": ModelSingleton,- "_get_model_async": _get_model_async,- "_maybe_enable_serial_execution": _maybe_enable_serial_execution,- "aio_predictor_execution_guard": aio_predictor_execution_guard,- "predictor_execution_guard": predictor_execution_guard,- }---@dataclass(frozen=True)-class _ProcessingWindow:- """记录单个 Hybrid 处理窗口的页码范围,统一同步和异步入口的窗口计算。"""-- index: int- total: int- start: int- end: int---def _build_processing_windows(page_count: int, configured_window_size: int) -> list[_ProcessingWindow]:- """根据页数和配置窗口大小生成稳定的 Hybrid 分段处理计划。"""- effective_window_size = min(page_count, configured_window_size) if page_count else 0- if effective_window_size <= 0:- return []-- total_windows = (page_count + effective_window_size - 1) // effective_window_size- return [- _ProcessingWindow(- index=window_index,- total=total_windows,- start=window_start,- end=min(page_count - 1, window_start + effective_window_size - 1),- )- for window_index, window_start in enumerate(range(0, page_count, effective_window_size))- ]---def _get_window_pdf_pages(pdf_doc: PDFDocument, window: _ProcessingWindow) -> list[PDFPage]:- """按窗口闭区间获取对应的 PDFPage 对象,供窗口内后续处理复用。"""- return [pdf_doc[page_idx] for page_idx in range(window.start, window.end + 1)]---def _log_processing_window_plan(page_count: int, configured_window_size: int, total_windows: int) -> None:- """输出 Hybrid 分段处理计划日志,避免同步和异步入口文案漂移。"""- logger.info(- f"Hybrid processing-window run. page_count={page_count}, "- f"window_size={configured_window_size}, total_windows={total_windows}"- )---def _log_processing_window(window: _ProcessingWindow, page_count: int, image_count: int) -> None:- """输出单个 Hybrid 处理窗口的页码范围日志。"""- logger.info(- f"Hybrid processing window {window.index + 1}/{window.total}: "- f"pages {window.start + 1}-{window.end + 1}/{page_count} "- f"({image_count} pages)"- )---def _close_images(images_list: list[dict[str, Any]]) -> None:- for image_dict in images_list or []:- pil_img = image_dict.get("img_pil")- if pil_img is not None:- try:- pil_img.close()- except Exception:- pass---def _normalize_page_size(page_image: Any) -> tuple[int, int]:- """从PIL或numpy图像中读取页面宽高,供归一化bbox还原为像素bbox。"""- if hasattr(page_image, "size"):- return page_image.size-- height, width = page_image.shape[:2]- return width, height---def _bbox_to_pixel_bbox(bbox: BBox | None, page_size: tuple[int, int]) -> BBox | None:- """将归一化或像素bbox统一成像素bbox,异常bbox返回None。"""- if bbox is None or len(bbox) != 4:- return None-- try:- x0, y0, x1, y1 = [float(v) for v in bbox]- except (TypeError, ValueError):- return None-- width, height = page_size- if all(0.0 <= value <= 1.0 for value in [x0, y0, x1, y1]):- x0, y0, x1, y1 = x0 * width, y0 * height, x1 * width, y1 * height-- left, right = sorted([x0, x1])- top, bottom = sorted([y0, y1])- if right <= left or bottom <= top:- return None- return (left, top, right, bottom)---def _normalize_layout_bbox_to_unit(bbox: BBox | None, page_size: tuple[int, int]) -> list[float] | None:- """将 layout 像素 bbox 归一化为 VLM ContentBlock 需要的 0-1 坐标。"""- pixel_bbox = _bbox_to_pixel_bbox(bbox, page_size)- if pixel_bbox is None:- return None-- page_width, page_height = page_size- if page_width <= 0 or page_height <= 0:- return None-- x0, y0, x1, y1 = pixel_bbox- unit_bbox = [- round(max(0.0, min(1.0, float(x0) / page_width)), 3),- round(max(0.0, min(1.0, float(y0) / page_height)), 3),- round(max(0.0, min(1.0, float(x1) / page_width)), 3),- round(max(0.0, min(1.0, float(y1) / page_height)), 3),- ]- if unit_bbox[2] <= unit_bbox[0] or unit_bbox[3] <= unit_bbox[1]:- return None- return unit_bbox---def _layout_item_to_content_block(layout_item: dict[str, Any], page_size: tuple[int, int]) -> dict | None:- """将本地 layout 小模型检测项转换为 mineru-vl-utils 的 ContentBlock。"""- label = layout_item.get("label") or layout_item.get("type")-- block_type = VLM_LAYOUT_LABEL_MAP.get(str(label))- if block_type is None:- return None-- bbox = _normalize_layout_bbox_to_unit(layout_item.get("bbox"), page_size)- if bbox is None:- return None-- content_block = {- "type": block_type,- "bbox": bbox,- "angle": layout_item.get("angle", 0),- }-- if block_type == BlockType.IMAGE and label == "seal":- content_block["sub_type"] = "seal"-- return content_block---def _get_crop_table_img(- np_img: np.ndarray,- table_res_bbox: BBox,- scale: float = 1,-) -> np.ndarray:- """按指定缩放裁剪表格图,保持 medium 表格处理只使用当前文件窗口图像。"""- bbox = normalize_to_int_bbox([float(v) / float(scale) for v in table_res_bbox])- if bbox is None:- return np_img[0:0, 0:0]- return get_crop_np_img(bbox, np_img, scale=scale)---def _collect_table_items(- images_layout_res: list[list[dict[str, Any]]],- np_images: list[np.ndarray],-) -> list[dict[str, Any]]:- table_items = []- for page_idx, (layout_res, np_img) in enumerate(zip(images_layout_res, np_images)):- for table_res in layout_res:- if table_res.get("label") != "table":- continue- table_img = _get_crop_table_img(np_img=np_img, table_res_bbox=table_res["bbox"])- if table_img.size == 0:- continue- table_items.append(- {- "table_img": table_img,- "layout_item": table_res,- "page_idx": page_idx,- }- )- return table_items---def _apply_table_rotate_labels(- table_items: list[dict[str, Any]],- rotate_labels: list[str],-) -> None:- """按分类输入顺序将表格旋转角写回原始 layout 检测项。"""- if len(rotate_labels) != len(table_items):- raise ValueError("Hybrid table orientation result count mismatch")-- for table_item, rotate_label in zip(table_items, rotate_labels):- table_item["layout_item"]["angle"] = int(rotate_label or "0")---def _build_vl_style_layout_blocks(- images_layout_res: list[list[dict[str, Any]]],- images_pil_list: list[Image.Image],-) -> list[list[Any]]:- """按页构造 Hybrid high 模式传给 VLM 的外部 layout blocks。"""- blocks_list: list[list[Any]] = []- for layout_res, image in zip(images_layout_res, images_pil_list):- page_size = _normalize_page_size(image)- page_blocks = []- for layout_item in layout_res:- content_block = _layout_item_to_content_block(layout_item, page_size)- if content_block is not None:- page_blocks.append(content_block)- blocks_list.append(page_blocks)- return blocks_list---def _convert_vlm_results_to_model_list(- vlm_results: Iterable[Iterable[Mapping[str, Any]]],-) -> list[list[dict[str, Any]]]:- """将 VLM 结果投影为允许进入 Analyze 的字段,丢弃未采用的外部属性。"""- return [- [- {- field_name: deepcopy(value)- for field_name, value in dict(block).items()- if field_name in VLM_MODEL_LIST_FIELDS- }- for block in page_blocks- ]- for page_blocks in vlm_results- ]---def _normalize_xhigh_vlm_blocks(model_list: list[list[dict[str, Any]]]) -> None:- """归一化 xhigh VLM 的视觉注释类型。"""- for page_model_list in model_list:- for block in page_model_list:- normalized_type = VLM_VISUAL_ANNOTATION_TYPE_MAP.get(block.get("type"))- if normalized_type is not None:- block["type"] = normalized_type---def _build_formula_inputs(images_layout_res: list[list[dict[str, Any]]]) -> list[list[dict[str, Any]]]:- """构造完整 MFD/MFR 输入,保留全部行内和行间公式框。"""- formula_inputs = []- for layout_res in images_layout_res:- page_formula_inputs = []- for res in layout_res:- label = res.get("label")- if label not in ["inline_formula", "display_formula"]:- continue- bbox = res.get("bbox")- if bbox is None or len(bbox) != 4:- continue- page_formula_inputs.append(- {- "label": label,- "bbox": list(bbox),- "score": float(res.get("score", 0.0)),- # layout 只提供公式位置;未运行 MFR 的 high/xhigh OCR 必须保留空 LaTeX。- "latex": "",- }- )- formula_inputs.append(page_formula_inputs)- return formula_inputs---def _split_formula_results(- images_formula_list: list[list[dict[str, Any]]],-) -> tuple[list[list[dict[str, Any]]], list[list[dict[str, Any]]]]:- """按原始标签拆分 MFR 结果,避免行间公式进入 inline sidecar。"""- inline_formula_list = []- display_formula_list = []- for page_formula_list in images_formula_list:- inline_formula_list.append([formula for formula in page_formula_list if formula.get("label") == "inline_formula"])- display_formula_list.append([formula for formula in page_formula_list if formula.get("label") == "display_formula"])- return inline_formula_list, display_formula_list---def _apply_medium_display_formula_results(- model_list: list[list[dict[str, Any]]],- display_formula_list: list[list[dict[str, Any]]],- images_pil_list: list[Image.Image],-) -> None:- """将 medium 行间公式 LaTeX 按页和 bbox 回填到对应 equation 块。"""- for page_idx, (page_model_list, page_display_formula_list, page_image) in enumerate(- zip(model_list, display_formula_list, images_pil_list)- ):- page_size = _normalize_page_size(page_image)- equation_blocks_by_bbox: dict[tuple[float, ...], list[dict[str, Any]]] = {}- for block in page_model_list:- if block.get("type") != BlockType.EQUATION:- continue- block_bbox = block.get("bbox")- if block_bbox is None or len(block_bbox) != 4:- continue- equation_blocks_by_bbox.setdefault(tuple(float(value) for value in block_bbox), []).append(block)-- for formula in page_display_formula_list:- normalized_bbox = _normalize_layout_bbox_to_unit(formula.get("bbox"), page_size)- if normalized_bbox is None:- continue- matched_blocks = equation_blocks_by_bbox.get(tuple(normalized_bbox), [])- if len(matched_blocks) != 1:- raise ValueError(- "Hybrid medium display formula must match exactly one equation block: "- f"page_idx={page_idx}, bbox={normalized_bbox}, matches={len(matched_blocks)}"- )- matched_blocks[0]["content"] = formula.get("latex", "")---def _build_ocr_det_type_and_mfr_enable(- parse_mode: Literal["txt", "ocr"],- effort: Literal["medium", "high", "xhigh"],-) -> tuple[set[str], bool]:- """返回 OCR 检测块类型,以及是否需要执行小模型公式识别。"""- if parse_mode not in ("txt", "ocr"):- raise ValueError(f"Unsupported parse mode: {parse_mode}")- if effort not in ("medium", "high", "xhigh"):- raise ValueError(f"Unsupported analyze effort: {effort}")-- if effort == "medium":- return PIPELINE_DET_TYPE, True- if parse_mode == "txt":- return VLM_TXT_DET_TYPE, True- return VLM_OCR_DET_TYPE, False---def _formula_item_to_pixel_bbox(item: dict[str, Any]) -> list[int] | None:- bbox = item.get("bbox")- if bbox is not None and len(bbox) == 4:- return [int(float(v)) for v in bbox]- return None---def _set_temp_pixel_bbox(res: dict[str, Any], pixel_bbox: list[int]) -> None:- """临时切换为像素 bbox,便于复用已有裁剪逻辑。"""- res["_normalized_bbox"] = list(res["bbox"])- res["bbox"] = pixel_bbox---def _restore_normalized_bbox(res: dict[str, Any]) -> None:- """恢复归一化 bbox,避免 OCR det 过程污染 Hybrid 输出。"""- normalized_bbox = res.pop("_normalized_bbox", None)- if normalized_bbox is not None:- res["bbox"] = normalized_bbox---def _collect_ocr_det_crops(- np_images: list[Any],- model_list: list[list[dict[str, Any]]],- mfd_res: list[Any],- ocr_det_type: set[str],-) -> tuple[list[list[dict[str, Any]]], list[_OcrDetCrop]]:- """收集 OCR det 需要处理的裁剪图,并为每页预建 sidecar 结果列表。"""- ocr_res_list: list[list[dict[str, Any]]] = []- crops: list[_OcrDetCrop] = []-- for np_image, page_mfd_res, page_results in zip(np_images, mfd_res, model_list):- page_ocr_res_list: list[dict[str, Any]] = []- ocr_res_list.append(page_ocr_res_list)- img_height, img_width = np_image.shape[:2]- for res in page_results:- if res["type"] not in ocr_det_type:- continue- x0 = max(0, int(res["bbox"][0] * img_width))- y0 = max(0, int(res["bbox"][1] * img_height))- x1 = min(img_width, int(res["bbox"][2] * img_width))- y1 = min(img_height, int(res["bbox"][3] * img_height))- if x1 <= x0 or y1 <= y0:- continue- _set_temp_pixel_bbox(res, [x0, y0, x1, y1])- try:- new_image, useful_list = crop_img(res, np_image, crop_paste_x=50, crop_paste_y=50)- finally:- _restore_normalized_bbox(res)- adjusted_mfdetrec_res = get_adjusted_mfdetrec_res(page_mfd_res, useful_list)- bgr_image = cv2.cvtColor(new_image, cv2.COLOR_RGB2BGR) # type: ignore- bgr_image = mask_formula_regions_for_ocr_det(bgr_image, adjusted_mfdetrec_res)- crops.append(- _OcrDetCrop(- bgr_image=bgr_image,- useful_list=useful_list,- adjusted_mfdetrec_res=adjusted_mfdetrec_res,- page_ocr_res_list=page_ocr_res_list,- )- )-- return ocr_res_list, crops---def _normalize_batch_ocr_det_boxes(dt_boxes: Any, adjusted_mfdetrec_res: list[Any]) -> list[Any]:- """对 batch OCR det 的检测框排序、合并,并按公式位置修正。"""- if dt_boxes is None or len(dt_boxes) == 0:- return []-- dt_boxes_sorted = sorted_boxes(dt_boxes)- dt_boxes_merged = merge_det_boxes(dt_boxes_sorted) if dt_boxes_sorted else []- if dt_boxes_merged and adjusted_mfdetrec_res:- return update_det_boxes(dt_boxes_merged, adjusted_mfdetrec_res)- return dt_boxes_merged---def _append_ocr_det_result(- crop: _OcrDetCrop,- ocr_res: Any,- need_rec_img: bool,-) -> None:- """将 OCR det 原始框转换为 Hybrid ocr_text sidecar 并写回对应页。"""- if not ocr_res:- return- ocr_result_list = get_ocr_result_list(- ocr_res,- crop.useful_list,- need_rec_img,- crop.bgr_image,- )- crop.page_ocr_res_list.extend(ocr_result_list)---def _ocr_det(- local_model_context: HybridLocalModelContext,- np_images: list[np.ndarray],- model_list: list[list[dict[str, Any]]],- mfd_res: list[Any],- need_rec_img: bool,- ocr_det_type: set[str],-) -> list[list[dict[str, Any]]]:- """执行 Hybrid OCR det sidecar 生成,按运行时配置选择单图或 batch 模式。"""- ocr_res_list, crops = _collect_ocr_det_crops(np_images, model_list, mfd_res, ocr_det_type)-- if crops:- batch_images = [crop.bgr_image for crop in crops]- det_batch_size = min(len(batch_images), BATCH_RATIO * OCR_DET_BASE_BATCH_SIZE)- batch_results = local_model_context.ocr_model.text_detector.batch_predict(- batch_images,- det_batch_size,- tqdm_enable=True,- tqdm_desc="OCR-det",- )-- for crop, (dt_boxes, _) in zip(crops, batch_results):- dt_boxes_final = _normalize_batch_ocr_det_boxes(dt_boxes, crop.adjusted_mfdetrec_res)- if dt_boxes_final:- ocr_res = [box.tolist() if hasattr(box, "tolist") else box for box in dt_boxes_final]- _append_ocr_det_result(crop, ocr_res, need_rec_img)- return ocr_res_list+from __future__ import annotations+from typing import Any, Literal, cast-def _collect_ocr_rec_inputs(- ocr_res_list: list[list[dict[str, Any]]],-) -> tuple[list[tuple[list[dict[str, Any]], dict[str, Any]]], list[Any]]:- """收集需要 OCR rec 的裁剪图,同时从 sidecar 中移除临时图像对象。"""- need_ocr_list = []- img_crop_list = []- for page_ocr_res_list in ocr_res_list:- for ocr_res in page_ocr_res_list:- if "np_img" in ocr_res:- need_ocr_list.append((page_ocr_res_list, ocr_res))- img_crop_list.append(ocr_res.pop("np_img"))- return need_ocr_list, img_crop_list---def _should_remove_low_confidence_ocr_text(ocr_text: str, ocr_score: float, ocr_res: dict[str, Any]) -> bool:- """判断 OCR rec 结果是否应因低置信或竖排噪声被丢弃。"""- if ocr_score < OcrConfidence.min_confidence:- return True-- layout_res_bbox = ocr_res.get("bbox")- if layout_res_bbox is None and ocr_res.get("poly") is not None:- layout_res_bbox = [- ocr_res["poly"][0],- ocr_res["poly"][1],- ocr_res["poly"][4],- ocr_res["poly"][5],- ]- if layout_res_bbox is None:- return True-- layout_res_width = layout_res_bbox[2] - layout_res_bbox[0]- layout_res_height = layout_res_bbox[3] - layout_res_bbox[1]- return (- ocr_text- in [- "(204号",- "(20",- "(2",- "(2号",- "(20号",- "号",- "(204",- "(cid:)",- "(ci:)",- "(cd:1)",- "cd:)",- "c)",- "(cd:)",- "c",- "id:)",- ":)",- "√:)",- "√i:)",- "−i:)",- "−:",- "i:)",- ]- and ocr_score < 0.8- and layout_res_width < layout_res_height- )---def _apply_ocr_rec_results(- local_model_context: HybridLocalModelContext,- ocr_res_list: list[list[dict[str, Any]]],-) -> None:- """执行 OCR rec 并把文本写回 sidecar,结果数量异常时显式报错。"""- need_ocr_list, img_crop_list = _collect_ocr_rec_inputs(ocr_res_list)- if not img_crop_list:- return-- ocr_result_list = local_model_context.ocr_model.ocr(- img_crop_list,- det=False,- tqdm_enable=True,- )[0]-- if len(ocr_result_list) != len(need_ocr_list):- raise ValueError(- f"Hybrid OCR rec result count mismatch: ocr_result_list={len(ocr_result_list)}, need_ocr_list={len(need_ocr_list)}"- )-- items_to_remove = []- for index, (page_ocr_res_list, need_ocr_res) in enumerate(need_ocr_list):- ocr_text, ocr_score = ocr_result_list[index]- need_ocr_res["text"] = ocr_text- need_ocr_res["score"] = float(f"{ocr_score:.3f}")- if _should_remove_low_confidence_ocr_text(ocr_text, ocr_score, need_ocr_res):- items_to_remove.append((page_ocr_res_list, need_ocr_res))-- for page_ocr_res_list, need_ocr_res in items_to_remove:- if need_ocr_res in page_ocr_res_list:- page_ocr_res_list.remove(need_ocr_res)---def _validate_text_formula_window_inputs(- images_list: list[dict[str, Any]],- pdf_pages: list[PDFPage],- model_list: list[list[dict[str, Any]]],- images_layout_res: list[list[dict[str, Any]]],-) -> None:- """校验文本公式处理所需的窗口分页数据,避免 zip 静默截断。"""- page_counts = {- "images": len(images_list),- "pdf_pages": len(pdf_pages),- "model_list": len(model_list),- "layout": len(images_layout_res),- }- if len(set(page_counts.values())) != 1:- raise ValueError(f"Hybrid text/formula window page count mismatch: {page_counts}")-- for page_idx, image_dict in enumerate(images_list):- if image_dict.get("img_pil") is None:- raise ValueError(f"Hybrid text/formula window image is missing img_pil: page_idx={page_idx}")- scale = float(image_dict.get("scale", 0) or 0)- if scale <= 0:- raise ValueError(f"Hybrid text/formula window image scale must be positive: page_idx={page_idx}")---def _build_pdf_text_line_spans(pdf_page: PDFPage) -> list[_AnalyzeSpan]:- """将标准方向的 pdftext line 转为私有 span,并复用现有字符清洗规则。"""- page_spans: list[_AnalyzeSpan] = []- for pdf_line in get_lines_from_chars(pdf_page.get_chars()):- try:- rotation = float(pdf_line.get("rotation", 0.0) or 0.0)- except (TypeError, ValueError):- continue- if not _is_supported_rotation(rotation):- continue-- raw_bbox = pdf_line.get("bbox")- bbox = getattr(raw_bbox, "bbox", raw_bbox)- try:- if bbox is None or len(bbox) != 4:- continue- x0, y0, x1, y1 = [float(value) for value in bbox]- except (TypeError, ValueError):- continue- if x1 <= x0 or y1 <= y0:- continue-- content = "".join(str(pdf_span.get("text", "") or "") for pdf_span in pdf_line.get("spans", []))- content = __replace_unicode(content)- content = __replace_ligatures(content).strip()- if not content:- continue-- page_spans.append(- _AnalyzeSpan(- type=ContentType.TEXT,- bbox=(x0, y0, x1, y1),- content=content,- score=1.0,- )- )- return page_spans---def _build_pdf_text_visual_run_spans(pdf_page: PDFPage) -> list[_AnalyzeSpan]:- """将 Low/TXT 原生粗行按 Flash 字符间隙拆成可独立分配的视觉 run。"""-- # 延迟导入避免 Hybrid 模块初始化时提前加载完整 Flash PDF 流水线。- from mineru.model.flash.native_pdf.native_text import _build_native_line_items-- line_items = _build_native_line_items(- get_lines_from_chars(pdf_page.get_chars()),- tuple(float(value) for value in pdf_page.size),- page_rotation=pdf_page.rotation,- supported_angles=_LOW_TXT_VISUAL_RUN_ANGLES,- )- page_spans: list[_AnalyzeSpan] = []- for line_item in line_items:- content = __replace_ligatures(__replace_unicode(line_item.text)).strip()- if not content:- continue- page_spans.append(- _AnalyzeSpan(- type=ContentType.TEXT,- bbox=line_item.bbox,- content=content,- score=1.0,- )- )- return page_spans---def _sidecar_bbox_to_page_bbox(- bbox: BBox | None,- page_size: tuple[float, float],- render_scale: float,-) -> BBox | None:- """将公式或 OCR sidecar bbox 转为 PDF point 坐标,供原生字符匹配和组行。"""- if bbox is None or len(bbox) != 4 or render_scale <= 0:- return None- try:- x0, y0, x1, y1 = [float(value) for value in bbox]- except (TypeError, ValueError):- return None-- page_width, page_height = page_size- if page_width <= 0 or page_height <= 0:- return None- if all(0.0 <= value <= 1.0 for value in [x0, y0, x1, y1]):- x0, y0, x1, y1 = x0 * page_width, y0 * page_height, x1 * page_width, y1 * page_height- else:- x0, y0, x1, y1 = (- x0 / render_scale,- y0 / render_scale,- x1 / render_scale,- y1 / render_scale,- )-- left, right = sorted([max(0.0, min(page_width, x0)), max(0.0, min(page_width, x1))])- top, bottom = sorted([max(0.0, min(page_height, y0)), max(0.0, min(page_height, y1))])- if right <= left or bottom <= top:- return None- return (left, top, right, bottom)---def _detect_table_angle_from_pdf_lines(- pdf_lines: list[dict[str, Any]],- table_bbox: BBox,-) -> int | None:- """统计表格框内标准方向文本行,满足强众数门槛时返回表格角度。"""- angle_counts: Counter[int] = Counter()- for pdf_line in pdf_lines:- try:- raw_bbox = pdf_line.get("bbox")- line_bbox = getattr(raw_bbox, "bbox", raw_bbox)- if line_bbox is None or len(line_bbox) != 4:- continue- x0, y0, x1, y1 = [float(value) for value in line_bbox]- if x1 <= x0 or y1 <= y0:- continue-- line_text = "".join(- str(pdf_span.get("text", "") or "")- for pdf_span in pdf_line.get("spans", [])- ).strip()- if not line_text:- continue-- rotation = float(pdf_line.get("rotation", 0.0) or 0.0)- except (AttributeError, TypeError, ValueError):- continue-- if (- calculate_overlap_area_in_bbox1_area_ratio(- (x0, y0, x1, y1),- table_bbox,- )- <= TABLE_TEXT_LINE_OVERLAP_THRESHOLD- ):- continue- if not _is_supported_rotation(rotation):- continue-- angle = int(round(math.degrees(rotation))) % 360- if angle in TABLE_TEXT_ORIENTATION_ANGLES:- angle_counts[angle] += 1-- valid_line_count = sum(angle_counts.values())- if valid_line_count < TABLE_TEXT_ORIENTATION_MIN_VALID_LINES:- return None-- max_count = max(angle_counts.values())- dominant_angles = [angle for angle, count in angle_counts.items() if count == max_count]- if len(dominant_angles) != 1:- return None- if max_count / valid_line_count < TABLE_TEXT_ORIENTATION_MIN_DOMINANCE_RATIO:- return None- return dominant_angles[0]---def _resolve_txt_table_orientations(- table_items: list[dict[str, Any]],- pdf_pages: list[PDFPage],- images_list: list[dict[str, Any]],-) -> list[dict[str, Any]]:- """优先用原生 PDF 文本行写回表格角度,并返回需要视觉兜底的表格。"""- fallback_table_items: list[dict[str, Any]] = []- page_lines_cache: dict[int, list[dict[str, Any]] | None] = {}-- for table_item in table_items:- page_idx = table_item.get("page_idx")- if (- not isinstance(page_idx, int)- or page_idx < 0- or page_idx >= len(pdf_pages)- or page_idx >= len(images_list)- ):- fallback_table_items.append(table_item)- continue-- try:- pdf_page = pdf_pages[page_idx]- render_scale = float(images_list[page_idx].get("scale", 0) or 0)- table_bbox = _sidecar_bbox_to_page_bbox(- table_item["layout_item"].get("bbox"),- tuple(float(value) for value in pdf_page.size),- render_scale,- )- except Exception as exc:- logger.warning(- "Hybrid txt table orientation falls back to visual model: "- f"page_idx={page_idx}, error={exc}"- )- fallback_table_items.append(table_item)- continue-- if table_bbox is None:- fallback_table_items.append(table_item)- continue-- if page_idx not in page_lines_cache:- try:- page_lines_cache[page_idx] = get_lines_from_chars(pdf_page.get_chars())- except Exception as exc:- logger.warning(- "Hybrid txt table orientation falls back to visual model: "- f"page_idx={page_idx}, error={exc}"- )- page_lines_cache[page_idx] = None-- pdf_lines = page_lines_cache[page_idx]- if pdf_lines is None:- fallback_table_items.append(table_item)- continue-- table_angle = _detect_table_angle_from_pdf_lines(pdf_lines, table_bbox)- if table_angle is None:- fallback_table_items.append(table_item)- continue- table_item["layout_item"]["angle"] = table_angle-- return fallback_table_items---def _apply_table_orientations(- table_items: list[dict[str, Any]],- parse_mode: Literal["txt", "ocr"],- pdf_pages: list[PDFPage],- images_list: list[dict[str, Any]],- hybrid_model: HybridLocalModelContext,-) -> None:- """按解析模式写回表格角度,文本证据不足时批量调用视觉方向模型。"""- if parse_mode == "txt":- fallback_table_items = _resolve_txt_table_orientations(- table_items,- pdf_pages,- images_list,- )- elif parse_mode == "ocr":- fallback_table_items = table_items- else:- raise ValueError(f"Unsupported parse mode: {parse_mode}")-- if not fallback_table_items:- return-- rotate_labels = hybrid_model.table_orientation_cls_model.batch_predict(- fallback_table_items,- det_batch_size=BATCH_RATIO * OCR_DET_BASE_BATCH_SIZE,- tqdm_enable=True,- )- _apply_table_rotate_labels(fallback_table_items, rotate_labels)---def _page_bbox_to_unit_bbox(bbox: BBox, page_size: tuple[float, float]) -> list[float] | None:- """将 PDF point bbox 转为页面级 0-1 坐标,并统一保留三位小数。"""- page_width, page_height = page_size- if page_width <= 0 or page_height <= 0 or len(bbox) != 4:- return None- x0, y0, x1, y1 = [float(value) for value in bbox]- if x1 <= x0 or y1 <= y0:- return None- normalized_bbox = [- round(max(0.0, min(1.0, x0 / page_width)), 3),- round(max(0.0, min(1.0, y0 / page_height)), 3),- round(max(0.0, min(1.0, x1 / page_width)), 3),- round(max(0.0, min(1.0, y1 / page_height)), 3),- ]- if normalized_bbox[2] <= normalized_bbox[0] or normalized_bbox[3] <= normalized_bbox[1]:- return None- return normalized_bbox---def _build_page_text_formula_spans(- page_inline_formula_list: list[dict[str, Any]],- page_ocr_res_list: list[dict[str, Any]],- page_size: tuple[float, float],- render_scale: float,-) -> list[_AnalyzeSpan]:- """将当前页行内公式和 OCR 结果转换为私有 span,供正文与公式共同组行。"""- page_spans: list[_AnalyzeSpan] = []- for formula in page_inline_formula_list:- bbox = _sidecar_bbox_to_page_bbox(formula.get("bbox"), page_size, render_scale)- if bbox is None:- continue- page_spans.append(- _AnalyzeSpan(- type=ContentType.INLINE_EQUATION,- bbox=bbox,- content=str(formula.get("latex", "") or "").strip(),- score=float(formula.get("score", 0.0) or 0.0),- )- )-- for ocr_res in page_ocr_res_list:- bbox = _sidecar_bbox_to_page_bbox(ocr_res.get("bbox"), page_size, render_scale)- if bbox is None:- continue- page_spans.append(- _AnalyzeSpan(- type=ContentType.TEXT,- bbox=bbox,- content=str(ocr_res.get("text", "") or ""),- score=float(ocr_res.get("score", 0.0) or 0.0),- )- )- return page_spans---def _fill_native_pdf_text_spans(- pdf_page: PDFPage,- page_spans: list[_AnalyzeSpan],- page_pil_image: Image.Image,- render_scale: float,- page_size: tuple[float, float],-) -> list[_AnalyzeSpan]:- """复用原生 PDF 字符回填逻辑,并为内容不足的 span 准备后置 OCR 裁图。"""- page_width, page_height = page_size- virtual_block = (0, 0, page_width, page_height, None, None, None, BlockType.TEXT)- return txt_spans_extract(- pdf_page,- page_spans,- page_pil_image,- render_scale,- [virtual_block],- [],- )---def _group_page_spans_by_block(- page_model_list: list[dict[str, Any]],- page_spans: list[_AnalyzeSpan],- page_size: tuple[float, float],- target_block_types: set[str],-) -> dict[int, list[_AnalyzeLine]]:- """按 block 原始顺序消费 span,并使用现有文本修复逻辑形成真实行。"""- span_matcher = SpanBlockMatcher(page_spans)- block_lines: dict[int, list[_AnalyzeLine]] = {}- for block_idx, block_item in enumerate(page_model_list):- block_type = str(block_item.get("type") or block_item.get("label") or "")- if block_type not in target_block_types:- continue- block_bbox = _bbox_to_pixel_bbox(block_item.get("bbox"), page_size)- if block_bbox is None:- block_lines[block_idx] = []- continue-- block_lines[block_idx] = group_spans_to_lines(- span_matcher.collect_for_block(block_bbox)- )- return block_lines---def _apply_window_post_ocr(- local_model_context: HybridLocalModelContext,- page_block_lines_list: list[dict[int, list[_AnalyzeLine]]],-) -> None:- """在当前窗口内识别原生字符不足的 span,保持 finalize 后置 OCR 的回退语义。"""- need_ocr_spans: list[_AnalyzeSpan] = []- img_crop_list: list[np.ndarray] = []- for block_lines in page_block_lines_list:- for lines in block_lines.values():- for line in lines:- for span in line.spans:- if span.image is None:- continue- need_ocr_spans.append(span)- img_crop_list.append(rotate_vertical_crop_if_needed(span.image))- span.image = None-- if not img_crop_list:- return- ocr_res_list = run_ocr_inference(- local_model_context.ocr_model.ocr,- img_crop_list,- det=False,- tqdm_enable=True,- )[0]- if len(ocr_res_list) != len(need_ocr_spans):- raise ValueError(- f"Hybrid post-OCR result count mismatch: ocr_res_list={len(ocr_res_list)}, need_ocr_spans={len(need_ocr_spans)}"- )-- for span, ocr_res in zip(need_ocr_spans, ocr_res_list):- ocr_text, ocr_score = ocr_res- if ocr_score > OcrConfidence.min_confidence:- span.content = ocr_text- span.score = float(f"{ocr_score:.3f}")- _clear_post_ocr_fallback(span)- elif _restore_post_ocr_fallback(span):- continue- else:- span.content = ""- span.score = 0.0---def _line_content_parts(line: _AnalyzeLine) -> list[tuple[str, str]]:- """提取一行内可输出的文本与行内公式,公式统一包装为反斜杠圆括号格式。"""- parts: list[tuple[str, str]] = []- for span in line.spans:- if span.type == ContentType.TEXT:- content = str(span.content or "").strip()- elif span.type == ContentType.INLINE_EQUATION:- latex = str(span.content or "").strip()- content = f"\\({latex}\\)" if latex else ""- else:- continue- if content:- parts.append((span.type, content))- return parts---def _lines_to_block_content(lines: list[_AnalyzeLine], block_type: str) -> str:- """将真实行折叠为统一 block content,保留目录/代码换行并处理自然语言跨行连接。"""- content_lines = [parts for line in lines if (parts := _line_content_parts(line))]- if not content_lines:- return ""-- rendered_lines = [" ".join(content for _, content in parts) for parts in content_lines]- if block_type == BlockType.INDEX or block_type in CODE_CONTENT_BLOCK_TYPES:- return "\n".join(rendered_lines).strip()-- text_for_language = "".join(- content for parts in content_lines for span_type, content in parts if span_type == ContentType.TEXT- )- block_language = detect_lang(text_for_language)- content_parts = [rendered_lines[0]]- for line_idx in range(1, len(rendered_lines)):- current_type, current_content = content_lines[line_idx][0]- next_starts_with_lowercase = (- current_type == ContentType.TEXT- and bool(current_content)- and current_content[0].islower()- )- content_parts[-1], separator = resolve_text_line_boundary(- content_parts[-1],- block_language=block_language,- next_starts_with_lowercase=next_starts_with_lowercase,- )- content_parts.extend([separator, rendered_lines[line_idx]])- return "".join(content_parts).strip()---def _build_ocr_det_line_items(lines: list[_AnalyzeLine], page_size: tuple[float, float]) -> list[dict[str, Any]]:- """将 Analyze 私有行转换为归一化行框。"""- line_items = []- for line in lines:- normalized_bbox = _page_bbox_to_unit_bbox(line.bbox, page_size)- if normalized_bbox is not None:- line_items.append({"bbox": normalized_bbox})- return line_items---def _apply_block_content_and_line_metadata(- page_model_list: list[dict[str, Any]],- block_lines: dict[int, list[_AnalyzeLine]],- page_size: tuple[float, float],-) -> None:- """将组行结果回填到 block,并为正文、视觉标题和视觉脚注保存行框。"""- for block_item in page_model_list:- block_type = str(block_item.get("type") or block_item.get("label") or "")- if block_type in LINE_METADATA_BLOCK_TYPES:- block_item["lines"] = []- else:- block_item.pop("lines", None)-- for block_idx, lines in block_lines.items():- block_item = page_model_list[block_idx]- block_type = str(block_item.get("type") or block_item.get("label") or "")- block_content = block_item.get("content")- has_nonempty_content = bool(block_content.strip()) if isinstance(block_content, str) else bool(block_content)- if not has_nonempty_content:- block_item["content"] = _lines_to_block_content(lines, block_type)-- if block_type in LINE_METADATA_BLOCK_TYPES:- block_item["lines"] = _build_ocr_det_line_items(lines, page_size)---def _fill_window_block_content_and_lines(- images_list: list[dict[str, Any]],- pdf_pages: list[PDFPage],- model_list: list[list[dict[str, Any]]],- inline_formula_list: list[list[dict[str, Any]]],- ocr_res_list: list[list[dict[str, Any]]],- parse_mode: Literal["txt", "ocr"],- ocr_det_type: set[str],- local_model_context: HybridLocalModelContext,-) -> list[list[dict[str, Any]]]:- """按页完成 span 回填与行级元数据构造,返回不含页面级 sidecar 的 model list。"""- page_counts = {- "images": len(images_list),- "pdf_pages": len(pdf_pages),- "model_list": len(model_list),- "inline_formulas": len(inline_formula_list),- "ocr_results": len(ocr_res_list),- }- if len(set(page_counts.values())) != 1:- raise ValueError(f"Hybrid block content page count mismatch: {page_counts}")-- target_block_types = set(ocr_det_type) | TITLE_BLOCK_TYPES | {BlockType.TEXT}- page_block_line_results: list[- tuple[list[dict[str, Any]], dict[int, list[_AnalyzeLine]], tuple[float, float]]- ] = []- for image_dict, pdf_page, page_model_list, page_inline_formula_list, page_ocr_res_list in zip(- images_list,- pdf_pages,- model_list,- inline_formula_list,- ocr_res_list,- ):- page_pil_image = image_dict["img_pil"]- render_scale = float(image_dict["scale"])- page_size = tuple(float(value) for value in pdf_page.size)- page_spans = _build_page_text_formula_spans(- page_inline_formula_list,- page_ocr_res_list,- page_size,- render_scale,- )- if parse_mode == "txt":- page_spans = _fill_native_pdf_text_spans(- pdf_page,- page_spans,- page_pil_image,- render_scale,- page_size,- )-- block_lines = _group_page_spans_by_block(- page_model_list,- page_spans,- page_size,- target_block_types,- )- page_block_line_results.append((page_model_list, block_lines, page_size))-- if parse_mode == "txt":- _apply_window_post_ocr(- local_model_context,- [block_lines for _, block_lines, _ in page_block_line_results],- )-- for page_model_list, block_lines, page_size in page_block_line_results:- _apply_block_content_and_line_metadata(- page_model_list,- block_lines,- page_size,- )- return model_list---def _medium_bbox_to_quad(bbox: list[float] | tuple[float, ...]) -> np.ndarray:- """将普通 bbox 转为表格模型 OCR token 使用的四点框。"""- x0, y0, x1, y1 = [float(v) for v in bbox]- return np.asarray([[x0, y0], [x1, y0], [x1, y1], [x0, y1]], dtype=np.float32)---def _normalize_medium_content(value: Any) -> str:- """将 medium 本地模型输出的文本字段规范成 Hybrid block 可消费的字符串。"""- if isinstance(value, list):- return "\n".join(str(item) for item in value if str(item).strip())- if isinstance(value, str):- return value.strip()- return ""---def _apply_seal_ocr(- local_model_context: HybridLocalModelContext,- model_list: list[list[dict[str, Any]]],- np_images: list[np.ndarray],-) -> None:- """对 medium/high 最终 seal block 逐张执行专用 OCR,并将多段文本按行写回 content。"""- if len(model_list) != len(np_images):- raise ValueError(- "Hybrid seal OCR page count mismatch: "- f"model_list={len(model_list)}, images={len(np_images)}"- )-- seal_tasks: list[tuple[dict[str, Any], np.ndarray]] = []- for page_model_list, np_img in zip(model_list, np_images):- image_h, image_w = np_img.shape[:2]- for block_item in page_model_list:- if (- block_item.get("type") != BlockType.IMAGE- or block_item.get("sub_type") != "seal"- ):- continue-- seal_bbox = normalize_to_int_bbox(- _bbox_to_pixel_bbox(block_item.get("bbox"), (image_w, image_h)),- image_size=(image_h, image_w),- )- if seal_bbox is None:- continue-- x0, y0, x1, y1 = seal_bbox- seal_crop_rgb = np_img[y0:y1, x0:x1]- if seal_crop_rgb.size == 0:- continue-- seal_crop_bgr = cv2.cvtColor(seal_crop_rgb, cv2.COLOR_RGB2BGR)- seal_tasks.append((block_item, seal_crop_bgr))-- if not seal_tasks:- return-- seal_model = local_model_context.seal_model- for block_item, seal_crop_bgr in tqdm(- seal_tasks,- total=len(seal_tasks),- desc="OCR-seal",- ):- seal_ocr_results = seal_model.ocr(seal_crop_bgr)- seal_ocr_result = seal_ocr_results[0] if seal_ocr_results else []-- seal_texts = []- for seal_item in seal_ocr_result or []:- if not isinstance(seal_item, (list, tuple)) or len(seal_item) != 2:- continue- rec_result = seal_item[1]- if not isinstance(rec_result, (list, tuple)) or not rec_result:- continue- seal_text = _normalize_medium_content(rec_result[0])- if seal_text:- seal_texts.append(seal_text)-- seal_content = "\n".join(seal_texts)- if seal_content:- block_item["content"] = seal_content---def _table_bbox_center(bbox: BBox) -> tuple[float, float]:- """计算 bbox 中心点,用于判断图片或公式应归属哪个表格。"""- return (float(bbox[0]) + float(bbox[2])) / 2.0, (float(bbox[1]) + float(bbox[3])) / 2.0---def _table_bbox_intersection(bbox1: BBox, bbox2: BBox) -> BBox | None:- """计算两个 bbox 的有效交集,无重叠时返回 None。"""- x0 = max(float(bbox1[0]), float(bbox2[0]))- y0 = max(float(bbox1[1]), float(bbox2[1]))- x1 = min(float(bbox1[2]), float(bbox2[2]))- y1 = min(float(bbox1[3]), float(bbox2[3]))- if x1 <= x0 or y1 <= y0:- return None- return (x0, y0, x1, y1)---def _select_table_owner(- item_bbox: BBox,- table_entries: list[dict[str, Any]],-) -> dict[str, Any] | None:- """为 low/medium 对象匹配所属表格,多表命中时选择交叠面积最大的表格。"""- center_x, center_y = _table_bbox_center(item_bbox)- candidates: list[tuple[float, dict[str, Any]]] = []- for table_entry in table_entries:- table_bbox = table_entry["table_bbox"]- if not (- float(table_bbox[0]) <= center_x <= float(table_bbox[2])- and float(table_bbox[1]) <= center_y <= float(table_bbox[3])- ):- continue- overlap_bbox = _table_bbox_intersection(item_bbox, table_bbox)- if overlap_bbox is None:- continue- overlap_area = float(overlap_bbox[2] - overlap_bbox[0]) * float(overlap_bbox[3] - overlap_bbox[1])- candidates.append((overlap_area, table_entry))-- if not candidates:- return None- return max(candidates, key=lambda item: item[0])[1]---def _normalize_visual_block_angle(angle: Any) -> int:- """规范视觉块角度为 0/90/180/270,无法识别的角度按 0 处理。"""- try:- normalized_angle = int(float(angle or 0)) % 360- except (TypeError, ValueError):- logger.warning(f"Unsupported visual block angle: {angle}, using 0")- return 0- if normalized_angle not in {0, 90, 180, 270}:- logger.warning(f"Unsupported visual block angle: {angle}, using 0")- return 0- return normalized_angle---def _rotate_visual_block_image_to_upright(image: np.ndarray, angle: int) -> np.ndarray:- """按 layout 视觉块角度把裁图旋转至正向,角度语义与方向分类模型保持一致。"""- if angle == 270:- return cv2.rotate(image, cv2.ROTATE_90_CLOCKWISE)- if angle == 90:- return cv2.rotate(image, cv2.ROTATE_90_COUNTERCLOCKWISE)- if angle == 180:- return cv2.rotate(image, cv2.ROTATE_180)- return image---def _rotate_medium_table_bbox(- bbox: BBox,- image_width: float,- image_height: float,- angle: int,-) -> BBox:- """把原表格裁图中的 bbox 同步转换到旋转后裁图坐标系。"""- x0, y0, x1, y1 = [float(value) for value in bbox]- if angle == 270:- # 顺时针旋转 90 度后,新 x 轴来自原 y 轴的反方向。- return (image_height - y1, x0, image_height - y0, x1)- if angle == 90:- # 逆时针旋转 90 度后,新 y 轴来自原 x 轴的反方向。- return (y0, image_width - x1, y1, image_width - x0)- if angle == 180:- return (image_width - x1, image_height - y1, image_width - x0, image_height - y0)- return (x0, y0, x1, y1)---def _get_medium_table_virtual_image_bbox(- bbox: BBox,- image_size: tuple[int, int],- box_size: float = 10.0,-) -> BBox:- """在图片中心生成小 OCR token 框,避免图片大框干扰单元格匹配。"""- image_width, image_height = image_size- center_x, center_y = _table_bbox_center(bbox)- half_size = box_size / 2.0- return (- max(0.0, center_x - half_size),- max(0.0, center_y - half_size),- min(float(image_width), center_x + half_size),- min(float(image_height), center_y + half_size),- )---def _encode_page_crop_as_jpeg_data_uri(- np_image: np.ndarray,- page_bbox: BBox,- angle: int,-) -> str:- """从页面原图按像素框裁剪,按视觉块方向回正后编码为 JPEG data URI。"""- image_h, image_w = np_image.shape[:2]- image_bbox = normalize_to_int_bbox(page_bbox, image_size=(image_h, image_w))- if image_bbox is None:- return ""- x0, y0, x1, y1 = image_bbox- crop_rgb = np_image[y0:y1, x0:x1].copy()- if crop_rgb.size == 0:- return ""-- crop_rgb = _rotate_visual_block_image_to_upright(crop_rgb, angle)- crop_bgr = cv2.cvtColor(crop_rgb, cv2.COLOR_RGB2BGR)- success, encoded = cv2.imencode(".jpg", crop_bgr)- if not success:- return ""- return f"data:image/jpeg;base64,{base64.b64encode(encoded.tobytes()).decode('ascii')}"---def _normalize_model_bbox_for_containment(raw_bbox: Any) -> BBox | None:- """校验模型 block 的四点框,返回可用于面积包含判断的浮点坐标。"""- try:- if raw_bbox is None or len(raw_bbox) != 4:- return None- bbox = tuple(float(value) for value in raw_bbox)- except (TypeError, ValueError):- return None-- if not all(math.isfinite(value) for value in bbox):- return None- if bbox[2] <= bbox[0] or bbox[3] <= bbox[1]:- return None- return bbox---def _collapse_image_blocks(- page_model_list: list[dict[str, Any]],- containment_threshold: float = IMAGE_BLOCK_CONTAINMENT_THRESHOLD,-) -> None:- """将 image_block 折叠为单个图片,并删除面积上被其包裹的非容器子块。"""- image_blocks = [block for block in page_model_list if block.get("type") == "image_block"]- if not image_blocks:- return-- image_block_ids = {id(block) for block in image_blocks}- image_block_bboxes = [- bbox- for block in image_blocks- if (bbox := _normalize_model_bbox_for_containment(block.get("bbox"))) is not None- ]-- retained_blocks: list[dict[str, Any]] = []- for block in page_model_list:- if id(block) in image_block_ids:- block["type"] = BlockType.IMAGE- retained_blocks.append(block)- continue-- block_bbox = _normalize_model_bbox_for_containment(block.get("bbox"))- is_contained = block_bbox is not None and any(- calculate_overlap_area_in_bbox1_area_ratio(block_bbox, image_block_bbox) >= containment_threshold- for image_block_bbox in image_block_bboxes- )- if not is_contained:- retained_blocks.append(block)-- page_model_list[:] = retained_blocks---def _supplement_missing_image_block_containers(- model_list: list[list[dict[str, Any]]],- layout_blocks_list: list[list[dict[str, Any]]],- containment_threshold: float = IMAGE_BLOCK_CONTAINMENT_THRESHOLD,- coverage_threshold: float = IMAGE_BLOCK_LAYOUT_COVERAGE_THRESHOLD,- min_visual_count: int = IMAGE_BLOCK_LAYOUT_MIN_VISUAL_COUNT,-) -> None:- """用本地 layout 整图框为 xhigh 结果补充缺失的 image_block 容器。"""- if len(model_list) != len(layout_blocks_list):- raise ValueError(- "Hybrid image-block fallback page count mismatch: "- f"model_list={len(model_list)}, layout_blocks={len(layout_blocks_list)}"- )-- for page_model_list, page_layout_blocks in zip(model_list, layout_blocks_list):- existing_image_block_bboxes = [- bbox- for block in page_model_list- if block.get("type") == "image_block"- if (bbox := _normalize_model_bbox_for_containment(block.get("bbox"))) is not None- ]-- existing_claimed_block_ids: set[int] = set()- if existing_image_block_bboxes:- for block in page_model_list:- if block.get("type") == "image_block":- continue- block_bbox = _normalize_model_bbox_for_containment(block.get("bbox"))- if block_bbox is not None and any(- calculate_overlap_area_in_bbox1_area_ratio(block_bbox, image_block_bbox)- >= containment_threshold- for image_block_bbox in existing_image_block_bboxes- ):- existing_claimed_block_ids.add(id(block))-- candidates: list[tuple[int, float, int, int, dict[str, Any], set[int]]] = []- for layout_order, layout_block in enumerate(page_layout_blocks):- if layout_block.get("type") != BlockType.IMAGE or layout_block.get("sub_type") == "seal":- continue-- layout_bbox = _normalize_model_bbox_for_containment(layout_block.get("bbox"))- if layout_bbox is None:- continue- if any(- calculate_overlap_area_2_minbox_area_ratio(layout_bbox, image_block_bbox)- >= containment_threshold- for image_block_bbox in existing_image_block_bboxes- ):- continue-- contained_blocks: list[tuple[int, dict[str, Any], BBox]] = []- for block_index, block in enumerate(page_model_list):- if block.get("type") == "image_block" or id(block) in existing_claimed_block_ids:- continue- block_bbox = _normalize_model_bbox_for_containment(block.get("bbox"))- if block_bbox is None:- continue- if (- calculate_overlap_area_in_bbox1_area_ratio(block_bbox, layout_bbox)- >= containment_threshold- ):- contained_blocks.append((block_index, block, block_bbox))-- contained_visuals = [- (block_index, block)- for block_index, block, _ in contained_blocks- if block.get("type") in LOCAL_LAYOUT_IMAGE_BLOCK_BODY_TYPES- ]- if len(contained_visuals) < min_visual_count:- continue-- layout_area = (layout_bbox[2] - layout_bbox[0]) * (layout_bbox[3] - layout_bbox[1])- contained_area = sum(- (block_bbox[2] - block_bbox[0]) * (block_bbox[3] - block_bbox[1])- for _, block, block_bbox in contained_blocks- if block.get("type") in LOCAL_LAYOUT_IMAGE_BLOCK_AREA_TYPES- )- coverage_ratio = contained_area / layout_area- if coverage_ratio < coverage_threshold and not math.isclose(- coverage_ratio,- coverage_threshold,- rel_tol=0.0,- abs_tol=1e-12,- ):- continue-- contained_block_ids = {id(block) for _, block, _ in contained_blocks}- first_block_index = min(block_index for block_index, _, _ in contained_blocks)- candidates.append(- (- -len(contained_visuals),- layout_area,- layout_order,- first_block_index,- layout_block,- contained_block_ids,- )- )-- claimed_block_ids: set[int] = set()- selected_containers: list[tuple[int, dict[str, Any]]] = []- for _, _, _, first_block_index, layout_block, block_ids in sorted(candidates):- if claimed_block_ids.intersection(block_ids):- continue- claimed_block_ids.update(block_ids)- selected_containers.append(- (- first_block_index,- {- "type": "image_block",- "bbox": list(layout_block["bbox"]),- "angle": layout_block.get("angle", 0),- "content": None,- },- )- )-- for insert_index, image_block in sorted(selected_containers, reverse=True):- page_model_list.insert(insert_index, image_block)---def _attach_visual_block_images(- model_list: list[list[dict[str, Any]]],- images_list: list[dict[str, Any]],- page_start_index: int = 0,-) -> None:- """在窗口页图释放前,为最终 model_list 视觉块写入回正后的页面裁图。"""- if len(model_list) != len(images_list):- raise ValueError(f"Hybrid visual crop page count mismatch: model_list={len(model_list)}, images={len(images_list)}")-- for page_offset, (page_model_list, image_dict) in enumerate(zip(model_list, images_list)):- _collapse_image_blocks(page_model_list)- visual_blocks = [- (block_idx, block)- for block_idx, block in enumerate(page_model_list)- if block.get("type") in MODEL_JSON_VISUAL_BLOCK_TYPES- ]- if not visual_blocks:- continue-- page_index = page_start_index + page_offset- page_pil_image = image_dict.get("img_pil")- if page_pil_image is None:- logger.warning(f"Skipping model visual block crops without page image: page={page_index}")- continue-- converted_page_image = None- try:- if getattr(page_pil_image, "mode", None) == "RGB":- page_rgb_image = page_pil_image- else:- converted_page_image = page_pil_image.convert("RGB")- page_rgb_image = converted_page_image-- page_size = _normalize_page_size(page_rgb_image)- np_image = np.asarray(page_rgb_image)- for block_idx, block in visual_blocks:- try:- pixel_bbox = _bbox_to_pixel_bbox(block.get("bbox"), page_size)- if pixel_bbox is None:- raise ValueError("invalid bbox")- angle = _normalize_visual_block_angle(block.get("angle", 0))- image_base64 = _encode_page_crop_as_jpeg_data_uri(- np_image,- pixel_bbox,- angle,- )- if not image_base64:- raise ValueError("empty crop or JPEG encoding failure")- block["image_base64"] = image_base64- except Exception as exc:- logger.warning(- "Skipping invalid model visual block crop: "- f"page={page_index}, block={block_idx}, type={block.get('type')}, "- f"bbox={block.get('bbox')}, error={exc}"- )- finally:- if converted_page_image is not None:- converted_page_image.close()---def _collect_medium_table_tasks(- model_list: list[list[dict[str, Any]]],- inline_formula_list: list[list[dict[str, Any]]],- np_images: list[np.ndarray],-) -> list[dict[str, Any]]:- """从当前窗口 model_list 收集表格任务,并提前消费表内图片和行内公式。"""- table_tasks: list[dict[str, Any]] = []- for page_idx, (page_model_list, page_inline_formulas, np_image) in enumerate(- zip(model_list, inline_formula_list, np_images)- ):- image_h, image_w = np_image.shape[:2]- page_size = (image_w, image_h)- table_entries: list[dict[str, Any]] = []- for block in page_model_list:- if block.get("type") != BlockType.TABLE:- continue- pixel_bbox = _bbox_to_pixel_bbox(block.get("bbox"), page_size)- table_bbox = normalize_to_int_bbox(pixel_bbox, image_size=(image_h, image_w))- if table_bbox is None:- continue- x0, y0, x1, y1 = table_bbox- table_crop = np_image[y0:y1, x0:x1].copy()- if table_crop.size == 0:- continue- table_entries.append(- {- "table_block": block,- "table_bbox": table_bbox,- "table_crop": table_crop,- "angle": _normalize_visual_block_angle(block.get("angle", 0)),- "inline_objects": [],- }- )-- if not table_entries:- continue-- consumed_image_ids: set[int] = set()- consumed_formula_ids: set[int] = set()- for block in page_model_list:- if block.get("type") != BlockType.IMAGE:- continue- image_bbox = _bbox_to_pixel_bbox(block.get("bbox"), page_size)- if image_bbox is None:- continue- owner = _select_table_owner(image_bbox, table_entries)- if owner is None:- continue- owner["inline_objects"].append(- {- "kind": "image",- "page_bbox": image_bbox,- "score": float(block.get("score", 1.0) or 0.0),- }- )- consumed_image_ids.add(id(block))-- for formula in page_inline_formulas:- latex = _normalize_medium_content(formula.get("latex", ""))- formula_bbox = _bbox_to_pixel_bbox(formula.get("bbox"), page_size)- if formula_bbox is None:- continue- owner = _select_table_owner(formula_bbox, table_entries)- if owner is None:- continue- owner["inline_objects"].append(- {- "kind": "formula",- "page_bbox": formula_bbox,- "latex": latex,- "score": float(formula.get("score", 1.0) or 0.0),- }- )- consumed_formula_ids.add(id(formula))-- # 匹配完成后立即删除原始对象;后续 OCR 或结构识别失败均不回滚。- page_model_list[:] = [block for block in page_model_list if id(block) not in consumed_image_ids]- page_inline_formulas[:] = [formula for formula in page_inline_formulas if id(formula) not in consumed_formula_ids]-- for table_entry in table_entries:- table_bbox = table_entry["table_bbox"]- table_crop = table_entry["table_crop"]- angle = table_entry["angle"]- crop_h, crop_w = table_crop.shape[:2]- rotated_crop = _rotate_visual_block_image_to_upright(table_crop, angle)- rotated_h, rotated_w = rotated_crop.shape[:2]- prepared_objects: list[dict[str, Any]] = []- for inline_object in table_entry["inline_objects"]:- overlap_bbox = _table_bbox_intersection(inline_object["page_bbox"], table_bbox)- if overlap_bbox is None:- continue- relative_bbox = (- float(overlap_bbox[0]) - float(table_bbox[0]),- float(overlap_bbox[1]) - float(table_bbox[1]),- float(overlap_bbox[2]) - float(table_bbox[0]),- float(overlap_bbox[3]) - float(table_bbox[1]),- )- rotated_bbox = _rotate_medium_table_bbox(relative_bbox, crop_w, crop_h, angle)- if inline_object["kind"] == "formula":- latex = inline_object["latex"]- content = f"<eq>{html.escape(latex)}</eq>" if latex else ""- token_bbox = rotated_bbox- else:- image_src = _encode_page_crop_as_jpeg_data_uri(np_image, inline_object["page_bbox"], angle)- content = f'<img src="{image_src}"/>' if image_src else ""- token_bbox = _get_medium_table_virtual_image_bbox(- rotated_bbox,- (rotated_w, rotated_h),- )- prepared_objects.append(- {- **inline_object,- "mask_bbox": rotated_bbox,- "token_bbox": token_bbox,- "content": content,- }- )-- table_tasks.append(- {- "page_idx": page_idx,- "table_block": table_entry["table_block"],- "table_bbox": table_bbox,- "angle": angle,- "table_img": rotated_crop,- "wired_table_img": rotated_crop,- "ocr_result": [],- "table_res": {},- "inline_objects": prepared_objects,- }- )- return table_tasks---def _sort_medium_table_ocr_result(ocr_result: list[list[Any]]) -> None:- """按 token 顶边和左边坐标排序,保证表格 OCR 输入顺序稳定。"""- def sort_key(item: list[Any]) -> tuple[float, float]:- """提取四点框的最小 y/x,兼容普通列表和 numpy 数组。"""- box = np.asarray(item[0], dtype=np.float32).reshape(-1, 2)- return float(np.min(box[:, 1])), float(np.min(box[:, 0]))-- ocr_result.sort(key=sort_key)---def _prepare_medium_table_ocr_results(- local_model_context: HybridLocalModelContext,- table_tasks: list[dict[str, Any]],-) -> None:- """遮盖表内图片和公式后逐表执行 OCR,并合并内联对象 token。"""- table_ocr_model = None- try:- table_ocr_model = local_model_context.get_ocr_model(- det_db_box_thresh=0.5,- det_db_unclip_ratio=1.6,- enable_merge_det_boxes=False,- )- except Exception as exc:- logger.warning(f"Hybrid medium table OCR model initialization failed: {exc}")-- for table_task in table_tasks:- ocr_result: list[list[Any]] = []- bgr_image = cv2.cvtColor(table_task["table_img"], cv2.COLOR_RGB2BGR)- mask_boxes = [{"bbox": item["mask_bbox"]} for item in table_task["inline_objects"]]- masked_image = mask_formula_regions_for_ocr_det(bgr_image, mask_boxes)-- if table_ocr_model is not None:- try:- page_ocr_results = run_ocr_inference(table_ocr_model.ocr, masked_image)- raw_ocr_result = page_ocr_results[0] if page_ocr_results else None- for raw_item in raw_ocr_result or []:- if not raw_item or len(raw_item) < 2:- continue- box, rec_result = raw_item[0], raw_item[1]- if not rec_result or len(rec_result) < 2:- continue- text, score = rec_result[0], rec_result[1]- normalized_text = _normalize_medium_content(text)- if not normalized_text:- continue- ocr_result.append(- [- np.asarray(box, dtype=np.float32),- html.escape(normalized_text),- float(score or 0.0),- ]- )- except Exception as exc:- logger.warning(- f"Hybrid medium table OCR failed: page_idx={table_task['page_idx']}, error={exc}"- )-- for inline_object in table_task["inline_objects"]:- if not inline_object["content"]:- continue- ocr_result.append(- [- _medium_bbox_to_quad(inline_object["token_bbox"]),- inline_object["content"],- inline_object["score"],- ]- )- _sort_medium_table_ocr_result(ocr_result)- table_task["ocr_result"] = ocr_result---def _trim_medium_table_html(html_code: Any) -> str:- """从模型输出中截取核心 table HTML;未带外围标签时保留原字符串。"""- if not isinstance(html_code, str):- return ""- stripped_html = html_code.strip()- lower_html = stripped_html.lower()- start_index = lower_html.find("<table")- end_index = lower_html.rfind("</table>")- if start_index >= 0 and end_index >= start_index:- return stripped_html[start_index : end_index + len("</table>")]- return stripped_html---def _apply_medium_table_recognition(- local_model_context: HybridLocalModelContext,- model_list: list[list[dict[str, Any]]],- inline_formula_list: list[list[dict[str, Any]]],- np_images: list[np.ndarray],-) -> None:- """基于 model_list 执行 medium 表格解析,采用分类 batch、无线 batch、有线单表调度。"""- table_tasks = _collect_medium_table_tasks(model_list, inline_formula_list, np_images)- if not table_tasks:- return-- _prepare_medium_table_ocr_results(local_model_context, table_tasks)-- try:- local_model_context.table_cls_model.batch_predict(table_tasks)- except Exception as exc:- # 分类失败不阻断无线模型,未获得分类结果的表格按 wireless-only 处理。- logger.warning(f"Hybrid medium table classification failed: {exc}")-- try:- local_model_context.wireless_table_model.batch_predict(table_tasks)- except Exception as exc:- logger.warning(f"Hybrid medium wireless table recognition failed: {exc}")-- for table_task in table_tasks:- cls_label = table_task["table_res"].get("cls_label")- try:- cls_score = float(table_task["table_res"].get("cls_score", 0.0) or 0.0)- except (TypeError, ValueError):- cls_score = 0.0- use_wired_model = cls_label == AtomicModel.WiredTable or (- cls_label == AtomicModel.WirelessTable and cls_score < 0.9- )- if use_wired_model:- try:- wireless_html = table_task["table_res"].get("html", "") or ""- wired_html = local_model_context.wired_table_model.predict(- table_task["wired_table_img"],- table_task["ocr_result"],- wireless_html,- )- if wired_html is not None:- table_task["table_res"]["html"] = wired_html- except Exception as exc:- logger.warning(- f"Hybrid medium wired table recognition failed: page_idx={table_task['page_idx']}, error={exc}"- )-- html_code = _trim_medium_table_html(table_task["table_res"].get("html", ""))- if html_code:- table_task["table_block"]["content"] = html_code---def _apply_medium_formula_number_ocr(- local_context: HybridLocalModelContext,- model_list: list[list[dict[str, Any]]],- np_images: list[np.ndarray],-) -> None:- """对 medium formula_number 裁剪图执行 OCR-rec,并把编号文本回填到原始 layout 项。"""- need_rec_items: list[dict[str, Any]] = []- formula_number_crops: list[np.ndarray] = []- for block_list, np_img in zip(model_list, np_images):- image_h, image_w = np_img.shape[:2]- bgr_image = cv2.cvtColor(np_img, cv2.COLOR_RGB2BGR)- for block_item in block_list:- if block_item.get("type") != BlockType.FORMULA_NUMBER:- continue-- formula_number_bbox = normalize_to_int_bbox(- _bbox_to_pixel_bbox(block_item.get("bbox"), (image_w, image_h)),- image_size=(image_h, image_w),- )- if formula_number_bbox is None:- continue-- # 使用 OCR rec 的标准旋转裁剪逻辑,保证 medium 编号裁图与正文 OCR-rec 输入一致。- formula_number_crops.append(- get_rotate_crop_image_for_text_rec(- bgr_image,- _medium_bbox_to_quad(formula_number_bbox).copy(),- )- )- need_rec_items.append(block_item)-- if not formula_number_crops:- return-- ocr_result_list = local_context.ocr_model.ocr(- formula_number_crops,- det=False,- tqdm_enable=True,- tqdm_desc="OCR-rec",- )[0]- if len(ocr_result_list) != len(need_rec_items):- raise ValueError(- "Hybrid medium formula number OCR rec result count mismatch: "- f"ocr_result_list={len(ocr_result_list)}, need_rec_items={len(need_rec_items)}"- )-- for block_item, ocr_result in zip(need_rec_items, ocr_result_list):- if not ocr_result or len(ocr_result) < 2:- continue- ocr_text, _ = ocr_result- normalized_text = _normalize_medium_content(ocr_text)- if normalized_text:- block_item["content"] = normalized_text---def _remove_low_table_inner_blocks(- images_list: list[dict[str, Any]],- model_list: list[list[dict[str, Any]]],-) -> None:- """按表格中心点归属规则移除 low 表内图片、公式和公式编号块。"""- inner_block_types = {- BlockType.IMAGE,- BlockType.EQUATION,- BlockType.FORMULA_NUMBER,- }- for image_dict, page_model_list in zip(images_list, model_list):- page_size = _normalize_page_size(image_dict["img_pil"])- table_entries = []- for block in page_model_list:- if block.get("type") != BlockType.TABLE:- continue- table_bbox = _bbox_to_pixel_bbox(block.get("bbox"), page_size)- if table_bbox is not None:- table_entries.append({"table_bbox": table_bbox})-- if not table_entries:- continue-- retained_blocks = []- for block in page_model_list:- if block.get("type") not in inner_block_types:- retained_blocks.append(block)- continue- block_bbox = _bbox_to_pixel_bbox(block.get("bbox"), page_size)- if block_bbox is None or _select_table_owner(block_bbox, table_entries) is None:- retained_blocks.append(block)- page_model_list[:] = retained_blocks---def _fill_low_table_contents(- images_list: list[dict[str, Any]],- pdf_pages: list[PDFPage],- model_list: list[list[dict[str, Any]]],- parse_mode: Literal["txt", "ocr"],- local_model_context: HybridLocalModelContext,-) -> None:- """为 low 表格回填空间投影纯文本,单表失败时保留空内容并继续。"""- table_entries: list[dict[str, Any]] = []- for page_idx, page_model_list in enumerate(model_list):- table_idx = 0- for block in page_model_list:- if block.get("type") != BlockType.TABLE:- continue- block["content"] = ""- table_entries.append(- {- "page_idx": page_idx,- "table_idx": table_idx,- "block": block,- }- )- table_idx += 1-- if not table_entries:- return-- # 表格一旦认领内部对象便立即从 model_list 删除,后续文本回填失败也不恢复。- _remove_low_table_inner_blocks(images_list, model_list)-- if parse_mode == "txt":- page_chars_cache: dict[int, list[Any]] = {}- for table_entry in table_entries:- page_idx = table_entry["page_idx"]- table_idx = table_entry["table_idx"]- table_block = table_entry["block"]- try:- pdf_page = pdf_pages[page_idx]- page_width, page_height = pdf_page.size- table_bbox = _bbox_to_pixel_bbox(- table_block.get("bbox"),- (int(page_width), int(page_height)),- )- if table_bbox is None:- raise ValueError("invalid table bbox")- if page_idx not in page_chars_cache:- page_chars_cache[page_idx] = pdf_page.get_chars()- table_block["content"] = project_pdf_table_text(- page_chars_cache[page_idx],- table_bbox,- table_block.get("angle", 0),- )- if not table_block["content"]:- logger.warning(- "Hybrid low table text is empty: "- f"parse_mode={parse_mode}, page_idx={page_idx}, "- f"table_idx={table_idx}, bbox={table_block.get('bbox')}"- )- except Exception as exc:- logger.warning(- "Hybrid low table text failed: "- f"parse_mode={parse_mode}, page_idx={page_idx}, "- f"table_idx={table_idx}, bbox={table_block.get('bbox')}, error={exc}"- )- return-- if parse_mode != "ocr":- raise ValueError(f"Unsupported parse mode: {parse_mode}")-- try:- table_ocr_model = local_model_context.get_ocr_model(- det_db_box_thresh=0.5,- det_db_unclip_ratio=1.6,- enable_merge_det_boxes=False,- )- except Exception as exc:- for table_entry in table_entries:- logger.warning(- "Hybrid low table text failed: "- f"parse_mode={parse_mode}, page_idx={table_entry['page_idx']}, "- f"table_idx={table_entry['table_idx']}, "- f"bbox={table_entry['block'].get('bbox')}, "- f"error=OCR model initialization failed: {exc}"- )- return-- page_image_cache: dict[int, np.ndarray] = {}- for table_entry in table_entries:- page_idx = table_entry["page_idx"]- table_idx = table_entry["table_idx"]- table_block = table_entry["block"]- try:- if page_idx not in page_image_cache:- page_image_cache[page_idx] = np.asarray(images_list[page_idx]["img_pil"]).copy()- np_image = page_image_cache[page_idx]- image_height, image_width = np_image.shape[:2]- pixel_bbox = _bbox_to_pixel_bbox(- table_block.get("bbox"),- (image_width, image_height),- )- table_bbox = normalize_to_int_bbox(- pixel_bbox,- image_size=(image_height, image_width),- )- if table_bbox is None:- raise ValueError("invalid table bbox")- x0, y0, x1, y1 = table_bbox- table_crop = np_image[y0:y1, x0:x1].copy()- if table_crop.size == 0:- raise ValueError("empty table crop")-- angle = _normalize_visual_block_angle(table_block.get("angle", 0))- rotated_crop = _rotate_visual_block_image_to_upright(table_crop, angle)- bgr_crop = cv2.cvtColor(rotated_crop, cv2.COLOR_RGB2BGR)- page_ocr_results = run_ocr_inference(table_ocr_model.ocr, bgr_crop)- raw_ocr_result = page_ocr_results[0] if page_ocr_results else None- rotated_height, rotated_width = rotated_crop.shape[:2]- table_block["content"] = project_ocr_table_text(- raw_ocr_result,- (rotated_width, rotated_height),- )- if not table_block["content"]:- logger.warning(- "Hybrid low table text is empty: "- f"parse_mode={parse_mode}, page_idx={page_idx}, "- f"table_idx={table_idx}, bbox={table_block.get('bbox')}"- )- except Exception as exc:- logger.warning(- "Hybrid low table text failed: "- f"parse_mode={parse_mode}, page_idx={page_idx}, "- f"table_idx={table_idx}, bbox={table_block.get('bbox')}, error={exc}"- )---def _process_low_text(- images_list: list[dict[str, Any]],- pdf_pages: list[PDFPage],- model_list: list[list[dict[str, Any]]],- parse_mode: Literal["txt", "ocr"],- local_model_context: HybridLocalModelContext,- images_layout_res: list[list[dict[str, Any]]],-) -> list[list[dict[str, Any]]]:- """使用 pdftext line 或本地 OCR 为 low layout block 填充文本内容。"""- _validate_text_formula_window_inputs(- images_list,- pdf_pages,- model_list,- images_layout_res,- )-- if parse_mode == "txt":- target_block_types = set(PIPELINE_DET_TYPE) | TITLE_BLOCK_TYPES | {BlockType.TEXT}- for pdf_page, page_model_list in zip(pdf_pages, model_list):- page_size = tuple(float(value) for value in pdf_page.size)- block_lines = _group_page_spans_by_block(- page_model_list,- _build_pdf_text_visual_run_spans(pdf_page),- page_size,- target_block_types,- )- _apply_block_content_and_line_metadata(- page_model_list,- block_lines,- page_size,- )- elif parse_mode == "ocr":- images_pil_list = [image_dict["img_pil"] for image_dict in images_list]- np_images = [np.asarray(pil_image).copy() for pil_image in images_pil_list]- empty_formula_list: list[list[dict[str, Any]]] = [[] for _ in model_list]- ocr_res_list = _ocr_det(- local_model_context,- np_images,- model_list,- empty_formula_list,- True,- PIPELINE_DET_TYPE,- )- _apply_ocr_rec_results(local_model_context, ocr_res_list)- model_list = _fill_window_block_content_and_lines(- images_list,- pdf_pages,- model_list,- empty_formula_list,- ocr_res_list,- parse_mode,- PIPELINE_DET_TYPE,- local_model_context,- )- else:- raise ValueError(f"Unsupported parse mode: {parse_mode}")-- _fill_low_table_contents(- images_list,- pdf_pages,- model_list,- parse_mode,- local_model_context,- )- return model_list---def _process_text_and_formulas(- images_list: list[dict[str, Any]],- pdf_pages: list[PDFPage],- model_list: list[list[dict[str, Any]]],- parse_mode: Literal["txt", "ocr"],- effort: Literal["medium", "high", "xhigh"],- local_model_context: HybridLocalModelContext,- images_layout_res: list[list[dict[str, Any]]],-) -> list[list[dict[str, Any]]]:- """在当前窗口内完成 OCR、公式、原生文本及 block 行信息回填。"""-- _validate_text_formula_window_inputs(- images_list,- pdf_pages,- model_list,- images_layout_res,- )- images_pil_list = [image_dict["img_pil"] for image_dict in images_list]-- # 遍历model_list,对文本块截图交由OCR识别- # 根据 parse_mode 和 effort 决定需要ocr的文本块的类型以及只开det还是det+rec- ocr_det_type, mfr_enable = _build_ocr_det_type_and_mfr_enable(- parse_mode=parse_mode,- effort=effort,- )-- # 将PIL图片转换为numpy数组- np_images = [np.asarray(pil_image).copy() for pil_image in images_pil_list]-- mfd_res = _build_formula_inputs(images_layout_res)- images_formula_list = mfd_res- interline_enable = effort == "medium"-- # medium 识别行内和行间公式;high/xhigh 的 txt 路径只识别行内公式。- if mfr_enable:- images_formula_list = local_model_context.mfr_model.batch_predict(- mfd_res,- np_images,- batch_size=BATCH_RATIO * MFR_BASE_BATCH_SIZE,- interline_enable=interline_enable,- )-- inline_formula_list, display_formula_list = _split_formula_results(images_formula_list)- if effort == "medium":- # 表格解析必须早于正文行填充,确保表内图片和行内公式只由表格模型消费一次。- _apply_medium_table_recognition(- local_model_context,- model_list,- inline_formula_list,- np_images,- )- # 将行间公式span回填入block- _apply_medium_display_formula_results(- model_list,- display_formula_list,- images_pil_list,- )- # 使用ocr识别行间公式标号- _apply_medium_formula_number_ocr(- local_model_context,- model_list,- np_images,- )-- # 行间公式标号回填到block- for page_model_list in model_list:- page_model_list[:] = optimize_hybrid_formula_number_blocks(page_model_list)-- need_rec_img = parse_mode == "ocr" and effort == "medium"- # vlm没有执行ocr,需要ocr_det- ocr_res_list = _ocr_det(- local_model_context,- np_images,- model_list,- mfd_res,- need_rec_img,- ocr_det_type,- )-- # 如果有rec_img则做ocr_rec- if need_rec_img:- _apply_ocr_rec_results(local_model_context, ocr_res_list)-- return _fill_window_block_content_and_lines(- images_list,- pdf_pages,- model_list,- inline_formula_list,- ocr_res_list,- parse_mode,- ocr_det_type,- local_model_context,- )---def _collect_layout_doc_title_bboxes(layout_res: list[dict[str, Any]], page_size: tuple[int, int]) -> list[BBox]:- """只收集layout小模型输出的doc_title框,忽略paragraph_title等其他类型。"""- doc_title_bboxes: list[BBox] = []- for layout_item in layout_res or []:- if layout_item.get("label") != BlockType.DOC_TITLE:- continue- bbox = _bbox_to_pixel_bbox(layout_item.get("bbox"), page_size)- if bbox is not None:- doc_title_bboxes.append(bbox)- return doc_title_bboxes---def _has_doc_title_overlap(title_bbox: BBox, doc_title_bboxes: list[BBox], overlap_threshold: float) -> bool:- """判断VLM标题框是否与任一layout doc_title框达到最小框重叠阈值。"""- return any(- calculate_overlap_area_2_minbox_area_ratio(title_bbox, doc_title_bbox) >= overlap_threshold- for doc_title_bbox in doc_title_bboxes- )---def _apply_layout_title_split(- model_list: list[list[dict[str, Any]]],- images_layout_res: list[list[dict[str, Any]]],- page_sizes: list[tuple[int, int]],- overlap_threshold: float = LAYOUT_TITLE_SPLIT_OVERLAP_THRESHOLD,-) -> None:- """用layout doc_title框将VLM title拆分为doc_title和paragraph_title。"""- for page_model_list, layout_res, page_size in zip(model_list, images_layout_res, page_sizes):- doc_title_bboxes = _collect_layout_doc_title_bboxes(layout_res, page_size)- for block in page_model_list:- if block.get("type") != _VLM_UNCLASSIFIED_TITLE_TYPE:- continue- title_bbox = _bbox_to_pixel_bbox(block.get("bbox"), page_size)- if title_bbox is None:- continue- if _has_doc_title_overlap(title_bbox, doc_title_bboxes, overlap_threshold):- block["type"] = BlockType.DOC_TITLE- else:- block["type"] = BlockType.PARAGRAPH_TITLE---def _is_valid_pdf_text_block(block: dict[str, Any]) -> bool:- """检查 PDF 文本块是否同时具有非空正文和完整合法的归一化行框。"""-- content = block.get("content")- if not isinstance(content, str) or not content.strip():- return False-- lines = block.get("lines")- if not isinstance(lines, list) or not lines:- return False- for line in lines:- if not isinstance(line, dict):- return False- bbox = line.get("bbox")- if not isinstance(bbox, (list, tuple)) or len(bbox) != 4:- return False- if any(- not isinstance(value, (int, float))- or isinstance(value, bool)- or not math.isfinite(float(value))- for value in bbox- ):- return False- x0, y0, x1, y1 = [float(value) for value in bbox]- if (- not all(0.0 <= value <= 1.0 for value in (x0, y0, x1, y1))- or x1 <= x0- or y1 <= y0- ):- return False- return True---def _normalize_natural_language_content(content: str) -> str:- """将自然语言中的全角字母和数字转为半角,同时原样保留行内公式片段。"""- normalized_parts: list[str] = []- cursor = 0- formula_markers = (("\\(", "\\)"), ("<eq>", "</eq>"))-- while cursor < len(content):- formula_starts = [- (start, opening, closing)- for opening, closing in formula_markers- if (start := content.find(opening, cursor)) >= 0- ]- if not formula_starts:- normalized_parts.append(full_to_half_exclude_marks(content[cursor:]))- break-- formula_start, opening, closing = min(formula_starts, key=lambda item: item[0])- normalized_parts.append(full_to_half_exclude_marks(content[cursor:formula_start]))- formula_end = content.find(closing, formula_start + len(opening))- if formula_end < 0:- normalized_parts.append(content[formula_start:])- break-- formula_end += len(closing)- normalized_parts.append(content[formula_start:formula_end])- cursor = formula_end-- return "".join(normalized_parts)+from loguru import logger+from mineru.backend.analysis.contracts import AnalyzeEffort, OfficeSuffix, ParseMode+from mineru.backend.analysis.office import analyze_office+from mineru.backend.analysis.pdf.pipeline import analyze_pdf+from mineru.backend.postprocess.pages import model_list_to_pages+from mineru.types import MiddleJson+from mineru.version import __version__ as mineru_version-def _normalize_pdf_model_list(model_list: list[list[dict[str, Any]]]) -> None:- """清理 PDF block 元数据、规范公式,并过滤正文或行框无效的文本块。"""- for page_idx, page_model_list in enumerate(model_list):- for block_idx, block in enumerate(page_model_list):- raw_type = block.get("type")- if raw_type == RAW_PHONETIC:- block["type"] = BlockType.TEXT- elif raw_type == BlockType.EQUATION:- equation_content = block.get("content")- if isinstance(equation_content, str):- if equation_content.startswith("\\["):- equation_content = equation_content[2:]- if equation_content.endswith("\\]"):- equation_content = equation_content[:-2]- block["content"] = equation_content.strip()- elif raw_type == _VLM_UNCLASSIFIED_TITLE_TYPE:- raise ValueError(- "Unclassified PDF title block: "- f"page_idx={page_idx}, block_idx={block_idx}"- )- block.pop("angle", None)- block.pop("score", None)- content = block.get("content")- if not isinstance(content, str):- continue- if block.get("type") in NATURAL_LANGUAGE_CONTENT_BLOCK_TYPES:- content = _normalize_natural_language_content(content)- block["content"] = _INLINE_FORMULA_PATTERN.sub(- lambda match: f"<eq>{match.group(1)}</eq>",- content,- )- page_model_list[:] = [- block- for block in page_model_list- if block.get("type") not in LINE_METADATA_BLOCK_TYPES- or _is_valid_pdf_text_block(block)- ]+_SUPPORTED_FILE_SUFFIXES = {"pdf", "docx", "pptx", "xlsx"}def _log_infer_performance(file_suffix: str, page_count: int, elapsed: float) -> None:- """使用未舍入耗时统一记录 model_list 生产阶段的处理速度。"""+ """使用未舍入耗时统一记录 model-list 生产速度。"""speed = page_count / elapsed if elapsed > 0 else 0.0logger.debug(f"model_list infer finished, file_suffix={file_suffix}, pages={page_count}, "@@ -2603,230 +34,26 @@ def doc_analyze(page_index_map: list[int] | None = None,file_suffix: Literal["pdf", "docx", "pptx", "xlsx"] = "pdf",) -> tuple[MiddleJson, list[list[dict[str, Any]]]]:+ """生产 model-list,并在统一边界构造严格 MiddleJson。"""if file_suffix not in _SUPPORTED_FILE_SUFFIXES:raise ValueError(f"Unsupported file suffix: {file_suffix!r}")- if file_suffix in _OFFICE_MODEL_MAP:- # Office Converter 直接产出完整 model_list,固定按 Flash TXT 模式处理。- effort = "flash"- parse_mode = "txt"- file_stream = BytesIO(file_bytes)- office_model = _OFFICE_MODEL_MAP[file_suffix]()- infer_started_at = time.perf_counter()- model_list = office_model.predict(file_stream)- infer_elapsed = time.perf_counter() - infer_started_at+ if file_suffix == "pdf":+ result = analyze_pdf(+ file_bytes,+ effort=cast(AnalyzeEffort, effort),+ parse_mode=cast(ParseMode, parse_mode),+ image_analysis=image_analysis,+ )else:- document = PDFDocument(file_bytes)- document_closed = False- model_list: list[list[dict[str, Any]]] = []- try:- if parse_mode == "auto":- parse_mode = document.classify()- if parse_mode not in ["txt", "ocr"]:- raise ValueError(f"parse_mode {parse_mode} is not supported")+ result = analyze_office(file_bytes, cast(OfficeSuffix, file_suffix))- # Flash 只处理原生文本,OCR 文档继续复用 Hybrid low 流程。- if effort == "flash" and parse_mode == "ocr":- effort = "low"-- flash_txt_mode = effort == "flash" and parse_mode == "txt"- page_count = document.page_count- hybrid_model = None-- if not flash_txt_mode:- hybrid_model_singleton = HybridLocalModelContextSingleton()- hybrid_model = hybrid_model_singleton.get_model()-- if effort in ["high", "xhigh"]:- vlm_runtime = _load_vlm_runtime()- vlm_backend = get_vlm_engine(inference_engine="auto", is_async=False)- vlm_predictor = vlm_runtime["ModelSingleton"]().get_model(- backend=vlm_backend,- model_path=None,- server_url=None,- )- vlm_predictor = vlm_runtime["_maybe_enable_serial_execution"](vlm_predictor, vlm_backend)- else:- vlm_predictor = None-- infer_started_at = time.perf_counter()- if flash_txt_mode:- # Flash 先对整份 PDF 生成完整 model_list,不依赖页面渲染和处理窗口。- from mineru.model.flash import PdfModel-- model_list = PdfModel().predict(document)-- configured_window_size = get_processing_window_size(default=64)- windows = _build_processing_windows(page_count, configured_window_size)- _log_processing_window_plan(page_count, configured_window_size, len(windows))-- for window in windows:- window_pages = _get_window_pdf_pages(document, window)- images_list = load_images_from_pdf_bytes_range(- pdf_bytes=file_bytes,- start_page_id=window.start,- end_page_id=window.end,- image_type="pil_img",- )- try:- if len(window_pages) != len(images_list):- raise ValueError("Hybrid processing window PDF page count does not match image count")- images_pil_list = [image_dict["img_pil"] for image_dict in images_list]- _log_processing_window(window, page_count, len(images_pil_list))-- if flash_txt_mode:- # Flash 仅切割当前窗口的外层列表,用于页图释放前原地补充视觉块裁图。- window_model_list = model_list[window.start : window.end + 1]- else:- np_images = [np.asarray(pil_image).copy() for pil_image in images_pil_list]- images_layout_res = hybrid_model.layout_model.batch_predict(- images_pil_list, batch_size=min(8, BATCH_RATIO * LAYOUT_BASE_BATCH_SIZE)- )-- # 使用小模型layout时对layout的表格做旋转检测- if effort in ["low", "medium", "high"]:- table_items = _collect_table_items(images_layout_res, np_images)- if table_items:- _apply_table_orientations(- table_items,- parse_mode,- window_pages,- images_list,- hybrid_model,- )-- vl_style_layout_blocks = _build_vl_style_layout_blocks(images_layout_res, images_pil_list)-- if parse_mode == "txt":- if effort in ["low", "medium"]:- window_model_list = vl_style_layout_blocks- elif effort == "high":- window_model_list = vlm_predictor.batch_extract_with_layout(- images=images_pil_list,- blocks_list=vl_style_layout_blocks,- not_extract_list=NOT_EXTRACT_TYPES,- image_analysis=False,- )- elif effort == "xhigh":- window_model_list = vlm_predictor.batch_two_step_extract(- images=images_pil_list,- not_extract_list=NOT_EXTRACT_TYPES,- image_analysis=image_analysis,- )- else:- raise ValueError(f"Unsupported analyze effort: {effort}")- elif parse_mode == "ocr":- if effort in ["low", "medium"]:- window_model_list = vl_style_layout_blocks- elif effort == "high":- window_model_list = vlm_predictor.batch_extract_with_layout(- images=images_pil_list,- blocks_list=vl_style_layout_blocks,- image_analysis=False,- )- elif effort == "xhigh":- window_model_list = vlm_predictor.batch_two_step_extract(- images=images_pil_list,- image_analysis=image_analysis,- )- else:- raise ValueError(f"Unsupported analyze effort: {effort}")- else:- raise ValueError(f"Unsupported parse mode: {parse_mode}")-- if effort in {"high", "xhigh"}:- window_model_list = _convert_vlm_results_to_model_list(window_model_list)- if effort == "xhigh":- _normalize_xhigh_vlm_blocks(window_model_list)- _apply_layout_title_split(- window_model_list,- images_layout_res,- [_normalize_page_size(image) for image in images_pil_list],- )-- if effort == "low":- window_model_list = _process_low_text(- images_list,- window_pages,- window_model_list,- parse_mode,- hybrid_model,- images_layout_res,- )- else:- window_model_list = _process_text_and_formulas(- images_list,- window_pages,- window_model_list,- parse_mode,- effort,- hybrid_model,- images_layout_res,- )-- if effort in {"medium", "high"}:- _apply_seal_ocr(hybrid_model, window_model_list, np_images)- elif effort == "xhigh":- _supplement_missing_image_block_containers(- window_model_list,- vl_style_layout_blocks,- )-- _attach_visual_block_images(- window_model_list,- images_list,- page_start_index=window.start,- )- if not flash_txt_mode:- model_list.extend(window_model_list)- finally:- _close_images(images_list)-- # 仅 PDF 模型结果需要统一清理块元数据并规范化行内公式。- _normalize_pdf_model_list(model_list)- infer_elapsed = time.perf_counter() - infer_started_at-- document.close()- document_closed = True- if hybrid_model is not None:- clean_memory(hybrid_model.device)- finally:- if not document_closed:- document.close()-- _log_infer_performance(file_suffix, len(model_list), infer_elapsed)-- # PDF 与 Office 的 model_list 在此汇合,后续统一生产 Middle JSON。+ _log_infer_performance(file_suffix, len(result.model_list), result.elapsed)middle_json = MiddleJson(- pages=model_list_to_pages(model_list, page_index_map),+ pages=model_list_to_pages(result.model_list, page_index_map),file_suffix=file_suffix,- effort=effort,- parse_mode=parse_mode,+ effort=result.effort,+ parse_mode=result.parse_mode,mineru_version=mineru_version,)- return middle_json, model_list---if __name__ == "__main__":- import json-- # 根据当前文件位置定位项目根目录,读取 demo 下的 PDF 和 Office 样例。- project_root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))- demo_file_paths = [- # os.path.join(project_root, "demo", "office_docs", "docx_01.docx"),- # os.path.join(project_root, "demo", "pdfs", "NPU_开发环境部署_参考指南.pdf"),- # "/Users/myhloli/pdf/png/2407.00079v4_origi-10.pdf",- "/Users/myhloli/pdf/跨页表格/跨页单元格3.pdf",- # os.path.join(project_root, "demo", "pdfs", "demo1.pdf"),- ]-- for file_path in demo_file_paths:- file_bytes = open(file_path, "rb").read()- file_suffix = os.path.splitext(file_path)[1].lstrip(".").lower()- file_suffix = "pdf"- middle_json, model_list = doc_analyze(file_bytes, effort="high", file_suffix=file_suffix)- model_json = json.dumps(model_list, ensure_ascii=False, indent=4)- logger.info(f"file_path: {file_path}")- logger.info(f"middle_json: {middle_json}")- logger.info(f"model_json: {model_json}")- logger.info(f"model_list: {model_list}")+ return middle_json, result.model_listdiff --git a/mineru/backend/local_model_runtime.py b/mineru/backend/local_model_runtime.pyindex 804bd60f..9d0c40db 100644--- a/mineru/backend/local_model_runtime.py+++ b/mineru/backend/local_model_runtime.py@@ -1,6 +1,6 @@+# Copyright (c) Opendatalab. All rights reserved."""Hybrid 与本地小模型共享的运行时初始化模块。"""-# Copyright (c) Opendatalab. All rights reserved.from __future__ import annotationsimport os@@ -12,6 +12,7 @@ from typing import Anyimport torchfrom loguru import logger+from ..model.model_types import AtomicModelNamefrom ..model.layout.pp_doclayoutv2 import PPDocLayoutV2LayoutModelfrom ..model.mfr.pp_formulanet_plus_m.predict_formula import FormulaRecognizerfrom ..model.mfr.unimernet.Unimernet import UnimernetModel@@ -25,18 +26,6 @@ from ..utils.enum_class import ModelPathfrom ..utils.models_download_utils import auto_download_and_get_model_root_pathfrom ..utils.ocr_language import normalize_ocr_model_lang--class AtomicModel:- """本地原子模型名称集合,供 Hybrid medium 和共享模型单例统一索引。"""-- Layout = "layout"- MFR = "mfr"- OCR = "ocr"- WirelessTable = "wireless_table"- WiredTable = "wired_table"- TableCls = "table_cls"- TableOrientationCls = "table_ori_cls"-LOCAL_MODEL_INIT_LOCK = threading.RLock()# 这些锁保护 Hybrid medium/high/extra_high 共享的 atom model/native 模型推理调用,避免多线程同时进入同一个模型对象。LOCAL_MODEL_LAYOUT_INFERENCE_LOCK = threading.RLock()@@ -109,9 +98,10 @@ def _resolve_mfr_model_path() -> str:def table_orientation_cls_model_init() -> MineruTableOrientationClsModel:+ """初始化表格方向分类包装器,并注入适配方向检测的 OCR 引擎。"""atom_model_manager = AtomModelSingleton()ocr_engine = atom_model_manager.get_atom_model(- atom_model_name=AtomicModel.OCR,+ atom_model_name=AtomicModelName.OCR,det_db_box_thresh=0.5,det_db_unclip_ratio=1.6,lang="ch",@@ -122,28 +112,40 @@ def table_orientation_cls_model_init() -> MineruTableOrientationClsModel:def table_cls_model_init() -> PaddleTableClsModel:+ """初始化有线与无线表格类型分类模型。"""return PaddleTableClsModel()def wired_table_model_init(lang: str | None = None) -> UnetTableModel:+ """初始化有线表格识别模型,并注入指定语言的 OCR 引擎。"""atom_model_manager = AtomModelSingleton()ocr_engine = atom_model_manager.get_atom_model(- atom_model_name=AtomicModel.OCR, det_db_box_thresh=0.5, det_db_unclip_ratio=1.6, lang=lang, enable_merge_det_boxes=False+ atom_model_name=AtomicModelName.OCR,+ det_db_box_thresh=0.5,+ det_db_unclip_ratio=1.6,+ lang=lang,+ enable_merge_det_boxes=False,)table_model = UnetTableModel(ocr_engine)return table_modeldef wireless_table_model_init(lang: str | None = None) -> PaddleTableModel:+ """初始化无线表格识别模型,并注入指定语言的 OCR 引擎。"""atom_model_manager = AtomModelSingleton()ocr_engine = atom_model_manager.get_atom_model(- atom_model_name=AtomicModel.OCR, det_db_box_thresh=0.5, det_db_unclip_ratio=1.6, lang=lang, enable_merge_det_boxes=False+ atom_model_name=AtomicModelName.OCR,+ det_db_box_thresh=0.5,+ det_db_unclip_ratio=1.6,+ lang=lang,+ enable_merge_det_boxes=False,)table_model = PaddleTableModel(ocr_engine)return table_modeldef mfr_model_init(weight_dir: str, device: str | torch.device = "cpu") -> UnimernetModel | FormulaRecognizer:+ """根据公式模型配置和权重目录初始化对应的公式识别器。"""if MFR_MODEL == "unimernet_small":mfr_model = UnimernetModel(weight_dir, device)elif MFR_MODEL == "pp_formulanet_plus_m":@@ -155,6 +157,7 @@ def mfr_model_init(weight_dir: str, device: str | torch.device = "cpu") -> Unimedef pp_doclayout_v2_model_init(weight: str, device: str | torch.device = "cpu") -> PPDocLayoutV2LayoutModel:+ """在指定设备上初始化 PP-DocLayoutV2 版面分析模型。"""if str(device).startswith("npu"):device = torch.device(device)model = PPDocLayoutV2LayoutModel(weight, device)@@ -167,6 +170,7 @@ def ocr_model_init(det_db_unclip_ratio: float = 1.5,enable_merge_det_boxes: bool = True,) -> PytorchPaddleOCR:+ """按语言和检测阈值初始化本地 Paddle OCR 模型。"""ocr_kwargs = {"lang": normalize_ocr_model_lang(lang),"det_db_box_thresh": det_db_box_thresh,@@ -177,23 +181,27 @@ def ocr_model_init(class AtomModelSingleton:+ """按模型配置缓存并复用本地原子模型实例。"""+_instance: AtomModelSingleton | None = None_models: dict[object, object] = {}_lock: threading.RLock = LOCAL_MODEL_INIT_LOCKdef __new__(cls, *args: Any, **kwargs: Any) -> AtomModelSingleton:+ """在线程锁保护下创建或返回唯一的原子模型管理器。"""with cls._lock:if cls._instance is None:cls._instance = super().__new__(cls)return cls._instancedef get_atom_model(self, atom_model_name: str, **kwargs: Any) -> Any:+ """根据模型名称和关键配置生成缓存键,并获取对应原子模型。"""lang = kwargs.get("lang", None)ocr_singleton_lang = normalize_ocr_model_lang(lang)- if atom_model_name in [AtomicModel.WiredTable, AtomicModel.WirelessTable]:+ if atom_model_name in [AtomicModelName.WiredTable, AtomicModelName.WirelessTable]:key = (atom_model_name, ocr_singleton_lang)- elif atom_model_name in [AtomicModel.OCR]:+ elif atom_model_name in [AtomicModelName.OCR]:key = (atom_model_name,kwargs.get("det_db_box_thresh", 0.5),@@ -201,7 +209,7 @@ class AtomModelSingleton:kwargs.get("det_db_unclip_ratio", 1.5),kwargs.get("enable_merge_det_boxes", True),)- elif atom_model_name in [AtomicModel.Layout, AtomicModel.MFR]:+ elif atom_model_name in [AtomicModelName.Layout, AtomicModelName.MFR]:key = (atom_model_name,kwargs.get("device"),@@ -216,29 +224,30 @@ class AtomModelSingleton:def atom_model_init(model_name: str, **kwargs: Any) -> Any:+ """将原子模型名称分派到具体初始化函数,并校验初始化结果。"""atom_model = None- if model_name == AtomicModel.Layout:+ if model_name == AtomicModelName.Layout:atom_model = pp_doclayout_v2_model_init(kwargs.get("pp_doclayout_v2_weights"), kwargs.get("device"))- elif model_name == AtomicModel.MFR:+ elif model_name == AtomicModelName.MFR:atom_model = mfr_model_init(kwargs.get("mfr_weight_dir"), kwargs.get("device"))- elif model_name == AtomicModel.OCR:+ elif model_name == AtomicModelName.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),)- elif model_name == AtomicModel.WirelessTable:+ elif model_name == AtomicModelName.WirelessTable:atom_model = wireless_table_model_init(kwargs.get("lang"),)- elif model_name == AtomicModel.WiredTable:+ elif model_name == AtomicModelName.WiredTable:atom_model = wired_table_model_init(kwargs.get("lang"),)- elif model_name == AtomicModel.TableCls:+ elif model_name == AtomicModelName.TableCls:atom_model = table_cls_model_init()- elif model_name == AtomicModel.TableOrientationCls:+ elif model_name == AtomicModelName.TableOrientationCls:atom_model = table_orientation_cls_model_init()else:logger.error("model name not allow")@@ -252,11 +261,14 @@ def atom_model_init(model_name: str, **kwargs: Any) -> Any:class HybridLocalModelContextSingleton:+ """全局缓存并复用 Hybrid 本地模型上下文。"""+_instance: HybridLocalModelContextSingleton | None = None_model: HybridLocalModelContext | None = None_lock: threading.RLock = LOCAL_MODEL_INIT_LOCKdef __new__(cls, *args: Any, **kwargs: Any) -> HybridLocalModelContextSingleton:+ """在线程锁保护下创建或返回唯一的上下文管理器。"""with cls._lock:if cls._instance is None:cls._instance = super().__new__(cls)@@ -273,6 +285,7 @@ class HybridLocalModelContextSingleton:def ocr_det_batch_setting() -> bool:+ """根据运行设备和 PyTorch 版本确定是否启用 OCR 检测批处理。"""import torch as _torchfrom packaging import version@@ -288,6 +301,8 @@ def ocr_det_batch_setting() -> bool:class HybridLocalModelContext:+ """集中管理 Hybrid 分析所需本地模型及其惰性加载生命周期。"""+def __init__(self,device: str | None = None,@@ -358,7 +373,7 @@ class HybridLocalModelContext:) -> PytorchPaddleOCR:"""获取 OCR 原子模型,默认使用当前 Hybrid 本地上下文语言并复用 singleton 缓存。"""return self.atom_model_manager.get_atom_model(- atom_model_name=AtomicModel.OCR,+ atom_model_name=AtomicModelName.OCR,det_db_box_thresh=det_db_box_thresh,lang="ch",det_db_unclip_ratio=det_db_unclip_ratio,@@ -368,7 +383,7 @@ class HybridLocalModelContext:def get_layout_model(self) -> PPDocLayoutV2LayoutModel:"""获取 Layout 原子模型,供 Hybrid 本地 layout、标题拆分和公式框检测复用。"""return self.atom_model_manager.get_atom_model(- atom_model_name=AtomicModel.Layout,+ atom_model_name=AtomicModelName.Layout,pp_doclayout_v2_weights=str(os.path.join(auto_download_and_get_model_root_path(ModelPath.pp_doclayout_v2),@@ -382,7 +397,7 @@ class HybridLocalModelContext:"""获取公式识别原子模型,统一复用当前公式模型配置和设备。"""mfr_model_path = _resolve_mfr_model_path()return self.atom_model_manager.get_atom_model(- atom_model_name=AtomicModel.MFR,+ atom_model_name=AtomicModelName.MFR,mfr_weight_dir=str(os.path.join(auto_download_and_get_model_root_path(mfr_model_path), mfr_model_path)),device=self.device,)@@ -390,32 +405,32 @@ class HybridLocalModelContext:def get_wireless_table_model(self) -> PaddleTableModel:"""获取无线表格识别原子模型。"""return self.atom_model_manager.get_atom_model(- atom_model_name=AtomicModel.WirelessTable,+ atom_model_name=AtomicModelName.WirelessTable,lang="ch",)def get_wired_table_model(self) -> UnetTableModel:"""获取有线表格识别原子模型。"""return self.atom_model_manager.get_atom_model(- atom_model_name=AtomicModel.WiredTable,+ atom_model_name=AtomicModelName.WiredTable,lang="ch",)def get_table_cls_model(self) -> PaddleTableClsModel:"""获取表格分类原子模型。"""return self.atom_model_manager.get_atom_model(- atom_model_name=AtomicModel.TableCls,+ atom_model_name=AtomicModelName.TableCls,)def get_table_orientation_cls_model(self) -> MineruTableOrientationClsModel:"""获取表格方向分类原子模型。"""return self.atom_model_manager.get_atom_model(- atom_model_name=AtomicModel.TableOrientationCls,+ atom_model_name=AtomicModelName.TableOrientationCls,)def get_seal_ocr_model(self) -> PytorchPaddleOCR:"""获取印章识别 OCR 原子模型"""return self.atom_model_manager.get_atom_model(- atom_model_name=AtomicModel.OCR,+ atom_model_name=AtomicModelName.OCR,lang="seal",)diff --git a/mineru/backend/magic_model.py b/mineru/backend/magic_model.pydeleted file mode 100644index 319bdc76..00000000--- a/mineru/backend/magic_model.py+++ /dev/null@@ -1,406 +0,0 @@-# Copyright (c) Opendatalab. All rights reserved.-import re-from typing import Any--from mineru.backend.utils.boxbase import calculate_overlap_area_in_bbox1_area_ratio-from mineru.backend.utils.raw_block_types import (- RAW_ALGORITHM,- RAW_CAPTION,- RAW_FOOTNOTE,-)-from mineru.backend.utils.visual_magic_model_utils import (- code_content_clean,- isolated_formula_clean,- clean_content,- _bbox_for_calculation,- regroup_visual_blocks,- fallback_inline_caption_fragments,- fallback_leading_table_continuation_captions,- fallback_no_bbox_caption_fragments,-)-from mineru.types import BlockType, VISUAL_MAIN_TYPES-from mineru.utils.guess_suffix_or_lang import guess_language_by_text---def _has_inline_formula_content(content: str | None) -> bool:- """判断 content 是否包含成对 <eq> 行内公式标记,用于 code/algorithm 分类。"""- return bool(content) and content.count("<eq>") == content.count("</eq>") and content.count("<eq>") > 0---class MagicModel:- def __init__(- self,- page_model_list: list[dict[str, Any]],- *,- use_bbox: bool | None = None,- ) -> None:- self.blocks = []- is_block_has_bbox = (- any(block_info.get("bbox") for block_info in page_model_list)- if use_bbox is None- else use_bbox- )- # 解析每个块- for index, block_info in enumerate(page_model_list):- code_block_sub_type = None- block_type = block_info.get("type", "")- block_content = block_info.get("content", "")-- if block_type == "image":- block_type = BlockType.IMAGE_BODY- elif block_type == "table":- block_type = BlockType.TABLE_BODY- elif block_type == "chart":- block_type = BlockType.CHART_BODY- elif block_type in [BlockType.CODE, RAW_ALGORITHM]:- code_block_sub_type = block_type- block_content = code_content_clean(block_content)- block_type = BlockType.CODE_BODY- elif block_type == BlockType.EQUATION:- block_content = isolated_formula_clean(block_content)-- if block_type not in [BlockType.IMAGE_BODY, BlockType.TABLE_BODY, BlockType.CHART_BODY]:- # 文本类块继续沿用现有 content 清洗规则,但不再拆分为 line/span。- if block_content:- block_content = clean_content(block_content) or ""- # 对于标题类块,去除换行符和多余空格- if block_type in [BlockType.DOC_TITLE, BlockType.PARAGRAPH_TITLE] and block_content:- block_content = re.sub(r"\n\s*", " ", block_content).strip()- # 处理 code/algorithm 分类的特殊情况:如果 code 类型的块中包含成对的行内公式标记,则将其分类为 algorithm。- if (- block_type == BlockType.CODE_BODY- and code_block_sub_type == "code"- and _has_inline_formula_content(block_content)- ):- code_block_sub_type = "algorithm"-- block = block_info- block["type"] = block_type- block["content"] = block_content- block["index"] = index- if code_block_sub_type:- block["sub_type"] = code_block_sub_type- self.blocks.append(block)-- if is_block_has_bbox:- fallback_inline_caption_fragments(self.blocks, VISUAL_MAIN_TYPES)- fallback_leading_table_continuation_captions(self.blocks, VISUAL_MAIN_TYPES)- else:- fallback_no_bbox_caption_fragments(self.blocks, VISUAL_MAIN_TYPES)--- self.text_blocks = []- self.ref_text_blocks = []- self.list_blocks = []- self.index_blocks = []-- for block in self.blocks:- if block["type"] == BlockType.TEXT:- self.text_blocks.append(block)- elif block["type"] == BlockType.REF_TEXT:- self.ref_text_blocks.append(block)- elif block["type"] == BlockType.LIST:- self.list_blocks.append(block)- elif block["type"] == BlockType.INDEX:- self.index_blocks.append(block)-- if is_block_has_bbox:- self.list_blocks, self.text_blocks, self.ref_text_blocks = fix_pdf_list_blocks(- self.list_blocks,- self.text_blocks,- self.ref_text_blocks,- )- self.index_blocks = fix_pdf_index_blocks(self.index_blocks)- else:- self.list_blocks = fix_office_list_blocks(self.list_blocks)- self.index_blocks = fix_office_index_blocks(self.index_blocks)-- visual_groups, unmatched_child_blocks = regroup_visual_blocks(- self.blocks,- use_bbox=is_block_has_bbox,- )- self.image_blocks = visual_groups[BlockType.IMAGE]- self.table_blocks = visual_groups[BlockType.TABLE]- self.chart_blocks = visual_groups[BlockType.CHART]- self.code_blocks = visual_groups[BlockType.CODE]-- for code_block in self.code_blocks:- if code_block["sub_type"] == "code":- for sub_block in code_block["content"]:- if sub_block.get("type") == BlockType.CODE_BODY:- guess_lang = guess_language_by_text(sub_block.get("content", ""))- code_block["guess_lang"] = guess_lang- break-- for block in unmatched_child_blocks:- block["type"] = BlockType.TEXT- self.text_blocks.append(block)-- # 移除已完成分类或分组的原始块,再写回处理后的顶层块。- replaced_block_types = {- BlockType.TEXT,- BlockType.REF_TEXT,- BlockType.LIST,- BlockType.INDEX,- RAW_CAPTION,- RAW_FOOTNOTE,- BlockType.IMAGE_BODY,- BlockType.TABLE_BODY,- BlockType.CHART_BODY,- BlockType.CODE_BODY,- BlockType.IMAGE_CAPTION,- BlockType.IMAGE_FOOTNOTE,- BlockType.TABLE_CAPTION,- BlockType.TABLE_FOOTNOTE,- BlockType.CHART_CAPTION,- BlockType.CHART_FOOTNOTE,- BlockType.CODE_CAPTION,- BlockType.CODE_FOOTNOTE,- }- self.blocks = [- block- for block in self.blocks- if block["type"] not in replaced_block_types- ]- self.blocks.extend(- self.list_blocks- + self.text_blocks- + self.ref_text_blocks- + self.index_blocks- + self.image_blocks- + self.table_blocks- + self.chart_blocks- + self.code_blocks- )-- @staticmethod- def fix_office_paragraph_titles(- model_list: list[list[dict[str, Any]]],- ) -> None:- """按文档级标题序列内化 Office 自动编号,并清除私有编号元数据。"""- counters: dict[int, int] = {}- for page_model_list in model_list:- for block in page_model_list:- if block.get("type") != BlockType.PARAGRAPH_TITLE:- continue-- raw_level = block.get("level")- level_is_valid = (- isinstance(raw_level, int)- and not isinstance(raw_level, bool)- and raw_level >= 1- )- level = raw_level if level_is_valid else 1- if not level_is_valid:- block.pop("level", None)-- is_numbered_style = block.pop("is_numbered_style", None)- block.pop("section_number", None)- content = block.get("content")- if not isinstance(content, str):- continue-- if is_numbered_style is True:- for ancestor_level in range(1, level):- counters.setdefault(ancestor_level, 1)- counters[level] = counters.get(level, 0) + 1- _clear_deeper_title_counters(counters, level)- section_number = ".".join(- str(counters[ancestor_level])- for ancestor_level in range(1, level + 1)- )- block["content"] = f"{section_number} {content}"- continue-- if is_numbered_style is False and level_is_valid:- number_match = re.match(r"^\s*(\d+(?:\.\d+)*)\b", _visible_text(content))- if number_match is None:- continue- number_parts = [int(part) for part in number_match.group(1).split(".")]- if len(number_parts) != level:- continue- counters.update(- (part_level, number)- for part_level, number in enumerate(number_parts, start=1)- )- _clear_deeper_title_counters(counters, level)---def fix_pdf_list_blocks(- list_blocks: list[dict[str, Any]],- text_blocks: list[dict[str, Any]],- ref_text_blocks: list[dict[str, Any]],-) -> tuple[list[dict[str, Any]], list[dict[str, Any]], list[dict[str, Any]]]:- """按 bbox 把 PDF text/ref_text 归入 list,并推断列表子类型。"""- for list_block in list_blocks:- list_block["content"] = []-- temp_text_blocks = text_blocks + ref_text_blocks- need_remove_blocks = []- for block in temp_text_blocks:- for list_block in list_blocks:- if (- calculate_overlap_area_in_bbox1_area_ratio(- _bbox_for_calculation(block["bbox"]),- _bbox_for_calculation(list_block["bbox"]),- )- >= 0.8- ):- list_block["content"].append(block)- need_remove_blocks.append(block)- break-- for block in need_remove_blocks:- if block in text_blocks:- text_blocks.remove(block)- elif block in ref_text_blocks:- ref_text_blocks.remove(block)-- list_blocks = [lb for lb in list_blocks if lb["content"]]-- for list_block in list_blocks:- type_count = {}- for sub_block in list_block["content"]:- sub_block_type = sub_block["type"]- if sub_block_type not in type_count:- type_count[sub_block_type] = 0- type_count[sub_block_type] += 1-- if type_count:- list_block["sub_type"] = max(type_count, key=type_count.get) # type: ignore- else:- list_block["sub_type"] = "text"-- return list_blocks, text_blocks, ref_text_blocks---def fix_pdf_index_blocks(- index_blocks: list[dict[str, Any]],-) -> list[dict[str, Any]]:- """将 PDF 目录块的多行内容拆分为多个文本子块。"""- for index_block in index_blocks:- index_block["content"] = [- {"type": "text", "content": content}- for content in index_block["content"].split("\n")- ]-- return index_blocks---def fix_office_index_blocks(- index_blocks: list[dict[str, Any]],-) -> list[dict[str, Any]]:- """递归移除 Office 目录私有字段,并禁止普通 text 子块携带 anchor。"""- pending_blocks = list(index_blocks)- while pending_blocks:- block = pending_blocks.pop()- block.pop("ilevel", None)- if block.get("type") == BlockType.TEXT:- block.pop("anchor", None)-- content = block.get("content")- if isinstance(content, list):- pending_blocks.extend(- child_block- for child_block in content- if isinstance(child_block, dict)- )-- return index_blocks---def _clear_deeper_title_counters(counters: dict[int, int], level: int) -> None:- """删除当前标题层级之后的旧计数,避免返回浅层后错误续接深层编号。"""- for counter_level in [value for value in counters if value > level]:- del counters[counter_level]---def _visible_text(content: str) -> str:- """移除简单富文本标签,供显式标题编号识别可见文本开头。"""- return re.sub(r"<[^>]+>", "", content)---def fix_office_list_blocks(- list_blocks: list[dict[str, Any]],-) -> list[dict[str, Any]]:- """将 Office 列表层级和起始序号写入文本内容,并移除原始列表元数据。"""-- def get_list_ilevel(list_block: dict[str, Any], parent_ilevel: int | None) -> int:- """读取列表层级,非法值按当前结构中的递归深度回退。"""- fallback_ilevel = 0 if parent_ilevel is None else parent_ilevel + 1- try:- ilevel = int(list_block.get("ilevel"))- except (TypeError, ValueError):- return fallback_ilevel- return ilevel if ilevel >= 0 else fallback_ilevel-- def get_ordered_list_start(list_block: dict[str, Any]) -> int:- """读取有序列表起始编号,保留合法的 0 并将非法值回退为 1。"""- start = list_block.get("start")- if start is None:- return 1- try:- start = int(start)- except (TypeError, ValueError):- return 1- return start if start >= 0 else 1-- def format_ordered_prefix(ordered_numbers: dict[int, int]) -> str:- """按列表层级拼接有序编号,单级编号保留末尾句点。"""- number_parts = [str(number) for _, number in sorted(ordered_numbers.items())]- if len(number_parts) == 1:- return f"{number_parts[0]}. "- return f"{'.'.join(number_parts)} "-- def fix_list_block(- list_block: dict[str, Any],- inherited_ordered_numbers: dict[int, int],- parent_ilevel: int | None,- ) -> None:- """递归处理单个列表块,并把当前位置的有序编号传给嵌套列表。"""- ilevel = get_list_ilevel(list_block, parent_ilevel)- base_ordered_numbers = {- level: number- for level, number in inherited_ordered_numbers.items()- if level < ilevel- }- active_ordered_numbers = dict(base_ordered_numbers)- is_ordered = list_block.get("attribute") == "ordered"- ordered_number = get_ordered_list_start(list_block)-- content = list_block.get("content")- if isinstance(content, list):- for child_block in content:- if not isinstance(child_block, dict):- continue-- child_type = child_block.get("type")- if child_type == BlockType.TEXT:- child_content = child_block.get("content")- if not isinstance(child_content, str):- continue-- if is_ordered:- active_ordered_numbers = dict(base_ordered_numbers)- active_ordered_numbers[ilevel] = ordered_number- prefix = format_ordered_prefix(active_ordered_numbers)- ordered_number += 1- else:- prefix = "- "- child_block["content"] = f"{prefix}{child_content}"- elif child_type == BlockType.LIST:- fix_list_block(- child_block,- dict(active_ordered_numbers),- ilevel,- )-- list_block.pop("attribute", None)- list_block.pop("ilevel", None)- list_block.pop("start", None)-- for list_block in list_blocks:- if isinstance(list_block, dict):- fix_list_block(list_block, {}, None)-- return list_blocksdiff --git a/mineru/backend/postprocess/__init__.py b/mineru/backend/postprocess/__init__.pynew file mode 100644index 00000000..289715f4--- /dev/null+++ b/mineru/backend/postprocess/__init__.py@@ -0,0 +1,2 @@+# Copyright (c) Opendatalab. All rights reserved.+"""将 raw model-list 转换为严格 Middle JSON 页对象的后处理层。"""diff --git a/mineru/backend/postprocess/content.py b/mineru/backend/postprocess/content.pynew file mode 100644index 00000000..e5fec885--- /dev/null+++ b/mineru/backend/postprocess/content.py@@ -0,0 +1,32 @@+# Copyright (c) Opendatalab. All rights reserved.+"""raw block 的文本、代码和公式内容清理规则。"""++from __future__ import annotations++import re+++def code_content_clean(content: str | None) -> str:+ """去除代码块外层 Markdown 围栏并保留代码正文。"""+ if not content:+ return ""+ lines = content.splitlines()+ start_idx = 1 if lines and lines[0].startswith("```") else 0+ end_idx = len(lines)+ if lines and end_idx > start_idx and lines[end_idx - 1].strip() == "```":+ end_idx -= 1+ if start_idx < end_idx:+ return "\n".join(lines[start_idx:end_idx]).strip()+ return ""+++def clean_content(content: str | None) -> str | None:+ """将成对的行间公式分隔符改为兼容文本清理的方括号。"""+ if content and content.count("\\[") == content.count("\\]") and content.count("\\[") > 0:++ def replace_pattern(match: re.Match[str]) -> str:+ """替换单个成对公式片段。"""+ return f"[{match.group(1)}]"++ content = re.sub(r"\\\[(.*?)\\\]", replace_pattern, content)+ return contentdiff --git a/mineru/backend/postprocess/lists.py b/mineru/backend/postprocess/lists.pynew file mode 100644index 00000000..36e49d36--- /dev/null+++ b/mineru/backend/postprocess/lists.py@@ -0,0 +1,187 @@+# Copyright (c) Opendatalab. All rights reserved.+"""PDF 与 Office 的列表、目录和标题编号后处理。"""++from __future__ import annotations++import re+from typing import Any++from mineru.types import BlockType+from mineru.utils.bbox_utils import calculate_overlap_area_in_bbox1_area_ratio++from .visual import _bbox_for_calculation+++def fix_office_paragraph_titles(model_list: list[list[dict[str, Any]]]) -> None:+ """按文档级标题序列内化 Office 自动编号,并清除私有编号元数据。"""+ counters: dict[int, int] = {}+ for page_model_list in model_list:+ for block in page_model_list:+ if block.get("type") != BlockType.PARAGRAPH_TITLE:+ continue+ raw_level = block.get("level")+ level_is_valid = isinstance(raw_level, int) and not isinstance(raw_level, bool) and raw_level >= 1+ level = raw_level if level_is_valid else 1+ if not level_is_valid:+ block.pop("level", None)+ is_numbered_style = block.pop("is_numbered_style", None)+ block.pop("section_number", None)+ content = block.get("content")+ if not isinstance(content, str):+ continue+ if is_numbered_style is True:+ for ancestor_level in range(1, level):+ counters.setdefault(ancestor_level, 1)+ counters[level] = counters.get(level, 0) + 1+ _clear_deeper_title_counters(counters, level)+ section_number = ".".join(str(counters[ancestor_level]) for ancestor_level in range(1, level + 1))+ block["content"] = f"{section_number} {content}"+ continue+ if is_numbered_style is False and level_is_valid:+ number_match = re.match(r"^\s*(\d+(?:\.\d+)*)\b", _visible_text(content))+ if number_match is None:+ continue+ number_parts = [int(part) for part in number_match.group(1).split(".")]+ if len(number_parts) != level:+ continue+ counters.update((part_level, number) for part_level, number in enumerate(number_parts, start=1))+ _clear_deeper_title_counters(counters, level)+++def fix_pdf_list_blocks(+ list_blocks: list[dict[str, Any]],+ text_blocks: list[dict[str, Any]],+ ref_text_blocks: list[dict[str, Any]],+) -> tuple[list[dict[str, Any]], list[dict[str, Any]], list[dict[str, Any]]]:+ """按 bbox 把 PDF text/ref_text 归入 list,并推断列表子类型。"""+ for list_block in list_blocks:+ list_block["content"] = []+ need_remove_blocks = []+ for block in text_blocks + ref_text_blocks:+ for list_block in list_blocks:+ if (+ calculate_overlap_area_in_bbox1_area_ratio(+ _bbox_for_calculation(block["bbox"]),+ _bbox_for_calculation(list_block["bbox"]),+ )+ >= 0.8+ ):+ list_block["content"].append(block)+ need_remove_blocks.append(block)+ break+ for block in need_remove_blocks:+ if block in text_blocks:+ text_blocks.remove(block)+ elif block in ref_text_blocks:+ ref_text_blocks.remove(block)+ list_blocks = [block for block in list_blocks if block["content"]]+ for list_block in list_blocks:+ type_count: dict[str, int] = {}+ for sub_block in list_block["content"]:+ sub_block_type = sub_block["type"]+ type_count[sub_block_type] = type_count.get(sub_block_type, 0) + 1+ list_block["sub_type"] = max(type_count, key=type_count.get) if type_count else "text" # type: ignore[arg-type]+ return list_blocks, text_blocks, ref_text_blocks+++def fix_pdf_index_blocks(index_blocks: list[dict[str, Any]]) -> list[dict[str, Any]]:+ """将 PDF 目录块的多行内容拆分为多个文本子块。"""+ for index_block in index_blocks:+ index_block["content"] = [{"type": "text", "content": content} for content in index_block["content"].split("\n")]+ return index_blocks+++def fix_office_index_blocks(index_blocks: list[dict[str, Any]]) -> list[dict[str, Any]]:+ """递归移除 Office 目录私有字段,并禁止普通 text 子块携带 anchor。"""+ pending_blocks = list(index_blocks)+ while pending_blocks:+ block = pending_blocks.pop()+ block.pop("ilevel", None)+ if block.get("type") == BlockType.TEXT:+ block.pop("anchor", None)+ content = block.get("content")+ if isinstance(content, list):+ pending_blocks.extend(child for child in content if isinstance(child, dict))+ return index_blocks+++def _clear_deeper_title_counters(counters: dict[int, int], level: int) -> None:+ """删除当前标题层级之后的旧计数。"""+ for counter_level in [value for value in counters if value > level]:+ del counters[counter_level]+++def _visible_text(content: str) -> str:+ """移除简单富文本标签,供显式标题编号识别可见文本开头。"""+ return re.sub(r"<[^>]+>", "", content)+++def fix_office_list_blocks(list_blocks: list[dict[str, Any]]) -> list[dict[str, Any]]:+ """将 Office 列表层级和起始序号写入文本内容,并移除原始元数据。"""++ def get_list_ilevel(list_block: dict[str, Any], parent_ilevel: int | None) -> int:+ """读取列表层级,非法值按递归深度回退。"""+ fallback_ilevel = 0 if parent_ilevel is None else parent_ilevel + 1+ try:+ ilevel = int(list_block.get("ilevel"))+ except (TypeError, ValueError):+ return fallback_ilevel+ return ilevel if ilevel >= 0 else fallback_ilevel++ def get_ordered_list_start(list_block: dict[str, Any]) -> int:+ """读取有序列表起始编号,保留合法的零值。"""+ start = list_block.get("start")+ if start is None:+ return 1+ try:+ start = int(start)+ except (TypeError, ValueError):+ return 1+ return start if start >= 0 else 1++ def format_ordered_prefix(ordered_numbers: dict[int, int]) -> str:+ """按列表层级拼接有序编号。"""+ number_parts = [str(number) for _, number in sorted(ordered_numbers.items())]+ if len(number_parts) == 1:+ return f"{number_parts[0]}. "+ return f"{'.'.join(number_parts)} "++ def fix_list_block(+ list_block: dict[str, Any],+ inherited_ordered_numbers: dict[int, int],+ parent_ilevel: int | None,+ ) -> None:+ """递归处理单个列表块,并向嵌套列表传递有序编号。"""+ ilevel = get_list_ilevel(list_block, parent_ilevel)+ base_ordered_numbers = {level: number for level, number in inherited_ordered_numbers.items() if level < ilevel}+ active_ordered_numbers = dict(base_ordered_numbers)+ is_ordered = list_block.get("attribute") == "ordered"+ ordered_number = get_ordered_list_start(list_block)+ content = list_block.get("content")+ if isinstance(content, list):+ for child_block in content:+ if not isinstance(child_block, dict):+ continue+ child_type = child_block.get("type")+ if child_type == BlockType.TEXT:+ child_content = child_block.get("content")+ if not isinstance(child_content, str):+ continue+ if is_ordered:+ active_ordered_numbers = dict(base_ordered_numbers)+ active_ordered_numbers[ilevel] = ordered_number+ prefix = format_ordered_prefix(active_ordered_numbers)+ ordered_number += 1+ else:+ prefix = "- "+ child_block["content"] = f"{prefix}{child_content}"+ elif child_type == BlockType.LIST:+ fix_list_block(child_block, dict(active_ordered_numbers), ilevel)+ list_block.pop("attribute", None)+ list_block.pop("ilevel", None)+ list_block.pop("start", None)++ for list_block in list_blocks:+ if isinstance(list_block, dict):+ fix_list_block(list_block, {}, None)+ return list_blocksdiff --git a/mineru/backend/postprocess/page_blocks.py b/mineru/backend/postprocess/page_blocks.pynew file mode 100644index 00000000..ffb3bf10--- /dev/null+++ b/mineru/backend/postprocess/page_blocks.py@@ -0,0 +1,195 @@+# Copyright (c) Opendatalab. All rights reserved.+"""单页 raw block 的内容清理、列表整理和视觉分组流水线。"""++from __future__ import annotations++import re+from typing import Any++from mineru.types import (+ RAW_ALGORITHM,+ RAW_CAPTION,+ RAW_FOOTNOTE,+ BlockType,+ VISUAL_MAIN_TYPES,+)+from mineru.utils.guess_suffix_or_lang import guess_language_by_text++from mineru.utils.text_utils import clean_isolated_formula++from .content import clean_content, code_content_clean+from .lists import (+ fix_office_index_blocks,+ fix_office_list_blocks,+ fix_pdf_index_blocks,+ fix_pdf_list_blocks,+)+from .visual import (+ fallback_inline_caption_fragments,+ fallback_leading_table_continuation_captions,+ fallback_no_bbox_caption_fragments,+ regroup_visual_blocks,+)++BlockDict = dict[str, Any]++_REPLACED_BLOCK_TYPES = {+ BlockType.TEXT,+ BlockType.REF_TEXT,+ BlockType.LIST,+ BlockType.INDEX,+ RAW_CAPTION,+ RAW_FOOTNOTE,+ BlockType.IMAGE_BODY,+ BlockType.TABLE_BODY,+ BlockType.CHART_BODY,+ BlockType.CODE_BODY,+ BlockType.IMAGE_CAPTION,+ BlockType.IMAGE_FOOTNOTE,+ BlockType.TABLE_CAPTION,+ BlockType.TABLE_FOOTNOTE,+ BlockType.CHART_CAPTION,+ BlockType.CHART_FOOTNOTE,+ BlockType.CODE_CAPTION,+ BlockType.CODE_FOOTNOTE,+}+++def _has_inline_formula_content(content: str | None) -> bool:+ """判断 content 是否包含成对行内公式标记。"""+ return bool(content) and content.count("<eq>") == content.count("</eq>") and content.count("<eq>") > 0+++def _normalize_raw_blocks(page_model_list: list[BlockDict]) -> list[BlockDict]:+ """原地规范化 raw block 类型、内容、索引和代码子类型。"""+ blocks: list[BlockDict] = []+ for index, block in enumerate(page_model_list):+ code_block_sub_type = None+ block_type = block.get("type", "")+ block_content = block.get("content", "")+ if block_type == BlockType.IMAGE:+ block_type = BlockType.IMAGE_BODY+ elif block_type == BlockType.TABLE:+ block_type = BlockType.TABLE_BODY+ elif block_type == BlockType.CHART:+ block_type = BlockType.CHART_BODY+ elif block_type in [BlockType.CODE, RAW_ALGORITHM]:+ code_block_sub_type = block_type+ block_content = code_content_clean(block_content)+ block_type = BlockType.CODE_BODY+ elif block_type == BlockType.EQUATION:+ block_content = clean_isolated_formula(block_content)++ if block_type not in [BlockType.IMAGE_BODY, BlockType.TABLE_BODY, BlockType.CHART_BODY]:+ if block_content:+ block_content = clean_content(block_content) or ""+ if block_type in [BlockType.DOC_TITLE, BlockType.PARAGRAPH_TITLE] and block_content:+ block_content = re.sub(r"\n\s*", " ", block_content).strip()+ if (+ block_type == BlockType.CODE_BODY+ and code_block_sub_type == BlockType.CODE+ and _has_inline_formula_content(block_content)+ ):+ code_block_sub_type = RAW_ALGORITHM++ block["type"] = block_type+ block["content"] = block_content+ block["index"] = index+ if code_block_sub_type:+ block["sub_type"] = code_block_sub_type+ blocks.append(block)+ return blocks+++def _apply_caption_fallbacks(blocks: list[BlockDict], *, use_bbox: bool) -> None:+ """按 PDF 或 Office 结构应用视觉标题兜底规则。"""+ if use_bbox:+ fallback_inline_caption_fragments(blocks, VISUAL_MAIN_TYPES)+ fallback_leading_table_continuation_captions(blocks, VISUAL_MAIN_TYPES)+ else:+ fallback_no_bbox_caption_fragments(blocks, VISUAL_MAIN_TYPES)+++def _partition_textual_blocks(+ blocks: list[BlockDict],+) -> tuple[list[BlockDict], list[BlockDict], list[BlockDict], list[BlockDict]]:+ """按 text、ref_text、list、index 四类分区 raw block。"""+ text_blocks: list[BlockDict] = []+ ref_text_blocks: list[BlockDict] = []+ list_blocks: list[BlockDict] = []+ index_blocks: list[BlockDict] = []+ for block in blocks:+ block_type = block["type"]+ if block_type == BlockType.TEXT:+ text_blocks.append(block)+ elif block_type == BlockType.REF_TEXT:+ ref_text_blocks.append(block)+ elif block_type == BlockType.LIST:+ list_blocks.append(block)+ elif block_type == BlockType.INDEX:+ index_blocks.append(block)+ return text_blocks, ref_text_blocks, list_blocks, index_blocks+++def _prepare_lists_and_indices(+ blocks: list[BlockDict],+ *,+ use_bbox: bool,+) -> tuple[list[BlockDict], list[BlockDict], list[BlockDict], list[BlockDict]]:+ """根据文档类型整理列表、目录以及被列表吸收的文本块。"""+ text_blocks, ref_text_blocks, list_blocks, index_blocks = _partition_textual_blocks(blocks)+ if use_bbox:+ list_blocks, text_blocks, ref_text_blocks = fix_pdf_list_blocks(+ list_blocks,+ text_blocks,+ ref_text_blocks,+ )+ index_blocks = fix_pdf_index_blocks(index_blocks)+ else:+ list_blocks = fix_office_list_blocks(list_blocks)+ index_blocks = fix_office_index_blocks(index_blocks)+ return text_blocks, ref_text_blocks, list_blocks, index_blocks+++def _annotate_code_languages(code_blocks: list[BlockDict]) -> None:+ """为普通代码主体推断语言,算法块保持既有子类型。"""+ for code_block in code_blocks:+ if code_block["sub_type"] != BlockType.CODE:+ continue+ for sub_block in code_block["content"]:+ if sub_block.get("type") == BlockType.CODE_BODY:+ code_block["guess_lang"] = guess_language_by_text(sub_block.get("content", ""))+ break+++def process_page_blocks(+ page_model_list: list[BlockDict],+ *,+ use_bbox: bool | None = None,+) -> list[BlockDict]:+ """按固定阶段将单页 raw model-list 转换为可对象化的顶层 blocks。"""+ resolved_use_bbox = any(block.get("bbox") for block in page_model_list) if use_bbox is None else use_bbox+ blocks = _normalize_raw_blocks(page_model_list)+ _apply_caption_fallbacks(blocks, use_bbox=resolved_use_bbox)+ text_blocks, ref_text_blocks, list_blocks, index_blocks = _prepare_lists_and_indices(+ blocks,+ use_bbox=resolved_use_bbox,+ )+ visual_groups, unmatched_child_blocks = regroup_visual_blocks(+ blocks,+ use_bbox=resolved_use_bbox,+ )+ image_blocks = visual_groups[BlockType.IMAGE]+ table_blocks = visual_groups[BlockType.TABLE]+ chart_blocks = visual_groups[BlockType.CHART]+ code_blocks = visual_groups[BlockType.CODE]+ _annotate_code_languages(code_blocks)+ for block in unmatched_child_blocks:+ block["type"] = BlockType.TEXT+ text_blocks.append(block)++ result = [block for block in blocks if block["type"] not in _REPLACED_BLOCK_TYPES]+ result.extend(+ list_blocks + text_blocks + ref_text_blocks + index_blocks + image_blocks + table_blocks + chart_blocks + code_blocks+ )+ return resultdiff --git a/mineru/backend/model_list_to_midlle_json.py b/mineru/backend/postprocess/pages.pysimilarity index 76%rename from mineru/backend/model_list_to_midlle_json.pyrename to mineru/backend/postprocess/pages.pyindex 9264b396..e9e63b36 100644--- a/mineru/backend/model_list_to_midlle_json.py+++ b/mineru/backend/postprocess/pages.py@@ -1,4 +1,6 @@# Copyright (c) Opendatalab. All rights reserved.+"""raw model-list 到严格 PageInfo 列表的唯一转换边界。"""+from __future__ import annotationsfrom copy import deepcopy@@ -6,9 +8,10 @@ from typing import Anyfrom pydantic import TypeAdapter-from mineru.backend.magic_model import MagicModel-from mineru.backend.utils.para_block_utils import merge_para_text_blocks-from mineru.backend.utils.table_merge import merge_table+from mineru.backend.postprocess.lists import fix_office_paragraph_titles+from mineru.backend.postprocess.page_blocks import process_page_blocks+from mineru.backend.postprocess.paragraphs import merge_para_text_blocks+from mineru.backend.postprocess.table_merge import merge_tablefrom mineru.types import PageInfoPAGE_INFO_LIST_ADAPTER = TypeAdapter(list[PageInfo])@@ -22,20 +25,12 @@ def _validate_page_index_map(if page_index_map is None:return list(range(page_count))if len(page_index_map) != page_count:- raise ValueError(- f"page_index_map length mismatch: pages={page_count}, mapping={len(page_index_map)}"- )- if any(- isinstance(page_idx, bool) or not isinstance(page_idx, int) or page_idx < 0- for page_idx in page_index_map- ):+ raise ValueError(f"page_index_map length mismatch: pages={page_count}, mapping={len(page_index_map)}")+ if any(isinstance(page_idx, bool) or not isinstance(page_idx, int) or page_idx < 0 for page_idx in page_index_map):raise ValueError("page_index_map values must be non-negative integers")if len(page_index_map) != len(set(page_index_map)):raise ValueError("page_index_map values must be unique")- if any(- current <= previous- for previous, current in zip(page_index_map, page_index_map[1:])- ):+ if any(current <= previous for previous, current in zip(page_index_map, page_index_map[1:])):raise ValueError("page_index_map values must preserve strictly increasing order")return list(page_index_map)@@ -43,10 +38,7 @@ def _validate_page_index_map(def _document_uses_bbox(model_list: list[list[dict[str, Any]]]) -> bool:"""按整份文档是否出现 bbox 判定 PDF/Office,避免空白首页误判。"""return any(- block.get("bbox") is not None- for page_model_list in model_list- for block in page_model_list- if isinstance(block, dict)+ block.get("bbox") is not None for page_model_list in model_list for block in page_model_list if isinstance(block, dict))@@ -67,9 +59,8 @@ def _blocks_to_raw_page_info(page_idx: int,use_bbox: bool,) -> dict[str, Any]:- """运行单页 MagicModel 并保留 raw dict,供跨页后处理继续消费。"""- magic_model = MagicModel(page_model_list, use_bbox=use_bbox)- page_blocks = magic_model.blocks+ """运行单页后处理流水线并保留 raw dict,供跨页处理继续消费。"""+ page_blocks = process_page_blocks(page_model_list, use_bbox=use_bbox)page_blocks.sort(key=lambda block: block["index"])return {"page_idx": page_idx, "blocks": page_blocks}@@ -84,7 +75,7 @@ def blocks_to_page_info(copied_blocks = deepcopy(page_model_list)resolved_use_bbox = _document_uses_bbox([copied_blocks]) if use_bbox is None else use_bboxif not resolved_use_bbox:- MagicModel.fix_office_paragraph_titles([copied_blocks])+ fix_office_paragraph_titles([copied_blocks])raw_page = _blocks_to_raw_page_info(copied_blocks,page_idx=page_idx,@@ -104,7 +95,7 @@ def model_list_to_pages(copied_model_list = deepcopy(model_list)use_bbox = _document_uses_bbox(copied_model_list)if not use_bbox:- MagicModel.fix_office_paragraph_titles(copied_model_list)+ fix_office_paragraph_titles(copied_model_list)raw_pages = [_blocks_to_raw_page_info(diff --git a/mineru/backend/utils/para_block_utils.py b/mineru/backend/postprocess/paragraphs.pysimilarity index 99%rename from mineru/backend/utils/para_block_utils.pyrename to mineru/backend/postprocess/paragraphs.pyindex 2bb3065a..c2521f62 100644--- a/mineru/backend/utils/para_block_utils.py+++ b/mineru/backend/postprocess/paragraphs.py@@ -1,4 +1,6 @@# Copyright (c) Opendatalab. All rights reserved.+"""PDF 段落延续关系的 raw model-list 后处理。"""+import mathfrom typing import Any, TypeAliasdiff --git a/mineru/backend/postprocess/table_merge/__init__.py b/mineru/backend/postprocess/table_merge/__init__.pynew file mode 100644index 00000000..63376e0f--- /dev/null+++ b/mineru/backend/postprocess/table_merge/__init__.py@@ -0,0 +1,21 @@+# Copyright (c) Opendatalab. All rights reserved.+"""跨页表格结构检测和内容合并的稳定入口。"""++from .content import merge_table_content+from .document import merge_table+from .html import (+ build_row_rendered_cell_segments,+ build_table_state_from_html,+ calculate_row_rendered_segments,+)+from .structure import can_merge_by_structure, detect_table_headers++__all__ = [+ "merge_table",+ "merge_table_content",+ "build_table_state_from_html",+ "build_row_rendered_cell_segments",+ "can_merge_by_structure",+ "calculate_row_rendered_segments",+ "detect_table_headers",+]diff --git a/mineru/backend/postprocess/table_merge/blocks.py b/mineru/backend/postprocess/table_merge/blocks.pynew file mode 100644index 00000000..49d9364b--- /dev/null+++ b/mineru/backend/postprocess/table_merge/blocks.py@@ -0,0 +1,158 @@+# Copyright (c) Opendatalab. All rights reserved.+"""MinerU table block 的主体、辅助文本和 bbox 访问规则。"""++from __future__ import annotations++import math+from typing import Any++from bs4 import BeautifulSoup++from mineru.types import BlockType++from .html import _build_front_cache, _scan_rows+from .models import (+ MAX_HEADER_ROWS,+ BlockDict,+ CalculationBBox,+ TableMergeState,+)+from .rules import is_table_continuation_text+++def _bbox_for_calculation(bbox: Any) -> CalculationBBox | None:+ """复制归一化 bbox 并放大为千分位整数,原始字段保持不变。"""+ if not isinstance(bbox, (list, tuple)) or len(bbox) != 4:+ return None+ if any(isinstance(value, bool) or not isinstance(value, (int, float)) for value in bbox):+ return None++ values = tuple(float(value) for value in bbox)+ if not all(math.isfinite(value) and 0 <= value <= 1 for value in values):+ return None++ x0, y0, x1, y1 = (int(round(value * 1000)) for value in values)+ if x1 <= x0 or y1 <= y0:+ return None+ return x0, y0, x1, y1+++def _table_children(table_block: BlockDict) -> list[BlockDict]:+ """读取 table 根块下的合法 dict 子块。"""+ content = table_block.get("content")+ if not isinstance(content, list):+ return []+ return [block for block in content if isinstance(block, dict)]+++def _find_table_body_block(table_block: BlockDict) -> BlockDict | None:+ """查找 dict table block 中的主体子块。"""+ for block in _table_children(table_block):+ if block.get("type") == BlockType.TABLE_BODY:+ return block+ return None+++def _build_post_body_child_index(table_block: BlockDict, offset: int) -> int | None:+ """为复制到前表的 footnote 生成表体后的安全 index。"""+ body_block = _find_table_body_block(table_block)+ if body_block is None:+ return None+ body_index = body_block.get("index")+ if not isinstance(body_index, int):+ return None++ child_indices = [block.get("index") for block in _table_children(table_block) if isinstance(block.get("index"), int)]+ return max([body_index, *child_indices]) + offset+++def _block_text(block: BlockDict) -> str:+ """递归读取 dict block 的文本内容,供续表标记判断使用。"""+ content = block.get("content")+ if isinstance(content, str):+ return content+ if not isinstance(content, list):+ return ""+ return "".join(_block_text(child) for child in content if isinstance(child, dict))+++def _is_continuation_caption(caption_block: BlockDict) -> bool:+ """判断 dict caption 文本是否带有续表标记。"""+ return is_table_continuation_text(_block_text(caption_block))+++def _is_post_table_non_continuation_caption(table_block: BlockDict, caption_block: BlockDict) -> bool:+ """判断 caption 是否是误挂到表格下方的新段落标题。++ 这类 caption 位于 table body 下方,且不含续表标记;它不应作为+ 当前表的新标题阻断跨页关系判断。+ """+ if _is_continuation_caption(caption_block):+ return False++ body_block = _find_table_body_block(table_block)+ if body_block is None:+ return False++ body_bbox = _bbox_for_calculation(body_block.get("bbox"))+ caption_bbox = _bbox_for_calculation(caption_block.get("bbox"))+ if body_bbox is None or caption_bbox is None:+ return False++ return caption_bbox[1] >= body_bbox[3]+++def _build_table_state(table_block: BlockDict, max_header_rows: int = MAX_HEADER_ROWS) -> TableMergeState | None:+ """从 dict table block 构建结构缓存,非法主体安全返回空。"""+ body_block = _find_table_body_block(table_block)+ if body_block is None:+ return None++ html = body_block.get("content")+ if not isinstance(html, str) or not html:+ return None++ soup = BeautifulSoup(html, "html.parser")+ tbody = soup.find("tbody") or soup.find("table")+ rows = soup.find_all("tr")+ if tbody is None or not rows:+ return None++ scan = _scan_rows(rows)+ if scan.total_cols <= 0 or scan.last_nonempty_row_metrics is None:+ return None+ front_header_info, front_first_data_row_metrics = _build_front_cache(rows, max_header_rows=max_header_rows)++ return TableMergeState(+ owner_block=table_block,+ body_block=body_block,+ soup=soup,+ tbody=tbody,+ rows=rows,+ total_cols=scan.total_cols,+ front_header_info=front_header_info,+ front_first_data_row_metrics=front_first_data_row_metrics,+ last_data_row_metrics=scan.last_nonempty_row_metrics,+ row_effective_cols=scan.row_effective_cols,+ tail_occupied=scan.tail_occupied,+ )+++def _get_or_create_table_state(+ table_block: BlockDict,+ state_cache: dict[int, TableMergeState],+ max_header_rows: int = MAX_HEADER_ROWS,+) -> TableMergeState | None:+ """按 table dict 对象身份复用 HTML 结构扫描结果。"""+ cache_key = id(table_block)+ state = state_cache.get(cache_key)+ if state is not None:+ return state++ try:+ state = _build_table_state(table_block, max_header_rows=max_header_rows)+ except (AssertionError, TypeError, ValueError):+ return None+ if state is not None:+ state_cache[cache_key] = state+ return statediff --git a/mineru/backend/postprocess/table_merge/content.py b/mineru/backend/postprocess/table_merge/content.pynew file mode 100644index 00000000..90bb7f75--- /dev/null+++ b/mineru/backend/postprocess/table_merge/content.py@@ -0,0 +1,435 @@+# Copyright (c) Opendatalab. All rights reserved.+"""跨页表格 HTML 内容、行列结构和单元格语义合并。"""++from __future__ import annotations++from copy import deepcopy++from bs4 import Tag++from mineru.types import BlockType++from .blocks import (+ _build_post_body_child_index,+ _build_table_state,+ _table_children,+)+from .html import (+ _colspan,+ _refresh_table_state_metrics,+ _rowspan,+ _scan_rows,+ _serialize_table_state_html,+ build_visual_col_mapping,+ calculate_row_columns,+ calculate_visual_columns,+)+from .models import BlockDict, TableMergeState+from .structure import (+ _expand_header_count_by_rowspan,+ can_merge_tables,+ check_row_columns_match,+ detect_table_headers,+)+++def adjust_table_rows_colspan(+ rows: list[Tag],+ start_idx: int,+ end_idx: int,+ row_effective_cols: list[int],+ reference_structure: list[int],+ reference_visual_cols: int,+ target_cols: int,+ match_reference_row: Tag,+) -> None:+ """调整表格行的colspan属性以匹配目标列数."""+ reference_row_copy = deepcopy(match_reference_row)++ for row_idx in range(start_idx, end_idx):+ row = rows[row_idx]+ cells = row.find_all(["td", "th"])+ if not cells:+ continue++ current_row_effective_cols = row_effective_cols[row_idx]+ current_row_cols = calculate_row_columns(row)++ if current_row_effective_cols >= target_cols or current_row_cols >= target_cols:+ continue++ if calculate_visual_columns(row) == reference_visual_cols and check_row_columns_match(row, reference_row_copy):+ if len(cells) <= len(reference_structure):+ for cell_idx, cell in enumerate(cells):+ if cell_idx < len(reference_structure) and reference_structure[cell_idx] > 1:+ cell["colspan"] = str(reference_structure[cell_idx])+ else:+ cols_diff = target_cols - current_row_effective_cols+ if cols_diff > 0:+ last_cell = cells[-1]+ current_last_span = _colspan(last_cell)+ last_cell["colspan"] = str(current_last_span + cols_diff)+++def _cell_has_semantic_content(cell: Tag) -> bool:+ """判断单元格是否仍包含用户可见的语义内容。"""+ if cell.get_text(strip=True):+ return True++ return cell.find(["img", "svg", "math", "eq", "table", "figure", "object", "embed", "canvas"]) is not None+++def _row_has_semantic_content(row: Tag) -> bool:+ """判断整行是否仍保留未并回的语义内容。"""+ return any(_cell_has_semantic_content(cell) for cell in row.find_all(["td", "th"]))+++def _insert_cell_before_visual_column(rows: list[Tag], target_row_index: int, start_vcol: int, cell: Tag) -> None:+ """将单元格插入到目标行中对应视觉列之前。"""+ target_row = rows[target_row_index]+ target_cells = target_row.find_all(["td", "th"])+ target_vcol_map = build_visual_col_mapping(rows, target_row_index)++ for idx, target_start_vcol in enumerate(target_vcol_map):+ if target_start_vcol >= start_vcol:+ target_cells[idx].insert_before(cell)+ return++ target_row.append(cell)+++def _carry_rowspan_structure_to_next_row(rows: list[Tag], row_idx: int) -> None:+ """下沉空白结构占位单元格,避免删除当前行后破坏后续列对齐。"""+ next_row_idx = row_idx + 1+ if next_row_idx >= len(rows):+ return++ current_row = rows[row_idx]+ current_cells = current_row.find_all(["td", "th"])+ current_vcol_map = build_visual_col_mapping(rows, row_idx)+ carried_cells = []++ for cell, start_vcol in zip(current_cells, current_vcol_map):+ rowspan = _rowspan(cell)+ if rowspan <= 1 or _cell_has_semantic_content(cell):+ continue++ carried_cell = deepcopy(cell)+ new_rowspan = rowspan - 1+ if new_rowspan > 1:+ carried_cell["rowspan"] = str(new_rowspan)+ else:+ carried_cell.attrs.pop("rowspan", None)+ carried_cells.append((start_vcol, carried_cell))++ for start_vcol, carried_cell in sorted(carried_cells, key=lambda item: item[0], reverse=True):+ _insert_cell_before_visual_column(rows, next_row_idx, start_vcol, carried_cell)+++def _clip_overlapped_blank_rowspan_cells(+ rows: list[Tag],+ initial_occupied: dict[int, set[int]],+) -> bool:+ """裁剪被上页 rowspan 覆盖的当前页空白结构占位。++ 跨页表格中,上一页未结束的 rowspan 会通过 initial_occupied 占住+ 当前页开头的视觉列。如果当前页表格识别又生成了同位置的空白+ rowspan 单元格,这个单元格只是结构占位;直接拼接会把同一视觉列+ 当成两列。这里仅裁剪无语义内容的空白占位,真实内容单元格不处理。+ """+ if not rows or not initial_occupied:+ return False++ cells_to_remove = []+ cells_to_move = []++ for row_idx, row in enumerate(rows):+ cells = row.find_all(["td", "th"])+ visual_col_map = build_visual_col_mapping(rows, row_idx)+ for cell, start_vcol in zip(cells, visual_col_map):+ rowspan = _rowspan(cell)+ if rowspan <= 1 or _cell_has_semantic_content(cell):+ continue++ colspan = _colspan(cell)+ occupied_cols = set(range(start_vcol, start_vcol + colspan))+ if not occupied_cols:+ continue++ overlap_rows = 0+ while overlap_rows < rowspan:+ covered_cols = initial_occupied.get(row_idx + overlap_rows, set())+ if not occupied_cols.issubset(covered_cols):+ break+ overlap_rows += 1++ if overlap_rows == 0:+ continue++ remaining_rowspan = rowspan - overlap_rows+ target_row_idx = row_idx + overlap_rows+ if remaining_rowspan > 0 and target_row_idx >= len(rows):+ continue++ cells_to_remove.append(cell)+ if remaining_rowspan > 0:+ moved_cell = deepcopy(cell)+ if remaining_rowspan > 1:+ moved_cell["rowspan"] = str(remaining_rowspan)+ else:+ moved_cell.attrs.pop("rowspan", None)+ cells_to_move.append((target_row_idx, start_vcol, moved_cell))++ if not cells_to_remove:+ return False++ for cell in cells_to_remove:+ cell.extract()++ for target_row_idx, start_vcol, moved_cell in sorted(+ cells_to_move,+ key=lambda item: (item[0], item[1]),+ reverse=True,+ ):+ _insert_cell_before_visual_column(rows, target_row_idx, start_vcol, moved_cell)++ return True+++def _apply_cell_merge(+ previous_state: TableMergeState,+ current_state: TableMergeState,+ header_count: int,+) -> bool:+ """应用 cell_merge 语义合并。++ 当 cell_merge 中的值为 1 时,将下表第一数据行对应单元格的内容+ 追加到上表最后一行对应单元格中。全部为 1 时删除该数据行,+ 混合时清空已合并单元格的内容但保留行。++ cell_merge 按视觉列索引对齐,通过构建视觉列映射来正确匹配+ 两个表格中可能因 rowspan 而具有不同 <td> 元素数量的行。+ 元数据仅从当前页 table body 读取,不依赖外层 table block。+ """+ current_body_block = current_state.body_block+ if not isinstance(current_body_block, dict):+ return False++ cell_merge = current_body_block.get("cell_merge")+ if not isinstance(cell_merge, list) or not cell_merge:+ return False++ rows2 = current_state.rows+ if header_count >= len(rows2):+ return False+ if not previous_state.rows:+ return False++ first_data_row = rows2[header_count]+ last_row = previous_state.rows[-1]++ cells1 = last_row.find_all(["td", "th"])+ cells2 = first_data_row.find_all(["td", "th"])++ # 构建视觉列到单元格索引的映射+ last_row_idx = len(previous_state.rows) - 1+ vcol_map1 = build_visual_col_mapping(previous_state.rows, last_row_idx)+ current_merge_rows = rows2[header_count:]+ vcol_map2 = build_visual_col_mapping(+ current_merge_rows,+ 0,+ initial_occupied=previous_state.tail_occupied,+ )++ # 构建视觉列 -> 单元格索引的反向映射(展开 colspan)+ vcol_to_cell1: dict[int, int] = {}+ for ci, start_vcol in enumerate(vcol_map1):+ colspan = int(cells1[ci].get("colspan", 1))+ for c in range(start_vcol, start_vcol + colspan):+ vcol_to_cell1[c] = ci+ vcol_to_cell2: dict[int, int] = {}+ for ci, start_vcol in enumerate(vcol_map2):+ colspan = int(cells2[ci].get("colspan", 1))+ for c in range(start_vcol, start_vcol + colspan):+ vcol_to_cell2[c] = ci++ # 按唯一 (src_cell_idx, dst_cell_idx) 对执行一次转移,避免 colspan 重复处理+ transferred_pairs: set[tuple[int, int]] = set()+ for vi, merge_flag in enumerate(cell_merge):+ if merge_flag == 1:+ ci1 = vcol_to_cell1.get(vi)+ ci2 = vcol_to_cell2.get(vi)+ if ci1 is not None and ci2 is not None:+ pair = (ci1, ci2)+ if pair not in transferred_pairs:+ for child in list(cells2[ci2].children):+ cells1[ci1].append(child.extract())+ transferred_pairs.add(pair)++ # 只清空确实成功转移过的源单元格+ cleared_ci2: set[int] = set()+ for vi, merge_flag in enumerate(cell_merge):+ if merge_flag == 1:+ ci1 = vcol_to_cell1.get(vi)+ ci2 = vcol_to_cell2.get(vi)+ if ci1 is not None and ci2 is not None and ci2 not in cleared_ci2:+ cells2[ci2].clear()+ cleared_ci2.add(ci2)++ if not _row_has_semantic_content(first_data_row):+ _carry_rowspan_structure_to_next_row(rows2, header_count)+ first_data_row.extract()+ if first_data_row in rows2:+ rows2.remove(first_data_row)++ return bool(transferred_pairs)+++def _perform_table_content_merge(+ previous_state: TableMergeState,+ current_state: TableMergeState,+ previous_table_block: BlockDict,+ current_table_block: BlockDict,+) -> bool:+ """在两个克隆表格上执行 HTML、单元格和 footnote 的内容合并。"""+ header_count, _, _ = detect_table_headers(previous_state, current_state)+ header_count = _expand_header_count_by_rowspan(current_state.rows, header_count)++ rows1 = previous_state.rows+ rows2 = current_state.rows+ if not rows1 or header_count >= len(rows2):+ return False++ previous_adjusted = False++ if header_count < len(rows2):+ current_merge_rows = rows2[header_count:]+ if _clip_overlapped_blank_rowspan_cells(current_merge_rows, previous_state.tail_occupied):+ _refresh_table_state_metrics(current_state)++ if rows1 and rows2 and header_count < len(rows2):+ last_row1 = rows1[-1]+ first_data_row2 = rows2[header_count]+ table_cols1 = previous_state.total_cols+ table_cols2 = current_state.total_cols++ if table_cols1 > table_cols2:+ reference_structure = [int(cell.get("colspan", 1)) for cell in last_row1.find_all(["td", "th"])]+ reference_visual_cols = calculate_visual_columns(last_row1)+ adjust_table_rows_colspan(+ rows2,+ header_count,+ len(rows2),+ current_state.row_effective_cols,+ reference_structure,+ reference_visual_cols,+ table_cols1,+ first_data_row2,+ )+ elif table_cols2 > table_cols1:+ reference_structure = [int(cell.get("colspan", 1)) for cell in first_data_row2.find_all(["td", "th"])]+ reference_visual_cols = calculate_visual_columns(first_data_row2)+ adjust_table_rows_colspan(+ rows1,+ 0,+ len(rows1),+ previous_state.row_effective_cols,+ reference_structure,+ reference_visual_cols,+ table_cols2,+ last_row1,+ )+ previous_adjusted = True++ if previous_adjusted:+ _refresh_table_state_metrics(previous_state)++ cell_merge_applied = _apply_cell_merge(previous_state, current_state, header_count)++ appended_rows = rows2[header_count:]+ append_start_idx = len(previous_state.rows)+ merged_rows = []++ if previous_state.tbody is None or current_state.tbody is None:+ return False++ for row in appended_rows:+ row.extract()+ previous_state.tbody.append(row)+ merged_rows.append(row)++ if not merged_rows and not cell_merge_applied:+ return False++ previous_state.rows.extend(merged_rows)++ if merged_rows:+ appended_scan = _scan_rows(+ merged_rows,+ initial_occupied=previous_state.tail_occupied,+ start_row_idx=append_start_idx,+ )+ previous_state.row_effective_cols.extend(appended_scan.row_effective_cols)+ previous_state.total_cols = max(previous_state.total_cols, appended_scan.total_cols)+ if appended_scan.last_nonempty_row_metrics is not None:+ previous_state.last_data_row_metrics = appended_scan.last_nonempty_row_metrics+ previous_state.tail_occupied = appended_scan.tail_occupied++ previous_content = previous_table_block.get("content")+ if not isinstance(previous_content, list):+ return False++ previous_table_block["content"] = [+ block for block in previous_content if not isinstance(block, dict) or block.get("type") != BlockType.TABLE_FOOTNOTE+ ]+ current_footnotes = [+ block for block in _table_children(current_table_block) if block.get("type") == BlockType.TABLE_FOOTNOTE+ ]+ footnote_base_index = _build_post_body_child_index(previous_table_block, 0)+ for footnote_offset, table_footnote in enumerate(current_footnotes, start=1):+ temp_table_footnote = deepcopy(table_footnote)+ temp_table_footnote.pop("_cross_page", None)+ if footnote_base_index is None:+ temp_table_footnote["index"] = 0+ else:+ temp_table_footnote["index"] = footnote_base_index + footnote_offset+ previous_table_block["content"].append(temp_table_footnote)++ previous_state.dirty = True+ return _serialize_table_state_html(previous_state)+++def merge_table_content(previous_table: BlockDict, current_table: BlockDict) -> BlockDict | None:+ """纯函数式合并两张跨页表格的内容,失败时返回 ``None``。++ 两个输入都会先深拷贝;返回块保留前表外层信息,只改克隆表体 HTML+ 并用当前表 footnote 替换前表 footnote,不会修改任何输入对象。+ """+ if (+ not isinstance(previous_table, dict)+ or not isinstance(current_table, dict)+ or previous_table.get("type") != BlockType.TABLE+ or current_table.get("type") != BlockType.TABLE+ ):+ return None++ previous_clone = deepcopy(previous_table)+ current_clone = deepcopy(current_table)+ try:+ previous_state = _build_table_state(previous_clone)+ current_state = _build_table_state(current_clone)+ if previous_state is None or current_state is None:+ return None+ if not can_merge_tables(current_state, previous_state):+ return None+ if not _perform_table_content_merge(+ previous_state,+ current_state,+ previous_clone,+ current_clone,+ ):+ return None+ except (AssertionError, TypeError, ValueError):+ return None++ return previous_clonediff --git a/mineru/backend/postprocess/table_merge/document.py b/mineru/backend/postprocess/table_merge/document.pynew file mode 100644index 00000000..55676096--- /dev/null+++ b/mineru/backend/postprocess/table_merge/document.py@@ -0,0 +1,111 @@+# Copyright (c) Opendatalab. All rights reserved.+"""文档页边界上的跨页表格识别与延续标记编排。"""++from __future__ import annotations++from typing import Any++from mineru.types import BlockType++from .blocks import _get_or_create_table_state+from .models import BlockDict, PageInfoDict, TableMergeState+from .structure import can_merge_tables++TABLE_BOUNDARY_IGNORED_TYPES = {+ BlockType.HEADER,+ BlockType.FOOTER,+ BlockType.PAGE_NUMBER,+ BlockType.PAGE_FOOTNOTE,+ BlockType.ASIDE_TEXT,+}+++def _clear_table_continuation_marker(table_block: BlockDict) -> None:+ """递归清除 table 根块及其子块中过期的 ``continues_prev``。"""+ table_block.pop("continues_prev", None)+ content = table_block.get("content")+ if not isinstance(content, list):+ return+ for child in content:+ if isinstance(child, dict):+ child.pop("continues_prev", None)+ _clear_nested_continuation_markers(child)+++def _clear_nested_continuation_markers(block: BlockDict) -> None:+ """清除表格子树中的旧延续标记,避免标记落到嵌套子块。"""+ content = block.get("content")+ if not isinstance(content, list):+ return+ for child in content:+ if isinstance(child, dict):+ child.pop("continues_prev", None)+ _clear_nested_continuation_markers(child)+++def _find_boundary_table(blocks: list[Any], *, from_end: bool) -> BlockDict | None:+ """从页边界扫描 table;噪声块可跳过,其他语义块立即阻断。"""+ ordered_blocks = reversed(blocks) if from_end else iter(blocks)+ for block in ordered_blocks:+ if not isinstance(block, dict):+ return None+ block_type = block.get("type")+ if block_type in TABLE_BOUNDARY_IGNORED_TYPES:+ continue+ if block_type == BlockType.TABLE:+ return block+ return None+ return None+++def _is_consecutive_page_pair(previous_page: PageInfoDict, current_page: PageInfoDict) -> bool:+ """按显式零基 page_idx 判断页面在文档中是否严格连续。"""+ previous_page_idx = previous_page.get("page_idx")+ current_page_idx = current_page.get("page_idx")+ return type(previous_page_idx) is int and type(current_page_idx) is int and current_page_idx == previous_page_idx + 1+++def merge_table(page_info_list: list[PageInfoDict]) -> None:+ """倒序识别连续页边界表格,并只在后表写入延续标记。"""+ if not isinstance(page_info_list, list):+ return++ for page_info in page_info_list:+ if not isinstance(page_info, dict):+ continue+ blocks = page_info.get("blocks")+ if not isinstance(blocks, list):+ continue+ for block in blocks:+ if isinstance(block, dict) and block.get("type") == BlockType.TABLE:+ _clear_table_continuation_marker(block)++ state_cache: dict[int, TableMergeState] = {}++ for page_position in range(len(page_info_list) - 1, 0, -1):+ current_page = page_info_list[page_position]+ previous_page = page_info_list[page_position - 1]+ if not isinstance(current_page, dict) or not isinstance(previous_page, dict):+ continue+ if not _is_consecutive_page_pair(previous_page, current_page):+ continue++ current_blocks = current_page.get("blocks")+ previous_blocks = previous_page.get("blocks")+ if not isinstance(current_blocks, list) or not isinstance(previous_blocks, list):+ continue++ current_table_block = _find_boundary_table(current_blocks, from_end=False)+ previous_table_block = _find_boundary_table(previous_blocks, from_end=True)+ if current_table_block is None or previous_table_block is None:+ continue++ current_state = _get_or_create_table_state(current_table_block, state_cache)+ previous_state = _get_or_create_table_state(previous_table_block, state_cache)+ if current_state is None or previous_state is None:+ continue++ if not can_merge_tables(current_state, previous_state):+ continue++ current_table_block["continues_prev"] = Truediff --git a/mineru/backend/postprocess/table_merge/html.py b/mineru/backend/postprocess/table_merge/html.pynew file mode 100644index 00000000..3fd44bc7--- /dev/null+++ b/mineru/backend/postprocess/table_merge/html.py@@ -0,0 +1,407 @@+# Copyright (c) Opendatalab. All rights reserved.+"""HTML 表格解析、行列扫描和结构状态缓存。"""++from __future__ import annotations++from typing import Any++from bs4 import BeautifulSoup, Tag++from mineru.utils.text_utils import full_to_half++from .models import (+ MAX_HEADER_ROWS,+ RenderedCellSegment,+ RowMetrics,+ RowScanResult,+ RowSignature,+ TableMergeState,+)+++def _colspan(cell: Any) -> int:+ """读取 HTML 单元格 colspan,非法值交由上层安全降级。"""+ val = cell.get("colspan", "1")+ assert isinstance(val, str)+ return int(val)+++def _rowspan(cell: Any) -> int:+ """读取 HTML 单元格 rowspan,非法值交由上层安全降级。"""+ val = cell.get("rowspan", "1")+ assert isinstance(val, str)+ return int(val)+++def _normalize_cell_text(cell: Tag) -> str:+ """生成表头匹配使用的半角无空白文本。"""+ return "".join(full_to_half(cell.get_text()).split())+++def _display_cell_text(cell: Tag) -> str:+ """生成保留内部空白的半角展示文本。"""+ return full_to_half(cell.get_text().strip())+++def _scan_rows(rows: list[Tag], initial_occupied: dict[int, set[int]] | None = None, start_row_idx: int = 0) -> RowScanResult:+ """单次扫描 HTML 行并缓存有效列、显式列和跨行占位指标。++ ``initial_occupied`` 使用相对首行的偏移记录未来行占位,从而保留跨越+ 前后表边界的 rowspan 结构。+ """+ occupied: dict[int, dict[int, bool]] = {}+ max_cols = 0++ for row_offset, cols in (initial_occupied or {}).items():+ if not cols:+ continue+ occupied[row_offset] = dict.fromkeys(cols, True)+ max_cols = max(max_cols, max(cols) + 1)++ row_effective_cols: list[int] = []+ row_metrics: list[RowMetrics] = []+ last_nonempty_row_metrics: RowMetrics | None = None++ for local_idx, row in enumerate(rows):+ occupied_row = occupied.setdefault(local_idx, {})+ col_idx = 0+ cells = row.find_all(["td", "th"])+ actual_cols = 0++ for cell in cells:+ while col_idx in occupied_row:+ col_idx += 1++ colspan = _colspan(cell)+ rowspan = _rowspan(cell)+ actual_cols += colspan++ for row_offset in range(rowspan):+ target_idx = local_idx + row_offset+ occupied_target = occupied.setdefault(target_idx, {})+ for col in range(col_idx, col_idx + colspan):+ occupied_target[col] = True++ col_idx += colspan+ max_cols = max(max_cols, col_idx)++ effective_cols = max(occupied_row.keys()) + 1 if occupied_row else 0+ row_effective_cols.append(effective_cols)+ max_cols = max(max_cols, effective_cols)++ metrics = RowMetrics(+ row_idx=start_row_idx + local_idx,+ effective_cols=effective_cols,+ actual_cols=actual_cols,+ visual_cols=len(cells),+ )+ row_metrics.append(metrics)+ if cells:+ last_nonempty_row_metrics = metrics++ tail_occupied = {+ row_idx - len(rows): set(cols.keys()) for row_idx, cols in occupied.items() if row_idx >= len(rows) and cols+ }++ return RowScanResult(+ row_effective_cols=row_effective_cols,+ row_metrics=row_metrics,+ total_cols=max_cols,+ last_nonempty_row_metrics=last_nonempty_row_metrics,+ tail_occupied=tail_occupied,+ )+++def _build_row_signature(row: Tag, effective_cols: int) -> RowSignature:+ """构建表头检测使用的行结构与文本签名。"""+ cells = row.find_all(["td", "th"])+ return RowSignature(+ effective_cols=effective_cols,+ colspans=tuple(_colspan(cell) for cell in cells),+ rowspans=tuple(_rowspan(cell) for cell in cells),+ normalized_texts=tuple(_normalize_cell_text(cell) for cell in cells),+ display_texts=tuple(_display_cell_text(cell) for cell in cells),+ )+++def _build_front_cache(+ rows: list[Tag], max_header_rows: int = MAX_HEADER_ROWS+) -> tuple[list[RowSignature], dict[int, RowMetrics]]:+ """缓存表格前部表头签名和首批数据行指标。"""+ front_limit = min(len(rows), max_header_rows + 1)+ front_rows = rows[:front_limit]+ front_scan = _scan_rows(front_rows)++ front_header_info = [+ _build_row_signature(front_rows[idx], front_scan.row_effective_cols[idx])+ for idx in range(min(len(front_rows), max_header_rows))+ ]+ front_first_data_row_metrics = dict(enumerate(front_scan.row_metrics))+ return front_header_info, front_first_data_row_metrics+++def _refresh_table_state_metrics(state: TableMergeState) -> None:+ """HTML 结构调整后重新计算表格状态指标。"""+ scan = _scan_rows(state.rows)+ state.row_effective_cols = scan.row_effective_cols+ state.total_cols = scan.total_cols+ state.last_data_row_metrics = scan.last_nonempty_row_metrics+ state.tail_occupied = scan.tail_occupied+ state.front_header_info, state.front_first_data_row_metrics = _build_front_cache(state.rows)+++def build_table_state_from_html(+ html: str,+ max_header_rows: int = MAX_HEADER_ROWS,+) -> TableMergeState | None:+ """从原始 HTML 构建 TableMergeState,不依赖 MinerU block 结构。++ 供外部工具(如 mineru-vl-utils)调用,用于跨页表格结构检测。+ 返回的 state 供 HTML-only 结构 helper 使用,不包含 MinerU block 所有者。+ """+ if not html:+ return None++ soup = BeautifulSoup(html, "html.parser")+ tbody = soup.find("tbody") or soup.find("table")+ rows = soup.find_all("tr")+ if tbody is None or not rows:+ return None++ try:+ scan = _scan_rows(rows)+ front_header_info, front_first_data_row_metrics = _build_front_cache(+ rows,+ max_header_rows=max_header_rows,+ )+ except (AssertionError, TypeError, ValueError):+ return None+ if scan.total_cols <= 0 or scan.last_nonempty_row_metrics is None:+ return None++ return TableMergeState(+ owner_block=None,+ body_block=None,+ soup=soup,+ tbody=tbody,+ rows=rows,+ total_cols=scan.total_cols,+ front_header_info=front_header_info,+ front_first_data_row_metrics=front_first_data_row_metrics,+ last_data_row_metrics=scan.last_nonempty_row_metrics,+ row_effective_cols=scan.row_effective_cols,+ tail_occupied=scan.tail_occupied,+ )+++def _serialize_table_state_html(state: TableMergeState) -> bool:+ """将合并后的 BeautifulSoup 写回克隆表体,缺失表体时返回失败。"""+ if state.body_block is None:+ return False+ state.body_block["content"] = str(state.soup)+ state.dirty = False+ return True+++def calculate_table_total_columns(soup: BeautifulSoup) -> int:+ """计算表格的总列数,通过分析整个表格结构来处理rowspan和colspan."""+ rows = soup.find_all("tr")+ return _scan_rows(rows).total_cols if rows else 0+++def build_table_occupied_matrix(soup: BeautifulSoup) -> dict[int, int]:+ """构建表格的占用矩阵,返回每行的有效列数."""+ rows = soup.find_all("tr")+ if not rows:+ return {}++ scan = _scan_rows(rows)+ return dict(enumerate(scan.row_effective_cols))+++def calculate_row_effective_columns(soup: BeautifulSoup, row_idx: int) -> int:+ """计算指定行的有效列数(考虑rowspan占用)."""+ row_effective_cols = build_table_occupied_matrix(soup)+ return row_effective_cols.get(row_idx, 0)+++def calculate_row_columns(row: Tag) -> int:+ """计算表格行的实际列数,考虑colspan属性."""+ cells = row.find_all(["td", "th"])+ column_count = 0++ for cell in cells:+ colspan = _colspan(cell)+ column_count += colspan++ return column_count+++def calculate_visual_columns(row: Tag) -> int:+ """计算表格行的视觉列数(实际td/th单元格数量,不考虑colspan)."""+ cells = row.find_all(["td", "th"])+ return len(cells)+++def _scan_row_visual_sources(+ rows: list[Tag],+ target_row_index: int,+ initial_occupied: dict[int, set[int]] | None = None,+) -> tuple[dict[int, tuple[int, int]], int]:+ """扫描到目标行,记录每个视觉列当前由哪个源单元格占据。++ initial_occupied 表示从上一页延续过来的 rowspan 占位,行号相对+ rows[0] 计算。它只作为虚拟源单元格参与列定位,不对应当前页真实+ <td>/<th> 元素。+ """+ if target_row_index < 0:+ target_row_index += len(rows)+ if target_row_index < 0 or target_row_index >= len(rows):+ return {}, 0++ # occupied[row_idx][col_idx] = (source_row_idx, source_cell_idx)+ occupied: dict[int, dict[int, tuple[int, int]]] = {}+ total_cols = 0+ for row_offset, cols in (initial_occupied or {}).items():+ if not cols:+ continue+ occupied[row_offset] = {col: (-1, col) for col in cols}+ total_cols = max(total_cols, max(cols) + 1)++ for r_idx in range(target_row_index + 1):+ occupied_row = occupied.setdefault(r_idx, {})+ col_idx = 0+ cells = rows[r_idx].find_all(["td", "th"])+ for cell_idx, cell in enumerate(cells):+ while col_idx in occupied_row:+ col_idx += 1+ colspan = _colspan(cell)+ rowspan = _rowspan(cell)+ source_marker = (r_idx, cell_idx)+ for ro in range(rowspan):+ target_idx = r_idx + ro+ occ = occupied.setdefault(target_idx, {})+ for c in range(col_idx, col_idx + colspan):+ occ[c] = source_marker+ col_idx += colspan+ total_cols = max(total_cols, col_idx)++ return occupied.get(target_row_index, {}), total_cols+++def build_visual_col_mapping(+ rows: list[Tag],+ target_row_index: int,+ initial_occupied: dict[int, set[int]] | None = None,+) -> list[int]:+ """构建目标行中每个显式 <td>/<th> 元素到视觉列位置的映射。++ 该映射会正确考虑从前序行继承而来的 rowspan 占位。+ initial_occupied 可额外传入上一页延续到当前切片的 rowspan 占位。+ """+ if target_row_index < 0:+ target_row_index += len(rows)+ if target_row_index < 0 or target_row_index >= len(rows):+ return []++ target_occupied, _ = _scan_row_visual_sources(+ rows,+ target_row_index,+ initial_occupied=initial_occupied,+ )++ col_idx = 0+ mapping = []+ target_cells = rows[target_row_index].find_all(["td", "th"])+ for cell in target_cells:+ while col_idx in target_occupied and target_occupied[col_idx][0] < target_row_index:+ col_idx += 1+ mapping.append(col_idx)+ colspan = _colspan(cell)+ col_idx += colspan+ return mapping+++def build_row_rendered_cell_segments(+ rows: list[Tag],+ target_row_index: int,+ initial_occupied: dict[int, set[int]] | None = None,+) -> list[RenderedCellSegment]:+ """构建目标行的渲染单元格段,保留每段覆盖的视觉列范围。++ 该函数复用表格行视觉来源扫描结果,语义与 calculate_row_rendered_segments()+ 保持一致:colspan 只算一个渲染段,rowspan 延续下来的单元格也会作为+ 目标行的渲染段返回。+ """+ if target_row_index < 0:+ target_row_index += len(rows)+ if target_row_index < 0 or target_row_index >= len(rows):+ return []++ target_occupied, total_cols = _scan_row_visual_sources(+ rows,+ target_row_index,+ initial_occupied=initial_occupied,+ )+ if total_cols == 0:+ return []++ segments: list[RenderedCellSegment] = []+ current_marker: tuple[int, int] | None = None+ current_start_col: int | None = None+ current_text = ""++ # 连续视觉列来自同一个源单元格时,合并为一个渲染段。+ for col_idx in range(total_cols):+ marker = target_occupied.get(col_idx)+ if marker is None:+ if current_marker is not None and current_start_col is not None:+ segments.append(RenderedCellSegment(text=current_text, start_col=current_start_col, end_col=col_idx))+ current_marker = None+ current_start_col = None+ current_text = ""+ continue++ if marker != current_marker:+ if current_marker is not None and current_start_col is not None:+ segments.append(RenderedCellSegment(text=current_text, start_col=current_start_col, end_col=col_idx))+ current_marker = marker+ current_start_col = col_idx+ source_row_idx, source_cell_idx = marker+ current_text = ""+ if source_row_idx >= 0:+ source_cells = rows[source_row_idx].find_all(["td", "th"])+ if source_cell_idx < len(source_cells):+ current_text = _display_cell_text(source_cells[source_cell_idx])++ if current_marker is not None and current_start_col is not None:+ segments.append(RenderedCellSegment(text=current_text, start_col=current_start_col, end_col=total_cols))++ return segments+++def calculate_row_rendered_segments(rows: list[Tag], target_row_index: int) -> int:+ """计算目标行渲染后的视觉段数。++ 段数按“渲染出来的单元格块”统计:+ - 当前行显式单元格各算一段,不展开 colspan+ - 从前序行继承而来的 rowspan 占位也算段+ - 只有连续列且来自同一个源单元格时才算同一段+ """+ target_occupied, total_cols = _scan_row_visual_sources(rows, target_row_index)+ if total_cols == 0:+ return 0++ segment_count = 0+ previous_marker: tuple[int, int] | None = None++ for col_idx in range(total_cols):+ marker = target_occupied.get(col_idx)+ if marker is None:+ previous_marker = None+ continue+ if marker != previous_marker:+ segment_count += 1+ previous_marker = marker++ return segment_countdiff --git a/mineru/backend/postprocess/table_merge/models.py b/mineru/backend/postprocess/table_merge/models.pynew file mode 100644index 00000000..1bc3ab57--- /dev/null+++ b/mineru/backend/postprocess/table_merge/models.py@@ -0,0 +1,77 @@+# Copyright (c) Opendatalab. All rights reserved.+"""跨页表格合并使用的内部状态模型。"""++from __future__ import annotations++from dataclasses import dataclass+from typing import Any, TypeAlias++MAX_HEADER_ROWS = 5++BlockDict: TypeAlias = dict[str, Any]+PageInfoDict: TypeAlias = dict[str, Any]+CalculationBBox: TypeAlias = tuple[int, int, int, int]+++@dataclass+class RowMetrics:+ """记录单行的有效列、实际列和视觉列指标。"""++ row_idx: int+ effective_cols: int+ actual_cols: int+ visual_cols: int+++@dataclass+class RowSignature:+ """记录表头行的列结构与规范化文本签名。"""++ effective_cols: int+ colspans: tuple[int, ...]+ rowspans: tuple[int, ...]+ normalized_texts: tuple[str, ...]+ display_texts: tuple[str, ...]++ @property+ def cell_count(self) -> int:+ """返回签名中的显式单元格数量。"""+ return len(self.colspans)+++@dataclass+class RenderedCellSegment:+ """记录一个渲染单元格覆盖的视觉列区间。"""++ text: str+ start_col: int+ end_col: int+++@dataclass+class RowScanResult:+ """封装一次 HTML 行扫描得到的列指标与跨行占位。"""++ row_effective_cols: list[int]+ row_metrics: list[RowMetrics]+ total_cols: int+ last_nonempty_row_metrics: RowMetrics | None+ tail_occupied: dict[int, set[int]]+++@dataclass+class TableMergeState:+ """缓存单张表格的 block 所有者、HTML 树和结构指标。"""++ owner_block: BlockDict | None+ body_block: BlockDict | None+ soup: Any+ tbody: Any+ rows: list[Any]+ total_cols: int+ front_header_info: list[RowSignature]+ front_first_data_row_metrics: dict[int, RowMetrics]+ last_data_row_metrics: RowMetrics | None+ row_effective_cols: list[int]+ tail_occupied: dict[int, set[int]]+ dirty: bool = Falsediff --git a/mineru/backend/utils/table_continuation.py b/mineru/backend/postprocess/table_merge/rules.pysimilarity index 91%rename from mineru/backend/utils/table_continuation.pyrename to mineru/backend/postprocess/table_merge/rules.pyindex 55eacad7..f033755a 100644--- a/mineru/backend/utils/table_continuation.py+++ b/mineru/backend/postprocess/table_merge/rules.py@@ -1,6 +1,7 @@# Copyright (c) Opendatalab. All rights reserved.+"""跨页表格延续文本与 caption 的轻量判定规则。"""-from .char_utils import full_to_half+from mineru.utils.text_utils import full_to_halfCONTINUATION_END_MARKERS = ["(续)",diff --git a/mineru/backend/postprocess/table_merge/structure.py b/mineru/backend/postprocess/table_merge/structure.pynew file mode 100644index 00000000..887e3745--- /dev/null+++ b/mineru/backend/postprocess/table_merge/structure.py@@ -0,0 +1,227 @@+# Copyright (c) Opendatalab. All rights reserved.+"""跨页表格的表头、宽度和边界行结构判定。"""++from __future__ import annotations++from typing import Any++from bs4 import Tag++from mineru.types import BlockType++from .blocks import (+ _bbox_for_calculation,+ _is_continuation_caption,+ _is_post_table_non_continuation_caption,+ _table_children,+)+from .html import _colspan, _rowspan, calculate_row_rendered_segments+from .models import MAX_HEADER_ROWS, TableMergeState+++def detect_table_headers(+ state1: TableMergeState, state2: TableMergeState, max_header_rows: int = MAX_HEADER_ROWS+) -> tuple[int, bool, list[list[str]]]:+ """检测并比较两个表格的表头,仅扫描前几行."""+ front_rows1 = state1.front_header_info[:max_header_rows]+ front_rows2 = state2.front_header_info[:max_header_rows]++ min_rows = min(len(front_rows1), len(front_rows2), max_header_rows)+ header_rows = 0+ headers_match = True+ header_texts = []++ for row_idx in range(min_rows):+ row1 = front_rows1[row_idx]+ row2 = front_rows2[row_idx]+ structure_match = (+ row1.cell_count == row2.cell_count+ and row1.effective_cols == row2.effective_cols+ and row1.colspans == row2.colspans+ and row1.rowspans == row2.rowspans+ and row1.normalized_texts == row2.normalized_texts+ )++ if structure_match:+ header_rows += 1+ header_texts.append(list(row1.display_texts))+ else:+ headers_match = header_rows > 0+ break++ if header_rows == 0:+ header_rows, headers_match, header_texts = _detect_table_headers_visual(state1, state2, max_header_rows=max_header_rows)++ return header_rows, headers_match, header_texts+++def _detect_table_headers_visual(+ state1: TableMergeState,+ state2: TableMergeState,+ max_header_rows: int = MAX_HEADER_ROWS,+) -> tuple[int, bool, list[list[str]]]:+ """基于视觉一致性检测表头(只比较文本内容,忽略colspan/rowspan差异)."""+ front_rows1 = state1.front_header_info[:max_header_rows]+ front_rows2 = state2.front_header_info[:max_header_rows]++ min_rows = min(len(front_rows1), len(front_rows2), max_header_rows)+ header_rows = 0+ headers_match = True+ header_texts = []++ for row_idx in range(min_rows):+ row1 = front_rows1[row_idx]+ row2 = front_rows2[row_idx]+ # OCR 识别表头时可能丢失 colspan/rowspan,这里用渲染段数约束视觉一致性。+ rendered_segments1 = calculate_row_rendered_segments(state1.rows, row_idx)+ rendered_segments2 = calculate_row_rendered_segments(state2.rows, row_idx)+ if row1.normalized_texts == row2.normalized_texts and rendered_segments1 == rendered_segments2:+ header_rows += 1+ header_texts.append(list(row1.display_texts))+ else:+ headers_match = header_rows > 0+ break++ if header_rows == 0:+ headers_match = False++ return header_rows, headers_match, header_texts+++def _expand_header_count_by_rowspan(rows: list[Tag], header_count: int) -> int:+ """按表头 rowspan 覆盖范围扩展跳过行数。++ 跨页续表的第一行表头可能包含 rowspan。如果只跳过已匹配的首行,+ 被该 rowspan 覆盖的后续表头行会失去占位来源,合并后形成半截表头。+ 因此跳过重复表头时,需要覆盖所有由已跳过表头行跨行占据的行。+ """+ if header_count <= 0 or not rows:+ return header_count++ expanded_header_count = min(header_count, len(rows))+ row_idx = 0+ while row_idx < expanded_header_count:+ row = rows[row_idx]+ for cell in row.find_all(["td", "th"]):+ rowspan = _rowspan(cell)+ if rowspan > 1:+ expanded_header_count = max(expanded_header_count, row_idx + rowspan)+ expanded_header_count = min(expanded_header_count, len(rows))+ row_idx += 1++ return expanded_header_count+++def can_merge_by_structure(+ current_state: TableMergeState,+ previous_state: TableMergeState,+ current_bbox: Any = None,+ previous_bbox: Any = None,+) -> bool:+ """仅基于表格结构判断是否可合并(不检查 caption/footnote)。++ 供外部工具调用,忽略 caption 和 footnote 检查。+ """+ if (+ current_bbox is not None+ and previous_bbox is not None+ and not _table_widths_are_compatible(+ current_bbox,+ previous_bbox,+ )+ ):+ return False++ if (+ previous_state.total_cols <= 0+ or current_state.total_cols <= 0+ or previous_state.last_data_row_metrics is None+ or current_state.last_data_row_metrics is None+ ):+ return False++ if previous_state.total_cols == current_state.total_cols:+ return True++ return check_rows_match(previous_state, current_state)+++def _table_widths_are_compatible(current_bbox: Any, previous_bbox: Any) -> bool:+ """使用千分位 bbox 判断两张表的宽度相对差是否小于百分之十。"""+ current_calc_bbox = _bbox_for_calculation(current_bbox)+ previous_calc_bbox = _bbox_for_calculation(previous_bbox)+ if current_calc_bbox is None or previous_calc_bbox is None:+ return False++ current_width = current_calc_bbox[2] - current_calc_bbox[0]+ previous_width = previous_calc_bbox[2] - previous_calc_bbox[0]+ min_width = min(current_width, previous_width)+ return min_width > 0 and abs(current_width - previous_width) / min_width < 0.1+++def can_merge_tables(current_state: TableMergeState, previous_state: TableMergeState) -> bool:+ """根据 dict 表格的辅助文本、宽度和 HTML 结构判断是否可合并。"""+ current_table_block = current_state.owner_block+ previous_table_block = previous_state.owner_block++ if not isinstance(previous_table_block, dict) or not isinstance(current_table_block, dict):+ return False++ previous_children = _table_children(previous_table_block)+ current_children = _table_children(current_table_block)+ footnote_count = sum(1 for block in previous_children if block.get("type") == BlockType.TABLE_FOOTNOTE)+ caption_blocks = [block for block in current_children if block.get("type") == BlockType.TABLE_CAPTION]+ merge_caption_blocks = [+ block for block in caption_blocks if not _is_post_table_non_continuation_caption(current_table_block, block)+ ]+ if merge_caption_blocks:+ has_continuation_marker = any(_is_continuation_caption(block) for block in merge_caption_blocks)++ if not has_continuation_marker:+ return False++ if footnote_count > 1:+ return False+ elif footnote_count > 0:+ return False++ if not _table_widths_are_compatible(current_table_block.get("bbox"), previous_table_block.get("bbox")):+ return False++ return can_merge_by_structure(current_state, previous_state)+++def check_rows_match(previous_state: TableMergeState, current_state: TableMergeState) -> bool:+ """检查表格边界行是否匹配."""+ last_row_metrics = previous_state.last_data_row_metrics+ if last_row_metrics is None:+ return False++ header_count, _, _ = detect_table_headers(previous_state, current_state)+ header_count = _expand_header_count_by_rowspan(current_state.rows, header_count)+ first_data_row_metrics = current_state.front_first_data_row_metrics.get(header_count)+ if first_data_row_metrics is None:+ return False++ previous_rendered_segments = calculate_row_rendered_segments(previous_state.rows, last_row_metrics.row_idx)+ current_rendered_segments = calculate_row_rendered_segments(current_state.rows, first_data_row_metrics.row_idx)++ return (+ last_row_metrics.effective_cols == first_data_row_metrics.effective_cols+ or last_row_metrics.actual_cols == first_data_row_metrics.actual_cols+ or previous_rendered_segments == current_rendered_segments+ )+++def check_row_columns_match(row1: Tag, row2: Tag) -> bool:+ """判断两行显式单元格数量与 colspan 结构是否一致。"""+ cells1 = row1.find_all(["td", "th"])+ cells2 = row2.find_all(["td", "th"])+ if len(cells1) != len(cells2):+ return False+ for cell1, cell2 in zip(cells1, cells2):+ colspan1 = _colspan(cell1)+ colspan2 = _colspan(cell2)+ if colspan1 != colspan2:+ return False+ return Truediff --git a/mineru/backend/utils/visual_magic_model_utils.py b/mineru/backend/postprocess/visual.pysimilarity index 90%rename from mineru/backend/utils/visual_magic_model_utils.pyrename to mineru/backend/postprocess/visual.pyindex e1ef1f6a..968ba078 100644--- a/mineru/backend/utils/visual_magic_model_utils.py+++ b/mineru/backend/postprocess/visual.py@@ -1,7 +1,8 @@# Copyright (c) Opendatalab. All rights reserved.+"""视觉主体、标题和脚注的 raw block 关联与分组。"""+from __future__ import annotations-import refrom copy import deepcopyfrom typing import Any@@ -12,9 +13,9 @@ from ...types import (VISUAL_RELATION_IGNORED_TYPES,VISUAL_TYPE_MAPPING,)-from .boxbase import bbox_center_distance, bbox_distance-from .raw_block_types import RAW_CAPTION, RAW_FOOTNOTE-from .table_continuation import is_table_continuation_text+from mineru.utils.bbox_utils import bbox_center_distance, bbox_distance+from mineru.types import RAW_CAPTION, RAW_FOOTNOTE+from .table_merge.rules import is_table_continuation_textINLINE_CAPTION_FRAGMENT_TYPES = {BlockType.TEXT, RAW_FOOTNOTE}STACKED_TABLE_CAPTION_CLUSTER_TYPES = {@@ -76,49 +77,6 @@ def _block_line_items(block: BlockDict) -> list[Any]:return list(block.get("lines") or [])-def isolated_formula_clean(txt: str) -> str:- latex = txt[:]- if latex.startswith("\\["):- latex = latex[2:]- if latex.endswith("\\]"):- latex = latex[:-2]- latex = latex.strip()- return latex---def code_content_clean(content: str | None) -> str:- """清理代码内容,移除Markdown代码块的开始和结束标记"""- if not content:- return ""-- lines = content.splitlines()- start_idx = 0- end_idx = len(lines)-- if lines and lines[0].startswith("```"):- start_idx = 1-- if lines and end_idx > start_idx and lines[end_idx - 1].strip() == "```":- end_idx -= 1-- if start_idx < end_idx:- return "\n".join(lines[start_idx:end_idx]).strip()- return ""---def clean_content(content: str | None) -> str | None:- if content and content.count("\\[") == content.count("\\]") and content.count("\\[") > 0:-- def replace_pattern(match: re.Match) -> str:- inner_content = match.group(1)- return f"[{inner_content}]"-- pattern = r"\\\[(.*?)\\\]"- content = re.sub(pattern, replace_pattern, content)-- return content--def fallback_inline_caption_fragments(blocks: list[BlockDict],visual_main_types: dict[str, str] | set[str],@@ -192,9 +150,7 @@ def fallback_leading_table_continuation_captions(returneffective_blocks = [- block- for block in sorted(blocks, key=_block_index)- if _block_type(block) not in VISUAL_RELATION_IGNORED_TYPES+ block for block in sorted(blocks, key=_block_index) if _block_type(block) not in VISUAL_RELATION_IGNORED_TYPES]if len(effective_blocks) < 2:return@@ -429,43 +385,24 @@ def regroup_visual_blocks("""按 bbox 或纯阅读顺序将通用 caption/footnote 归入视觉主体。"""ordered_blocks = sorted(blocks, key=_block_index)if use_bbox:- visual_relation_blocks = [- block- for block in ordered_blocks- if not is_transparent_visual_relation_block(block)- ]+ visual_relation_blocks = [block for block in ordered_blocks if not is_transparent_visual_relation_block(block)]else:visual_relation_blocks = ordered_blocks- position_by_index = {- _block_index(block): pos- for pos, block in enumerate(visual_relation_blocks)- }- main_blocks = [- block- for block in visual_relation_blocks- if _block_type(block) in VISUAL_MAIN_TYPES- ]- child_blocks = [- block- for block in visual_relation_blocks- if _block_type(block) in VISUAL_CHILD_TYPE_MAPPING- ]+ position_by_index = {_block_index(block): pos for pos, block in enumerate(visual_relation_blocks)}+ main_blocks = [block for block in visual_relation_blocks if _block_type(block) in VISUAL_MAIN_TYPES]+ child_blocks = [block for block in visual_relation_blocks if _block_type(block) in VISUAL_CHILD_TYPE_MAPPING]grouped_children: dict[int, dict[str, list[BlockDict]]] = {- _block_index(block): {"captions": [], "footnotes": []}- for block in main_blocks+ _block_index(block): {"captions": [], "footnotes": []} for block in main_blocks}unmatched_child_blocks: list[BlockDict] = []for child_block in child_blocks:- child_visual_type, child_kind = VISUAL_CHILD_TYPE_MAPPING[- _block_type(child_block)- ]+ child_visual_type, child_kind = VISUAL_CHILD_TYPE_MAPPING[_block_type(child_block)]candidate_main_blocks = [main_blockfor main_block in main_blocks- if child_visual_type is None- or VISUAL_MAIN_TYPES[_block_type(main_block)] == child_visual_type+ if child_visual_type is None or VISUAL_MAIN_TYPES[_block_type(main_block)] == child_visual_type]parent_block = find_best_visual_parent(child_block,@@ -478,9 +415,7 @@ def regroup_visual_blocks(unmatched_child_blocks.append(child_block)continue- grouped_children[_block_index(parent_block)][f"{child_kind}s"].append(- child_block- )+ grouped_children[_block_index(parent_block)][f"{child_kind}s"].append(child_block)grouped_blocks: dict[str, list[BlockDict]] = {BlockType.IMAGE: [],@@ -595,11 +530,7 @@ def find_best_visual_parent(if not use_bbox:child_index = _block_index(child_block)- previous_candidates = [- main_block- for main_block in closest_index_candidates- if _block_index(main_block) < child_index- ]+ previous_candidates = [main_block for main_block in closest_index_candidates if _block_index(main_block) < child_index]if previous_candidates:return max(previous_candidates, key=_block_index)return min(closest_index_candidates, key=_block_index)@@ -650,10 +581,7 @@ def effective_visual_index_diff(type_by_index: dict[int, str] | None = None,) -> int:"""按有效块序列计算视觉子块与主体距离,吸收的 image 子成员视为零成本。"""- position_by_index = {- _block_index(block): position- for position, block in enumerate(ordered_blocks)- }+ position_by_index = {_block_index(block): position for position, block in enumerate(ordered_blocks)}child_pos = position_by_index[_block_index(child_block)]main_pos = position_by_index[_block_index(main_block)]start_pos = min(child_pos, main_pos)@@ -676,6 +604,7 @@ def is_visual_neighbor(type_by_index: dict[int, str] | None = None,use_bbox: bool = True,) -> bool:+ """判断视觉标题或脚注与主体之间是否仅隔着允许跳过的关联块。"""child_kind = child_kind_from_type(block_type(child_block, type_by_index))child_index = _block_index(child_block)main_index = _block_index(main_block)diff --git a/mineru/backend/utils/boxbase.py b/mineru/backend/utils/boxbase.pydeleted file mode 100644index bc295761..00000000--- a/mineru/backend/utils/boxbase.py+++ /dev/null@@ -1,129 +0,0 @@-# Copyright (c) Opendatalab. All rights reserved.-from __future__ import annotations--import math--from ...types import BBox---def bbox_relative_pos(bbox1: BBox, bbox2: BBox) -> tuple[bool, bool, bool, bool]:- """判断两个矩形框的相对位置关系.-- Args:- bbox1: 一个四元组,表示第一个矩形框的左上角和右下角的坐标,格式为(x1, y1, x1b, y1b)- bbox2: 一个四元组,表示第二个矩形框的左上角和右下角的坐标,格式为(x2, y2, x2b, y2b)-- Returns:- 一个四元组,表示矩形框1相对于矩形框2的位置关系,格式为(left, right, bottom, top)- 其中,left表示矩形框1是否在矩形框2的左侧,right表示矩形框1是否在矩形框2的右侧,- bottom表示矩形框1是否在矩形框2的下方,top表示矩形框1是否在矩形框2的上方- """- x1, y1, x1b, y1b = bbox1- x2, y2, x2b, y2b = bbox2-- left = x2b < x1- right = x1b < x2- bottom = y2b < y1- top = y1b < y2- return left, right, bottom, top---def bbox_distance(bbox1: BBox, bbox2: BBox) -> float:- """计算两个矩形框的距离。-- Args:- bbox1 (tuple): 第一个矩形框的坐标,格式为 (x1, y1, x2, y2),其中 (x1, y1) 为左上角坐标,(x2, y2) 为右下角坐标。- bbox2 (tuple): 第二个矩形框的坐标,格式为 (x1, y1, x2, y2),其中 (x1, y1) 为左上角坐标,(x2, y2) 为右下角坐标。-- Returns:- float: 矩形框之间的距离。- """-- def dist(point1: tuple[float, float], point2: tuple[float, float]) -> float: # noqa: ANN202- return math.sqrt((point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2)-- x1, y1, x1b, y1b = bbox1- x2, y2, x2b, y2b = bbox2-- left, right, bottom, top = bbox_relative_pos(bbox1, bbox2)-- if top and left:- return dist((x1, y1b), (x2b, y2))- elif left and bottom:- return dist((x1, y1), (x2b, y2b))- elif bottom and right:- return dist((x1b, y1), (x2, y2b))- elif right and top:- return dist((x1b, y1b), (x2, y2))- elif left:- return x1 - x2b- elif right:- return x2 - x1b- elif bottom:- return y1 - y2b- elif top:- return y2 - y1b- return 0.0---def bbox_center_distance(bbox1: BBox, bbox2: BBox) -> float:- """计算两个矩形框中心点之间的欧氏距离。-- Args:- bbox1 (tuple): 第一个矩形框的坐标,格式为 (x1, y1, x2, y2)- bbox2 (tuple): 第二个矩形框的坐标,格式为 (x1, y1, x2, y2)-- Returns:- float: 两个矩形框中心点之间的距离- """- x1, y1, x1b, y1b = bbox1- x2, y2, x2b, y2b = bbox2-- # 计算中心点- center1_x = (x1 + x1b) / 2- center1_y = (y1 + y1b) / 2- center2_x = (x2 + x2b) / 2- center2_y = (y2 + y2b) / 2-- # 计算欧氏距离- return math.sqrt((center1_x - center2_x) ** 2 + (center1_y - center2_y) ** 2)---def calculate_overlap_area_2_minbox_area_ratio(bbox1: BBox, bbox2: BBox) -> float:- """计算box1和box2的重叠面积占最小面积的box的比例."""- # Determine the coordinates of the intersection rectangle- x_left = max(bbox1[0], bbox2[0])- y_top = max(bbox1[1], bbox2[1])- x_right = min(bbox1[2], bbox2[2])- y_bottom = min(bbox1[3], bbox2[3])-- if x_right < x_left or y_bottom < y_top:- return 0.0-- # The area of overlap area- intersection_area = (x_right - x_left) * (y_bottom - y_top)- min_box_area = min([(bbox1[2] - bbox1[0]) * (bbox1[3] - bbox1[1]), (bbox2[3] - bbox2[1]) * (bbox2[2] - bbox2[0])])- if min_box_area == 0:- return 0- else:- return intersection_area / min_box_area---def calculate_overlap_area_in_bbox1_area_ratio(bbox1: BBox, bbox2: BBox) -> float:- """计算box1和box2的重叠面积占bbox1的比例."""- # Determine the coordinates of the intersection rectangle- x_left = max(bbox1[0], bbox2[0])- y_top = max(bbox1[1], bbox2[1])- x_right = min(bbox1[2], bbox2[2])- y_bottom = min(bbox1[3], bbox2[3])-- if x_right < x_left or y_bottom < y_top:- return 0.0-- # The area of overlap area- intersection_area = (x_right - x_left) * (y_bottom - y_top)- bbox1_area = (bbox1[2] - bbox1[0]) * (bbox1[3] - bbox1[1])- if bbox1_area == 0:- return 0- else:- return intersection_area / bbox1_areadiff --git a/mineru/backend/utils/formula_number.py b/mineru/backend/utils/formula_number.pydeleted file mode 100644index 41006616..00000000--- a/mineru/backend/utils/formula_number.py+++ /dev/null@@ -1,86 +0,0 @@-# Copyright (c) Opendatalab. All rights reserved.-from __future__ import annotations--from typing import Any--from ...types import BlockType-from .char_utils import full_to_half-from .visual_magic_model_utils import isolated_formula_clean---def normalize_formula_tag_content(tag_content: str) -> str:- """归一化公式编号文本,去掉全角字符和包裹括号后用于 \\tag{}。"""- tag_content = full_to_half(str(tag_content or "").strip())- if tag_content.startswith("("):- tag_content = tag_content[1:].strip()- if tag_content.endswith(")"):- tag_content = tag_content[:-1].strip()- return tag_content---def normalize_formula_content_for_tag(formula_content: str) -> str:- """归一化待合并编号的公式正文,去掉 VLM/Hybrid 可能携带的展示公式分隔符。"""- return isolated_formula_clean(str(formula_content or ""))---def build_tagged_formula_content(formula_content: str, tag_content: str) -> str | None:- """将公式正文和编号文本合成为带 LaTeX tag 的纯公式内容。"""- formula_content = normalize_formula_content_for_tag(formula_content)- tag_content = normalize_formula_tag_content(tag_content)- if not formula_content or not tag_content:- return None- return f"{formula_content}\\tag{{{tag_content}}}"---def _is_hybrid_equation_block(block: dict[str, Any]) -> bool:- """判断 raw Hybrid/VLM block 是否表示可合并编号的行间公式。"""- return str(block.get("type") or "").lower() in {- BlockType.EQUATION,- "display_formula",- }---def _is_hybrid_formula_number_block(block: dict[str, Any]) -> bool:- """判断 raw Hybrid/VLM block 是否表示公式编号。"""- return str(block.get("type") or "").lower() == BlockType.FORMULA_NUMBER---def _append_hybrid_formula_number_tag(equation_block: dict[str, Any], number_block: dict[str, Any]) -> None:- """把 raw Hybrid/VLM 公式编号合并到相邻公式 block 的 content/latex 字段。"""- target_key = "latex" if equation_block.get("latex") else "content"- tagged_content = build_tagged_formula_content(- str(equation_block.get(target_key) or ""),- str(number_block.get("content") or number_block.get("text") or ""),- )- if tagged_content:- equation_block[target_key] = tagged_content---def optimize_hybrid_formula_number_blocks(page_model_list: list[dict[str, Any]]) -> list[dict[str, Any]]:- """合并 Hybrid raw model list 中的 formula_number,并返回新的 block 列表。"""- optimized_blocks: list[dict[str, Any]] = []- blocks = list(page_model_list)- for index, block in enumerate(blocks):- if not _is_hybrid_formula_number_block(block):- optimized_blocks.append(block)- continue-- prev_block = blocks[index - 1] if index > 0 else None- if prev_block and _is_hybrid_equation_block(prev_block):- _append_hybrid_formula_number_tag(prev_block, block)- continue-- next_block = blocks[index + 1] if index + 1 < len(blocks) else None- next_next_block = blocks[index + 2] if index + 2 < len(blocks) else None- if (- next_block- and _is_hybrid_equation_block(next_block)- and (next_next_block is None or not _is_hybrid_formula_number_block(next_next_block))- ):- _append_hybrid_formula_number_tag(next_block, block)- continue-- fallback_block = dict(block)- fallback_block["type"] = BlockType.TEXT- optimized_blocks.append(fallback_block)- return optimized_blocksdiff --git a/mineru/backend/utils/raw_block_types.py b/mineru/backend/utils/raw_block_types.pydeleted file mode 100644index 336379c2..00000000--- a/mineru/backend/utils/raw_block_types.py+++ /dev/null@@ -1,24 +0,0 @@-# Copyright (c) Opendatalab. All rights reserved.-from typing import Literal, TypeAlias--# 这些字符串不能作为公开 Block.type discriminator,只用于 raw 阶段或 Block 内部枚举值。-RawBlockType: TypeAlias = Literal[- "algorithm",- "caption",- "footnote",- "phonetic",-]--RAW_ALGORITHM: RawBlockType = "algorithm"-RAW_CAPTION: RawBlockType = "caption"-RAW_FOOTNOTE: RawBlockType = "footnote"-RAW_PHONETIC: RawBlockType = "phonetic"--RAW_ONLY_BLOCK_TYPES = frozenset(- {- RAW_ALGORITHM,- RAW_CAPTION,- RAW_FOOTNOTE,- RAW_PHONETIC,- }-)diff --git a/mineru/backend/utils/span_orientation.py b/mineru/backend/utils/span_orientation.pydeleted file mode 100644index 7557596f..00000000--- a/mineru/backend/utils/span_orientation.py+++ /dev/null@@ -1,29 +0,0 @@-# Copyright (c) Opendatalab. All rights reserved.-from .analyze_draft import _AnalyzeSpan--VERTICAL_SPAN_HEIGHT_TO_WIDTH_RATIO_THRESHOLD = 2-VERTICAL_SPAN_IN_BLOCK_THRESHOLD = 0.8---def is_vertical_text_block_by_spans(spans: list[_AnalyzeSpan]) -> bool:- """根据块内文本 span 的高宽比判断文本块是否更像竖排文本。"""- valid_span_count = 0- vertical_span_count = 0- for span in spans:- bbox = span.bbox- if not bbox or len(bbox) < 4:- continue-- span_width = bbox[2] - bbox[0]- span_height = bbox[3] - bbox[1]- if span_width <= 0 or span_height <= 0:- continue-- valid_span_count += 1- if span_height / span_width > VERTICAL_SPAN_HEIGHT_TO_WIDTH_RATIO_THRESHOLD:- vertical_span_count += 1-- if valid_span_count == 0:- return False-- return vertical_span_count / valid_span_count > VERTICAL_SPAN_IN_BLOCK_THRESHOLDdiff --git a/mineru/backend/utils/table_merge.py b/mineru/backend/utils/table_merge.pydeleted file mode 100644index 3ce3b420..00000000--- a/mineru/backend/utils/table_merge.py+++ /dev/null@@ -1,1308 +0,0 @@-# Copyright (c) Opendatalab. All rights reserved.-from __future__ import annotations--import math-from copy import deepcopy-from dataclasses import dataclass-from typing import Any, TypeAlias--from bs4 import BeautifulSoup, Tag--from ...types import BlockType-from .char_utils import full_to_half-from .table_continuation import is_table_continuation_text--MAX_HEADER_ROWS = 5--# 页边界扫描时可忽略的版面噪声块;其余非表格块都会阻断跨页关系。-TABLE_BOUNDARY_IGNORED_TYPES = {- BlockType.HEADER,- BlockType.FOOTER,- BlockType.PAGE_NUMBER,- BlockType.PAGE_FOOTNOTE,- BlockType.ASIDE_TEXT,-}--BlockDict: TypeAlias = dict[str, Any]-PageInfoDict: TypeAlias = dict[str, Any]-CalculationBBox: TypeAlias = tuple[int, int, int, int]---@dataclass-class RowMetrics:- row_idx: int- effective_cols: int- actual_cols: int- visual_cols: int---@dataclass-class RowSignature:- effective_cols: int- colspans: tuple[int, ...]- rowspans: tuple[int, ...]- normalized_texts: tuple[str, ...]- display_texts: tuple[str, ...]-- @property- def cell_count(self) -> int:- return len(self.colspans)---@dataclass-class RenderedCellSegment:- text: str- start_col: int- end_col: int---@dataclass-class RowScanResult:- row_effective_cols: list[int]- row_metrics: list[RowMetrics]- total_cols: int- last_nonempty_row_metrics: RowMetrics | None- tail_occupied: dict[int, set[int]]---@dataclass-class TableMergeState:- owner_block: BlockDict | None- body_block: BlockDict | None- soup: Any- tbody: Any- rows: list[Any]- total_cols: int- front_header_info: list[RowSignature]- front_first_data_row_metrics: dict[int, RowMetrics]- last_data_row_metrics: RowMetrics | None- row_effective_cols: list[int]- tail_occupied: dict[int, set[int]]- dirty: bool = False---def _colspan(cell: Any) -> int:- """读取 HTML 单元格 colspan,非法值交由上层安全降级。"""- val = cell.get("colspan", "1")- assert isinstance(val, str)- return int(val)---def _rowspan(cell: Any) -> int:- """读取 HTML 单元格 rowspan,非法值交由上层安全降级。"""- val = cell.get("rowspan", "1")- assert isinstance(val, str)- return int(val)---def _normalize_cell_text(cell: Tag) -> str:- """生成表头匹配使用的半角无空白文本。"""- return "".join(full_to_half(cell.get_text()).split())---def _display_cell_text(cell: Tag) -> str:- """生成保留内部空白的半角展示文本。"""- return full_to_half(cell.get_text().strip())---def _scan_rows(rows: list[Tag], initial_occupied: dict[int, set[int]] | None = None, start_row_idx: int = 0) -> RowScanResult:- """Scan rows once and cache effective-column metrics.-- initial_occupied stores future-row occupancy relative to the first scanned row- and preserves rowspans that cross a merge boundary.- """- occupied: dict[int, dict[int, bool]] = {}- max_cols = 0-- for row_offset, cols in (initial_occupied or {}).items():- if not cols:- continue- occupied[row_offset] = dict.fromkeys(cols, True)- max_cols = max(max_cols, max(cols) + 1)-- row_effective_cols: list[int] = []- row_metrics: list[RowMetrics] = []- last_nonempty_row_metrics: RowMetrics | None = None-- for local_idx, row in enumerate(rows):- occupied_row = occupied.setdefault(local_idx, {})- col_idx = 0- cells = row.find_all(["td", "th"])- actual_cols = 0-- for cell in cells:- while col_idx in occupied_row:- col_idx += 1-- colspan = _colspan(cell)- rowspan = _rowspan(cell)- actual_cols += colspan-- for row_offset in range(rowspan):- target_idx = local_idx + row_offset- occupied_target = occupied.setdefault(target_idx, {})- for col in range(col_idx, col_idx + colspan):- occupied_target[col] = True-- col_idx += colspan- max_cols = max(max_cols, col_idx)-- effective_cols = max(occupied_row.keys()) + 1 if occupied_row else 0- row_effective_cols.append(effective_cols)- max_cols = max(max_cols, effective_cols)-- metrics = RowMetrics(- row_idx=start_row_idx + local_idx,- effective_cols=effective_cols,- actual_cols=actual_cols,- visual_cols=len(cells),- )- row_metrics.append(metrics)- if cells:- last_nonempty_row_metrics = metrics-- tail_occupied = {- row_idx - len(rows): set(cols.keys()) for row_idx, cols in occupied.items() if row_idx >= len(rows) and cols- }-- return RowScanResult(- row_effective_cols=row_effective_cols,- row_metrics=row_metrics,- total_cols=max_cols,- last_nonempty_row_metrics=last_nonempty_row_metrics,- tail_occupied=tail_occupied,- )---def _build_row_signature(row: Tag, effective_cols: int) -> RowSignature:- """构建表头检测使用的行结构与文本签名。"""- cells = row.find_all(["td", "th"])- return RowSignature(- effective_cols=effective_cols,- colspans=tuple(_colspan(cell) for cell in cells),- rowspans=tuple(_rowspan(cell) for cell in cells),- normalized_texts=tuple(_normalize_cell_text(cell) for cell in cells),- display_texts=tuple(_display_cell_text(cell) for cell in cells),- )---def _build_front_cache(- rows: list[Tag], max_header_rows: int = MAX_HEADER_ROWS-) -> tuple[list[RowSignature], dict[int, RowMetrics]]:- """缓存表格前部表头签名和首批数据行指标。"""- front_limit = min(len(rows), max_header_rows + 1)- front_rows = rows[:front_limit]- front_scan = _scan_rows(front_rows)-- front_header_info = [- _build_row_signature(front_rows[idx], front_scan.row_effective_cols[idx])- for idx in range(min(len(front_rows), max_header_rows))- ]- front_first_data_row_metrics = dict(enumerate(front_scan.row_metrics))- return front_header_info, front_first_data_row_metrics---def _bbox_for_calculation(bbox: Any) -> CalculationBBox | None:- """复制归一化 bbox 并放大为千分位整数,原始字段保持不变。"""- if not isinstance(bbox, (list, tuple)) or len(bbox) != 4:- return None- if any(isinstance(value, bool) or not isinstance(value, (int, float)) for value in bbox):- return None-- values = tuple(float(value) for value in bbox)- if not all(math.isfinite(value) and 0 <= value <= 1 for value in values):- return None-- x0, y0, x1, y1 = (int(round(value * 1000)) for value in values)- if x1 <= x0 or y1 <= y0:- return None- return x0, y0, x1, y1---def _table_children(table_block: BlockDict) -> list[BlockDict]:- """读取 table 根块下的合法 dict 子块。"""- content = table_block.get("content")- if not isinstance(content, list):- return []- return [block for block in content if isinstance(block, dict)]---def _find_table_body_block(table_block: BlockDict) -> BlockDict | None:- """查找 dict table block 中的主体子块。"""- for block in _table_children(table_block):- if block.get("type") == BlockType.TABLE_BODY:- return block- return None---def _build_post_body_child_index(table_block: BlockDict, offset: int) -> int | None:- """为复制到前表的 footnote 生成表体后的安全 index。"""- body_block = _find_table_body_block(table_block)- if body_block is None:- return None- body_index = body_block.get("index")- if not isinstance(body_index, int):- return None-- child_indices = [block.get("index") for block in _table_children(table_block) if isinstance(block.get("index"), int)]- return max([body_index, *child_indices]) + offset---def _block_text(block: BlockDict) -> str:- """递归读取 dict block 的文本内容,供续表标记判断使用。"""- content = block.get("content")- if isinstance(content, str):- return content- if not isinstance(content, list):- return ""- return "".join(_block_text(child) for child in content if isinstance(child, dict))---def _is_continuation_caption(caption_block: BlockDict) -> bool:- """判断 dict caption 文本是否带有续表标记。"""- return is_table_continuation_text(_block_text(caption_block))---def _is_post_table_non_continuation_caption(table_block: BlockDict, caption_block: BlockDict) -> bool:- """判断 caption 是否是误挂到表格下方的新段落标题。-- 这类 caption 位于 table body 下方,且不含续表标记;它不应作为- 当前表的新标题阻断跨页关系判断。- """- if _is_continuation_caption(caption_block):- return False-- body_block = _find_table_body_block(table_block)- if body_block is None:- return False-- body_bbox = _bbox_for_calculation(body_block.get("bbox"))- caption_bbox = _bbox_for_calculation(caption_block.get("bbox"))- if body_bbox is None or caption_bbox is None:- return False-- return caption_bbox[1] >= body_bbox[3]---def _refresh_table_state_metrics(state: TableMergeState) -> None:- """HTML 结构调整后重新计算表格状态指标。"""- scan = _scan_rows(state.rows)- state.row_effective_cols = scan.row_effective_cols- state.total_cols = scan.total_cols- state.last_data_row_metrics = scan.last_nonempty_row_metrics- state.tail_occupied = scan.tail_occupied- state.front_header_info, state.front_first_data_row_metrics = _build_front_cache(state.rows)---def build_table_state_from_html(- html: str,- max_header_rows: int = MAX_HEADER_ROWS,-) -> TableMergeState | None:- """从原始 HTML 构建 TableMergeState,不依赖 MinerU block 结构。-- 供外部工具(如 mineru-vl-utils)调用,用于跨页表格结构检测。- 返回的 state 供 HTML-only 结构 helper 使用,不包含 MinerU block 所有者。- """- if not html:- return None-- soup = BeautifulSoup(html, "html.parser")- tbody = soup.find("tbody") or soup.find("table")- rows = soup.find_all("tr")- if tbody is None or not rows:- return None-- try:- scan = _scan_rows(rows)- front_header_info, front_first_data_row_metrics = _build_front_cache(- rows,- max_header_rows=max_header_rows,- )- except (AssertionError, TypeError, ValueError):- return None- if scan.total_cols <= 0 or scan.last_nonempty_row_metrics is None:- return None-- return TableMergeState(- owner_block=None,- body_block=None,- soup=soup,- tbody=tbody,- rows=rows,- total_cols=scan.total_cols,- front_header_info=front_header_info,- front_first_data_row_metrics=front_first_data_row_metrics,- last_data_row_metrics=scan.last_nonempty_row_metrics,- row_effective_cols=scan.row_effective_cols,- tail_occupied=scan.tail_occupied,- )---def _build_table_state(table_block: BlockDict, max_header_rows: int = MAX_HEADER_ROWS) -> TableMergeState | None:- """从 dict table block 构建结构缓存,非法主体安全返回空。"""- body_block = _find_table_body_block(table_block)- if body_block is None:- return None-- html = body_block.get("content")- if not isinstance(html, str) or not html:- return None-- soup = BeautifulSoup(html, "html.parser")- tbody = soup.find("tbody") or soup.find("table")- rows = soup.find_all("tr")- if tbody is None or not rows:- return None-- scan = _scan_rows(rows)- if scan.total_cols <= 0 or scan.last_nonempty_row_metrics is None:- return None- front_header_info, front_first_data_row_metrics = _build_front_cache(rows, max_header_rows=max_header_rows)-- return TableMergeState(- owner_block=table_block,- body_block=body_block,- soup=soup,- tbody=tbody,- rows=rows,- total_cols=scan.total_cols,- front_header_info=front_header_info,- front_first_data_row_metrics=front_first_data_row_metrics,- last_data_row_metrics=scan.last_nonempty_row_metrics,- row_effective_cols=scan.row_effective_cols,- tail_occupied=scan.tail_occupied,- )---def _get_or_create_table_state(- table_block: BlockDict,- state_cache: dict[int, TableMergeState],- max_header_rows: int = MAX_HEADER_ROWS,-) -> TableMergeState | None:- """按 table dict 对象身份复用 HTML 结构扫描结果。"""- cache_key = id(table_block)- state = state_cache.get(cache_key)- if state is not None:- return state-- try:- state = _build_table_state(table_block, max_header_rows=max_header_rows)- except (AssertionError, TypeError, ValueError):- return None- if state is not None:- state_cache[cache_key] = state- return state---def _serialize_table_state_html(state: TableMergeState) -> bool:- """将合并后的 BeautifulSoup 写回克隆表体,缺失表体时返回失败。"""- if state.body_block is None:- return False- state.body_block["content"] = str(state.soup)- state.dirty = False- return True---def calculate_table_total_columns(soup: BeautifulSoup) -> int:- """计算表格的总列数,通过分析整个表格结构来处理rowspan和colspan."""- rows = soup.find_all("tr")- return _scan_rows(rows).total_cols if rows else 0---def build_table_occupied_matrix(soup: BeautifulSoup) -> dict[int, int]:- """构建表格的占用矩阵,返回每行的有效列数."""- rows = soup.find_all("tr")- if not rows:- return {}-- scan = _scan_rows(rows)- return dict(enumerate(scan.row_effective_cols))---def calculate_row_effective_columns(soup: BeautifulSoup, row_idx: int) -> int:- """计算指定行的有效列数(考虑rowspan占用)."""- row_effective_cols = build_table_occupied_matrix(soup)- return row_effective_cols.get(row_idx, 0)---def calculate_row_columns(row: Tag) -> int:- """计算表格行的实际列数,考虑colspan属性."""- cells = row.find_all(["td", "th"])- column_count = 0-- for cell in cells:- colspan = _colspan(cell)- column_count += colspan-- return column_count---def calculate_visual_columns(row: Tag) -> int:- """计算表格行的视觉列数(实际td/th单元格数量,不考虑colspan)."""- cells = row.find_all(["td", "th"])- return len(cells)---def _scan_row_visual_sources(- rows: list[Tag],- target_row_index: int,- initial_occupied: dict[int, set[int]] | None = None,-) -> tuple[dict[int, tuple[int, int]], int]:- """扫描到目标行,记录每个视觉列当前由哪个源单元格占据。-- initial_occupied 表示从上一页延续过来的 rowspan 占位,行号相对- rows[0] 计算。它只作为虚拟源单元格参与列定位,不对应当前页真实- <td>/<th> 元素。- """- if target_row_index < 0:- target_row_index += len(rows)- if target_row_index < 0 or target_row_index >= len(rows):- return {}, 0-- # occupied[row_idx][col_idx] = (source_row_idx, source_cell_idx)- occupied: dict[int, dict[int, tuple[int, int]]] = {}- total_cols = 0- for row_offset, cols in (initial_occupied or {}).items():- if not cols:- continue- occupied[row_offset] = {col: (-1, col) for col in cols}- total_cols = max(total_cols, max(cols) + 1)-- for r_idx in range(target_row_index + 1):- occupied_row = occupied.setdefault(r_idx, {})- col_idx = 0- cells = rows[r_idx].find_all(["td", "th"])- for cell_idx, cell in enumerate(cells):- while col_idx in occupied_row:- col_idx += 1- colspan = _colspan(cell)- rowspan = _rowspan(cell)- source_marker = (r_idx, cell_idx)- for ro in range(rowspan):- target_idx = r_idx + ro- occ = occupied.setdefault(target_idx, {})- for c in range(col_idx, col_idx + colspan):- occ[c] = source_marker- col_idx += colspan- total_cols = max(total_cols, col_idx)-- return occupied.get(target_row_index, {}), total_cols---def build_visual_col_mapping(- rows: list[Tag],- target_row_index: int,- initial_occupied: dict[int, set[int]] | None = None,-) -> list[int]:- """构建目标行中每个显式 <td>/<th> 元素到视觉列位置的映射。-- 该映射会正确考虑从前序行继承而来的 rowspan 占位。- initial_occupied 可额外传入上一页延续到当前切片的 rowspan 占位。- """- if target_row_index < 0:- target_row_index += len(rows)- if target_row_index < 0 or target_row_index >= len(rows):- return []-- target_occupied, _ = _scan_row_visual_sources(- rows,- target_row_index,- initial_occupied=initial_occupied,- )-- col_idx = 0- mapping = []- target_cells = rows[target_row_index].find_all(["td", "th"])- for cell in target_cells:- while col_idx in target_occupied and target_occupied[col_idx][0] < target_row_index:- col_idx += 1- mapping.append(col_idx)- colspan = _colspan(cell)- col_idx += colspan- return mapping---def build_row_rendered_cell_segments(- rows: list[Tag],- target_row_index: int,- initial_occupied: dict[int, set[int]] | None = None,-) -> list[RenderedCellSegment]:- """构建目标行的渲染单元格段,保留每段覆盖的视觉列范围。-- 该函数复用表格行视觉来源扫描结果,语义与 calculate_row_rendered_segments()- 保持一致:colspan 只算一个渲染段,rowspan 延续下来的单元格也会作为- 目标行的渲染段返回。- """- if target_row_index < 0:- target_row_index += len(rows)- if target_row_index < 0 or target_row_index >= len(rows):- return []-- target_occupied, total_cols = _scan_row_visual_sources(- rows,- target_row_index,- initial_occupied=initial_occupied,- )- if total_cols == 0:- return []-- segments: list[RenderedCellSegment] = []- current_marker: tuple[int, int] | None = None- current_start_col: int | None = None- current_text = ""-- # 连续视觉列来自同一个源单元格时,合并为一个渲染段。- for col_idx in range(total_cols):- marker = target_occupied.get(col_idx)- if marker is None:- if current_marker is not None and current_start_col is not None:- segments.append(RenderedCellSegment(text=current_text, start_col=current_start_col, end_col=col_idx))- current_marker = None- current_start_col = None- current_text = ""- continue-- if marker != current_marker:- if current_marker is not None and current_start_col is not None:- segments.append(RenderedCellSegment(text=current_text, start_col=current_start_col, end_col=col_idx))- current_marker = marker- current_start_col = col_idx- source_row_idx, source_cell_idx = marker- current_text = ""- if source_row_idx >= 0:- source_cells = rows[source_row_idx].find_all(["td", "th"])- if source_cell_idx < len(source_cells):- current_text = _display_cell_text(source_cells[source_cell_idx])-- if current_marker is not None and current_start_col is not None:- segments.append(RenderedCellSegment(text=current_text, start_col=current_start_col, end_col=total_cols))-- return segments---def calculate_row_rendered_segments(rows: list[Tag], target_row_index: int) -> int:- """计算目标行渲染后的视觉段数。-- 段数按“渲染出来的单元格块”统计:- - 当前行显式单元格各算一段,不展开 colspan- - 从前序行继承而来的 rowspan 占位也算段- - 只有连续列且来自同一个源单元格时才算同一段- """- target_occupied, total_cols = _scan_row_visual_sources(rows, target_row_index)- if total_cols == 0:- return 0-- segment_count = 0- previous_marker: tuple[int, int] | None = None-- for col_idx in range(total_cols):- marker = target_occupied.get(col_idx)- if marker is None:- previous_marker = None- continue- if marker != previous_marker:- segment_count += 1- previous_marker = marker-- return segment_count---def detect_table_headers(- state1: TableMergeState, state2: TableMergeState, max_header_rows: int = MAX_HEADER_ROWS-) -> tuple[int, bool, list[list[str]]]:- """检测并比较两个表格的表头,仅扫描前几行."""- front_rows1 = state1.front_header_info[:max_header_rows]- front_rows2 = state2.front_header_info[:max_header_rows]-- min_rows = min(len(front_rows1), len(front_rows2), max_header_rows)- header_rows = 0- headers_match = True- header_texts = []-- for row_idx in range(min_rows):- row1 = front_rows1[row_idx]- row2 = front_rows2[row_idx]- structure_match = (- row1.cell_count == row2.cell_count- and row1.effective_cols == row2.effective_cols- and row1.colspans == row2.colspans- and row1.rowspans == row2.rowspans- and row1.normalized_texts == row2.normalized_texts- )-- if structure_match:- header_rows += 1- header_texts.append(list(row1.display_texts))- else:- headers_match = header_rows > 0- break-- if header_rows == 0:- header_rows, headers_match, header_texts = _detect_table_headers_visual(state1, state2, max_header_rows=max_header_rows)-- return header_rows, headers_match, header_texts---def _detect_table_headers_visual(- state1: TableMergeState,- state2: TableMergeState,- max_header_rows: int = MAX_HEADER_ROWS,-) -> tuple[int, bool, list[list[str]]]:- """基于视觉一致性检测表头(只比较文本内容,忽略colspan/rowspan差异)."""- front_rows1 = state1.front_header_info[:max_header_rows]- front_rows2 = state2.front_header_info[:max_header_rows]-- min_rows = min(len(front_rows1), len(front_rows2), max_header_rows)- header_rows = 0- headers_match = True- header_texts = []-- for row_idx in range(min_rows):- row1 = front_rows1[row_idx]- row2 = front_rows2[row_idx]- # OCR 识别表头时可能丢失 colspan/rowspan,这里用渲染段数约束视觉一致性。- rendered_segments1 = calculate_row_rendered_segments(state1.rows, row_idx)- rendered_segments2 = calculate_row_rendered_segments(state2.rows, row_idx)- if row1.normalized_texts == row2.normalized_texts and rendered_segments1 == rendered_segments2:- header_rows += 1- header_texts.append(list(row1.display_texts))- else:- headers_match = header_rows > 0- break-- if header_rows == 0:- headers_match = False-- return header_rows, headers_match, header_texts---def _expand_header_count_by_rowspan(rows: list[Tag], header_count: int) -> int:- """按表头 rowspan 覆盖范围扩展跳过行数。-- 跨页续表的第一行表头可能包含 rowspan。如果只跳过已匹配的首行,- 被该 rowspan 覆盖的后续表头行会失去占位来源,合并后形成半截表头。- 因此跳过重复表头时,需要覆盖所有由已跳过表头行跨行占据的行。- """- if header_count <= 0 or not rows:- return header_count-- expanded_header_count = min(header_count, len(rows))- row_idx = 0- while row_idx < expanded_header_count:- row = rows[row_idx]- for cell in row.find_all(["td", "th"]):- rowspan = _rowspan(cell)- if rowspan > 1:- expanded_header_count = max(expanded_header_count, row_idx + rowspan)- expanded_header_count = min(expanded_header_count, len(rows))- row_idx += 1-- return expanded_header_count---def can_merge_by_structure(- current_state: TableMergeState,- previous_state: TableMergeState,- current_bbox: Any = None,- previous_bbox: Any = None,-) -> bool:- """仅基于表格结构判断是否可合并(不检查 caption/footnote)。-- 供外部工具调用,忽略 caption 和 footnote 检查。- """- if (- current_bbox is not None- and previous_bbox is not None- and not _table_widths_are_compatible(- current_bbox,- previous_bbox,- )- ):- return False-- if (- previous_state.total_cols <= 0- or current_state.total_cols <= 0- or previous_state.last_data_row_metrics is None- or current_state.last_data_row_metrics is None- ):- return False-- if previous_state.total_cols == current_state.total_cols:- return True-- return check_rows_match(previous_state, current_state)---def _table_widths_are_compatible(current_bbox: Any, previous_bbox: Any) -> bool:- """使用千分位 bbox 判断两张表的宽度相对差是否小于百分之十。"""- current_calc_bbox = _bbox_for_calculation(current_bbox)- previous_calc_bbox = _bbox_for_calculation(previous_bbox)- if current_calc_bbox is None or previous_calc_bbox is None:- return False-- current_width = current_calc_bbox[2] - current_calc_bbox[0]- previous_width = previous_calc_bbox[2] - previous_calc_bbox[0]- min_width = min(current_width, previous_width)- return min_width > 0 and abs(current_width - previous_width) / min_width < 0.1---def can_merge_tables(current_state: TableMergeState, previous_state: TableMergeState) -> bool:- """根据 dict 表格的辅助文本、宽度和 HTML 结构判断是否可合并。"""- current_table_block = current_state.owner_block- previous_table_block = previous_state.owner_block-- if not isinstance(previous_table_block, dict) or not isinstance(current_table_block, dict):- return False-- previous_children = _table_children(previous_table_block)- current_children = _table_children(current_table_block)- footnote_count = sum(1 for block in previous_children if block.get("type") == BlockType.TABLE_FOOTNOTE)- caption_blocks = [block for block in current_children if block.get("type") == BlockType.TABLE_CAPTION]- merge_caption_blocks = [- block for block in caption_blocks if not _is_post_table_non_continuation_caption(current_table_block, block)- ]- if merge_caption_blocks:- has_continuation_marker = any(_is_continuation_caption(block) for block in merge_caption_blocks)-- if not has_continuation_marker:- return False-- if footnote_count > 1:- return False- elif footnote_count > 0:- return False-- if not _table_widths_are_compatible(current_table_block.get("bbox"), previous_table_block.get("bbox")):- return False-- return can_merge_by_structure(current_state, previous_state)---def check_rows_match(previous_state: TableMergeState, current_state: TableMergeState) -> bool:- """检查表格边界行是否匹配."""- last_row_metrics = previous_state.last_data_row_metrics- if last_row_metrics is None:- return False-- header_count, _, _ = detect_table_headers(previous_state, current_state)- header_count = _expand_header_count_by_rowspan(current_state.rows, header_count)- first_data_row_metrics = current_state.front_first_data_row_metrics.get(header_count)- if first_data_row_metrics is None:- return False-- previous_rendered_segments = calculate_row_rendered_segments(previous_state.rows, last_row_metrics.row_idx)- current_rendered_segments = calculate_row_rendered_segments(current_state.rows, first_data_row_metrics.row_idx)-- return (- last_row_metrics.effective_cols == first_data_row_metrics.effective_cols- or last_row_metrics.actual_cols == first_data_row_metrics.actual_cols- or previous_rendered_segments == current_rendered_segments- )---def check_row_columns_match(row1: Tag, row2: Tag) -> bool:- """判断两行显式单元格数量与 colspan 结构是否一致。"""- cells1 = row1.find_all(["td", "th"])- cells2 = row2.find_all(["td", "th"])- if len(cells1) != len(cells2):- return False- for cell1, cell2 in zip(cells1, cells2):- colspan1 = _colspan(cell1)- colspan2 = _colspan(cell2)- if colspan1 != colspan2:- return False- return True---def adjust_table_rows_colspan(- rows: list[Tag],- start_idx: int,- end_idx: int,- row_effective_cols: list[int],- reference_structure: list[int],- reference_visual_cols: int,- target_cols: int,- match_reference_row: Tag,-) -> None:- """调整表格行的colspan属性以匹配目标列数."""- reference_row_copy = deepcopy(match_reference_row)-- for row_idx in range(start_idx, end_idx):- row = rows[row_idx]- cells = row.find_all(["td", "th"])- if not cells:- continue-- current_row_effective_cols = row_effective_cols[row_idx]- current_row_cols = calculate_row_columns(row)-- if current_row_effective_cols >= target_cols or current_row_cols >= target_cols:- continue-- if calculate_visual_columns(row) == reference_visual_cols and check_row_columns_match(row, reference_row_copy):- if len(cells) <= len(reference_structure):- for cell_idx, cell in enumerate(cells):- if cell_idx < len(reference_structure) and reference_structure[cell_idx] > 1:- cell["colspan"] = str(reference_structure[cell_idx])- else:- cols_diff = target_cols - current_row_effective_cols- if cols_diff > 0:- last_cell = cells[-1]- current_last_span = _colspan(last_cell)- last_cell["colspan"] = str(current_last_span + cols_diff)---def _cell_has_semantic_content(cell: Tag) -> bool:- """判断单元格是否仍包含用户可见的语义内容。"""- if cell.get_text(strip=True):- return True-- return cell.find(["img", "svg", "math", "eq", "table", "figure", "object", "embed", "canvas"]) is not None---def _row_has_semantic_content(row: Tag) -> bool:- """判断整行是否仍保留未并回的语义内容。"""- return any(_cell_has_semantic_content(cell) for cell in row.find_all(["td", "th"]))---def _insert_cell_before_visual_column(rows: list[Tag], target_row_index: int, start_vcol: int, cell: Tag) -> None:- """将单元格插入到目标行中对应视觉列之前。"""- target_row = rows[target_row_index]- target_cells = target_row.find_all(["td", "th"])- target_vcol_map = build_visual_col_mapping(rows, target_row_index)-- for idx, target_start_vcol in enumerate(target_vcol_map):- if target_start_vcol >= start_vcol:- target_cells[idx].insert_before(cell)- return-- target_row.append(cell)---def _carry_rowspan_structure_to_next_row(rows: list[Tag], row_idx: int) -> None:- """下沉空白结构占位单元格,避免删除当前行后破坏后续列对齐。"""- next_row_idx = row_idx + 1- if next_row_idx >= len(rows):- return-- current_row = rows[row_idx]- current_cells = current_row.find_all(["td", "th"])- current_vcol_map = build_visual_col_mapping(rows, row_idx)- carried_cells = []-- for cell, start_vcol in zip(current_cells, current_vcol_map):- rowspan = _rowspan(cell)- if rowspan <= 1 or _cell_has_semantic_content(cell):- continue-- carried_cell = deepcopy(cell)- new_rowspan = rowspan - 1- if new_rowspan > 1:- carried_cell["rowspan"] = str(new_rowspan)- else:- carried_cell.attrs.pop("rowspan", None)- carried_cells.append((start_vcol, carried_cell))-- for start_vcol, carried_cell in sorted(carried_cells, key=lambda item: item[0], reverse=True):- _insert_cell_before_visual_column(rows, next_row_idx, start_vcol, carried_cell)---def _clip_overlapped_blank_rowspan_cells(- rows: list[Tag],- initial_occupied: dict[int, set[int]],-) -> bool:- """裁剪被上页 rowspan 覆盖的当前页空白结构占位。-- 跨页表格中,上一页未结束的 rowspan 会通过 initial_occupied 占住- 当前页开头的视觉列。如果当前页表格识别又生成了同位置的空白- rowspan 单元格,这个单元格只是结构占位;直接拼接会把同一视觉列- 当成两列。这里仅裁剪无语义内容的空白占位,真实内容单元格不处理。- """- if not rows or not initial_occupied:- return False-- cells_to_remove = []- cells_to_move = []-- for row_idx, row in enumerate(rows):- cells = row.find_all(["td", "th"])- visual_col_map = build_visual_col_mapping(rows, row_idx)- for cell, start_vcol in zip(cells, visual_col_map):- rowspan = _rowspan(cell)- if rowspan <= 1 or _cell_has_semantic_content(cell):- continue-- colspan = _colspan(cell)- occupied_cols = set(range(start_vcol, start_vcol + colspan))- if not occupied_cols:- continue-- overlap_rows = 0- while overlap_rows < rowspan:- covered_cols = initial_occupied.get(row_idx + overlap_rows, set())- if not occupied_cols.issubset(covered_cols):- break- overlap_rows += 1-- if overlap_rows == 0:- continue-- remaining_rowspan = rowspan - overlap_rows- target_row_idx = row_idx + overlap_rows- if remaining_rowspan > 0 and target_row_idx >= len(rows):- continue-- cells_to_remove.append(cell)- if remaining_rowspan > 0:- moved_cell = deepcopy(cell)- if remaining_rowspan > 1:- moved_cell["rowspan"] = str(remaining_rowspan)- else:- moved_cell.attrs.pop("rowspan", None)- cells_to_move.append((target_row_idx, start_vcol, moved_cell))-- if not cells_to_remove:- return False-- for cell in cells_to_remove:- cell.extract()-- for target_row_idx, start_vcol, moved_cell in sorted(- cells_to_move,- key=lambda item: (item[0], item[1]),- reverse=True,- ):- _insert_cell_before_visual_column(rows, target_row_idx, start_vcol, moved_cell)-- return True---def _apply_cell_merge(- previous_state: TableMergeState,- current_state: TableMergeState,- header_count: int,-) -> bool:- """应用 cell_merge 语义合并。-- 当 cell_merge 中的值为 1 时,将下表第一数据行对应单元格的内容- 追加到上表最后一行对应单元格中。全部为 1 时删除该数据行,- 混合时清空已合并单元格的内容但保留行。-- cell_merge 按视觉列索引对齐,通过构建视觉列映射来正确匹配- 两个表格中可能因 rowspan 而具有不同 <td> 元素数量的行。- 元数据仅从当前页 table body 读取,不依赖外层 table block。- """- current_body_block = current_state.body_block- if not isinstance(current_body_block, dict):- return False-- cell_merge = current_body_block.get("cell_merge")- if not isinstance(cell_merge, list) or not cell_merge:- return False-- rows2 = current_state.rows- if header_count >= len(rows2):- return False- if not previous_state.rows:- return False-- first_data_row = rows2[header_count]- last_row = previous_state.rows[-1]-- cells1 = last_row.find_all(["td", "th"])- cells2 = first_data_row.find_all(["td", "th"])-- # 构建视觉列到单元格索引的映射- last_row_idx = len(previous_state.rows) - 1- vcol_map1 = build_visual_col_mapping(previous_state.rows, last_row_idx)- current_merge_rows = rows2[header_count:]- vcol_map2 = build_visual_col_mapping(- current_merge_rows,- 0,- initial_occupied=previous_state.tail_occupied,- )-- # 构建视觉列 -> 单元格索引的反向映射(展开 colspan)- vcol_to_cell1: dict[int, int] = {}- for ci, start_vcol in enumerate(vcol_map1):- colspan = int(cells1[ci].get("colspan", 1))- for c in range(start_vcol, start_vcol + colspan):- vcol_to_cell1[c] = ci- vcol_to_cell2: dict[int, int] = {}- for ci, start_vcol in enumerate(vcol_map2):- colspan = int(cells2[ci].get("colspan", 1))- for c in range(start_vcol, start_vcol + colspan):- vcol_to_cell2[c] = ci-- # 按唯一 (src_cell_idx, dst_cell_idx) 对执行一次转移,避免 colspan 重复处理- transferred_pairs: set[tuple[int, int]] = set()- for vi, merge_flag in enumerate(cell_merge):- if merge_flag == 1:- ci1 = vcol_to_cell1.get(vi)- ci2 = vcol_to_cell2.get(vi)- if ci1 is not None and ci2 is not None:- pair = (ci1, ci2)- if pair not in transferred_pairs:- for child in list(cells2[ci2].children):- cells1[ci1].append(child.extract())- transferred_pairs.add(pair)-- # 只清空确实成功转移过的源单元格- cleared_ci2: set[int] = set()- for vi, merge_flag in enumerate(cell_merge):- if merge_flag == 1:- ci1 = vcol_to_cell1.get(vi)- ci2 = vcol_to_cell2.get(vi)- if ci1 is not None and ci2 is not None and ci2 not in cleared_ci2:- cells2[ci2].clear()- cleared_ci2.add(ci2)-- if not _row_has_semantic_content(first_data_row):- _carry_rowspan_structure_to_next_row(rows2, header_count)- first_data_row.extract()- if first_data_row in rows2:- rows2.remove(first_data_row)-- return bool(transferred_pairs)---def _perform_table_content_merge(- previous_state: TableMergeState,- current_state: TableMergeState,- previous_table_block: BlockDict,- current_table_block: BlockDict,-) -> bool:- """在两个克隆表格上执行 HTML、单元格和 footnote 的内容合并。"""- header_count, _, _ = detect_table_headers(previous_state, current_state)- header_count = _expand_header_count_by_rowspan(current_state.rows, header_count)-- rows1 = previous_state.rows- rows2 = current_state.rows- if not rows1 or header_count >= len(rows2):- return False-- previous_adjusted = False-- if header_count < len(rows2):- current_merge_rows = rows2[header_count:]- if _clip_overlapped_blank_rowspan_cells(current_merge_rows, previous_state.tail_occupied):- _refresh_table_state_metrics(current_state)-- if rows1 and rows2 and header_count < len(rows2):- last_row1 = rows1[-1]- first_data_row2 = rows2[header_count]- table_cols1 = previous_state.total_cols- table_cols2 = current_state.total_cols-- if table_cols1 > table_cols2:- reference_structure = [int(cell.get("colspan", 1)) for cell in last_row1.find_all(["td", "th"])]- reference_visual_cols = calculate_visual_columns(last_row1)- adjust_table_rows_colspan(- rows2,- header_count,- len(rows2),- current_state.row_effective_cols,- reference_structure,- reference_visual_cols,- table_cols1,- first_data_row2,- )- elif table_cols2 > table_cols1:- reference_structure = [int(cell.get("colspan", 1)) for cell in first_data_row2.find_all(["td", "th"])]- reference_visual_cols = calculate_visual_columns(first_data_row2)- adjust_table_rows_colspan(- rows1,- 0,- len(rows1),- previous_state.row_effective_cols,- reference_structure,- reference_visual_cols,- table_cols2,- last_row1,- )- previous_adjusted = True-- if previous_adjusted:- _refresh_table_state_metrics(previous_state)-- cell_merge_applied = _apply_cell_merge(previous_state, current_state, header_count)-- appended_rows = rows2[header_count:]- append_start_idx = len(previous_state.rows)- merged_rows = []-- if previous_state.tbody is None or current_state.tbody is None:- return False-- for row in appended_rows:- row.extract()- previous_state.tbody.append(row)- merged_rows.append(row)-- if not merged_rows and not cell_merge_applied:- return False-- previous_state.rows.extend(merged_rows)-- if merged_rows:- appended_scan = _scan_rows(- merged_rows,- initial_occupied=previous_state.tail_occupied,- start_row_idx=append_start_idx,- )- previous_state.row_effective_cols.extend(appended_scan.row_effective_cols)- previous_state.total_cols = max(previous_state.total_cols, appended_scan.total_cols)- if appended_scan.last_nonempty_row_metrics is not None:- previous_state.last_data_row_metrics = appended_scan.last_nonempty_row_metrics- previous_state.tail_occupied = appended_scan.tail_occupied-- previous_content = previous_table_block.get("content")- if not isinstance(previous_content, list):- return False-- previous_table_block["content"] = [- block for block in previous_content if not isinstance(block, dict) or block.get("type") != BlockType.TABLE_FOOTNOTE- ]- current_footnotes = [- block for block in _table_children(current_table_block) if block.get("type") == BlockType.TABLE_FOOTNOTE- ]- footnote_base_index = _build_post_body_child_index(previous_table_block, 0)- for footnote_offset, table_footnote in enumerate(current_footnotes, start=1):- temp_table_footnote = deepcopy(table_footnote)- temp_table_footnote.pop("_cross_page", None)- if footnote_base_index is None:- temp_table_footnote["index"] = 0- else:- temp_table_footnote["index"] = footnote_base_index + footnote_offset- previous_table_block["content"].append(temp_table_footnote)-- previous_state.dirty = True- return _serialize_table_state_html(previous_state)---def merge_table_content(previous_table: BlockDict, current_table: BlockDict) -> BlockDict | None:- """纯函数式合并两张跨页表格的内容,失败时返回 ``None``。-- 两个输入都会先深拷贝;返回块保留前表外层信息,只改克隆表体 HTML- 并用当前表 footnote 替换前表 footnote,不会修改任何输入对象。- """- if (- not isinstance(previous_table, dict)- or not isinstance(current_table, dict)- or previous_table.get("type") != BlockType.TABLE- or current_table.get("type") != BlockType.TABLE- ):- return None-- previous_clone = deepcopy(previous_table)- current_clone = deepcopy(current_table)- try:- previous_state = _build_table_state(previous_clone)- current_state = _build_table_state(current_clone)- if previous_state is None or current_state is None:- return None- if not can_merge_tables(current_state, previous_state):- return None- if not _perform_table_content_merge(- previous_state,- current_state,- previous_clone,- current_clone,- ):- return None- except (AssertionError, TypeError, ValueError):- return None-- return previous_clone---def _clear_table_continuation_marker(table_block: BlockDict) -> None:- """递归清除 table 根块及其子块中过期的 ``continues_prev``。"""- table_block.pop("continues_prev", None)- content = table_block.get("content")- if not isinstance(content, list):- return- for child in content:- if isinstance(child, dict):- child.pop("continues_prev", None)- _clear_nested_continuation_markers(child)---def _clear_nested_continuation_markers(block: BlockDict) -> None:- """清除表格子树中的旧延续标记,避免标记落到嵌套子块。"""- content = block.get("content")- if not isinstance(content, list):- return- for child in content:- if isinstance(child, dict):- child.pop("continues_prev", None)- _clear_nested_continuation_markers(child)---def _find_boundary_table(blocks: list[Any], *, from_end: bool) -> BlockDict | None:- """从页边界扫描 table;噪声块可跳过,其他语义块立即阻断。"""- ordered_blocks = reversed(blocks) if from_end else iter(blocks)- for block in ordered_blocks:- if not isinstance(block, dict):- return None- block_type = block.get("type")- if block_type in TABLE_BOUNDARY_IGNORED_TYPES:- continue- if block_type == BlockType.TABLE:- return block- return None- return None---def _is_consecutive_page_pair(previous_page: PageInfoDict, current_page: PageInfoDict) -> bool:- """按显式零基 page_idx 判断页面在文档中是否严格连续。"""- previous_page_idx = previous_page.get("page_idx")- current_page_idx = current_page.get("page_idx")- return type(previous_page_idx) is int and type(current_page_idx) is int and current_page_idx == previous_page_idx + 1---def merge_table(page_info_list: list[PageInfoDict]) -> None:- """倒序识别连续页边界表格,并只在后表写入延续标记。"""- if not isinstance(page_info_list, list):- return-- for page_info in page_info_list:- if not isinstance(page_info, dict):- continue- blocks = page_info.get("blocks")- if not isinstance(blocks, list):- continue- for block in blocks:- if isinstance(block, dict) and block.get("type") == BlockType.TABLE:- _clear_table_continuation_marker(block)-- state_cache: dict[int, TableMergeState] = {}-- for page_position in range(len(page_info_list) - 1, 0, -1):- current_page = page_info_list[page_position]- previous_page = page_info_list[page_position - 1]- if not isinstance(current_page, dict) or not isinstance(previous_page, dict):- continue- if not _is_consecutive_page_pair(previous_page, current_page):- continue-- current_blocks = current_page.get("blocks")- previous_blocks = previous_page.get("blocks")- if not isinstance(current_blocks, list) or not isinstance(previous_blocks, list):- continue-- current_table_block = _find_boundary_table(current_blocks, from_end=False)- previous_table_block = _find_boundary_table(previous_blocks, from_end=True)- if current_table_block is None or previous_table_block is None:- continue-- current_state = _get_or_create_table_state(current_table_block, state_cache)- previous_state = _get_or_create_table_state(previous_table_block, state_cache)- if current_state is None or previous_state is None:- continue-- if not can_merge_tables(current_state, previous_state):- continue-- current_table_block["continues_prev"] = Truediff --git a/mineru/model/flash/docx/docx_converter.py b/mineru/model/flash/docx/docx_converter.pyindex 464e169f..19f0f2c1 100644--- a/mineru/model/flash/docx/docx_converter.py+++ b/mineru/model/flash/docx/docx_converter.py@@ -17,11 +17,11 @@ from mammoth.conversion import convert_document_element_to_htmlfrom mammoth.docx import body_xmlfrom pydantic import AnyUrl-from mineru.backend.utils.office_chart import extract_chart_html_from_ooxml-from mineru.backend.utils.office_image import (+from mineru.model.flash.office.chart import extract_chart_html_from_ooxml+from mineru.model.flash.office.image import (serialize_office_image,)-from mineru.backend.utils.raw_block_types import RAW_CAPTION+from mineru.types import RAW_CAPTIONfrom mineru.model.flash.docx.package_normalizer import normalize_docx_packagefrom mineru.model.flash.docx.tools.math.omml import oMath2Latexfrom mineru.model.flash.docx.tools.office_xml import read_strdiff --git a/mineru/model/flash/native_pdf/code_blocks.py b/mineru/model/flash/native_pdf/code_blocks.pyindex 4f22318a..95f3a0c4 100644--- a/mineru/model/flash/native_pdf/code_blocks.py+++ b/mineru/model/flash/native_pdf/code_blocks.py@@ -9,7 +9,7 @@ import statisticsimport unicodedatafrom typing import Any-from mineru.backend.utils.table_text import project_pdf_spatial_text+from mineru.utils.spatial_text import project_pdf_spatial_textfrom mineru.types import BBoxfrom mineru.utils.pdf_document import PDFPathInfodiff --git a/mineru/model/flash/native_pdf/line_layout.py b/mineru/model/flash/native_pdf/line_layout.pyindex 48893ce7..6760d26a 100644--- a/mineru/model/flash/native_pdf/line_layout.py+++ b/mineru/model/flash/native_pdf/line_layout.py@@ -9,7 +9,7 @@ import reimport statistics-from mineru.backend.utils.char_utils import is_hyphen_at_line_end+from mineru.utils.text_utils import is_hyphen_at_line_endfrom mineru.types import BBoxfrom .models import (diff --git a/mineru/model/flash/native_pdf/pipeline.py b/mineru/model/flash/native_pdf/pipeline.pyindex 57083ba1..e69d412b 100644--- a/mineru/model/flash/native_pdf/pipeline.py+++ b/mineru/model/flash/native_pdf/pipeline.py@@ -8,7 +8,7 @@ from dataclasses import replacefrom typing import Any-from mineru.backend.utils.xycut_pp_sorter import sort_entries+from mineru.model.flash.xycut import sort_entriesfrom mineru.utils.pdf_document import PDFDocument, PDFImageInfo, get_lines_from_charsfrom .models import (diff --git a/mineru/model/flash/native_pdf/tables.py b/mineru/model/flash/native_pdf/tables.pyindex 33505feb..4fae40b7 100644--- a/mineru/model/flash/native_pdf/tables.py+++ b/mineru/model/flash/native_pdf/tables.py@@ -11,8 +11,8 @@ from typing import Any, Literalfrom loguru import logger-from mineru.backend.utils.char_utils import resolve_text_line_boundary-from mineru.backend.utils.table_text import project_pdf_table_text+from mineru.utils.text_utils import resolve_text_line_boundary+from mineru.utils.spatial_text import project_pdf_table_textfrom mineru.types import BBoxfrom mineru.utils.pdf_document import PDFPathInfofrom mineru.utils.language import detect_langdiff --git a/mineru/model/flash/native_pdf/text_blocks.py b/mineru/model/flash/native_pdf/text_blocks.pyindex 0445ea32..1c7d99d4 100644--- a/mineru/model/flash/native_pdf/text_blocks.py+++ b/mineru/model/flash/native_pdf/text_blocks.py@@ -9,7 +9,7 @@ import statisticsfrom typing import Any, Sequence-from mineru.backend.utils.char_utils import (+from mineru.utils.text_utils import (is_hyphen_at_line_end,resolve_text_line_boundary,)diff --git a/mineru/model/flash/native_pdf/visual_annotations.py b/mineru/model/flash/native_pdf/visual_annotations.pyindex bf8051c2..3ec2a1cb 100644--- a/mineru/model/flash/native_pdf/visual_annotations.py+++ b/mineru/model/flash/native_pdf/visual_annotations.py@@ -12,7 +12,7 @@ from dataclasses import dataclassfrom typing import Any, Literal-from mineru.backend.utils.xycut_pp_sorter import sort_entries+from mineru.model.flash.xycut import sort_entriesfrom mineru.types import BBoxfrom .geometry import (diff --git a/mineru/model/flash/office/__init__.py b/mineru/model/flash/office/__init__.pynew file mode 100644index 00000000..987b6c08--- /dev/null+++ b/mineru/model/flash/office/__init__.py@@ -0,0 +1 @@+"""Flash Office 模型共享实现。"""diff --git a/mineru/backend/utils/office_chart.py b/mineru/model/flash/office/chart.pysimilarity index 90%rename from mineru/backend/utils/office_chart.pyrename to mineru/model/flash/office/chart.pyindex 9c23822f..b8a25270 100644--- a/mineru/backend/utils/office_chart.py+++ b/mineru/model/flash/office/chart.py@@ -1,4 +1,6 @@# Copyright (c) Opendatalab. All rights reserved.+"""Flash Office 文档中的 OOXML 图表解析与表格化渲染。"""+from __future__ import annotationsimport math@@ -41,6 +43,8 @@ _PLOT_TAGS: Final = (@dataclassclass SeriesSpec:+ """保存单个 OOXML 图表序列的公式引用、名称和缓存数据。"""+name_formula: str | None = Noneliteral_name: str | None = Nonecat_formula: str | None = None@@ -56,6 +60,8 @@ class SeriesSpec:@dataclassclass ChartSpec:+ """保存图表类型、坐标轴信息和全部序列的规范化描述。"""+chart_type: strplot_kind: strtitle: str = ""@@ -68,7 +74,7 @@ class ChartSpec:def html_table_from_excel_bytes(excel_bytes: bytes) -> str:- """Convert the first non-empty worksheet in an embedded workbook to HTML."""+ """将嵌入工作簿中第一个非空工作表转换为 HTML 表格。"""if not excel_bytes:return ""@@ -160,6 +166,7 @@ def _render_embedded_workbook_table(rows: list[list[str]]) -> str:def extract_chart_html_from_ooxml(chart_xml: bytes, workbook_bytes: bytes | None) -> str:+ """解析 OOXML 图表并按工作簿、缓存和普通表格的优先级生成 HTML。"""spec = parse_chart_spec_from_ooxml(chart_xml)if spec is None or not spec.series:if workbook_bytes:@@ -182,6 +189,7 @@ def extract_chart_html_from_ooxml(chart_xml: bytes, workbook_bytes: bytes | Nonedef parse_chart_spec_from_ooxml(chart_xml: bytes) -> ChartSpec | None:+ """解析图表 XML,生成统一的图表类型、坐标轴和序列描述。"""try:root = etree.fromstring(chart_xml,@@ -280,6 +288,7 @@ def parse_chart_spec_from_ooxml(chart_xml: bytes) -> ChartSpec | None:def render_chart_html_from_workbook(spec: ChartSpec, workbook_bytes: bytes) -> str:+ """根据图表公式从嵌入工作簿读取数据并渲染 HTML 表格。"""try:workbook = load_workbook(filename=BytesIO(workbook_bytes),@@ -302,6 +311,7 @@ def render_chart_html_from_workbook(spec: ChartSpec, workbook_bytes: bytes) -> sdef render_chart_html_from_cache(spec: ChartSpec) -> str:+ """在工作簿不可用时使用 OOXML 图表缓存数据渲染 HTML 表格。"""if spec.plot_kind in {"category", "date"}:categories = []for series in spec.series:@@ -336,6 +346,7 @@ def render_chart_html_from_cache(spec: ChartSpec) -> str:def _render_category_like_chart_from_workbook(spec: ChartSpec, workbook: Workbook) -> str:+ """从工作簿渲染分类轴或日期轴图表的二维 HTML 表格。"""categories = []for series in spec.series:@@ -380,6 +391,7 @@ def _render_category_like_chart_from_workbook(spec: ChartSpec, workbook: Workboodef _render_scatter_like_chart_from_workbook(spec: ChartSpec, workbook: Workbook) -> str:+ """读取工作簿中的散点图横纵轴数据并渲染 HTML 表格。"""x_sequences, series_names, series_y_values = _read_scatter_axes_from_workbook(spec,workbook,@@ -393,6 +405,7 @@ def _render_scatter_like_chart_from_workbook(spec: ChartSpec, workbook: Workbookdef _render_bubble_chart_from_workbook(spec: ChartSpec, workbook: Workbook) -> str:+ """读取工作簿中的气泡图横纵轴和尺寸数据并渲染 HTML 表格。"""x_sequences, series_names, series_y_values, series_sizes = _read_bubble_axes_from_workbook(spec,workbook,@@ -407,6 +420,7 @@ def _render_bubble_chart_from_workbook(spec: ChartSpec, workbook: Workbook) -> sdef _render_scatter_like_chart_from_cache(spec: ChartSpec) -> str:+ """使用 OOXML 缓存的横纵轴数据渲染散点图 HTML 表格。"""x_sequences = []series_names = []series_y_values = []@@ -426,6 +440,7 @@ def _render_scatter_like_chart_from_cache(spec: ChartSpec) -> str:def _render_bubble_chart_from_cache(spec: ChartSpec) -> str:+ """使用 OOXML 缓存的横纵轴和尺寸数据渲染气泡图 HTML 表格。"""x_sequences = []series_names = []series_y_values = []@@ -450,6 +465,7 @@ def _render_bubble_chart_from_cache(spec: ChartSpec) -> str:def _read_scatter_axes_from_workbook(spec: ChartSpec, workbook: Workbook) -> tuple[list[list[float]] | None, list[str], list[list[float]]]:+ """按序列公式读取散点图的 X 轴、序列名称和 Y 轴数据。"""x_sequences = []series_names = []series_y_values = []@@ -477,6 +493,7 @@ def _read_scatter_axes_from_workbook(def _read_bubble_axes_from_workbook(spec: ChartSpec, workbook: Workbook) -> tuple[list[list[float]] | None, list[str], list[list[float]], list[list[float]]]:+ """按序列公式读取气泡图的 X/Y 轴、名称和气泡尺寸数据。"""x_sequences = []series_names = []series_y_values = []@@ -505,6 +522,7 @@ def _read_bubble_axes_from_workbook(def _read_formula_vector(workbook: Workbook, formula: str) -> tuple[str, list[Any]] | None:+ """解析单行或单列单元格公式,并从工作簿读取对应的一维数据。"""parsed = _parse_formula(formula)if parsed is None:return None@@ -531,6 +549,7 @@ def _read_formula_vector(workbook: Workbook, formula: str) -> tuple[str, list[Andef _read_formula_scalar(workbook: Workbook, formula: str) -> str | None:+ """读取公式引用区域的首个有效值并转换为字符串。"""read_result = _read_formula_vector(workbook, formula)if read_result is None:return None@@ -546,6 +565,7 @@ def _read_formula_scalar(workbook: Workbook, formula: str) -> str | None:def _parse_formula(formula: str) -> tuple[str, int, int, int, int] | None:+ """将工作表区域公式解析为工作表名称和规范化单元格边界。"""formula = formula.strip()if not formula:return None@@ -565,10 +585,12 @@ def _parse_formula(formula: str) -> tuple[str, int, int, int, int] | None:def _unescape_formula_sheet_name(sheet_name: str) -> str:+ """还原 OOXML 公式中以双单引号转义的工作表名称。"""return sheet_name.replace("''", "'")def _extract_reference_formula(container: etree._Element) -> str | None:+ """从字符串、数字或多级字符串引用容器中提取公式文本。"""ref_element = _find_reference_element(container)if ref_element is None:return None@@ -584,6 +606,7 @@ def _extract_reference_cache(date_hint: bool = False,date_1904: bool = False,) -> list[str]:+ """从图表引用容器提取缓存数据,并按日期提示规范化值。"""ref_element = _find_reference_element(container)if ref_element is None:return []@@ -611,6 +634,7 @@ def _extract_cache_points(date_hint: bool = False,date_1904: bool = False,) -> list[str]:+ """按缓存点索引还原连续序列,并拒绝异常大的稀疏索引范围。"""points = {}for point in cache_element.findall("c:pt", namespaces=_NS):raw_index = point.get("idx")@@ -640,6 +664,7 @@ def _extract_cache_points(def _extract_multilevel_string_cache(ref_element: etree._Element) -> list[str]:+ """合并多级分类缓存的同索引文本,生成扁平分类标签序列。"""level_maps = []max_index = -1for level in ref_element.findall("c:multiLvlStrCache/c:lvl", namespaces=_NS):@@ -671,6 +696,7 @@ def _extract_multilevel_string_cache(ref_element: etree._Element) -> list[str]:def _extract_tx_formula(tx_element: etree._Element) -> str | None:+ """从图表序列名称节点提取字符串引用公式。"""if tx_element is None:return Nonestr_ref = tx_element.find("c:strRef", namespaces=_NS)@@ -683,6 +709,7 @@ def _extract_tx_formula(tx_element: etree._Element) -> str | None:def _extract_tx_text(tx_element: etree._Element) -> str | None:+ """从图表序列名称节点提取缓存文本或直接文本。"""if tx_element is None:return None@@ -699,6 +726,7 @@ def _extract_tx_text(tx_element: etree._Element) -> str | None:def _extract_title_text(title_element: etree._Element) -> str:+ """拼接图表标题节点中的全部富文本片段。"""if title_element is None:return ""texts = title_element.findall(".//a:t", namespaces=_NS)@@ -706,6 +734,7 @@ def _extract_title_text(title_element: etree._Element) -> str:def _find_reference_element(container: etree._Element) -> object | None:+ """在容器中查找受支持的字符串、数字或多级字符串引用节点。"""if container is None:return Nonefor tag_name in ("strRef", "numRef", "multiLvlStrRef"):@@ -716,6 +745,7 @@ def _find_reference_element(container: etree._Element) -> object | None:def _first_non_none(*values: Any) -> object | None:+ """返回参数序列中的第一个非空对象。"""for value in values:if value is not None:return value@@ -723,6 +753,7 @@ def _first_non_none(*values: Any) -> object | None:def _collect_plot_elements(plot_area: etree._Element) -> list[tuple[str, etree._Element]]:+ """收集绘图区中受支持的图表节点及其局部标签名。"""plot_elements = []for child in plot_area:if not isinstance(child.tag, str):@@ -734,6 +765,7 @@ def _collect_plot_elements(plot_area: etree._Element) -> list[tuple[str, etree._def _plot_kind_from_tag_name(tag_name: str, has_date_axis: bool) -> str:+ """根据 OOXML 图表标签和日期轴信息归一化绘图类别。"""if tag_name == "scatterChart":return "scatter"if tag_name == "bubbleChart":@@ -744,6 +776,7 @@ def _plot_kind_from_tag_name(tag_name: str, has_date_axis: bool) -> str:def _chart_uses_date_1904(root: etree._Element) -> bool:+ """判断图表是否使用以 1904 年为起点的 Excel 日期系统。"""date_1904 = root.find("c:date1904", namespaces=_NS)if date_1904 is None:return False@@ -751,6 +784,7 @@ def _chart_uses_date_1904(root: etree._Element) -> bool:def _resolve_series_name(series: SeriesSpec, index: int, workbook: Workbook | None = None) -> str:+ """按工作簿引用、缓存名称和默认序号依次解析序列名称。"""if workbook is not None and series.name_formula:workbook_name = _read_formula_scalar(workbook, series.name_formula)if workbook_name:@@ -761,6 +795,7 @@ def _resolve_series_name(series: SeriesSpec, index: int, workbook: Workbook | Nodef _get_shared_axis_values(sequences: list[list[Any]]) -> list[Any] | None:+ """判断多个序列是否共享相同轴值,并在一致时返回首个序列。"""if not sequences:return None@@ -772,6 +807,7 @@ def _get_shared_axis_values(sequences: list[list[Any]]) -> list[Any] | None:def _normalize_sequence(sequence: list[Any]) -> list[str]:+ """将轴值序列统一转换为可比较的字符串列表。"""return [_stringify_cell_value(value) for value in sequence]@@ -782,6 +818,7 @@ def _render_scatter_like_chart_table(*,x_axis_title: str,) -> str:+ """按共享或独立 X 轴布局,将散点图序列渲染为 HTML 表格。"""if not x_sequences or not series_names or len(x_sequences) != len(series_names):return ""@@ -822,6 +859,7 @@ def _render_bubble_chart_table(*,x_axis_title: str,) -> str:+ """按共享或独立 X 轴布局,将气泡图三维序列渲染为 HTML 表格。"""if (not x_sequencesor not series_names@@ -876,6 +914,7 @@ def _stringify_series_values(date_hint: bool = False,date_1904: bool = False,) -> list[str]:+ """将图表序列值批量转换为适合 HTML 输出的文本。"""return [_stringify_cell_value(value,@@ -892,6 +931,7 @@ def _stringify_cache_value(date_hint: bool = False,date_1904: bool = False,) -> str:+ """规范化 OOXML 缓存值,并在需要时转换 Excel 日期序列号。"""if value in (None, ""):return ""@@ -911,6 +951,7 @@ def _stringify_cell_value(date_hint: bool = False,date_1904: bool = False,) -> str:+ """将工作簿单元格值转换为稳定文本,并保留日期时间语义。"""if value in (None, ""):return ""@@ -930,6 +971,7 @@ def _stringify_cell_value(def _excel_serial_to_iso(serial: float, *, date_1904: bool = False) -> str | None:+ """把 Excel 日期序列号转换为 ISO 文本,无效数值返回空结果。"""if not math.isfinite(serial):return Nonetry:@@ -948,12 +990,14 @@ def _excel_serial_to_iso(serial: float, *, date_1904: bool = False) -> str | Nondef _stringify_non_date_value(value: Any) -> str:+ """将非日期值转换为文本,并去除整数浮点值末尾的小数部分。"""if isinstance(value, float) and value.is_integer():return str(int(value))return str(value)def _render_html_table(headers: list[str], columns: list[list[str]], row_count: int) -> str:+ """按表头、列数据和行数生成已转义的紧凑 HTML 表格。"""if row_count <= 0 or len(headers) != len(columns):return ""diff --git a/mineru/backend/utils/office_image.py b/mineru/model/flash/office/image.pysimilarity index 89%rename from mineru/backend/utils/office_image.pyrename to mineru/model/flash/office/image.pyindex ee0f1def..62cd81f0 100644--- a/mineru/backend/utils/office_image.py+++ b/mineru/model/flash/office/image.py@@ -1,4 +1,6 @@# Copyright (c) Opendatalab. All rights reserved.+"""Flash Office 文档的图片识别、转码与占位图生成。"""+from functools import lru_cachefrom io import BytesIOfrom pathlib import PurePosixPath@@ -7,8 +9,8 @@ from typing import Finalfrom loguru import loggerfrom PIL import Image, ImageDraw, ImageFont, UnidentifiedImageError-from ...utils.check_sys_env import is_windows_environment-from ...utils.pdf_reader import image_to_b64str+from ....utils.check_sys_env import is_windows_environment+from ....utils.pdf_reader import image_to_b64strVECTOR_IMAGE_FORMATS = frozenset({"WMF", "EMF"})VECTOR_IMAGE_EXTENSIONS = frozenset({".wmf", ".emf"})@@ -31,10 +33,12 @@ STANDARD_VECTOR_PLACEHOLDER_LINES: Final = (def is_vector_image(pil_image: Image.Image) -> bool:+ """判断已由 Pillow 打开的图片是否属于 WMF/EMF 矢量格式。"""return (getattr(pil_image, "format", None) or "").upper() in VECTOR_IMAGE_FORMATSdef is_vector_image_part(part_name: object | None = None, content_type: str | None = None) -> bool:+ """根据 OOXML 部件扩展名和内容类型判断是否为矢量图片。"""suffix = PurePosixPath(str(part_name or "")).suffix.lower()if suffix in VECTOR_IMAGE_EXTENSIONS:return True@@ -43,6 +47,7 @@ def is_vector_image_part(part_name: object | None = None, content_type: str | Nodef _vector_image_format_label(part_name: object | None = None, content_type: str | None = None) -> str:+ """从 OOXML 部件信息推断用于日志和占位图的矢量格式名称。"""suffix = PurePosixPath(str(part_name or "")).suffix.lower()normalized_content_type = (content_type or "").lower()if suffix == ".wmf" or "wmf" in normalized_content_type:@@ -53,6 +58,7 @@ def _vector_image_format_label(part_name: object | None = None, content_type: stdef _load_placeholder_font(font_size: int) -> ImageFont.FreeTypeFont | ImageFont.ImageFont:+ """按优先级加载占位图字体,均不可用时退回 Pillow 默认字体。"""for font_name in ("DejaVuSans.ttf", "Arial.ttf", "LiberationSans-Regular.ttf"):try:return ImageFont.truetype(font_name, font_size)@@ -62,6 +68,7 @@ def _load_placeholder_font(font_size: int) -> ImageFont.FreeTypeFont | ImageFontdef create_text_placeholder(size: tuple[int, int], lines: list[str]) -> Image.Image:+ """按目标尺寸绘制带边框和居中文案的 RGB 占位图。"""width = max(int(size[0]), 1)height = max(int(size[1]), 1)placeholder = Image.new("RGB", (width, height), (240, 240, 240))@@ -128,6 +135,7 @@ def get_standard_vector_placeholder_data_uri() -> str:def serialize_vector_image_with_placeholder(pil_image: Image.Image, image_format_override: str | None = None) -> str:+ """在支持的平台序列化矢量图,失败或不支持时返回标准占位图。"""image_format = (image_format_override or getattr(pil_image, "format", None) or "WMF/EMF").upper()if is_windows_environment():@@ -147,6 +155,7 @@ def serialize_vector_part_with_placeholder(content_type: str | None = None,size: tuple[int, int] = (320, 180),) -> str:+ """跳过未加载的矢量部件并返回可嵌入文档的标准占位图。"""image_format = _vector_image_format_label(part_name, content_type)logger.debug(f"Skipping {image_format} image part before Pillow load, "@@ -161,6 +170,7 @@ def serialize_office_image(part_name: object | None = None,content_type: str | None = None,) -> str | None:+ """识别并序列化 Office 图片,透明图保留 PNG,普通位图优先使用 JPEG。"""if is_vector_image_part(part_name, content_type):if not is_windows_environment():return serialize_vector_part_with_placeholder(part_name, content_type)diff --git a/mineru/model/flash/pptx/pptx_converter.py b/mineru/model/flash/pptx/pptx_converter.pyindex bc2ac73f..f4061cd6 100644--- a/mineru/model/flash/pptx/pptx_converter.py+++ b/mineru/model/flash/pptx/pptx_converter.py@@ -12,12 +12,12 @@ from pptx import Presentation, presentationfrom pptx.enum.shapes import MSO_SHAPE_TYPE, PP_PLACEHOLDERfrom pptx.oxml.text import CT_TextLineBreak-from mineru.backend.utils.office_chart import extract_chart_html_from_ooxml-from mineru.backend.utils.office_image import PIL_IMAGE_LOAD_ERRORS, is_vector_image, serialize_vector_image_with_placeholder+from mineru.model.flash.office.chart import extract_chart_html_from_ooxml+from mineru.model.flash.office.image import PIL_IMAGE_LOAD_ERRORS, is_vector_image, serialize_vector_image_with_placeholderfrom mineru.model.flash.docx.tools.math.omml import oMath2Latexfrom mineru.model.office_stream import read_stream_bytes_from_start, rewind_streamfrom mineru.model.flash.pptx.package_normalizer import normalize_pptx_package-from mineru.model.flash.pptx.xycut_pp_sorter import sort_entries+from mineru.model.flash.xycut import sort_entriesfrom mineru.types import BlockTypefrom mineru.utils.office_rich_text import OfficeRichTextSegment, build_rich_text_from_segmentsfrom mineru.utils.pdf_reader import image_to_b64strdiff --git a/mineru/model/flash/pptx/xycut_pp_sorter.py b/mineru/model/flash/pptx/xycut_pp_sorter.pydeleted file mode 100644index 895bda61..00000000--- a/mineru/model/flash/pptx/xycut_pp_sorter.py+++ /dev/null@@ -1,22 +0,0 @@-# Copyright (c) Opendatalab. All rights reserved.-"""兼容旧 PPTX 导入路径的共享 XYCut++ 重导出模块。"""--from mineru.backend.utils.xycut_pp_sorter import (- DEFAULT_BETA,- DEFAULT_DENSITY_THRESHOLD,- MIN_GAP_THRESHOLD,- MIN_OVERLAP_COUNT,- NARROW_ELEMENT_WIDTH_RATIO,- OVERLAP_THRESHOLD,- sort_entries,-)--__all__ = [- "DEFAULT_BETA",- "DEFAULT_DENSITY_THRESHOLD",- "MIN_GAP_THRESHOLD",- "MIN_OVERLAP_COUNT",- "NARROW_ELEMENT_WIDTH_RATIO",- "OVERLAP_THRESHOLD",- "sort_entries",-]diff --git a/mineru/model/flash/xlsx/xlsx_converter.py b/mineru/model/flash/xlsx/xlsx_converter.pyindex 3a232107..13b88091 100644--- a/mineru/model/flash/xlsx/xlsx_converter.py+++ b/mineru/model/flash/xlsx/xlsx_converter.py@@ -19,7 +19,7 @@ from PIL import Imagefrom pydantic import BaseModel, Field, NonNegativeInt, PositiveIntfrom pydantic.dataclasses import dataclass-from mineru.backend.utils.office_image import is_vector_image, serialize_vector_image_with_placeholder+from mineru.model.flash.office.image import is_vector_image, serialize_vector_image_with_placeholderfrom mineru.model.flash.docx.tools.math.omml import oMath2Latexfrom mineru.model.office_stream import read_stream_bytes_from_start, rewind_streamfrom mineru.model.flash.xlsx.package_normalizer import normalize_xlsx_packagediff --git a/mineru/backend/utils/xycut_pp_sorter.py b/mineru/model/flash/xycut.pysimilarity index 100%rename from mineru/backend/utils/xycut_pp_sorter.pyrename to mineru/model/flash/xycut.pydiff --git a/mineru/model/model_types.py b/mineru/model/model_types.pynew file mode 100644index 00000000..d2ed8f1b--- /dev/null+++ b/mineru/model/model_types.py@@ -0,0 +1,13 @@+"""模型层共享的稳定标识类型。"""+++class AtomicModelName:+ """本地原子模型名称集合,供运行时和模型实现统一索引。"""++ Layout = "layout"+ MFR = "mfr"+ OCR = "ocr"+ WirelessTable = "wireless_table"+ WiredTable = "wired_table"+ TableCls = "table_cls"+ TableOrientationCls = "table_ori_cls"diff --git a/mineru/model/table/cls/paddle_table_cls.py b/mineru/model/table/cls/paddle_table_cls.pyindex 8e99291f..42eff60f 100644--- a/mineru/model/table/cls/paddle_table_cls.py+++ b/mineru/model/table/cls/paddle_table_cls.py@@ -14,7 +14,7 @@ from mineru.utils.models_download_utils import auto_download_and_get_model_root_class PaddleTableClsModel:def __init__(self):- from mineru.backend.local_model_runtime import AtomicModel+ from mineru.model.model_types import AtomicModelNameself.sess = onnxruntime.InferenceSession(os.path.join(auto_download_and_get_model_root_path(ModelPath.paddle_table_cls), ModelPath.paddle_table_cls)@@ -24,7 +24,7 @@ class PaddleTableClsModel:self.std = [0.229, 0.224, 0.225]self.scale = 0.00392156862745098self.mean = [0.485, 0.456, 0.406]- self.labels = [AtomicModel.WiredTable, AtomicModel.WirelessTable]+ self.labels = [AtomicModelName.WiredTable, AtomicModelName.WirelessTable]def preprocess(self, input_img):# 放大图片,使其最短边长为256diff --git a/mineru/types.py b/mineru/types.pyindex 5b19659f..1d925e96 100644--- a/mineru/types.py+++ b/mineru/types.py@@ -11,7 +11,28 @@ from typing import Annotated, Any, ClassVar, Literal, TypeAlias, Unionfrom pydantic import BaseModel, ConfigDict, Field, TypeAdapter, field_validator, model_validator-from .backend.utils.raw_block_types import RAW_ALGORITHM++# 这些字符串不能作为公开 Block.type discriminator,只用于 raw 阶段或 Block 内部枚举值。+RawBlockType: TypeAlias = Literal[+ "algorithm",+ "caption",+ "footnote",+ "phonetic",+]++RAW_ALGORITHM: RawBlockType = "algorithm"+RAW_CAPTION: RawBlockType = "caption"+RAW_FOOTNOTE: RawBlockType = "footnote"+RAW_PHONETIC: RawBlockType = "phonetic"++RAW_ONLY_BLOCK_TYPES = frozenset(+ {+ RAW_ALGORITHM,+ RAW_CAPTION,+ RAW_FOOTNOTE,+ RAW_PHONETIC,+ }+)Tier = Literal["flash",@@ -657,9 +678,7 @@ class MiddleJson(_StrictMiddleModel):for page in self.pages:for block in page.blocks:if block.bbox is None:- raise ValueError(- f"PDF top-level block requires bbox: page_idx={page.page_idx}, index={block.index}"- )+ raise ValueError(f"PDF top-level block requires bbox: page_idx={page.page_idx}, index={block.index}")return selfdef export(@@ -712,9 +731,7 @@ def _prepare_export_copy(middle_json: MiddleJson) -> tuple[MiddleJson, dict[str,data_uri = getattr(block, "image_base64", None)if data_uri is not None:if block.index is None:- raise ValueError(- f"Image carrier requires index: page_idx={page.page_idx}, type={block.type}"- )+ raise ValueError(f"Image carrier requires index: page_idx={page.page_idx}, type={block.type}")image_bytes, extension = parse_image_data_uri_strict(data_uri)relative_path = f"images/page_{page.page_idx}_{block.type}_{block.index}.{extension}"_register_export_file(image_files, relative_path, image_bytes)@@ -725,9 +742,7 @@ def _prepare_export_copy(middle_json: MiddleJson) -> tuple[MiddleJson, dict[str,if not isinstance(content, str) or "data:image/" not in content:continueif block.index is None:- raise ValueError(- f"HTML image carrier requires index: page_idx={page.page_idx}, type={block.type}"- )+ raise ValueError(f"HTML image carrier requires index: page_idx={page.page_idx}, type={block.type}")ordinal = 0def _replace_data_uri(match: Any) -> str:@@ -735,9 +750,7 @@ def _prepare_export_copy(middle_json: MiddleJson) -> tuple[MiddleJson, dict[str,nonlocal ordinalordinal += 1image_bytes, extension = parse_image_data_uri_strict(match.group(0))- relative_path = (- f"images/page_{page.page_idx}_{block.type}_{block.index}_{ordinal}.{extension}"- )+ relative_path = f"images/page_{page.page_idx}_{block.type}_{block.index}_{ordinal}.{extension}"_register_export_file(image_files, relative_path, image_bytes)return relative_path@@ -820,19 +833,13 @@ def _commit_export_files(files: dict[Path, bytes], *, overwrite: bool) -> None:def _validate_export_path_relationships(relative_paths: list[str]) -> None:"""拒绝任一导出文件占用另一文件的父目录,避免提交阶段才产生冲突。"""- path_parts = {- relative_path: Path(relative_path).parts- for relative_path in relative_paths- }+ path_parts = {relative_path: Path(relative_path).parts for relative_path in relative_paths}for relative_path, parts in path_parts.items():for other_path, other_parts in path_parts.items():if relative_path == other_path or len(parts) >= len(other_parts):continueif other_parts[: len(parts)] == parts:- raise ValueError(- "Export file path conflicts with a required directory: "- f"{relative_path} -> {other_path}"- )+ raise ValueError(f"Export file path conflicts with a required directory: {relative_path} -> {other_path}")def _export_middle_json(@@ -859,15 +866,11 @@ def _export_middle_json(relative_files[safe_json_name] = json_bytes_validate_export_path_relationships(list(relative_files))absolute_files = {- _resolve_export_target(output_dir, relative_path): payload- for relative_path, payload in relative_files.items()+ _resolve_export_target(output_dir, relative_path): payload for relative_path, payload in relative_files.items()}_commit_export_files(absolute_files, overwrite=overwrite)json_path = _resolve_export_target(output_dir, safe_json_name)- image_paths = tuple(- _resolve_export_target(output_dir, relative_path)- for relative_path in sorted(image_files)- )+ image_paths = tuple(_resolve_export_target(output_dir, relative_path) for relative_path in sorted(image_files))return MiddleJsonExportResult(middle_json=exported,json_path=json_path,diff --git a/mineru/utils/bbox_utils.py b/mineru/utils/bbox_utils.pyindex 6ea7f54f..447eec10 100644--- a/mineru/utils/bbox_utils.py+++ b/mineru/utils/bbox_utils.py@@ -54,3 +54,73 @@ def normalize_to_int_bbox(return Nonereturn (int(xmin), int(ymin), int(xmax), int(ymax))+++def bbox_relative_pos(bbox1: BBox, bbox2: BBox) -> tuple[bool, bool, bool, bool]:+ """返回 bbox1 相对 bbox2 的左、右、下、上位置关系。"""+ x1, y1, x1b, y1b = bbox1+ x2, y2, x2b, y2b = bbox2+ left = x2b < x1+ right = x1b < x2+ bottom = y2b < y1+ top = y1b < y2+ return left, right, bottom, top+++def bbox_distance(bbox1: BBox, bbox2: BBox) -> float:+ """计算两个不相交矩形之间的最短欧氏距离。"""+ x1, y1, x1b, y1b = bbox1+ x2, y2, x2b, y2b = bbox2+ left, right, bottom, top = bbox_relative_pos(bbox1, bbox2)+ if top and left:+ return math.hypot(x1 - x2b, y1b - y2)+ if left and bottom:+ return math.hypot(x1 - x2b, y1 - y2b)+ if bottom and right:+ return math.hypot(x1b - x2, y1 - y2b)+ if right and top:+ return math.hypot(x1b - x2, y1b - y2)+ if left:+ return x1 - x2b+ if right:+ return x2 - x1b+ if bottom:+ return y1 - y2b+ if top:+ return y2 - y1b+ return 0.0+++def bbox_center_distance(bbox1: BBox, bbox2: BBox) -> float:+ """计算两个矩形中心点之间的欧氏距离。"""+ center1 = ((bbox1[0] + bbox1[2]) / 2, (bbox1[1] + bbox1[3]) / 2)+ center2 = ((bbox2[0] + bbox2[2]) / 2, (bbox2[1] + bbox2[3]) / 2)+ return math.hypot(center1[0] - center2[0], center1[1] - center2[1])+++def calculate_overlap_area_2_minbox_area_ratio(bbox1: BBox, bbox2: BBox) -> float:+ """计算交集面积占两个矩形较小面积的比例。"""+ x_left = max(bbox1[0], bbox2[0])+ y_top = max(bbox1[1], bbox2[1])+ x_right = min(bbox1[2], bbox2[2])+ y_bottom = min(bbox1[3], bbox2[3])+ if x_right <= x_left or y_bottom <= y_top:+ return 0.0+ overlap = (x_right - x_left) * (y_bottom - y_top)+ area1 = max(0.0, (bbox1[2] - bbox1[0]) * (bbox1[3] - bbox1[1]))+ area2 = max(0.0, (bbox2[2] - bbox2[0]) * (bbox2[3] - bbox2[1]))+ min_area = min(area1, area2)+ return overlap / min_area if min_area > 0 else 0.0+++def calculate_overlap_area_in_bbox1_area_ratio(bbox1: BBox, bbox2: BBox) -> float:+ """计算两个矩形交集面积占 bbox1 面积的比例。"""+ x_left = max(bbox1[0], bbox2[0])+ y_top = max(bbox1[1], bbox2[1])+ x_right = min(bbox1[2], bbox2[2])+ y_bottom = min(bbox1[3], bbox2[3])+ if x_right <= x_left or y_bottom <= y_top:+ return 0.0+ overlap = (x_right - x_left) * (y_bottom - y_top)+ area1 = max(0.0, (bbox1[2] - bbox1[0]) * (bbox1[3] - bbox1[1]))+ return overlap / area1 if area1 > 0 else 0.0diff --git a/mineru/utils/draw_bbox.py b/mineru/utils/draw_bbox.pyindex fe2e7b34..8b46d1ff 100644--- a/mineru/utils/draw_bbox.py+++ b/mineru/utils/draw_bbox.py@@ -9,8 +9,7 @@ from loguru import loggerfrom pypdf import PageObject, PdfReader, PdfWriterfrom reportlab.pdfgen import canvas-from ..backend.utils.raw_block_types import RAW_PHONETIC-from ..types import BBox, Block, BlockType, ContentType, PageInfo, Span+from ..types import BBox, RAW_PHONETIC, Block, BlockType, ContentType, PageInfo, Span# 文本类 block 共用 text bbox 样式,避免新增文本形态时遗漏多个绘制入口。TEXT_LIKE_BLOCK_TYPES_FOR_BBOX = {diff --git a/mineru/backend/utils/table_text.py b/mineru/utils/spatial_text.pysimilarity index 93%rename from mineru/backend/utils/table_text.pyrename to mineru/utils/spatial_text.pyindex 14ab4368..c63a9dbe 100644--- a/mineru/backend/utils/table_text.py+++ b/mineru/utils/spatial_text.py@@ -1,4 +1,6 @@# Copyright (c) Opendatalab. All rights reserved.+"""将 PDF 字符或 OCR 结果投影为空间文本的共享算法。"""+from __future__ import annotationsimport statistics@@ -195,10 +197,7 @@ def _build_pdf_spatial_items(chars: list[Char], table_bbox: BBox, angle: int) ->if segment_parts and segment_bbox is not None and last_char_bbox is not None:gap = local_bbox[0] - last_char_bbox[2]- y_overlap = (- local_bbox[1] < segment_bbox[3] + _Y_TOLERANCE- and local_bbox[3] > segment_bbox[1] - _Y_TOLERANCE- )+ y_overlap = local_bbox[1] < segment_bbox[3] + _Y_TOLERANCE and local_bbox[3] > segment_bbox[1] - _Y_TOLERANCEstrict_below = local_bbox[1] > last_char_bbox[3]segment_width = segment_bbox[2] - segment_bbox[0]line_changed = (@@ -221,11 +220,7 @@ def _build_pdf_spatial_items(chars: list[Char], table_bbox: BBox, angle: int) ->else:previous_char = segment_parts[-1][-1] if segment_parts[-1] else ""current_char = normalized_char[0]- if (- previous_char.isalnum()- and current_char.isalnum()- and gap > char_height * _MISSING_SPACE_HEIGHT_RATIO- ):+ if previous_char.isalnum() and current_char.isalnum() and gap > char_height * _MISSING_SPACE_HEIGHT_RATIO:segment_parts.append(" ")if segment_bbox is None:@@ -277,9 +272,7 @@ def _build_ocr_spatial_items(ocr_result: Any, table_size: tuple[int, int]) -> lidef _compute_text_grid_size(items: list[_SpatialTextItem]) -> tuple[float, float]:"""使用文本项的平均字符宽度和框高计算稳健的中位网格尺寸。"""char_widths = [- (item.bbox[2] - item.bbox[0]) / max(1, len(item.text))- for item in items- if item.bbox[2] > item.bbox[0] and item.text+ (item.bbox[2] - item.bbox[0]) / max(1, len(item.text)) for item in items if item.bbox[2] > item.bbox[0] and item.text]heights = [item.bbox[3] - item.bbox[1] for item in items if item.bbox[3] > item.bbox[1]]median_width = statistics.median(char_widths) if char_widths else 1.0@@ -308,17 +301,13 @@ def _form_spatial_lines(line_top = min(line_item.bbox[1] for line_item in current_line)line_bottom = max(line_item.bbox[3] for line_item in current_line)horizontal_collision = any(- min(line_item.bbox[2], item.bbox[2]) - max(line_item.bbox[0], item.bbox[0])- > max(5.0, median_width / 3.0)+ min(line_item.bbox[2], item.bbox[2]) - max(line_item.bbox[0], item.bbox[0]) > max(5.0, median_width / 3.0)for line_item in current_line)proposed_top = min(line_top, item.bbox[1])proposed_bottom = max(line_bottom, item.bbox[3])item_center_y = (item.bbox[1] + item.bbox[3]) / 2.0- vertically_compatible = (- line_top <= item_center_y <= line_bottom- or line_top <= item.bbox[1] <= line_bottom- )+ vertically_compatible = line_top <= item_center_y <= line_bottom or line_top <= item.bbox[1] <= line_bottomif (not horizontal_collisionand vertically_compatible@@ -357,11 +346,7 @@ def _project_spatial_items(preserve_blank_rows: bool = False,) -> str:"""把空间文本项投影到等宽字符网格,并按需保留明显的空白行。"""- valid_items = [- item- for item in items- if item.text and item.bbox[2] > item.bbox[0] and item.bbox[3] > item.bbox[1]- ]+ valid_items = [item for item in items if item.text and item.bbox[2] > item.bbox[0] and item.bbox[3] > item.bbox[1]]if not valid_items:return ""@@ -371,11 +356,7 @@ def _project_spatial_items(previous_bottom: float | None = Nonefor line in spatial_lines:line_top = min(item.bbox[1] for item in line)- if (- preserve_blank_rows- and previous_bottom is not None- and line_top - previous_bottom > 1.25 * median_height- ):+ if preserve_blank_rows and previous_bottom is not None and line_top - previous_bottom > 1.25 * median_height:blank_count = max(1,round((line_top - previous_bottom) / median_height) - 1,diff --git a/mineru/backend/utils/char_utils.py b/mineru/utils/text_utils.pysimilarity index 82%rename from mineru/backend/utils/char_utils.pyrename to mineru/utils/text_utils.pyindex 25f5f2ad..ea36b437 100644--- a/mineru/backend/utils/char_utils.py+++ b/mineru/utils/text_utils.py@@ -1,4 +1,6 @@# Copyright (c) Opendatalab. All rights reserved.+"""跨模型共享的文本字符规范化与换行连接规则。"""+import re# 中日韩文本的物理换行通常不需要插入额外空格,集中定义以供各后端和渲染器共享。@@ -42,14 +44,7 @@ def resolve_text_line_boundary(def full_to_half_exclude_marks(text: str) -> str:- """Convert full-width characters to half-width characters using code point manipulation.-- Args:- text: String containing full-width characters-- Returns:- String with full-width characters converted to half-width- """+ """将全角英文字母和数字转换为半角形式,同时保留全角标点。"""result = []for char in text:code = ord(char)@@ -62,14 +57,7 @@ def full_to_half_exclude_marks(text: str) -> str:def full_to_half(text: str) -> str:- """Convert full-width characters to half-width characters using code point manipulation.-- Args:- text: String containing full-width characters-- Returns:- String with full-width characters converted to half-width- """+ """将全角 ASCII 字母、数字和标点统一转换为半角形式。"""result = []for char in text:code = ord(char)@@ -79,3 +67,13 @@ def full_to_half(text: str) -> str:else:result.append(char)return "".join(result)+++def clean_isolated_formula(content: str) -> str:+ """移除行间公式外层的反斜杠方括号并清理首尾空白。"""+ latex = content[:]+ if latex.startswith("\\["):+ latex = latex[2:]+ if latex.endswith("\\]"):+ latex = latex[:-2]+ return latex.strip()diff --git a/pyproject.toml b/pyproject.tomlindex 91d2c7d9..20ccafd5 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -52,7 +52,7 @@ dependencies = ["openai>=1.70.0,<3","beautifulsoup4>=4.13.5,<5","magika>=0.6.2,<1.1.0",- "mineru-vl-utils>=1.0.5,<2",+ "mineru-vl-utils>=1.2.1,<2","python-docx>=1.2.0,<2",'pypptx-with-oxml>=1.0.3,<2',"mammoth>=1.11.0,<2",diff --git a/tests/unittest/test_backend_architecture.py b/tests/unittest/test_backend_architecture.pynew file mode 100644index 00000000..d2a71ed0--- /dev/null+++ b/tests/unittest/test_backend_architecture.py@@ -0,0 +1,133 @@+from __future__ import annotations++import ast+from pathlib import Path++from mineru.backend.postprocess import table_merge++_PROJECT_ROOT = Path(__file__).resolve().parents[2]+_COPYRIGHT_HEADER = "# Copyright (c) Opendatalab. All rights reserved."+_CHINESE_DOCSTRING_EXTRA_PATHS = (+ "mineru/model/flash/office",+ "mineru/model/flash/xycut.py",+ "mineru/model/model_types.py",+ "mineru/utils/spatial_text.py",+ "mineru/utils/text_utils.py",+)+++def _absolute_imports(path: Path) -> set[str]:+ """读取 Python 文件中的绝对 import 模块名。"""+ tree = ast.parse(path.read_text(encoding="utf-8"))+ imports: set[str] = set()+ for node in ast.walk(tree):+ if isinstance(node, ast.Import):+ imports.update(alias.name for alias in node.names)+ elif isinstance(node, ast.ImportFrom) and node.level == 0 and node.module:+ imports.add(node.module)+ return imports+++def _relative_imports(path: Path) -> set[str]:+ """读取 Python 文件对同包模块的相对 import 名称。"""+ tree = ast.parse(path.read_text(encoding="utf-8"))+ return {node.module for node in ast.walk(tree) if isinstance(node, ast.ImportFrom) and node.level > 0 and node.module}+++def _contains_chinese(text: str) -> bool:+ """判断职责说明中是否至少包含一个中文字符。"""+ return any("\u4e00" <= char <= "\u9fff" for char in text)+++def _iter_refactored_python_paths() -> list[Path]:+ """收集 backend 及本次从 utils 迁出的公共 Python 模块。"""+ paths = list((_PROJECT_ROOT / "mineru/backend").rglob("*.py"))+ for relative_path in _CHINESE_DOCSTRING_EXTRA_PATHS:+ path = _PROJECT_ROOT / relative_path+ paths.extend(path.rglob("*.py") if path.is_dir() else [path])+ return sorted(paths)+++def test_backend_python_files_have_copyright_header() -> None:+ """守卫 backend 下每个 Python 文件都以统一版权声明开头。"""+ offenders = [+ str(path.relative_to(_PROJECT_ROOT))+ for path in (_PROJECT_ROOT / "mineru/backend").rglob("*.py")+ if path.read_text(encoding="utf-8").splitlines()[0] != _COPYRIGHT_HEADER+ ]+ assert not offenders+++def test_refactored_definitions_have_chinese_docstrings() -> None:+ """守卫 backend 及迁出模块中的函数、方法和类均有中文职责说明。"""+ offenders: list[str] = []+ for path in _iter_refactored_python_paths():+ tree = ast.parse(path.read_text(encoding="utf-8"))+ for node in ast.walk(tree):+ if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):+ continue+ docstring = ast.get_docstring(node)+ if not docstring or not _contains_chinese(docstring):+ relative_path = path.relative_to(_PROJECT_ROOT)+ offenders.append(f"{relative_path}:{node.lineno}:{node.name}")+ assert not offenders+++def test_model_and_types_do_not_import_backend() -> None:+ """守卫模型层和公开类型层不再反向依赖 backend。"""+ paths = [*_PROJECT_ROOT.glob("mineru/model/**/*.py"), _PROJECT_ROOT / "mineru/types.py"]+ offenders = {+ str(path.relative_to(_PROJECT_ROOT)): sorted(+ module for module in _absolute_imports(path) if module.startswith("mineru.backend")+ )+ for path in paths+ }+ assert not {path: modules for path, modules in offenders.items() if modules}+++def test_analysis_does_not_import_postprocess() -> None:+ """守卫 model-list 生产层不反向调用 Middle JSON 后处理层。"""+ offenders = {+ str(path.relative_to(_PROJECT_ROOT)): sorted(+ module for module in _absolute_imports(path) if module.startswith("mineru.backend.postprocess")+ )+ for path in _PROJECT_ROOT.glob("mineru/backend/analysis/**/*.py")+ }+ assert not {path: modules for path, modules in offenders.items() if modules}+++def test_backend_utils_package_is_removed() -> None:+ """守卫 backend/utils 不再承载任何 Python 源码。"""+ utils_path = _PROJECT_ROOT / "mineru/backend/utils"+ assert not utils_path.exists()+++def test_table_merge_package_keeps_one_way_internal_dependencies() -> None:+ """守卫 table_merge 低层模块不反向导入内容合并或文档编排模块。"""+ package_path = _PROJECT_ROOT / "mineru/backend/postprocess/table_merge"+ allowed_imports = {+ "models.py": set(),+ "html.py": {"models"},+ "blocks.py": {"html", "models", "rules"},+ "structure.py": {"blocks", "html", "models"},+ "content.py": {"blocks", "html", "models", "structure"},+ "document.py": {"blocks", "models", "structure"},+ "rules.py": set(),+ }+ actual_imports = {filename: _relative_imports(package_path / filename) for filename in allowed_imports}+ assert actual_imports == allowed_imports+++def test_table_merge_public_contract_remains_callable() -> None:+ """验证本地入口和 mineru-vl-utils 使用的七个公开函数保持可调用。"""+ function_names = [+ "merge_table",+ "merge_table_content",+ "build_table_state_from_html",+ "build_row_rendered_cell_segments",+ "can_merge_by_structure",+ "calculate_row_rendered_segments",+ "detect_table_headers",+ ]+ assert table_merge.__all__ == function_names+ assert all(callable(getattr(table_merge, name, None)) for name in function_names)diff --git a/tests/unittest/test_backend_block_object_regressions.py b/tests/unittest/test_backend_block_object_regressions.pyindex ccbc618a..2b80f7dd 100644--- a/tests/unittest/test_backend_block_object_regressions.py+++ b/tests/unittest/test_backend_block_object_regressions.py@@ -1,71 +1,47 @@-from __future__ import annotations+from mineru.backend.postprocess.pages import model_list_to_pages+from mineru.types import BlockType, ImageBlock-from types import SimpleNamespace-from PIL import Image--from mineru.backend.pdf import hybrid_analyze-from mineru.backend.pdf.model_output_to_middle_json import blocks_to_page_info as hybrid_blocks_to_page_info-from mineru.types import BlockType---def _fake_pdf_page(width: int = 200, height: int = 200) -> SimpleNamespace:- return SimpleNamespace(size=(width, height))---def _image_dict(width: int = 200, height: int = 200) -> dict[str, object]:- return {"scale": 1.0, "img_pil": Image.new("RGB", (width, height), "white")}---def test_hybrid_block_objects_sort_and_group_without_dict_access() -> None:- page_info = hybrid_blocks_to_page_info(+def test_postprocess_groups_pdf_visual_blocks_without_dict_access() -> None:+ """验证 PDF raw 视觉块会在严格对象化边界完成分组。"""+ page = model_list_to_pages([- {- "type": "image_caption",- "bbox": [0.05, 0.05, 0.6, 0.12],- "content": "Figure 1",- },- {- "type": "image",- "bbox": [0.05, 0.15, 0.6, 0.45],- },- ],- _image_dict(),- _fake_pdf_page(),- 0,- _ocr_enable=True,- _vlm_ocr_enable=True,- )+ [+ {+ "type": BlockType.IMAGE_CAPTION,+ "bbox": [0.05, 0.05, 0.6, 0.12],+ "content": "Figure 1",+ },+ {+ "type": BlockType.IMAGE,+ "bbox": [0.05, 0.15, 0.6, 0.45],+ },+ ]+ ]+ )[0]- assert len(page_info.preproc_blocks) == 1- visual_block = page_info.preproc_blocks[0]- assert visual_block.type == BlockType.IMAGE- assert {block.type for block in visual_block.blocks} == {BlockType.IMAGE_BODY, BlockType.IMAGE_CAPTION}+ assert len(page.blocks) == 1+ assert isinstance(page.blocks[0], ImageBlock)+ assert {block.type for block in page.blocks[0].content} == {+ BlockType.IMAGE_BODY,+ BlockType.IMAGE_CAPTION,+ }-def test_hybrid_medium_vision_footnote_groups_as_image_footnote() -> None:- """medium 的 vision_footnote 应作为视觉脚注挂到相邻 image 下,而不是进入 page footnote。"""- page_image = Image.new("RGB", (200, 200), "white")- model_list = hybrid_analyze._build_medium_hybrid_model_list(+def test_postprocess_groups_raw_vision_footnote_as_image_footnote() -> None:+ """验证通用 raw footnote 会归入相邻图片而不是页脚注。"""+ page = model_list_to_pages([[- {"label": "image", "bbox": [20, 20, 120, 90], "score": 0.9},- {"label": "vision_footnote", "bbox": [24, 94, 120, 120], "text": "Figure note", "score": 0.9},+ {"type": BlockType.IMAGE, "bbox": [0.1, 0.1, 0.6, 0.45]},+ {"type": "footnote", "bbox": [0.12, 0.47, 0.6, 0.6], "content": "Figure note"},]- ],- [page_image],- )-- page_info = hybrid_blocks_to_page_info(- model_list[0],- _image_dict(),- _fake_pdf_page(),- 0,- _ocr_enable=True,- _vlm_ocr_enable=False,- )-- assert len(page_info.preproc_blocks) == 1- visual_block = page_info.preproc_blocks[0]- assert visual_block.type == BlockType.IMAGE- assert {block.type for block in visual_block.blocks} == {BlockType.IMAGE_BODY, BlockType.IMAGE_FOOTNOTE}+ ]+ )[0]++ assert len(page.blocks) == 1+ assert isinstance(page.blocks[0], ImageBlock)+ assert {block.type for block in page.blocks[0].content} == {+ BlockType.IMAGE_BODY,+ BlockType.IMAGE_FOOTNOTE,+ }diff --git a/tests/unittest/test_flash_office_models.py b/tests/unittest/test_flash_office_models.pyindex 602aa302..ae1fb461 100644--- a/tests/unittest/test_flash_office_models.py+++ b/tests/unittest/test_flash_office_models.py@@ -12,12 +12,6 @@ import pytestimport mineru.model.flash as flash_modelsimport mineru.model.flash.model as flat_model_module-from mineru.backend.office import docx_analyze as docx_backend-from mineru.backend.office import pptx_analyze as pptx_backend-from mineru.backend.office import xlsx_analyze as xlsx_backend-from mineru.backend.office.docx_analyze import office_docx_analyze-from mineru.backend.office.pptx_analyze import office_pptx_analyze-from mineru.backend.office.xlsx_analyze import office_xlsx_analyzefrom mineru.model.flash import DocxModel, PdfModel, PptxModel, XlsxModelfrom mineru.model.flash.docx import docx_converter as docx_converter_modulefrom mineru.model.flash.docx import main as docx_main@@ -25,7 +19,6 @@ from mineru.model.flash.pptx import main as pptx_mainfrom mineru.model.flash.pptx import pptx_converter as pptx_converter_modulefrom mineru.model.flash.xlsx import main as xlsx_mainfrom mineru.model.flash.xlsx import xlsx_converter as xlsx_converter_module-from mineru.parser.office import DocxParser, PptxParser, XlsxParser_PROJECT_ROOT = Path(__file__).resolve().parents[2]@@ -151,43 +144,6 @@ def test_convert_path_delegates_to_binary_helper(assert file_stream.closed- ("backend_module", "analyze_name", "model_name"),- [- (docx_backend, "office_docx_analyze", "DocxModel"),- (pptx_backend, "office_pptx_analyze", "PptxModel"),- (xlsx_backend, "office_xlsx_analyze", "XlsxModel"),- ],-)-def test_office_backend_uses_document_model(- monkeypatch: pytest.MonkeyPatch,- backend_module: ModuleType,- analyze_name: str,- model_name: str,-) -> None:- """验证 Office 后端调用对应模型,并保留中间结果转换边界。"""-- model_output = [[{"content": "model"}]]- middle_json = [MagicMock()]- image_cache = MagicMock()- model = MagicMock()- model.predict.return_value = model_output- model_factory = MagicMock(return_value=model)- middle_json_builder = MagicMock(return_value=middle_json)- monkeypatch.setattr(backend_module, model_name, model_factory)- monkeypatch.setattr(backend_module, "result_to_middle_json", middle_json_builder)-- result = getattr(backend_module, analyze_name)(b"office", image_cache=image_cache)-- assert result == (middle_json, model_output)- model_factory.assert_called_once_with()- file_stream = model.predict.call_args.args[0]- assert isinstance(file_stream, BytesIO)- assert file_stream.getvalue() == b"office"- assert not file_stream.closed- middle_json_builder.assert_called_once_with(model_output, image_cache=image_cache)--def test_models_are_exported_from_flash_root() -> None:"""验证四个模型统一由 Flash 根包公开。"""@@ -238,14 +194,6 @@ def test_importing_pdf_model_does_not_load_office_converters() -> None:assert result.returncode == 0, result.stderr-def test_office_parsers_bind_existing_analyzers() -> None:- """验证三个 Office Parser 仍绑定原有的后端分析入口。"""-- assert DocxParser()._analyze_fn is office_docx_analyze- assert PptxParser()._analyze_fn is office_pptx_analyze- assert XlsxParser()._analyze_fn is office_xlsx_analyze--@pytest.mark.parametrize("module_name",["mineru.model.docx", "mineru.model.pptx", "mineru.model.xlsx"],diff --git a/tests/unittest/test_flash_pdf_code_blocks.py b/tests/unittest/test_flash_pdf_code_blocks.pyindex 7f017cf7..97961db8 100644--- a/tests/unittest/test_flash_pdf_code_blocks.py+++ b/tests/unittest/test_flash_pdf_code_blocks.py@@ -7,7 +7,7 @@ import pytestfrom mineru.model.flash import PdfModelfrom mineru.model.flash.native_pdf import code_blocks, models, pipeline-from mineru.backend.utils.table_text import project_pdf_spatial_text+from mineru.utils.spatial_text import project_pdf_spatial_textfrom mineru.utils.pdf_document import PDFDocument, PDFPathInfofrom _flash_pdf_test_utils import _text_line@@ -292,10 +292,13 @@ def test_rule_delimited_listing_rejects_vertical_track_spanning_candidate() -> N[],)- assert code_blocks._vertical_rule_candidate_height_coverage(- source.drawing_lines[-1].bbox,- (20.0, 20.0, 180.0, 105.0),- ) == 1.0+ assert (+ code_blocks._vertical_rule_candidate_height_coverage(+ source.drawing_lines[-1].bbox,+ (20.0, 20.0, 180.0, 105.0),+ )+ == 1.0+ )assert blocks == []assert claimed == set()@@ -303,21 +306,12 @@ def test_rule_delimited_listing_rejects_vertical_track_spanning_candidate() -> Ndef test_kvcache_algorithm_pdf_materializes_caption_and_code() -> None:"""验证真实长算法页面输出相邻 caption/code,且来源文本不再重复。"""- pdf_path = (- Path(__file__).parents[2]- / "demo"- / "pdfs"- / "2407.00079v4_origi-10.pdf"- )+ pdf_path = Path(__file__).parents[2] / "demo" / "pdfs" / "2407.00079v4_origi-10.pdf"with PDFDocument(str(pdf_path)) as pdf_doc:page = PdfModel().predict(pdf_doc)[0]caption_text = "Algorithm 1 KVCache-centric Scheduling Algorithm"- captions = [- block- for block in page- if block["type"] == "caption" and block.get("content") == caption_text- ]+ captions = [block for block in page if block["type"] == "caption" and block.get("content") == caption_text]code = [block for block in page if block["type"] == "code"]assert len(captions) == 1@@ -325,11 +319,7 @@ def test_kvcache_algorithm_pdf_materializes_caption_and_code() -> None:assert len(code) == 1assert code[0]["bbox"] == [0.176, 0.108, 0.824, 0.539]assert page.index(captions[0]) + 1 == page.index(code[0])- assert not [- block- for block in page- if block["type"] == "header" and block.get("content") == caption_text- ]+ assert not [block for block in page if block["type"] == "header" and block.get("content") == caption_text]code_content = str(code[0]["content"])probes = (@@ -340,7 +330,4 @@ def test_kvcache_algorithm_pdf_materializes_caption_and_code() -> None:)assert all(probe in code_content for probe in probes)for probe in probes:- assert sum(- probe in str(block.get("content", ""))- for block in page- ) == 1+ assert sum(probe in str(block.get("content", "")) for block in page) == 1diff --git a/tests/unittest/test_flash_pdf_extractor.py b/tests/unittest/test_flash_pdf_extractor.pyindex dfde2974..7e3e5fdf 100644--- a/tests/unittest/test_flash_pdf_extractor.py+++ b/tests/unittest/test_flash_pdf_extractor.py@@ -1,162 +1,8 @@-from __future__ import annotations--import sys-from types import ModuleType-from typing import Any-from unittest.mock import MagicMock--import pytest--from mineru.backend.flash import pdf_extractor-from mineru.model.flash import PdfModel-from mineru.model.flash.native_pdf import (- pipeline,-)---def _install_pdf_document(- monkeypatch: pytest.MonkeyPatch,- *,- page_count: int = 1,- classified_mode: str = "txt",-) -> tuple[MagicMock, MagicMock]:- """安装支持上下文管理的 PDFDocument 替身并返回文档与管理器。"""-- pdf_doc = MagicMock()- pdf_doc.page_count = page_count- pdf_doc.classify.return_value = classified_mode- context_manager = MagicMock()- context_manager.__enter__.return_value = pdf_doc- context_manager.__exit__.return_value = False- monkeypatch.setattr(pdf_extractor, "PDFDocument", MagicMock(return_value=context_manager))- return pdf_doc, context_manager---def _install_hybrid_analyze(- monkeypatch: pytest.MonkeyPatch,- *,- model_list: list[list[dict[str, Any]]],-) -> MagicMock:- """安装 Hybrid analyze 模块替身,避免路由测试加载真实模型。"""-- hybrid_doc_analyze = MagicMock(return_value=([object()], model_list))- analyze_module = ModuleType("mineru.backend.hybrid.analyze")- analyze_module.doc_analyze = hybrid_doc_analyze # type: ignore[attr-defined]- monkeypatch.setitem(sys.modules, "mineru.backend.hybrid.analyze", analyze_module)- return hybrid_doc_analyze--- ("parse_mode", "expected_classify_calls"),- [- ("ocr", 0),- ("auto", 1),- ],-)-def test_ocr_mode_delegates_to_hybrid_low(- monkeypatch: pytest.MonkeyPatch,- parse_mode: str,- expected_classify_calls: int,-) -> None:- """验证显式或自动判定的 OCR 模式都精确委托 Hybrid low。"""-- pdf_bytes = b"%PDF-1.7\n"- page_index_map = [7]- expected_model_list = [[{"type": "text", "content": "hybrid"}]]- pdf_doc, context_manager = _install_pdf_document(- monkeypatch,- classified_mode="ocr",- )- hybrid_doc_analyze = _install_hybrid_analyze(- monkeypatch,- model_list=expected_model_list,- )-- result = pdf_extractor.doc_analyze(- pdf_bytes,- parse_mode=parse_mode, # type: ignore[arg-type]- page_index_map=page_index_map,- )-- assert result is expected_model_list- assert pdf_doc.classify.call_count == expected_classify_calls- assert context_manager.__exit__.call_count == 1- hybrid_doc_analyze.assert_called_once_with(- pdf_bytes,- effort="low",- parse_mode="ocr",- page_index_map=page_index_map,- )--- ("parse_mode", "expected_classify_calls"),- [- ("txt", 0),- ("auto", 1),- ],-)-def test_txt_mode_keeps_native_flash_path(- monkeypatch: pytest.MonkeyPatch,- parse_mode: str,- expected_classify_calls: int,-) -> None:- """验证显式或自动判定的文本模式继续使用 Flash 原生路径。"""-- expected_model_list = [[{"type": "text", "content": "native"}]]- pdf_doc, _context_manager = _install_pdf_document(- monkeypatch,- classified_mode="txt",- )- native_predict = MagicMock(return_value=expected_model_list)- monkeypatch.setattr(PdfModel, "predict", native_predict)- hybrid_doc_analyze = _install_hybrid_analyze(- monkeypatch,- model_list=[[{"type": "text", "content": "unexpected"}]],- )-- result = pdf_extractor.doc_analyze(- b"%PDF-1.7\n",- parse_mode=parse_mode, # type: ignore[arg-type]- )-- assert result is expected_model_list- assert pdf_doc.classify.call_count == expected_classify_calls- native_predict.assert_called_once_with(pdf_doc)- hybrid_doc_analyze.assert_not_called()---def test_invalid_parse_mode_is_rejected_before_opening_pdf(monkeypatch: pytest.MonkeyPatch) -> None:- """验证非法解析模式在打开 PDF 前保持原有报错行为。"""-- pdf_document = MagicMock()- monkeypatch.setattr(pdf_extractor, "PDFDocument", pdf_document)-- with pytest.raises(ValueError, match="parse_mode invalid is not supported"):- pdf_extractor.doc_analyze(b"%PDF-1.7\n", parse_mode="invalid") # type: ignore[arg-type]-- pdf_document.assert_not_called()---def test_page_index_map_mismatch_is_rejected_before_hybrid_call(monkeypatch: pytest.MonkeyPatch) -> None:- """验证页映射长度不匹配时不会进入 Hybrid low。"""-- _install_pdf_document(monkeypatch, page_count=2, classified_mode="ocr")- hybrid_doc_analyze = _install_hybrid_analyze(monkeypatch, model_list=[])-- with pytest.raises(ValueError, match="Flash page_index_map length mismatch"):- pdf_extractor.doc_analyze(- b"%PDF-1.7\n",- parse_mode="ocr",- page_index_map=[0],- )-- hybrid_doc_analyze.assert_not_called()+from mineru.model.flash.native_pdf import pipelinedef test_marginal_header_row_does_not_break_two_column_reading_order() -> None:- """验证页眉页码独立按视觉行排序,正文仍保持左栏后右栏的阅读顺序。"""-+ """验证边缘页眉按视觉行排序且正文保持先左栏后右栏。"""blocks = [{"type": "header", "bbox": (80.0, 2.0, 120.0, 12.0), "angle": 0, "content": "center"},{"type": "page_number", "bbox": (2.0, 0.0, 12.0, 14.0), "angle": 0, "content": "page"},@@ -167,10 +13,7 @@ def test_marginal_header_row_does_not_break_two_column_reading_order() -> None:{"type": "text", "bbox": (120.0, 45.0, 200.0, 65.0), "angle": 0, "content": "right two"},]- sorted_blocks = pipeline._sort_blocks_with_visual_row_groups(- blocks,- (200.0, 100.0),- )+ sorted_blocks = pipeline._sort_blocks_with_visual_row_groups(blocks, (200.0, 100.0))assert [block["content"] for block in sorted_blocks] == ["page",@@ -184,8 +27,7 @@ def test_marginal_header_row_does_not_break_two_column_reading_order() -> None:def test_overlapping_span_captions_follow_visual_center_order() -> None:- """验证同一跨栏带中轻微重叠的图注按视觉中心由上到下稳定排序。"""-+ """验证跨栏带中轻微重叠的图注按视觉中心稳定排序。"""common = {"type": "text","angle": 0,diff --git a/tests/unittest/test_flash_pdf_pipeline.py b/tests/unittest/test_flash_pdf_pipeline.pyindex 0e162f5a..69c67489 100644--- a/tests/unittest/test_flash_pdf_pipeline.py+++ b/tests/unittest/test_flash_pdf_pipeline.py@@ -5,7 +5,6 @@ import inspectimport pytest-from mineru.backend.flash import pdf_extractorfrom mineru.model.flash import PdfModelfrom mineru.model.flash.native_pdf import (auxiliary_text,@@ -78,9 +77,7 @@ def test_prepare_page_materializes_table_against_original_semantic_lines("""记录表格物化阶段可见的来源行。"""assert candidates == []- observed["materialize"] = [- line.source_index for line in materialization_source.lines- ]+ observed["materialize"] = [line.source_index for line in materialization_source.lines]return [], [], set()monkeypatch.setattr(pipeline, "_detect_table_candidates", fake_detect)@@ -187,7 +184,6 @@ def test_flash_extractor_has_no_local_ocr_runtime_logic() -> None:source = "\n".join(inspect.getsource(module)for module in (- pdf_extractor,PdfModel,auxiliary_text,formulas,@@ -224,13 +220,6 @@ def test_flash_extractor_has_no_local_ocr_runtime_logic() -> None:assert not [token for token in forbidden_tokens if token in source]-def test_flash_extractor_only_exports_supported_entrypoints() -> None:- """验证旧模块只声明两个稳定公共入口,不再承载内部实现。"""-- assert pdf_extractor.__all__ == ["doc_analyze", "extract_pages_text"]- assert not hasattr(pdf_extractor, "_analyze_native_document")--def test_native_pdf_domain_modules_do_not_import_each_other() -> None:"""守卫领域处理器只依赖共享层,跨领域组合统一留在 pipeline。"""@@ -363,12 +352,8 @@ def test_index_is_claimed_before_formula_anchor_growth() -> None:assert [block["type"] for block in blocks].count("index") == 1assert not [block for block in blocks if block["type"] == "equation"]- assert next(block for block in blocks if block["type"] == "index")[- "content"- ].count("entry-") == 6- assert next(block for block in blocks if block["content"] == "contents")[- "type"- ] == "paragraph_title"+ assert next(block for block in blocks if block["type"] == "index")["content"].count("entry-") == 6+ assert next(block for block in blocks if block["content"] == "contents")["type"] == "paragraph_title"def test_numbered_formula_rows_are_not_claimed_as_index() -> None:@@ -387,9 +372,7 @@ def test_numbered_formula_rows_are_not_claimed_as_index() -> None:for index in range(10)]source_index = 10- for row_index, top in enumerate(- (102.0, 113.0, 124.0, 135.0, 146.0, 157.0)- ):+ for row_index, top in enumerate((102.0, 113.0, 124.0, 135.0, 146.0, 157.0)):visual_row_id = 100 + row_indexlines.extend([diff --git a/tests/unittest/test_flash_pdf_samples.py b/tests/unittest/test_flash_pdf_samples.pyindex 3c37c806..30177585 100644--- a/tests/unittest/test_flash_pdf_samples.py+++ b/tests/unittest/test_flash_pdf_samples.py@@ -1,12 +1,13 @@from __future__ import annotationsfrom collections import Counter+from copy import deepcopyfrom pathlib import Pathfrom typing import Anyimport unicodedata--from mineru.backend.flash import pdf_extractor+from mineru.backend.postprocess.page_blocks import process_page_blocks+from mineru.model.flash import PdfModelfrom mineru.model.flash.native_pdf import (formulas,geometry,@@ -14,39 +15,34 @@ from mineru.model.flash.native_pdf import (line_merging,models,native_text,- pipeline,tables,)-from mineru.backend.pdf.magic_model import MagicModel-from mineru.utils.pdf_document import get_lines_from_chars+from mineru.utils.pdf_document import PDFDocument, get_lines_from_charsdef _native_model_list(pdf_name: str) -> list[list[dict[str, Any]]]:"""运行仓库内数字 PDF 样例并返回 Flash 原生模型输出。"""pdf_path = Path(__file__).parents[2] / "demo" / "pdfs" / pdf_name- with pdf_extractor.PDFDocument(str(pdf_path)) as pdf_doc:- return pipeline._analyze_native_document(pdf_doc)+ with PDFDocument(str(pdf_path)) as pdf_doc:+ return PdfModel().predict(pdf_doc)def _txt_model_list(pdf_name: str) -> list[list[dict[str, Any]]]:"""显式使用 Flash TXT 模式解析仓库内回归 PDF,禁止经过 auto 分类。"""pdf_path = Path(__file__).parents[2] / "demo" / "pdfs" / pdf_name- return pdf_extractor.doc_analyze(- pdf_path.read_bytes(),- parse_mode="txt",- )+ with PDFDocument(pdf_path.read_bytes()) as pdf_doc:+ return PdfModel().predict(pdf_doc)def _auto_model_list(pdf_name: str) -> list[list[dict[str, Any]]]:"""通过稳定公共入口以 auto 模式解析仓库内最小回归 PDF。"""pdf_path = Path(__file__).parents[2] / "demo" / "pdfs" / pdf_name- return pdf_extractor.doc_analyze(- pdf_path.read_bytes(),- parse_mode="auto",- )+ with PDFDocument(pdf_path.read_bytes()) as pdf_doc:+ assert pdf_doc.classify() == "txt"+ return PdfModel().predict(pdf_doc)def _native_table_counts(pdf_name: str) -> list[int]:@@ -59,7 +55,7 @@ def _native_page_source(pdf_name: str, page_idx: int) -> models._PageSource:"""读取指定样例页并构造候选检测与认领测试使用的页面源。"""pdf_path = Path(__file__).parents[2] / "demo" / "pdfs" / pdf_name- with pdf_extractor.PDFDocument(str(pdf_path)) as pdf_doc:+ with PDFDocument(str(pdf_path)) as pdf_doc:page_size = pdf_doc.page_size(page_idx)chars = pdf_doc.get_page_chars(page_idx)lines = native_text._build_native_line_items(@@ -78,6 +74,14 @@ def _native_page_source(pdf_name: str, page_idx: int) -> models._PageSource:)+def _grouped_visual_blocks(+ page_blocks: list[dict[str, Any]],+ block_type: str,+) -> list[dict[str, Any]]:+ """通过新的单页后处理入口返回指定类型的视觉容器,且不修改原始样例结果。"""+ return [block for block in process_page_blocks(deepcopy(page_blocks), use_bbox=True) if block.get("type") == block_type]++def _normalized_content_probe(text: str) -> str:"""去除空白、标点与 dash 差异,生成原生行内容覆盖检查使用的探针。"""@@ -105,20 +109,16 @@ def _blocks_containing("""返回归一化内容中包含指定探针的模型块。"""normalized_probe = _normalized_content_probe(probe)- return [- block- for block in blocks- if normalized_probe- in _normalized_content_probe(str(block.get("content", "")))- ]+ return [block for block in blocks if normalized_probe in _normalized_content_probe(str(block.get("content", "")))]def test_all_demo_pdfs_keep_expected_txt_block_inventory() -> None:- """验证 15 份 demo PDF 在显式 TXT 模式下保持预期块库存与页脚迁移。"""+ """验证 15 份既有 demo PDF 在 TXT 模式下保持预期块库存与页脚迁移。"""pdf_names = sorted(path.namefor path in (Path(__file__).parents[2] / "demo" / "pdfs").glob("*.pdf")+ if path.name != "2407.00079v4_origi-10.pdf")inventory: Counter[str] = Counter()page_count = 0@@ -126,20 +126,12 @@ def test_all_demo_pdfs_keep_expected_txt_block_inventory() -> None:for pdf_name in pdf_names:model_list = _txt_model_list(pdf_name)page_count += len(model_list)- inventory.update(- block["type"]- for page in model_list- for block in page- )+ inventory.update(block["type"] for page in model_list for block in page)unsafe_content.extend((pdf_name, page_index, block_index, unsafe_chars)for page_index, page in enumerate(model_list)for block_index, block in enumerate(page)- if (- unsafe_chars := _unsafe_flash_content_characters(- str(block.get("content", ""))- )- )+ if (unsafe_chars := _unsafe_flash_content_characters(str(block.get("content", "")))))assert len(pdf_names) == 15@@ -198,14 +190,8 @@ def test_demo1_keeps_five_real_tables_without_formula_false_positive() -> None:[0.087, 0.153, 0.922, 0.333],[0.087, 0.697, 0.922, 0.876],]- assert [block["bbox"] for block in model_list[8] if block["type"] == "table"] == [- [0.078, 0.167, 0.913, 0.333]- ]- page5_visual_blocks = [- block- for block in model_list[4]- if block["type"] in {"caption", "table", "footnote"}- ]+ assert [block["bbox"] for block in model_list[8] if block["type"] == "table"] == [[0.078, 0.167, 0.913, 0.333]]+ page5_visual_blocks = [block for block in model_list[4] if block["type"] in {"caption", "table", "footnote"}]assert [block["type"] for block in page5_visual_blocks] == ["caption","table",@@ -218,22 +204,16 @@ def test_demo1_keeps_five_real_tables_without_formula_false_positive() -> None:]assert [block["angle"] for block in page5_visual_blocks] == [270, 270, 270]assert page5_visual_blocks[2]["content"] == (- "For *rainfall distribution, U, uniform; W, winter dominated; "- "S, summer dominated. BFI, baseflow index."+ "For *rainfall distribution, U, uniform; W, winter dominated; S, summer dominated. BFI, baseflow index.")- assert [- [child.type for child in group.blocks]- for group in MagicModel(model_list[5], 1000, 1000).get_table_blocks()- ] == [+ assert [[child["type"] for child in group["content"]] for group in _grouped_visual_blocks(model_list[5], "table")] == [["table_caption", "table_body", "table_footnote"],["table_caption", "table_body", "table_footnote"],]page1_footnotes = [block for block in model_list[0] if block["type"] == "page_footnote"]assert len(page1_footnotes) == 1assert page1_footnotes[0]["content"].startswith("* Corresponding author.")- copyright_block = next(- block for block in model_list[0] if block["content"].startswith("0022-1694/$")- )+ copyright_block = next(block for block in model_list[0] if block["content"].startswith("0022-1694/$"))assert copyright_block["type"] == "footer"assert copyright_block["bbox"] == [0.078, 0.87, 0.513, 0.894]assert "doi:10.1016/j.jhydrol.2005.01.006" in copyright_block["content"]@@ -258,12 +238,8 @@ def test_demo1_rotated_table_claims_all_206_lines_without_residual_text() -> Non"caption","footnote",}- assert next(- block for block in annotation_blocks if block["type"] == "caption"- )["bbox"] == next(- annotation.bbox- for annotation in candidates[0].annotations- if annotation.kind == "caption"+ assert next(block for block in annotation_blocks if block["type"] == "caption")["bbox"] == next(+ annotation.bbox for annotation in candidates[0].annotations if annotation.kind == "caption")assert blocks[0]["bbox"] == candidates[0].core_bboxassert len(rotated_indices) == 206@@ -309,11 +285,7 @@ def test_demo2_page1_forms_sixteen_blocks_and_keeps_figure_caption_separate() ->assert "Left camera" not in caption_block["content"]assert sum(block["content"].count("Left camera") for block in page) == 1assert graphic_block["bbox"] == [0.516, 0.311, 0.913, 0.442]- copyright_block = next(- block- for block in page- if block["content"].startswith("978-1-4673-5208-6")- )+ copyright_block = next(block for block in page if block["content"].startswith("978-1-4673-5208-6"))assert copyright_block["type"] == "footer"@@ -343,9 +315,7 @@ def test_demo2_pages2_to6_restore_paragraphs_formulas_and_reading_order() -> Nonpage3 = model_list[2]page3_contents = [block["content"] for block in page3]- assert next(- block for block in page3 if block["content"] == "B. Temporal cost aggregation"- )["type"] == "paragraph_title"+ assert next(block for block in page3 if block["content"] == "B. Temporal cost aggregation")["type"] == "paragraph_title"assert page3_contents[12] == "D. Iterative Disparity Refinement"assert all(block["bbox"][2] <= 0.5 for block in page3[:12])assert "O(ω2) to O(ω)" in page3_contents[0]@@ -384,15 +354,11 @@ def test_demo2_pages2_to6_restore_paragraphs_formulas_and_reading_order() -> Nonassert "noise ranging between ±0 to ±40" in optimal_feedbackassert optimal_feedback.endswith("temporal stereo matching is used.")assert references_title["type"] == "paragraph_title"- assert [content.partition("]")[0] + "]" for content in page5_references] == [- f"[{number}]" for number in range(1, 6)- ]+ assert [content.partition("]")[0] + "]" for content in page5_references] == [f"[{number}]" for number in range(1, 6)]page6_contents = [block["content"] for block in model_list[5]]assert len(page6_contents) == 16- assert [content.partition("]")[0] + "]" for content in page6_contents] == [- f"[{number}]" for number in range(6, 22)- ]+ assert [content.partition("]")[0] + "]" for content in page6_contents] == [f"[{number}]" for number in range(6, 22)]def test_demo2_container_claims_are_pairwise_disjoint() -> None:@@ -401,9 +367,7 @@ def test_demo2_container_claims_are_pairwise_disjoint() -> None:for page_idx in (1, 2, 3):source = _native_page_source("demo2.pdf", page_idx)table_candidates = tables._detect_table_candidates(source)- table_blocks, _table_annotations, table_claimed = (- tables._materialize_table_blocks(source, table_candidates)- )+ table_blocks, _table_annotations, table_claimed = tables._materialize_table_blocks(source, table_candidates)table_bboxes = [block["bbox"] for block in table_blocks]_graphic_blocks, graphic_claimed = graphics._build_graphic_like_blocks(source,@@ -411,11 +375,7 @@ def test_demo2_container_claims_are_pairwise_disjoint() -> None:table_claimed,)remaining = line_merging._merge_same_baseline_text_lines(- [- line- for line in source.lines- if line.source_index not in table_claimed | graphic_claimed- ],+ [line for line in source.lines if line.source_index not in table_claimed | graphic_claimed],source.page_size,table_bboxes,)@@ -441,25 +401,18 @@ def test_demo2_page4_groups_five_graphics_and_keeps_table1() -> None:table_blocks = [block for block in page if block["type"] == "table"]graphic_markers = ("Frame 30", "Noise: ±0", "Noise: ±20", "Noise: ±40", "Noise ±")graphic_blocks = [- next(block for block in page if block["type"] == "image" and marker in block["content"])- for marker in graphic_markers+ next(block for block in page if block["type"] == "image" and marker in block["content"]) for marker in graphic_markers]assert len(table_blocks) == 1- table_caption = next(- block for block in page if str(block["content"]).startswith("Table I:")- )+ table_caption = next(block for block in page if str(block["content"]).startswith("Table I:"))assert table_caption["type"] == "caption"assert "Table I:" not in table_blocks[0]["content"]assert "Symbol" in table_blocks[0]["content"]assert len({id(block) for block in graphic_blocks}) == 5assert "Frame 90" in graphic_blocks[0]["content"]assert all("Figure" not in block["content"] for block in graphic_blocks)- body_tail_block = next(- block- for block in page- if block["content"].startswith("of the synthetic stereo scene")- )+ body_tail_block = next(block for block in page if block["content"].startswith("of the synthetic stereo scene"))assert body_tail_block["type"] == "text"assert body_tail_block["content"].endswith("discontinuity map.")assert "discontinuity map." not in graphic_blocks[0]["content"]@@ -509,22 +462,19 @@ def test_demo2_table_captions_and_numeric_footnotes_are_independent_blocks() ->[0.53, 0.391, 0.91, 0.438],]for page_index in (3, 4):- assert [- child.type- for child in MagicModel(- model_list[page_index],- 1000,- 1000,- ).get_table_blocks()[0].blocks- ] == ["table_caption", "table_body", "table_footnote"]+ assert [child["type"] for child in _grouped_visual_blocks(model_list[page_index], "table")[0]["content"]] == [+ "table_caption",+ "table_body",+ "table_footnote",+ ]def test_demo3_keeps_tables_and_covers_every_native_source_line() -> None:"""验证 demo3 容器、后续页段落边界及每条原生 source line 均保持稳定。"""pdf_path = Path(__file__).parents[2] / "demo" / "pdfs" / "demo3.pdf"- with pdf_extractor.PDFDocument(str(pdf_path)) as pdf_doc:- model_list = pipeline._analyze_native_document(pdf_doc)+ with PDFDocument(str(pdf_path)) as pdf_doc:+ model_list = PdfModel().predict(pdf_doc)source_lines_by_page: list[list[models._LineItem]] = []for page_idx in range(pdf_doc.page_count):page_size = pdf_doc.page_size(page_idx)@@ -563,29 +513,13 @@ def test_demo3_keeps_tables_and_covers_every_native_source_line() -> None:assert sum(len(page) for page in model_list) == 173assert sum(block["type"] == "caption" for page in model_list for block in page) == 8page7_tables = [block for block in model_list[6] if block["type"] == "table"]- page7_table4 = next(- block for block in page7_tables if "Number of parameters" in block["content"]- )- page7_table4_caption = next(- block- for block in model_list[6]- if block["content"] == "Table 4: Model size comparison."- )+ page7_table4 = next(block for block in page7_tables if "Number of parameters" in block["content"])+ page7_table4_caption = next(block for block in model_list[6] if block["content"] == "Table 4: Model size comparison.")page7_inline_body = next(- block- for block in model_list[6]- if block["content"].startswith("Row, Column, & Global Positional IDs.")- )- page9_conclusion = next(- block- for block in model_list[8]- if block["content"].startswith("In this paper, we identified")- )- page10_first_reference = next(- block- for block in model_list[9]- if block["content"].startswith("Xiang Deng, Huan Sun")+ block for block in model_list[6] if block["content"].startswith("Row, Column, & Global Positional IDs."))+ page9_conclusion = next(block for block in model_list[8] if block["content"].startswith("In this paper, we identified"))+ page10_first_reference = next(block for block in model_list[9] if block["content"].startswith("Xiang Deng, Huan Sun"))assert all(marker in page7_table4["content"]for marker in (@@ -644,17 +578,8 @@ def test_demo3_auxiliary_text_types_match_real_page_geometry() -> None:1,0,]- assert not [- block- for block in model_list[6]- if block["type"] in {"aside_text", "page_footnote"}- ]- assert not [- block- for page in model_list- for block in page- if block["type"] == "footer"- ]+ assert not [block for block in model_list[6] if block["type"] in {"aside_text", "page_footnote"}]+ assert not [block for page in model_list for block in page if block["type"] == "footer"]def test_demo3_pages1_and2_fix_title_front_matter_and_embedding_formula() -> None:@@ -671,25 +596,13 @@ def test_demo3_pages1_and2_fix_title_front_matter_and_embedding_formula() -> Non}- front_matter = [- block for block in page1 if block["content"] in front_matter_contents- ]- released_code = next(- block for block in page1 if "TABLEFORMER.md" in block["content"]- )+ front_matter = [block for block in page1 if block["content"] in front_matter_contents]+ released_code = next(block for block in page1 if "TABLEFORMER.md" in block["content"])aside = next(block for block in page1 if block["type"] == "aside_text")- introduction = next(- block for block in page1 if block["content"].startswith("Recently, semi-structured")- )- nutshell = next(- block for block in page1 if block["content"].startswith("In a nutshell")- )- figure_caption = next(- block for block in page1 if block["content"].startswith("Figure 1:")- )- tables_body = next(- block for block in page1 if block["content"].startswith("tables or rows")- )+ introduction = next(block for block in page1 if block["content"].startswith("Recently, semi-structured"))+ nutshell = next(block for block in page1 if block["content"].startswith("In a nutshell"))+ figure_caption = next(block for block in page1 if block["content"].startswith("Figure 1:"))+ tables_body = next(block for block in page1 if block["content"].startswith("tables or rows"))assert title["type"] == "doc_title"assert len(front_matter) == len(front_matter_contents)@@ -707,9 +620,7 @@ def test_demo3_pages1_and2_fix_title_front_matter_and_embedding_formula() -> Nonassert "tables or rows" not in figure_caption["content"]assert tables_body["type"] == "text"- section_title = next(- block for block in page2 if block["content"].startswith("2 Preliminaries:")- )+ section_title = next(block for block in page2 if block["content"].startswith("2 Preliminaries:"))equations = [block for block in page2 if block["type"] == "equation"]assert section_title["type"] == "paragraph_title"assert section_title["content"] == "2 Preliminaries: TAPAS for Table Encoding"@@ -744,30 +655,15 @@ def test_demo3_pages6_7_and10_fix_caption_inline_titles_and_reference_tail() ->page7 = model_list[6]page10 = model_list[9]- table2_caption = next(- block for block in page6 if block["content"].startswith("Table 2:")- )+ table2_caption = next(block for block in page6 if block["content"].startswith("Table 2:"))assert table2_caption["type"] == "caption"assert "Median of 5 independent runs are reported." in table2_caption["content"]assert table2_caption["content"].endswith("not reported in the original paper.")- assert sum(- "not reported in the original paper." in block["content"]- for block in page6- ) == 1+ assert sum("not reported in the original paper." in block["content"] for block in page6) == 1- attention_bias = next(- block for block in page7 if block["content"].startswith("Attention Bias Scaling.")- )- positional_ids = next(- block- for block in page7- if block["content"].startswith("Row, Column, & Global Positional IDs.")- )- formula6 = next(- block- for block in page7- if block["type"] == "equation" and "(6)" in block["content"]- )+ attention_bias = next(block for block in page7 if block["content"].startswith("Attention Bias Scaling."))+ positional_ids = next(block for block in page7 if block["content"].startswith("Row, Column, & Global Positional IDs."))+ formula6 = next(block for block in page7 if block["type"] == "equation" and "(6)" in block["content"])assert attention_bias["type"] == "text"assert attention_bias["content"].endswith("attention score by:")assert positional_ids["type"] == "text"@@ -777,23 +673,15 @@ def test_demo3_pages6_7_and10_fix_caption_inline_titles_and_reference_tail() ->blockfor block in page7if block["type"] == "paragraph_title"- and block["content"].startswith(- ("Attention Bias Scaling.", "Row, Column, & Global Positional IDs.")- )+ and block["content"].startswith(("Attention Bias Scaling.", "Row, Column, & Global Positional IDs."))]- ying_reference = next(- block for block in page10 if block["content"].startswith("Chengxuan Ying")- )- yu_reference = next(- block for block in page10 if block["content"].startswith("Tao Yu")- )+ ying_reference = next(block for block in page10 if block["content"].startswith("Chengxuan Ying"))+ yu_reference = next(block for block in page10 if block["content"].startswith("Tao Yu"))assert ying_reference["type"] == yu_reference["type"] == "text"assert ying_reference["content"].endswith("arXiv:2106.05234.")assert "Tao Yu" not in ying_reference["content"]- assert not [- block for block in page10 if block["content"] == "arXiv:2106.05234."- ]+ assert not [block for block in page10 if block["content"] == "arXiv:2106.05234."]def test_demo3_page3_form_image_formulas_titles_and_inline_body_are_whole() -> None:@@ -819,10 +707,7 @@ def test_demo3_page3_form_image_formulas_titles_and_inline_body_are_whole() -> Nfor block in page)caption_blocks = [- block- for block in page- if "Figure 2:" in block["content"]- or "types of task independent biases" in block["content"]+ block for block in page if "Figure 2:" in block["content"] or "types of task independent biases" in block["content"]]assert len(caption_blocks) == 1assert caption_blocks[0]["type"] == "caption"@@ -832,9 +717,7 @@ def test_demo3_page3_form_image_formulas_titles_and_inline_body_are_whole() -> Nformula1 = next(block for block in page if "(1)" in block["content"])section3 = next(block for block in page if block["content"].startswith("3 TABLEFORMER:"))inline_item = next(block for block in page if block["content"].startswith("2) Per cell positional ids."))- inline_heading = next(- block for block in page if block["content"].startswith("Positional Encoding in TABLEFORMER.")- )+ inline_heading = next(block for block in page if block["content"].startswith("Positional Encoding in TABLEFORMER."))assert formula1["type"] == "equation"assert "Q = HWQ" in formula1["content"] and "K = HWK" in formula1["content"]assert section3["type"] == "paragraph_title"@@ -848,17 +731,11 @@ def test_demo3_pages4_and5_fix_lists_formula_titles_italics_and_footnotes() -> Npage4, page5 = _native_model_list("demo3.pdf")[3:5]left_bullets = [- block- for block in page4- if block["type"] == "text"- and block["content"].startswith("•")- and block["bbox"][2] <= 0.5+ block for block in page4 if block["type"] == "text" and block["content"].startswith("•") and block["bbox"][2] <= 0.5]assert len(left_bullets) == 6assert all(len(block["content"].split()) > 8 for block in left_bullets)- attention_biases = next(- block for block in page4 if block["content"].startswith("Attention Biases in TABLEFORMER.")- )+ attention_biases = next(block for block in page4 if block["content"].startswith("Attention Biases in TABLEFORMER."))assert attention_biases["type"] == "text"assert "13 bias types" in attention_biases["content"]@@ -872,8 +749,7 @@ def test_demo3_pages4_and5_fix_lists_formula_titles_italics_and_footnotes() -> Nrelation_blocks = [blockfor block in page4- if "Relation between TABLEFORMER and ETC." in block["content"]- or "ETC (Ainslie et al., 2020)" in block["content"]+ if "Relation between TABLEFORMER and ETC." in block["content"] or "ETC (Ainslie et al., 2020)" in block["content"]]assert len(relation_blocks) == 1assert relation_blocks[0]["type"] == "text"@@ -892,21 +768,16 @@ def test_demo3_pages4_and5_fix_lists_formula_titles_italics_and_footnotes() -> Nassert continuation in inline_block["content"]assert next(block for block in page5 if block["content"] == "4.2 Baselines")["type"] == "paragraph_title"- assert next(- block for block in page5 if block["content"] == "4.3 Perturbing Tables as Augmented Data"- )["type"] == "paragraph_title"- italic_body = next(- block for block in page5 if block["content"].startswith("Could we alleviate")+ assert (+ next(block for block in page5 if block["content"] == "4.3 Perturbing Tables as Augmented Data")["type"]+ == "paragraph_title")+ italic_body = next(block for block in page5 if block["content"].startswith("Could we alleviate"))assert italic_body["type"] == "text"assert italic_body["content"].endswith("without making any")- final_bullet = next(- block for block in page5 if block["content"].startswith("• How does TABLEFORMER compare")- )- final_footnote = next(- block for block in page5 if block["content"].startswith("3By perturbation")- )+ final_bullet = next(block for block in page5 if block["content"].startswith("• How does TABLEFORMER compare"))+ final_footnote = next(block for block in page5 if block["content"].startswith("3By perturbation"))assert final_bullet["type"] == "text"assert final_footnote["type"] == "page_footnote"assert "3By perturbation" not in final_bullet["content"]@@ -918,26 +789,15 @@ def test_demo4_nct00083083_targeted_flash_regressions() -> None:model_list = _native_model_list("demo4.pdf")page1 = model_list[0]- assert any(- block["type"] == "header"- and "07388-8" in str(block["content"])- for block in page1- )- assert next(- block for block in page1 if block["content"] == "ORIGINAL ARTICLE"- )["type"] == "text"+ assert any(block["type"] == "header" and "07388-8" in str(block["content"]) for block in page1)+ assert next(block for block in page1 if block["content"] == "ORIGINAL ARTICLE")["type"] == "text"author_line = _blocks_containing(page1, "Rucha Ronghe1")[0]assert author_line["content"] == (- "Rucha Ronghe1 · Teresa Crespo Gonzalez2 · Catriona Wimberley3,4,5 "- "· Karla Suchacki3,6 · Adriana A. S. Tavares3,4"+ "Rucha Ronghe1 · Teresa Crespo Gonzalez2 · Catriona Wimberley3,4,5 · Karla Suchacki3,6 · Adriana A. S. Tavares3,4")assert _blocks_containing(page1, "contributed equally")[0]["type"] == "page_footnote"assert _blocks_containing(page1, "University of Edinburgh")[0]["type"] == "page_footnote"- assert [- block["bbox"]- for block in page1- if block["type"] == "footer"- ] == [[0.086, 0.934, 0.157, 0.957]]+ assert [block["bbox"] for block in page1 if block["type"] == "footer"] == [[0.086, 0.934, 0.157, 0.957]]abstract_sections = [_blocks_containing(page1, opener)@@ -955,9 +815,7 @@ def test_demo4_nct00083083_targeted_flash_regressions() -> None:("glucose metabolism", "chemoradiation", "0.77", "NSCLC patients"),strict=True,):- assert _normalized_content_probe(tail) in _normalized_content_probe(- str(matches[0]["content"])- )+ assert _normalized_content_probe(tail) in _normalized_content_probe(str(matches[0]["content"]))email = _blocks_containing(page1, "[email protected]")[0]affiliation_blocks = [@@ -968,22 +826,14 @@ def test_demo4_nct00083083_targeted_flash_regressions() -> None:and str(block.get("content", "")).lstrip()[:1] in set("123456")]assert len(affiliation_blocks) == 6- assert {- str(block["content"]).lstrip()[:1]- for block in affiliation_blocks- } == set("123456")+ assert {str(block["content"]).lstrip()[:1] for block in affiliation_blocks} == set("123456")assert not [- block- for block in page1- if block["type"] == "page_footnote"- and str(block.get("content", "")).strip() in set("123456")+ block for block in page1 if block["type"] == "page_footnote" and str(block.get("content", "")).strip() in set("123456")]introduction = _blocks_containing(page1, "Cancer is one of the leading causes")assert len(introduction) == 1- assert "throughoutthebody14" in _normalized_content_probe(- str(introduction[0]["content"])- )+ assert "throughoutthebody14" in _normalized_content_probe(str(introduction[0]["content"]))cross_lane_visual_regions = {4: [@@ -1025,24 +875,16 @@ def test_demo4_nct00083083_targeted_flash_regressions() -> None:page4 = model_list[3]caption_tail = _blocks_containing(page4, "included in the ACRIN 6668 study")assert len(caption_tail) == 1- assert _normalized_content_probe(str(caption_tail[0]["content"])).startswith(- "inreducingglucoseuptake"- )+ assert _normalized_content_probe(str(caption_tail[0]["content"])).startswith("inreducingglucoseuptake")figure_caption = _blocks_containing(page4, "Fig. 1 Conventional")figure_body = _blocks_containing(page4, "in reducing glucose uptake")assert len(figure_caption) == 1assert len(figure_body) == 1assert figure_caption[0] is not figure_body[0]assert figure_caption[0]["type"] == "caption"- assert "inreducingglucoseuptake" not in _normalized_content_probe(- str(figure_caption[0]["content"])- )+ assert "inreducingglucoseuptake" not in _normalized_content_probe(str(figure_caption[0]["content"]))side_caption = _blocks_containing(page4, "Fig. 2 [18F]FDG uptake")- side_image = next(- block- for block in page4- if block["type"] == "image" and block["bbox"] == [0.3, 0.608, 0.914, 0.897]- )+ side_image = next(block for block in page4 if block["type"] == "image" and block["bbox"] == [0.3, 0.608, 0.914, 0.897])assert len(side_caption) == 1assert side_caption[0]["type"] == "caption"assert side_caption[0]["bbox"][2] < side_image["bbox"][0]@@ -1052,9 +894,7 @@ def test_demo4_nct00083083_targeted_flash_regressions() -> None:model_list[1],"Table 1 Patient demographics",)[0]- page2_table = next(- block for block in model_list[1] if block["type"] == "table"- )+ page2_table = next(block for block in model_list[1] if block["type"] == "table")assert [page2_table_caption["type"], page2_table["type"]] == ["caption","table",@@ -1064,14 +904,10 @@ def test_demo4_nct00083083_targeted_flash_regressions() -> None:[0.514, 0.615, 0.914, 0.894],]assert "Patient demographics" not in str(page2_table["content"])- assert [- child.type- for child in MagicModel(- model_list[1],- 1000,- 1000,- ).get_table_blocks()[0].blocks- ] == ["table_caption", "table_body"]+ assert [child["type"] for child in _grouped_visual_blocks(model_list[1], "table")[0]["content"]] == [+ "table_caption",+ "table_body",+ ]page5 = model_list[4]right_continuation = _blocks_containing(@@ -1079,16 +915,12 @@ def test_demo4_nct00083083_targeted_flash_regressions() -> None:"also observed when conducting Cox regression",)assert len(right_continuation) == 1- assert "importantlythereisahomogenisation" in _normalized_content_probe(- str(right_continuation[0]["content"])- )+ assert "importantlythereisahomogenisation" in _normalized_content_probe(str(right_continuation[0]["content"]))page6 = model_list[5]left_continuation = _blocks_containing(page6, "This study aimed")assert len(left_continuation) == 1- assert "primarytumoursite" in _normalized_content_probe(- str(left_continuation[0]["content"])- )+ assert "primarytumoursite" in _normalized_content_probe(str(left_continuation[0]["content"]))page9 = model_list[8]assert not [block for block in page9 if block["type"] == "equation"]@@ -1100,25 +932,12 @@ def test_demo4_nct00083083_targeted_flash_regressions() -> None:reference_blocks = [blockfor block in page11- if block["type"] == "text"- and any(- str(block["content"]).lstrip().startswith(f"{number}.")- for number in range(45, 54)- )+ if block["type"] == "text" and any(str(block["content"]).lstrip().startswith(f"{number}.") for number in range(45, 54))]assert len(reference_blocks) == 9- assert {- int(str(block["content"]).lstrip().partition(".")[0])- for block in reference_blocks- } == set(range(45, 54))- reference48 = next(- block- for block in reference_blocks- if str(block["content"]).lstrip().startswith("48.")- )- assert "103389fimmu20231222129" in _normalized_content_probe(- str(reference48["content"])- )+ assert {int(str(block["content"]).lstrip().partition(".")[0]) for block in reference_blocks} == set(range(45, 54))+ reference48 = next(block for block in reference_blocks if str(block["content"]).lstrip().startswith("48."))+ assert "103389fimmu20231222129" in _normalized_content_probe(str(reference48["content"]))assert "\u200b" not in str(reference48["content"])assert "fimmu.2023.1222129" in str(reference48["content"])@@ -1150,12 +969,8 @@ def test_demo5_targeted_table_and_footer_regressions() -> None:blockfor block in pageif block["type"] == "text"- and table_bbox[0]- <= (block["bbox"][0] + block["bbox"][2]) / 2- <= table_bbox[2]- and table_bbox[1]- <= (block["bbox"][1] + block["bbox"][3]) / 2- <= table_bbox[3]+ and table_bbox[0] <= (block["bbox"][0] + block["bbox"][2]) / 2 <= table_bbox[2]+ and table_bbox[1] <= (block["bbox"][1] + block["bbox"][3]) / 2 <= table_bbox[3]]for page_number in (9, 10, 22, 38, 70, 77):@@ -1167,12 +982,8 @@ def test_demo5_targeted_table_and_footer_regressions() -> None:blockfor block in pageif block["type"] == "text"- and table_bbox[0]- <= (block["bbox"][0] + block["bbox"][2]) / 2- <= table_bbox[2]- and table_bbox[1]- <= (block["bbox"][1] + block["bbox"][3]) / 2- <= table_bbox[3]+ and table_bbox[0] <= (block["bbox"][0] + block["bbox"][2]) / 2 <= table_bbox[2]+ and table_bbox[1] <= (block["bbox"][1] + block["bbox"][3]) / 2 <= table_bbox[3]]assert not residual_text@@ -1193,12 +1004,8 @@ def test_demo5_targeted_table_and_footer_regressions() -> None:blockfor block in pageif block["type"] in {"text", "header"}- and expected_bbox[0]- <= (block["bbox"][0] + block["bbox"][2]) / 2- <= expected_bbox[2]- and expected_bbox[1]- <= (block["bbox"][1] + block["bbox"][3]) / 2- <= expected_bbox[3]+ and expected_bbox[0] <= (block["bbox"][0] + block["bbox"][2]) / 2 <= expected_bbox[2]+ and expected_bbox[1] <= (block["bbox"][1] + block["bbox"][3]) / 2 <= expected_bbox[3]]page77_note = _blocks_containing(model_list[76], "注:(1)指气量")@@ -1235,16 +1042,15 @@ def test_demo5_targeted_table_and_footer_regressions() -> None:tail_probe,)- magic_model = MagicModel(page, 1000, 1000)- table_blocks = magic_model.get_table_blocks()+ table_blocks = _grouped_visual_blocks(page, "table")assert len(table_blocks) == 1- assert [child.type for child in table_blocks[0].blocks][-2:] == [+ assert [child["type"] for child in table_blocks[0]["content"]][-2:] == ["table_body","table_footnote",]- table_footnote = table_blocks[0].blocks[-1]- assert table_footnote.bbox == tuple(round(value * 1000) for value in expected_bbox)- assert _normalized_content_probe(tail_probe) in _normalized_content_probe(str(table_footnote.content))+ table_footnote = table_blocks[0]["content"][-1]+ assert table_footnote["bbox"] == expected_bbox+ assert _normalized_content_probe(tail_probe) in _normalized_content_probe(str(table_footnote["content"]))expected_footnote_pages = {2, 6, 7, 31, 36, 39, 43, 49, 53, 55, 57, 58, 59, 77}assert {@@ -1252,18 +1058,10 @@ def test_demo5_targeted_table_and_footer_regressions() -> None:for page_number, page in enumerate(model_list, start=1)if any(block["type"] == "footnote" for block in page)} == expected_footnote_pages- assert sum(- block["type"] == "footnote"- for page in model_list- for block in page- ) == 14+ assert sum(block["type"] == "footnote" for page in model_list for block in page) == 14assert sum(block["type"] == "caption" for page in model_list for block in page) == 25- page2_visual_blocks = [- block- for block in model_list[1]- if block["type"] in {"caption", "table", "footnote"}- ]+ page2_visual_blocks = [block for block in model_list[1] if block["type"] in {"caption", "table", "footnote"}]assert [block["type"] for block in page2_visual_blocks] == ["caption","table",@@ -1275,31 +1073,19 @@ def test_demo5_targeted_table_and_footer_regressions() -> None:[0.151, 0.873, 0.53, 0.886],]assert "表1 排污单位基本信息表" not in str(page2_visual_blocks[1]["content"])- assert "指生产经营场所地址所在地邮政编码" not in str(- page2_visual_blocks[1]["content"]- )- assert [- child.type- for child in MagicModel(- model_list[1],- 1000,- 1000,- ).get_table_blocks()[0].blocks- ] == ["table_caption", "table_body", "table_footnote"]-- page4_table_groups = MagicModel(- model_list[3],- 1000,- 1000,- ).get_table_blocks()- assert [- [child.type for child in group.blocks]- for group in page4_table_groups- ] == [+ assert "指生产经营场所地址所在地邮政编码" not in str(page2_visual_blocks[1]["content"])+ assert [child["type"] for child in _grouped_visual_blocks(model_list[1], "table")[0]["content"]] == [+ "table_caption",+ "table_body",+ "table_footnote",+ ]++ page4_table_groups = _grouped_visual_blocks(model_list[3], "table")+ assert [[child["type"] for child in group["content"]] for group in page4_table_groups] == [["table_caption", "table_body"],["table_caption", "table_body"],]- assert [group.blocks[0].bbox for group in page4_table_groups] == [+ assert [tuple(round(value * 1000) for value in group["content"][0]["bbox"]) for group in page4_table_groups] == [(425, 308, 575, 326),(406, 619, 594, 637),]@@ -1311,11 +1097,7 @@ def test_demo5_targeted_table_and_footer_regressions() -> None:)assert len(in_border_note) == 1assert in_border_note[0]["type"] == "table"- assert not [- block- for block in model_list[page_number - 1]- if block["type"] == "footnote"- ]+ assert not [block for block in model_list[page_number - 1] if block["type"] == "footnote"]page62_note = _blocks_containing(model_list[61],"排入城镇集中污水处理设施的生活污水",@@ -1341,14 +1123,8 @@ def test_demo5_targeted_table_and_footer_regressions() -> None:assert page58_continuation[0]["bbox"] == [0.086, 0.155, 0.803, 0.221]page9 = model_list[8]- page_number_block = next(- block for block in page9 if block["type"] == "page_number"- )- empty_footer = next(- block- for block in page9- if block["type"] == "footer" and not str(block["content"]).strip()- )+ page_number_block = next(block for block in page9 if block["type"] == "page_number")+ empty_footer = next(block for block in page9 if block["type"] == "footer" and not str(block["content"]).strip())assert empty_footer["bbox"][1] > page_number_block["bbox"][3]@@ -1368,11 +1144,7 @@ def test_demo6_default3_targeted_title_regressions() -> None:"八、监督部门","九、联系方式",}- assert {- block["content"]- for block in blocks- if block["type"] == "paragraph_title"- } == expected_titles+ assert {block["content"] for block in blocks if block["type"] == "paragraph_title"} == expected_titlesfor probe in ("招标编号",@@ -1393,12 +1165,7 @@ def test_demo6_default3_targeted_title_regressions() -> None:assert [block["content"] for block in page7_images] == ["(签名)", "(盖章)"]assert sum("签名" in str(block["content"]) for block in model_list[6]) == 1assert sum("盖章" in str(block["content"]) for block in model_list[6]) == 1- assert not [- block- for page in model_list- for block in page- if block["type"] in {"caption", "footnote"}- ]+ assert not [block for page in model_list for block in page if block["type"] in {"caption", "footnote"}]def test_mixed_elements_pages_03_06_force_txt_regressions() -> None:@@ -1426,9 +1193,7 @@ def test_mixed_elements_pages_03_06_force_txt_regressions() -> None:assert not [blockfor block in page4- if block["type"] == "text"- and 0.65 <= block["bbox"][1] <= 0.87- and block["bbox"][2] - block["bbox"][0] < 0.05+ if block["type"] == "text" and 0.65 <= block["bbox"][1] <= 0.87 and block["bbox"][2] - block["bbox"][0] < 0.05]math_paragraph = _blocks_containing(page4,@@ -1436,7 +1201,7 @@ def test_mixed_elements_pages_03_06_force_txt_regressions() -> None:)assert len(math_paragraph) == 1assert math_paragraph[0]["bbox"] == [0.081, 0.665, 0.475, 0.911]- assert set(math_paragraph[0]) == {"type", "bbox", "angle", "content"}+ assert set(math_paragraph[0]) == {"type", "bbox", "angle", "content", "lines"}for probe in ("where T0","Fermi-level density",@@ -1461,9 +1226,7 @@ def test_mixed_elements_pages_03_06_force_txt_regressions() -> None:assert [block["bbox"]for block in page4- if block["type"] in {"text", "image", "caption"}- and block["bbox"][0] >= 0.49- and block["bbox"][1] >= 0.49+ if block["type"] in {"text", "image", "caption"} and block["bbox"][0] >= 0.49 and block["bbox"][1] >= 0.49] == [[0.498, 0.509, 0.892, 0.634],[0.503, 0.66, 0.886, 0.871],@@ -1476,11 +1239,7 @@ def test_mixed_elements_pages_03_06_force_txt_regressions() -> None:assert axis_label[0]["type"] == "image"assert _blocks_containing(page5, "MIKOLAICHUK et al.")[0]["type"] == "header"assert len([block for block in page5 if block["type"] == "footer"]) == 1- lower_graphs = [- block- for block in page5- if block["type"] == "image" and block["bbox"][1] >= 0.6- ]+ lower_graphs = [block for block in page5 if block["type"] == "image" and block["bbox"][1] >= 0.6]assert len(lower_graphs) == 1assert lower_graphs[0]["bbox"] == [0.096, 0.634, 0.46, 0.862]assert "σT1/2, S K1/2/m" in str(lower_graphs[0]["content"])@@ -1492,16 +1251,10 @@ def test_mixed_elements_pages_03_06_force_txt_regressions() -> None:assert sum(block["type"] == "caption" for page in model_list for block in page) == 4figure1_caption = _blocks_containing(page4, "Fig. 1. Electron micrographs")- panel_images = [- block- for block in page4- if block["type"] == "image" and block["bbox"][3] < 0.44- ]+ panel_images = [block for block in page4 if block["type"] == "image" and block["bbox"][3] < 0.44]assert len(figure1_caption) == 1assert len(panel_images) == 4- assert max(page4.index(block) for block in panel_images) < page4.index(- figure1_caption[0]- )+ assert max(page4.index(block) for block in panel_images) < page4.index(figure1_caption[0])def test_caibao_table_reclaims_repeated_dates_but_keeps_real_marginals() -> None:@@ -1533,18 +1286,8 @@ def test_caibao_page2_parallel_chart_captions_stay_separate() -> None:model_list = _txt_model_list("caibao1.pdf")page = model_list[1]- first_caption = [- block- for block in page- if block["type"] == "caption"- and str(block["content"]).startswith("图表1")- ]- second_caption = [- block- for block in page- if block["type"] == "caption"- and str(block["content"]).startswith("图表2")- ]+ first_caption = [block for block in page if block["type"] == "caption" and str(block["content"]).startswith("图表1")]+ second_caption = [block for block in page if block["type"] == "caption" and str(block["content"]).startswith("图表2")]assert len(page) == 20assert len(first_caption) == len(second_caption) == 1@@ -1553,11 +1296,7 @@ def test_caibao_page2_parallel_chart_captions_stay_separate() -> None:assert second_caption[0]["bbox"] == [0.513, 0.235, 0.843, 0.245]assert "行业周涨幅" not in str(first_caption[0]["content"])assert "汽车指数上周下跌" not in str(second_caption[0]["content"])- assert [- block["bbox"]- for block in page- if block["type"] == "image" and block["bbox"][1] < 0.5- ] == [+ assert [block["bbox"] for block in page if block["type"] == "image" and block["bbox"][1] < 0.5] == [[0.082, 0.267, 0.48, 0.447],[0.522, 0.254, 0.92, 0.46],]@@ -1576,10 +1315,7 @@ def test_caibao_page2_parallel_chart_captions_stay_separate() -> None:assert first_index + 3 == second_indexpage3_captions = [- block- for block in model_list[2]- if block["type"] == "caption"- and str(block["content"]).startswith(("图表4", "图表5"))+ block for block in model_list[2] if block["type"] == "caption" and str(block["content"]).startswith(("图表4", "图表5"))]assert [block["bbox"] for block in page3_captions] == [[0.073, 0.181, 0.298, 0.191],@@ -1613,46 +1349,28 @@ def test_caibao_page2_parallel_chart_captions_stay_separate() -> None:for block in model_list[page_number - 1]if block["type"] == "footnote" and block is not page7_table_note[0])- assert sum(- block["type"] == "caption"- for page_blocks in model_list- for block in page_blocks- ) == 15- assert sum(- block["type"] == "footnote"- for page_blocks in model_list- for block in page_blocks- ) == 17-- page7_table_groups = MagicModel(- model_list[6],- 1000,- 1000,- ).get_table_blocks()- assert [- [child.type for child in group.blocks]- for group in page7_table_groups- ] == [+ assert sum(block["type"] == "caption" for page_blocks in model_list for block in page_blocks) == 15+ assert sum(block["type"] == "footnote" for page_blocks in model_list for block in page_blocks) == 17++ page7_table_groups = _grouped_visual_blocks(model_list[6], "table")+ assert [[child["type"] for child in group["content"]] for group in page7_table_groups] == [["table_caption", "table_body", "table_footnote"],["table_caption", "table_body", "table_footnote"],]- assert [child.bbox for child in page7_table_groups[0].blocks] == [+ assert [tuple(round(value * 1000) for value in child["bbox"]) for child in page7_table_groups[0]["content"]] == [(76, 83, 364, 94),(72, 94, 930, 480),(73, 483, 219, 504),]- page2_magic_model = MagicModel(page, 1000, 1000)+ page2_image_groups = _grouped_visual_blocks(page, "image")for caption_prefix in ("图表1", "图表2"):image_group = next(group- for group in page2_magic_model.get_image_blocks()- if any(- str(child.content).startswith(caption_prefix)- for child in group.blocks- )+ for group in page2_image_groups+ if any(str(child["content"]).startswith(caption_prefix) for child in group["content"]))- assert [child.type for child in image_group.blocks] == [+ assert [child["type"] for child in image_group["content"]] == ["image_caption","image_body","image_footnote",@@ -1663,11 +1381,7 @@ def test_iebm_left_indented_compact_formula_is_equation() -> None:"""验证右栏左缩进紧凑公式通过公共 auto 入口输出为 equation。"""page = _auto_model_list("IEBM_A_2667169_O-5.pdf")[0]- target = [- block- for block in page- if block["bbox"] == [0.532, 0.292, 0.658, 0.312]- ]+ target = [block for block in page if block["bbox"] == [0.532, 0.292, 0.658, 0.312]]assert len(target) == 1assert target[0]["type"] == "equation"@@ -1682,20 +1396,10 @@ def test_npu_numbered_figure_captions_are_independent_annotations() -> None:expected_counts = {6: 1, 7: 1, 14: 2, 15: 2, 16: 2, 17: 1, 18: 1, 19: 2, 20: 2}assert {- page_number: sum(block["type"] == "caption" for block in model_list[page_number - 1])- for page_number in expected_counts+ page_number: sum(block["type"] == "caption" for block in model_list[page_number - 1]) for page_number in expected_counts} == expected_counts- assert sum(- block["type"] == "caption"- for page in model_list- for block in page- ) == 14- assert all(- str(block["content"]).startswith("图 ")- for page in model_list- for block in page- if block["type"] == "caption"- )+ assert sum(block["type"] == "caption" for page in model_list for block in page) == 14+ assert all(str(block["content"]).startswith("图 ") for page in model_list for block in page if block["type"] == "caption")assert not [block for page in model_list for block in page if block["type"] == "footnote"]@@ -1704,28 +1408,17 @@ def test_frozen_soil_page3_formula3_remains_one_equation() -> None:page = _txt_model_list("中文论文.pdf")[2]equations = [block for block in page if block["type"] == "equation"]- formula3 = [- block- for block in equations- if "(3)" in str(block.get("content", ""))- ]+ formula3 = [block for block in equations if "(3)" in str(block.get("content", ""))]assert len(page) == 30assert len(equations) == 4assert len(formula3) == 1assert formula3[0]["bbox"] == [0.653, 0.703, 0.898, 0.751]- assert all(- probe in str(formula3[0]["content"])- for probe in ("at = 1", "2 ln", "1 - εt", "εt", "(3)")- )+ assert all(probe in str(formula3[0]["content"]) for probe in ("at = 1", "2 ln", "1 - εt", "εt", "(3)"))assert not [blockfor block in page- if block["type"] == "text"- and any(- probe in str(block.get("content", ""))- for probe in ("at = 1", "2 ln", "1 - εt")- )+ if block["type"] == "text" and any(probe in str(block.get("content", "")) for probe in ("at = 1", "2 ln", "1 - εt"))]for marker in ("(1)", "(2)", "(3)", "(4)"):assert sum(marker in str(block.get("content", "")) for block in equations) == 1@@ -1737,12 +1430,7 @@ def test_frozen_soil_reference_tails_remain_single_text_blocks() -> None:model_list = _auto_model_list("中文论文.pdf")page = model_list[8]- captions = [- block- for page_blocks in model_list- for block in page_blocks- if block["type"] == "caption"- ]+ captions = [block for page_blocks in model_list for block in page_blocks if block["type"] == "caption"]assert len(captions) == 18page2 = model_list[1]image = next(block for block in page2 if block["type"] == "image")@@ -1750,46 +1438,32 @@ def test_frozen_soil_reference_tails_remain_single_text_blocks() -> None:english_caption = _blocks_containing(page2, "Fig. 1 Schematic diagram")assert len(chinese_caption) == len(english_caption) == 1assert chinese_caption[0]["type"] == english_caption[0]["type"] == "caption"- assert page2.index(image) < page2.index(chinese_caption[0]) < page2.index(- english_caption[0]- )+ assert page2.index(image) < page2.index(chinese_caption[0]) < page2.index(english_caption[0])page3 = model_list[2]- page3_table_group = MagicModel(- page3,- 1000,- 1000,- ).get_table_blocks()[0]- assert [child.type for child in page3_table_group.blocks] == [+ page3_table_group = _grouped_visual_blocks(page3, "table")[0]+ assert [child["type"] for child in page3_table_group["content"]] == ["table_caption","table_caption","table_body","table_footnote",]- assert [child.bbox for child in page3_table_group.blocks] == [+ assert [tuple(round(value * 1000) for value in child["bbox"]) for child in page3_table_group["content"]] == [(184, 684, 411, 708),(116, 700, 473, 725),(107, 721, 483, 838),(107, 838, 489, 925),]- assert str(page3_table_group.blocks[0].content).startswith("表1")- assert str(page3_table_group.blocks[1].content).startswith("Table 1")+ assert str(page3_table_group["content"][0]["content"]).startswith("表1")+ assert str(page3_table_group["content"][1]["content"]).startswith("Table 1")- page5_table_groups = MagicModel(- model_list[4],- 1000,- 1000,- ).get_table_blocks()- assert [- [child.type for child in group.blocks]- for group in page5_table_groups- ] == [+ page5_table_groups = _grouped_visual_blocks(model_list[4], "table")+ assert [[child["type"] for child in group["content"]] for group in page5_table_groups] == [["table_caption", "table_caption", "table_body"],["table_caption", "table_caption", "table_body"],]assert [- [child.bbox for child in group.blocks]- for group in page5_table_groups+ [tuple(round(value * 1000) for value in child["bbox"]) for child in group["content"]] for group in page5_table_groups] == [[(217, 121, 373, 145),@@ -1830,11 +1504,7 @@ def test_mixed_elements_pages_07_10_force_txt_regressions() -> None:page7, page8, page9, page10 = model_listauthor_blocks = [- block- for block in page7- if block["type"] == "text"- and 0.15 <= block["bbox"][1]- and block["bbox"][3] <= 0.28+ block for block in page7 if block["type"] == "text" and 0.15 <= block["bbox"][1] and block["bbox"][3] <= 0.28]assert len(author_blocks) == 4assert {@@ -1861,44 +1531,26 @@ def test_mixed_elements_pages_07_10_force_txt_regressions() -> None:assert page8.index(algorithm2[0]) + 1 == page8.index(code_blocks[2])assert sum(block["type"] == "caption" for page in model_list for block in page) == 6- page10_table_groups = MagicModel(- page10,- 1000,- 1000,- ).get_table_blocks()- assert [- [child.type for child in group.blocks]- for group in page10_table_groups- ] == [+ page10_table_groups = _grouped_visual_blocks(page10, "table")+ assert [[child["type"] for child in group["content"]] for group in page10_table_groups] == [["table_caption", "table_body"],["table_caption", "table_body"],]assert [- [child.bbox for child in group.blocks]- for group in page10_table_groups+ [tuple(round(value * 1000) for value in child["bbox"]) for child in group["content"]] for group in page10_table_groups] == [[(151, 333, 432, 344), (112, 352, 470, 496)],[(193, 607, 389, 618), (121, 626, 461, 710)],]- assert all(- "TABLE" not in str(group.blocks[-1].content)- for group in page10_table_groups- )+ assert all("TABLE" not in str(group["content"][-1]["content"]) for group in page10_table_groups)- page8_magic_model = MagicModel(page8, 1000, 1000)algorithm_groups = [group- for group in page8_magic_model.get_code_blocks()- if any(- str(child.content).startswith("Algorithm")- for child in group.blocks- )+ for group in _grouped_visual_blocks(page8, "code")+ if any(str(child["content"]).startswith("Algorithm") for child in group["content"])]assert len(algorithm_groups) == 2- assert all(- [child.type for child in group.blocks] == ["code_caption", "code_body"]- for group in algorithm_groups- )+ assert all([child["type"] for child in group["content"]] == ["code_caption", "code_body"] for group in algorithm_groups)framework_title = _blocks_containing(page9,@@ -1937,17 +1589,8 @@ def test_mixed_elements_pages_11_15_force_txt_regressions() -> None:assert len(matches) == 1assert matches[0]["type"] == "paragraph_title"- assert {- block["content"]- for block in all_blocks- if block["type"] == "page_number"- } == {"91", "92", "93", "94"}- assert not [- block- for block in all_blocks- if block["type"] == "image"- and str(block["content"]).strip() in {"91", "92"}- ]+ assert {block["content"] for block in all_blocks if block["type"] == "page_number"} == {"91", "92", "93", "94"}+ assert not [block for block in all_blocks if block["type"] == "image" and str(block["content"]).strip() in {"91", "92"}]figure2 = _blocks_containing(model_list[2], "Fig. 2. Pathological changes")figure6 = _blocks_containing(model_list[3], "Fig. 6. Effect of ecabet")@@ -1970,20 +1613,16 @@ def test_mixed_elements_pages_11_15_force_txt_regressions() -> None:assert page1_right_column_tail[0]["type"] == "text"assert not [block for block in model_list[0] if block["type"] == "footer"]- table_group = MagicModel(- model_list[3],- 1000,- 1000,- ).get_table_blocks()[0]- assert [child.type for child in table_group.blocks] == [+ table_group = _grouped_visual_blocks(model_list[3], "table")[0]+ assert [child["type"] for child in table_group["content"]] == ["table_caption","table_body",]- assert [child.bbox for child in table_group.blocks] == [+ assert [tuple(round(value * 1000) for value in child["bbox"]) for child in table_group["content"]] == [(79, 93, 798, 103),(79, 109, 922, 247),]- assert "Table 1." not in str(table_group.blocks[1].content)+ assert "Table 1." not in str(table_group["content"][1]["content"])online_footer = _blocks_containing(model_list[4], "http://www.birkhauser.ch/IPh")assert len(online_footer) == 1@@ -2008,16 +1647,8 @@ def test_mixed_elements_pages_39_40_force_txt_regressions() -> None:assert len(continuation) == 1assert continuation[0]["type"] == "text"assert "Coupling this observation" in continuation[0]["content"]- assert not [- block- for page in model_list- for block in page- if block["type"] in {"caption", "footnote"}- ]- assert sum(- "Coupling this observation" in str(block["content"])- for block in page40- ) == 1+ assert not [block for page in model_list for block in page if block["type"] in {"caption", "footnote"}]+ assert sum("Coupling this observation" in str(block["content"]) for block in page40) == 1equation9_following = _blocks_containing(page40,"Clearly, the random variable",diff --git a/tests/unittest/test_middle_json_block_models.py b/tests/unittest/test_middle_json_block_models.pyindex 22267308..0af7ae49 100644--- a/tests/unittest/test_middle_json_block_models.py+++ b/tests/unittest/test_middle_json_block_models.py@@ -7,7 +7,7 @@ import pytestfrom pydantic import ValidationErrorimport mineru.types as types_module-from mineru.backend.utils.raw_block_types import RAW_ONLY_BLOCK_TYPES+from mineru.types import RAW_ONLY_BLOCK_TYPESfrom mineru.types import (BLOCK_ADAPTER,BLOCK_TYPES,@@ -82,11 +82,7 @@ def test_all_29_public_discriminators_parse_to_concrete_models() -> None:def test_public_block_type_declarations_match_block_union() -> None:"""验证 BlockType、BlockTypes 和 BLOCK_TYPES 只公开 Block 联合的 discriminator。"""- class_values = {- value- for name, value in vars(BlockType).items()- if name.isupper()- }+ class_values = {value for name, value in vars(BlockType).items() if name.isupper()}assert class_values == BLOCK_TYPESassert set(get_args(BlockTypes)) == BLOCK_TYPES@@ -193,7 +189,8 @@ def test_list_subtype_allows_mixed_direct_text_children() -> None:"""验证 List subtype 是子项类型的统计结果,不约束每个直接子项。"""block = parse_block({- "type": "list", "sub_type": "ref_text",+ "type": "list",+ "sub_type": "ref_text","content": [{"type": "text", "content": "x"},{"type": "ref_text", "content": "r1"},diff --git a/tests/unittest/test_office_parser_regressions.py b/tests/unittest/test_office_parser_regressions.pyindex 4985c3ae..414be080 100644--- a/tests/unittest/test_office_parser_regressions.py+++ b/tests/unittest/test_office_parser_regressions.py@@ -1,80 +1,24 @@-from pathlib import Path+from pytest import MonkeyPatch-from mineru.backend.office.office_magic_model import fix_two_layer_blocks-from mineru.backend.utils import office_image-from mineru.parser.html import HtmlParser-from mineru.types import EMPTY_BBOX, Block, BlockType, ContentType, Line, Span+from mineru.model.flash.office import image as office_image-def test_html_parser_populates_required_bbox_and_index_fields(tmp_path: Path) -> None:- html_file = tmp_path / "sample.html"- html_file.write_text(- "<html><body><h1>Hello</h1><p>World</p></body></html>", encoding="utf-8"- )-- result = HtmlParser().parse(html_file)-- blocks = result.pages[0].para_blocks- assert [block.index for block in blocks] == [0, 1]- assert [block.bbox for block in blocks] == [EMPTY_BBOX, EMPTY_BBOX]- assert all(line.bbox == EMPTY_BBOX for block in blocks for line in block.lines)- assert all(- span.bbox == EMPTY_BBOX- for block in blocks- for line in block.lines- for span in line.spans- )---def test_office_two_layer_blocks_accept_block_dataclasses() -> None:- caption = Block(- index=0,- type=BlockType.IMAGE_CAPTION,- bbox=EMPTY_BBOX,- lines=[- Line(- bbox=EMPTY_BBOX,- spans=[- Span(type=ContentType.TEXT, bbox=EMPTY_BBOX, content="Figure 1")- ],- )- ],- )- body = Block(- index=1,- type=BlockType.IMAGE_BODY,- bbox=EMPTY_BBOX,- lines=[- Line(- bbox=EMPTY_BBOX,- spans=[- Span(type=ContentType.IMAGE, bbox=EMPTY_BBOX, image_path="figure.png")- ],- )- ],- )-- fixed_blocks, not_included = fix_two_layer_blocks([caption, body], BlockType.IMAGE)+def test_vector_image_part_skip_log_is_debug(monkeypatch: MonkeyPatch) -> None:+ """验证 WMF/EMF 占位图使用 debug 日志而不是 warning。"""- assert not_included == []- assert len(fixed_blocks) == 1- assert fixed_blocks[0].type == BlockType.IMAGE- assert [block.type for block in fixed_blocks[0].blocks] == [- BlockType.IMAGE_CAPTION,- BlockType.IMAGE_BODY,- ]---def test_vector_image_part_skip_log_is_debug(monkeypatch) -> None:class _Logger:+ """记录图片工具日志级别的测试替身。"""+def __init__(self) -> None:self.debug_messages: list[str] = []self.warning_messages: list[str] = []def debug(self, message: str) -> None:+ """记录 debug 日志。"""self.debug_messages.append(message)def warning(self, message: str) -> None:+ """记录 warning 日志。"""self.warning_messages.append(message)fake_logger = _Logger()@@ -86,9 +30,7 @@ def test_vector_image_part_skip_log_is_debug(monkeypatch) -> None:)assert (- office_image.serialize_vector_part_with_placeholder(- "/word/media/image3.wmf", "image/x-wmf"- )+ office_image.serialize_vector_part_with_placeholder("/word/media/image3.wmf", "image/x-wmf")== "data:image/jpeg;base64,placeholder")assert len(fake_logger.debug_messages) == 1diff --git a/tests/unittest/test_parser_flash.py b/tests/unittest/test_parser_flash.pydeleted file mode 100644index 41834996..00000000--- a/tests/unittest/test_parser_flash.py+++ /dev/null@@ -1,102 +0,0 @@-from __future__ import annotations--import pytest--from mineru.errors import MineruError-from mineru.parser.pdf import PdfFlashParser---def test_flash_parser_preserves_page_indices_for_empty_pages(monkeypatch) -> None:- from mineru.backend.flash import pdf_extractor-- parser = PdfFlashParser()- monkeypatch.setattr(PdfFlashParser, "_pdf_bytes_to_tempfile", staticmethod(lambda pdf_bytes: "dummy.pdf"))- monkeypatch.setattr(pdf_extractor, "extract_pages_text", lambda filepath: ["first", "", "third"])-- pages, model_output = parser._run_analysis(b"%PDF", page_index_map=[10, 12, 13])-- assert model_output is None- assert [page.page_idx for page in pages] == [10, 12, 13]- assert [len(page.para_blocks) for page in pages] == [1, 0, 1]---def test_flash_parser_unlinks_temp_pdf_after_success(monkeypatch, tmp_path) -> None:- from mineru.backend.flash import pdf_extractor-- temp_pdf = tmp_path / "flash-success.pdf"- temp_pdf.write_bytes(b"%PDF")- parser = PdfFlashParser()- monkeypatch.setattr(PdfFlashParser, "_pdf_bytes_to_tempfile", staticmethod(lambda pdf_bytes: str(temp_pdf)))- monkeypatch.setattr(pdf_extractor, "extract_pages_text", lambda filepath: ["page text"])-- parser._run_analysis(b"%PDF")-- assert not temp_pdf.exists()---def test_flash_parser_unlinks_temp_pdf_after_extractor_failure(monkeypatch, tmp_path) -> None:- from mineru.backend.flash import pdf_extractor-- temp_pdf = tmp_path / "flash-failure.pdf"- temp_pdf.write_bytes(b"%PDF")- parser = PdfFlashParser()- monkeypatch.setattr(PdfFlashParser, "_pdf_bytes_to_tempfile", staticmethod(lambda pdf_bytes: str(temp_pdf)))-- def _raise(_filepath: str) -> list[str]:- raise RuntimeError("extract failed")-- monkeypatch.setattr(pdf_extractor, "extract_pages_text", _raise)-- with pytest.raises(RuntimeError, match="extract failed"):- parser._run_analysis(b"%PDF")-- assert not temp_pdf.exists()---def test_pdf_parser_rejects_explicit_page_range_with_no_selected_pages(monkeypatch) -> None:- from mineru.utils import pdf_document, pdfium_guard-- class _FakePdfDocument:- def __init__(self, pdf_bytes: bytes) -> None:- self.page_count = 5-- parser = PdfFlashParser()- monkeypatch.setattr(pdf_document, "PDFDocument", _FakePdfDocument)- monkeypatch.setattr(pdfium_guard, "safe_rewrite_pdf_bytes_with_pdfium_result", lambda *args, **kwargs: pytest.fail("rewrite called"))-- with pytest.raises(MineruError) as exc_info:- parser._maybe_adjust_pdf_bytes(b"%PDF", "pdf", "6")-- assert exc_info.value.code == "page_range_invalid"---def test_flash_pdf_extractor_serializes_pdfium_calls(monkeypatch) -> None:- from mineru.backend.flash import pdf_extractor-- assert not hasattr(pdf_extractor, "open_pdfium_document")- assert not hasattr(pdf_extractor, "pdfium_guard")-- state = {"entered": False, "closed": False, "requested_pages": []}-- class _FakePdfDocument:- def __init__(self, filepath: str) -> None:- assert filepath == "dummy.pdf"- self.page_count = 2-- def __enter__(self) -> "_FakePdfDocument":- state["entered"] = True- return self-- def __exit__(self, exc_type, exc, tb) -> None:- state["closed"] = True-- def get_page_text(self, page_idx: int) -> str:- assert state["entered"] is True- state["requested_pages"].append(page_idx)- return "page text"-- monkeypatch.setattr(pdf_extractor, "PDFDocument", _FakePdfDocument)-- assert pdf_extractor.extract_pages_text("dummy.pdf") == ["page text", "page text"]- assert state["requested_pages"] == [0, 1]- assert state["closed"] is Truediff --git a/tests/unittest/test_pdf_analyze_block_content.py b/tests/unittest/test_pdf_analyze_block_content.pyindex 4d80ef01..cdc60625 100644--- a/tests/unittest/test_pdf_analyze_block_content.py+++ b/tests/unittest/test_pdf_analyze_block_content.py@@ -10,9 +10,11 @@ from mineru_vl_utils.structs import ContentBlock as VlmContentBlockfrom mineru_vl_utils.structs import ExtractResultfrom mineru.backend import analyze-from mineru.backend.utils.analyze_draft import _AnalyzeLine, _AnalyzeSpan-from mineru.backend.utils.raw_block_types import RAW_ALGORITHM, RAW_CAPTION, RAW_FOOTNOTE-from mineru.backend.utils.span_pre_proc import (+from mineru.backend.analysis.pdf import constants, layout, ocr, pipeline, tables, window+from mineru.backend.analysis.pdf.text import content as text_content+from mineru.backend.analysis.pdf.text.models import _AnalyzeLine, _AnalyzeSpan+from mineru.types import RAW_ALGORITHM, RAW_CAPTION, RAW_FOOTNOTE+from mineru.backend.analysis.pdf.text.native import (POST_OCR_FALLBACK_CONTENT_KEY,POST_OCR_FALLBACK_SCORE_KEY,)@@ -76,7 +78,7 @@ def test_convert_vlm_results_to_model_list_uses_builtin_containers() -> None:)source_page = ExtractResult([source_block], layout_scored=object())- model_list = analyze._convert_vlm_results_to_model_list([source_page, ExtractResult()])+ model_list = layout._convert_vlm_results_to_model_list([source_page, ExtractResult()])assert type(model_list) is listassert all(type(page) is list for page in model_list)@@ -105,7 +107,7 @@ def test_convert_vlm_results_deep_copies_projected_mutable_fields() -> None:"cell_merge": source_cell_merge,}- model_list = analyze._convert_vlm_results_to_model_list([[source_block]])+ model_list = layout._convert_vlm_results_to_model_list([[source_block]])model_list[0][0]["cell_merge"].append(1)assert source_cell_merge == [1, 0]@@ -166,11 +168,11 @@ def test_doc_analyze_converts_vlm_results_before_downstream_processing(assert all(type(block) is dict for page in window_model_list for block in page)return window_model_list- xhigh_normalizer = MagicMock(wraps=analyze._normalize_xhigh_vlm_blocks)- monkeypatch.setattr(analyze, "PDFDocument", MagicMock(return_value=fake_document))- monkeypatch.setattr(analyze, "HybridLocalModelContextSingleton", MagicMock(return_value=hybrid_singleton))+ xhigh_normalizer = MagicMock(wraps=layout._normalize_xhigh_vlm_blocks)+ monkeypatch.setattr(pipeline, "PDFDocument", MagicMock(return_value=fake_document))+ monkeypatch.setattr(pipeline, "HybridLocalModelContextSingleton", MagicMock(return_value=hybrid_singleton))monkeypatch.setattr(- analyze,+ pipeline,"_load_vlm_runtime",MagicMock(return_value={@@ -179,19 +181,19 @@ def test_doc_analyze_converts_vlm_results_before_downstream_processing(}),)- monkeypatch.setattr(analyze, "get_vlm_engine", MagicMock(return_value="transformers"))+ monkeypatch.setattr(pipeline, "get_vlm_engine", MagicMock(return_value="transformers"))monkeypatch.setattr(- analyze,+ window,"load_images_from_pdf_bytes_range",MagicMock(return_value=[{"img_pil": page_image, "scale": 1.0}]),)- monkeypatch.setattr(analyze, "_process_text_and_formulas", fake_process_text_and_formulas)- monkeypatch.setattr(analyze, "_normalize_xhigh_vlm_blocks", xhigh_normalizer)- monkeypatch.setattr(analyze, "_apply_seal_ocr", MagicMock())- monkeypatch.setattr(analyze, "_supplement_missing_image_block_containers", MagicMock())- monkeypatch.setattr(analyze, "_attach_visual_block_images", MagicMock())+ monkeypatch.setattr(window, "_process_text_and_formulas", fake_process_text_and_formulas)+ monkeypatch.setattr(window, "_normalize_xhigh_vlm_blocks", xhigh_normalizer)+ monkeypatch.setattr(window, "_apply_seal_ocr", MagicMock())+ monkeypatch.setattr(window, "_supplement_missing_image_block_containers", MagicMock())+ monkeypatch.setattr(window, "_attach_visual_block_images", MagicMock())monkeypatch.setattr(analyze, "model_list_to_pages", MagicMock(return_value=[]))- monkeypatch.setattr(analyze, "clean_memory", MagicMock())+ monkeypatch.setattr(pipeline, "clean_memory", MagicMock())middle_json, model_list = analyze.doc_analyze(b"fake-pdf",@@ -235,7 +237,7 @@ def test_xhigh_vlm_blocks_normalize_visual_annotation_types() -> None:{"type": BlockType.TEXT, "content": "text"},]- analyze._normalize_xhigh_vlm_blocks([page_blocks])+ layout._normalize_xhigh_vlm_blocks([page_blocks])assert [block["type"] for block in page_blocks] == [RAW_CAPTION,@@ -257,7 +259,7 @@ def test_xhigh_vlm_blocks_normalize_visual_annotation_types() -> None:def test_five_pdf_text_types_keep_normalized_line_metadata() -> None:"""验证五类 PDF 文本块统一保留公开的归一化 lines。"""- assert analyze.LINE_METADATA_BLOCK_TYPES == {+ assert constants.LINE_METADATA_BLOCK_TYPES == {BlockType.TEXT,BlockType.DOC_TITLE,BlockType.PARAGRAPH_TITLE,@@ -286,7 +288,7 @@ def test_five_pdf_text_types_keep_normalized_line_metadata() -> None:unrelated_block,]- analyze._apply_block_content_and_line_metadata(+ text_content._apply_block_content_and_line_metadata(page_blocks,{0: _build_text_lines("text"),@@ -301,9 +303,7 @@ def test_five_pdf_text_types_keep_normalized_line_metadata() -> None:assert text_block["lines"] == [{"bbox": [0.0, 0.0, 0.5, 0.01]}]assert doc_title_block["lines"] == [{"bbox": [0.0, 0.0, 0.5, 0.01]}]- assert paragraph_title_block["lines"] == [- {"bbox": [0.0, 0.0, 0.5, 0.01]}- ]+ assert paragraph_title_block["lines"] == [{"bbox": [0.0, 0.0, 0.5, 0.01]}]assert caption_block["lines"] == [{"bbox": [0.0, 0.0, 0.5, 0.01]},{"bbox": [0.0, 0.01, 0.5, 0.02]},@@ -318,12 +318,12 @@ def test_high_ocr_detects_lines_for_all_five_pdf_text_types() -> None:"""验证 High/XHigh OCR 对标题、正文、caption 和 footnote 都执行行检测。"""- ocr_det_type, mfr_enabled = analyze._build_ocr_det_type_and_mfr_enable(+ ocr_det_type, mfr_enabled = ocr._build_ocr_det_type_and_mfr_enable("ocr",effort,)- assert ocr_det_type == analyze.LINE_METADATA_BLOCK_TYPES+ assert ocr_det_type == constants.LINE_METADATA_BLOCK_TYPESassert mfr_enabled is False@@ -335,7 +335,7 @@ def test_window_post_ocr_batches_all_pages_once() -> None:[("第一页一", 0.91), ("第一页二", 0.82), ("第二页一", 0.73), ("第二页二", 0.64)]]- analyze._apply_window_post_ocr(local_model_context, page_block_lines_list)+ text_content._apply_window_post_ocr(local_model_context, page_block_lines_list)local_model_context.ocr_model.ocr.assert_called_once()call_args = local_model_context.ocr_model.ocr.call_args@@ -350,7 +350,7 @@ def test_window_post_ocr_skips_empty_window() -> None:"""验证窗口内没有待识别裁图时不会调用 OCR-rec。"""local_model_context = MagicMock()- analyze._apply_window_post_ocr(local_model_context, [{}, {0: []}])+ text_content._apply_window_post_ocr(local_model_context, [{}, {0: []}])local_model_context.ocr_model.ocr.assert_not_called()@@ -362,7 +362,7 @@ def test_window_post_ocr_rejects_result_count_mismatch() -> None:local_model_context.ocr_model.ocr.return_value = [[("仅一个结果", 0.9)]]with pytest.raises(ValueError, match="ocr_res_list=1, need_ocr_spans=2"):- analyze._apply_window_post_ocr(local_model_context, page_block_lines_list)+ text_content._apply_window_post_ocr(local_model_context, page_block_lines_list)def test_window_post_ocr_keeps_low_confidence_fallback_semantics() -> None:@@ -375,7 +375,7 @@ def test_window_post_ocr_keeps_low_confidence_fallback_semantics() -> None:local_model_context = MagicMock()local_model_context.ocr_model.ocr.return_value = [[("低置信文本", 0.0), ("低置信文本", 0.0)]]- analyze._apply_window_post_ocr(local_model_context, page_block_lines_list)+ text_content._apply_window_post_ocr(local_model_context, page_block_lines_list)assert spans[0].content == "原生文本"assert spans[0].score == 0.88@@ -388,9 +388,9 @@ def test_fill_window_batches_txt_post_ocr_before_page_content(monkeypatch: pytes"""验证 TXT 窗口先统一 OCR-rec,再按页生成最终 block content。"""page_block_lines_list, _ = _build_post_ocr_page_block_lines(11, 22)grouped_page_lines = iter(page_block_lines_list)- monkeypatch.setattr(analyze, "_build_page_text_formula_spans", lambda *_args: [])- monkeypatch.setattr(analyze, "_fill_native_pdf_text_spans", lambda _page, spans, *_args: spans)- monkeypatch.setattr(analyze, "_group_page_spans_by_block", lambda *_args: next(grouped_page_lines))+ monkeypatch.setattr(text_content, "_build_page_text_formula_spans", lambda *_args: [])+ monkeypatch.setattr(text_content, "_fill_native_pdf_text_spans", lambda _page, spans, *_args: spans)+ monkeypatch.setattr(text_content, "_group_page_spans_by_block", lambda *_args: next(grouped_page_lines))local_model_context = MagicMock()local_model_context.ocr_model.ocr.return_value = [[("窗口第一页", 0.9), ("窗口第二页", 0.8)]]model_list = [@@ -399,7 +399,7 @@ def test_fill_window_batches_txt_post_ocr_before_page_content(monkeypatch: pytes]pdf_pages = [MagicMock(size=(100.0, 100.0)), MagicMock(size=(100.0, 100.0))]- result = analyze._fill_window_block_content_and_lines(+ result = text_content._fill_window_block_content_and_lines([{"img_pil": object(), "scale": 1.0}, {"img_pil": object(), "scale": 1.0}],pdf_pages,model_list,@@ -419,12 +419,12 @@ def test_fill_window_ocr_mode_does_not_run_txt_post_ocr(monkeypatch: pytest.Monk"""验证 OCR 模式不进入 TXT 的窗口级 post-OCR 分支。"""page_block_lines_list, spans = _build_post_ocr_page_block_lines(11)spans[0].content = "已有 OCR 文本"- monkeypatch.setattr(analyze, "_build_page_text_formula_spans", lambda *_args: [])- monkeypatch.setattr(analyze, "_group_page_spans_by_block", lambda *_args: page_block_lines_list[0])+ monkeypatch.setattr(text_content, "_build_page_text_formula_spans", lambda *_args: [])+ monkeypatch.setattr(text_content, "_group_page_spans_by_block", lambda *_args: page_block_lines_list[0])local_model_context = MagicMock()model_list = [[{"type": BlockType.TEXT, "bbox": [0.0, 0.0, 1.0, 1.0], "content": ""}]]- analyze._fill_window_block_content_and_lines(+ text_content._fill_window_block_content_and_lines([{"img_pil": object(), "scale": 1.0}],[MagicMock(size=(100.0, 100.0))],model_list,@@ -448,7 +448,7 @@ def test_empty_index_content_preserves_grouped_line_breaks() -> None:"content": "",}- analyze._apply_block_content_and_line_metadata(+ text_content._apply_block_content_and_line_metadata([block],{0: _build_text_lines("第一行", "第二行")},(100.0, 100.0),@@ -464,7 +464,7 @@ def test_empty_index_content_preserves_grouped_line_breaks() -> None:def test_text_content_keeps_natural_paragraph_joining() -> None:"""验证普通中文正文仍沿用自然段跨行连接规则,不受目录修复影响。"""- content = analyze._lines_to_block_content(+ content = text_content._lines_to_block_content(_build_text_lines("第一行", "第二行"),BlockType.TEXT,)@@ -475,7 +475,7 @@ def test_text_content_keeps_natural_paragraph_joining() -> None:@pytest.mark.parametrize("block_type", [BlockType.CODE, RAW_ALGORITHM])def test_code_content_keeps_existing_line_breaks(block_type: str) -> None:"""验证 code/algorithm 原有的逐行拼接语义保持不变。"""- content = analyze._lines_to_block_content(+ content = text_content._lines_to_block_content(_build_text_lines("line one", "line two"),block_type,)@@ -492,7 +492,7 @@ def test_existing_index_content_is_not_overwritten() -> None:"content": "已有目录一\n已有目录二",}- analyze._apply_block_content_and_line_metadata(+ text_content._apply_block_content_and_line_metadata([block],{0: _build_text_lines("回填目录一", "回填目录二")},(100.0, 100.0),@@ -537,9 +537,9 @@ def test_low_txt_visual_runs_split_distant_text_before_layout_matching(pdf_page.size = (100.0, 100.0)pdf_page.rotation = 0pdf_page.get_chars.return_value = []- monkeypatch.setattr(analyze, "get_lines_from_chars", lambda _chars: pdf_lines)+ monkeypatch.setattr(tables, "get_lines_from_chars", lambda _chars: pdf_lines)- spans = analyze._build_pdf_text_visual_run_spans(pdf_page)+ spans = tables._build_pdf_text_visual_run_spans(pdf_page)assert [(span.content, span.bbox) for span in spans] == [("Left", (5.0, 10.0, 21.0, 20.0)),@@ -552,7 +552,7 @@ def test_existing_text_content_is_preserved_while_lines_are_refreshed() -> None:block = {"type": BlockType.TEXT, "content": "existing content"}- analyze._apply_block_content_and_line_metadata(+ text_content._apply_block_content_and_line_metadata([block],{0: _build_text_lines("native content")},(200.0, 100.0),@@ -574,15 +574,15 @@ def test_npu_page_three_low_visual_runs_keep_index_line_structure() -> None:"angle": 0,"content": "",}- block_lines = analyze._group_page_spans_by_block(+ block_lines = text_content._group_page_spans_by_block([index_block],- analyze._build_pdf_text_visual_run_spans(page),+ tables._build_pdf_text_visual_run_spans(page),page_size,{BlockType.INDEX},)assert len(block_lines[0]) == 24- analyze._apply_block_content_and_line_metadata(+ text_content._apply_block_content_and_line_metadata([index_block],block_lines,page_size,diff --git a/tests/unittest/test_pdf_analyze_visual_blocks.py b/tests/unittest/test_pdf_analyze_visual_blocks.pyindex 1ced73cd..18592866 100644--- a/tests/unittest/test_pdf_analyze_visual_blocks.py+++ b/tests/unittest/test_pdf_analyze_visual_blocks.py@@ -10,7 +10,9 @@ import pytestfrom PIL import Image, ImageDrawfrom mineru.backend import analyze-from mineru.backend.utils.raw_block_types import RAW_ALGORITHM, RAW_CAPTION, RAW_FOOTNOTE, RAW_PHONETIC+from mineru.backend.analysis import office+from mineru.backend.analysis.pdf import constants, formulas, normalization, pipeline, tables, visuals, window+from mineru.types import RAW_ALGORITHM, RAW_CAPTION, RAW_FOOTNOTE, RAW_PHONETICfrom mineru.types import BlockType, MiddleJson@@ -90,7 +92,7 @@ def test_visual_block_crop_rotates_to_upright("content": "keep-content",}- analyze._attach_visual_block_images([[block]], [{"img_pil": page_image}])+ visuals._attach_visual_block_images([[block]], [{"img_pil": page_image}])crop_image = _decode_jpeg_data_uri(block["image_base64"])try:@@ -113,7 +115,7 @@ def test_medium_table_task_reuses_visual_block_upright_rotation() -> None:"angle": 270,}- table_tasks = analyze._collect_medium_table_tasks(+ table_tasks = tables._collect_medium_table_tasks([[table_block]],[[]],[np_image],@@ -156,7 +158,7 @@ def test_visual_block_types_receive_jpeg_data_uri_only() -> None:"image_base64": "keep-text-field",}- analyze._attach_visual_block_images(+ visuals._attach_visual_block_images([[*visual_blocks, text_block]],[{"img_pil": page_image}],page_start_index=7,@@ -191,7 +193,7 @@ def test_visual_block_crop_clips_page_boundary_and_skips_invalid_bbox() -> None:"angle": 0,}- analyze._attach_visual_block_images(+ visuals._attach_visual_block_images([[clipped_block, invalid_block]],[{"img_pil": page_image}],)@@ -270,7 +272,7 @@ def test_image_block_collapses_contained_blocks_before_visual_crop() -> None:external_caption,]- analyze._attach_visual_block_images(+ visuals._attach_visual_block_images([page_model_list],[{"img_pil": page_image}],)@@ -311,7 +313,7 @@ def test_image_block_collapse_keeps_invalid_bbox_blocks() -> None:}page_model_list = [invalid_image_block, valid_child, invalid_child]- analyze._collapse_image_blocks(page_model_list)+ visuals._collapse_image_blocks(page_model_list)assert page_model_list == [invalid_image_block, valid_child, invalid_child]assert invalid_image_block["type"] == BlockType.IMAGE@@ -355,13 +357,13 @@ def test_xhigh_layout_image_supplements_missing_container_before_crop() -> None:]]- analyze._supplement_missing_image_block_containers(+ visuals._supplement_missing_image_block_containers([page_model_list],layout_blocks_list,)assert sum(block.get("type") == "image_block" for block in page_model_list) == 1- analyze._attach_visual_block_images(+ visuals._attach_visual_block_images([page_model_list],[{"img_pil": page_image}],)@@ -429,13 +431,10 @@ def test_xhigh_layout_image_fallback_requires_visual_count_and_coverage(expected_container_count: int,) -> None:"""验证回退要求至少两个 image/chart,且白名单面积占比大于等于 0.9。"""- page_model_list = [- {"type": block_type, "bbox": bbox}- for block_type, bbox in zip(block_types, block_bboxes)- ]+ page_model_list = [{"type": block_type, "bbox": bbox} for block_type, bbox in zip(block_types, block_bboxes)]layout_blocks_list = [[{"type": layout_type, "bbox": [0.0, 0.0, 1.0, 1.0], "angle": 0}]]- analyze._supplement_missing_image_block_containers(+ visuals._supplement_missing_image_block_containers([page_model_list],layout_blocks_list,)@@ -445,7 +444,7 @@ def test_xhigh_layout_image_fallback_requires_visual_count_and_coverage(def test_xhigh_layout_image_fallback_uses_whitelist_for_area_but_absorbs_all_types() -> None:"""验证白名单只负责面积判定,回退成功后仍吸收框内所有类型。"""- assert analyze.LOCAL_LAYOUT_IMAGE_BLOCK_AREA_TYPES == {+ assert constants.LOCAL_LAYOUT_IMAGE_BLOCK_AREA_TYPES == {BlockType.IMAGE,BlockType.CHART,BlockType.IMAGE_CAPTION,@@ -461,7 +460,7 @@ def test_xhigh_layout_image_fallback_uses_whitelist_for_area_but_absorbs_all_typ{"type": BlockType.CHART_CAPTION, "bbox": [0.9, 0.0, 1.0, 1.0]},]- analyze._supplement_missing_image_block_containers(+ visuals._supplement_missing_image_block_containers([insufficient_page],layout_blocks_list,)@@ -479,11 +478,11 @@ def test_xhigh_layout_image_fallback_uses_whitelist_for_area_but_absorbs_all_typexternal_text,]- analyze._supplement_missing_image_block_containers(+ visuals._supplement_missing_image_block_containers([qualifying_page],layout_blocks_list,)- analyze._collapse_image_blocks(qualifying_page)+ visuals._collapse_image_blocks(qualifying_page)assert len(qualifying_page) == 2assert qualifying_page[0]["type"] == BlockType.IMAGE@@ -512,7 +511,7 @@ def test_xhigh_layout_image_fallback_does_not_duplicate_existing_or_overlapping_]]- analyze._supplement_missing_image_block_containers(+ visuals._supplement_missing_image_block_containers([page_model_list],layout_blocks_list,)@@ -526,7 +525,7 @@ def test_xhigh_layout_image_fallback_does_not_duplicate_existing_or_overlapping_def test_visual_block_crop_rejects_page_count_mismatch() -> None:"""验证 model_list 与渲染页数量不一致时抛出明确异常,避免静默漏页。"""with pytest.raises(ValueError, match="Hybrid visual crop page count mismatch"):- analyze._attach_visual_block_images([[]], [])+ visuals._attach_visual_block_images([[]], [])def test_normalize_pdf_model_list_updates_in_place() -> None:@@ -581,20 +580,14 @@ def test_normalize_pdf_model_list_updates_in_place() -> None:],]- result = analyze._normalize_pdf_model_list(model_list)+ result = normalization._normalize_pdf_model_list(model_list)assert result is Noneassert model_list[0][0]["content"] == "前 <eq>a+b</eq> 中 <eq>c_d</eq> 后"assert model_list[0][1]["content"] == "已有 <eq>x</eq> 保持不变"assert model_list[0][2]["content"] == "未闭合 \\(formula"- assert [block["content"] for block in model_list[1]] == [- "跨行 \\(a\nb\\)"- ]- assert all(- "angle" not in block and "score" not in block- for page_model_list in model_list- for block in page_model_list- )+ assert [block["content"] for block in model_list[1]] == ["跨行 \\(a\nb\\)"]+ assert all("angle" not in block and "score" not in block for page_model_list in model_list for block in page_model_list)@pytest.mark.parametrize(@@ -620,13 +613,17 @@ def test_normalize_pdf_model_list_converts_full_width_alphanumeric_for_textual_bblock_type: str,) -> None:"""验证 PDF 自然语言块统一转换全角字母和数字,同时保留全角标点。"""- model_list = [[{- "type": block_type,- "content": "Az0,。!?()",- "lines": [{"bbox": [0.1, 0.1, 0.9, 0.2]}],- }]]+ model_list = [+ [+ {+ "type": block_type,+ "content": "Az0,。!?()",+ "lines": [{"bbox": [0.1, 0.1, 0.9, 0.2]}],+ }+ ]+ ]- analyze._normalize_pdf_model_list(model_list)+ normalization._normalize_pdf_model_list(model_list)assert model_list[0][0]["content"] == "Az0,。!?()"expected_type = BlockType.TEXT if block_type == RAW_PHONETIC else block_type@@ -635,13 +632,17 @@ def test_normalize_pdf_model_list_converts_full_width_alphanumeric_for_textual_bdef test_normalize_pdf_model_list_preserves_inline_formulas_during_full_width_cleanup() -> None:"""验证两种行内公式片段不参与全角转换,普通正文仍正常清洗。"""- model_list = [[{- "type": BlockType.TEXT,- "content": "前A1 \\(F2+x\\) 中B3 <eq>C4+y</eq> 后D5",- "lines": [{"bbox": [0.1, 0.1, 0.9, 0.2]}],- }]]+ model_list = [+ [+ {+ "type": BlockType.TEXT,+ "content": "前A1 \\(F2+x\\) 中B3 <eq>C4+y</eq> 后D5",+ "lines": [{"bbox": [0.1, 0.1, 0.9, 0.2]}],+ }+ ]+ ]- analyze._normalize_pdf_model_list(model_list)+ normalization._normalize_pdf_model_list(model_list)assert model_list[0][0]["content"] == "前A1 <eq>F2+x</eq> 中B3 <eq>C4+y</eq> 后D5"@@ -658,13 +659,17 @@ def test_normalize_pdf_model_list_preserves_content_after_unclosed_inline_formulexpected: str,) -> None:"""验证未闭合公式从起始符到文本末尾均保持原样,避免误清洗公式内容。"""- model_list = [[{- "type": BlockType.TEXT,- "content": content,- "lines": [{"bbox": [0.1, 0.1, 0.9, 0.2]}],- }]]+ model_list = [+ [+ {+ "type": BlockType.TEXT,+ "content": content,+ "lines": [{"bbox": [0.1, 0.1, 0.9, 0.2]}],+ }+ ]+ ]- analyze._normalize_pdf_model_list(model_list)+ normalization._normalize_pdf_model_list(model_list)assert model_list[0][0]["content"] == expected@@ -686,28 +691,30 @@ def test_normalize_pdf_model_list_skips_non_natural_language_content(block_type:"""验证表格、代码、公式、视觉主体和未知类型不执行自然语言全角清洗。"""model_list = [[{"type": block_type, "content": "Az0,。!?()"}]]- analyze._normalize_pdf_model_list(model_list)+ normalization._normalize_pdf_model_list(model_list)assert model_list[0][0]["content"] == "Az0,。!?()"def test_normalize_pdf_model_list_converts_phonetic_and_cleans_equation() -> None:"""验证 phonetic 转公开类型,同时 equation 保持类型并清理展示分隔符。"""- model_list = [[- {- "type": RAW_PHONETIC,- "bbox": [0.1, 0.1, 0.9, 0.2],- "content": "phonetic",- "lines": [{"bbox": [0.1, 0.1, 0.9, 0.2]}],- },- {- "type": BlockType.EQUATION,- "bbox": [0.1, 0.3, 0.9, 0.4],- "content": r"\[x+1\]",- },- ]]+ model_list = [+ [+ {+ "type": RAW_PHONETIC,+ "bbox": [0.1, 0.1, 0.9, 0.2],+ "content": "phonetic",+ "lines": [{"bbox": [0.1, 0.1, 0.9, 0.2]}],+ },+ {+ "type": BlockType.EQUATION,+ "bbox": [0.1, 0.3, 0.9, 0.4],+ "content": r"\[x+1\]",+ },+ ]+ ]- analyze._normalize_pdf_model_list(model_list)+ normalization._normalize_pdf_model_list(model_list)assert model_list[0][0]["type"] == BlockType.TEXTassert model_list[0][1] == {@@ -722,7 +729,7 @@ def test_formula_number_optimizer_recognizes_canonical_and_upstream_equation_typequation_type: str,) -> None:"""验证公式编号只需兼容 canonical equation 与上游 display_formula 标签。"""- optimized = analyze.optimize_hybrid_formula_number_blocks(+ optimized = formulas.optimize_hybrid_formula_number_blocks([{"type": equation_type, "content": r"\[x+1\]"},{"type": BlockType.FORMULA_NUMBER, "content": "(2)"},@@ -739,7 +746,7 @@ def test_formula_number_optimizer_recognizes_canonical_and_upstream_equation_typdef test_formula_number_optimizer_does_not_accept_legacy_interline_equation() -> None:"""验证旧 interline_equation 不再被公式编号合并逻辑视为合法公式块。"""- optimized = analyze.optimize_hybrid_formula_number_blocks(+ optimized = formulas.optimize_hybrid_formula_number_blocks([{"type": "interline_equation", "content": "x+1"},{"type": BlockType.FORMULA_NUMBER, "content": "(2)"},@@ -755,8 +762,8 @@ def test_formula_number_optimizer_does_not_accept_legacy_interline_equation() ->def test_normalize_pdf_model_list_rejects_unclassified_vlm_title() -> None:"""验证未被 layout 结果分类的 VLM title 以页块位置明确报错。"""with pytest.raises(ValueError, match="page_idx=0, block_idx=0"):- analyze._normalize_pdf_model_list(- [[{"type": analyze._VLM_UNCLASSIFIED_TITLE_TYPE, "bbox": [0.1, 0.1, 0.9, 0.2], "content": "title"}]]+ normalization._normalize_pdf_model_list(+ [[{"type": constants._VLM_UNCLASSIFIED_TITLE_TYPE, "bbox": [0.1, 0.1, 0.9, 0.2], "content": "title"}]])@@ -796,7 +803,7 @@ def test_normalize_pdf_model_list_removes_five_text_types_with_invalid_lines(model_list = [[{"type": block_type, "content": "valid", "lines": invalid_lines}]]- analyze._normalize_pdf_model_list(model_list)+ normalization._normalize_pdf_model_list(model_list)assert model_list == [[]]@@ -828,7 +835,7 @@ def test_normalize_pdf_model_list_removes_five_text_types_with_empty_content(]]- analyze._normalize_pdf_model_list(model_list)+ normalization._normalize_pdf_model_list(model_list)assert model_list == [[]]@@ -855,7 +862,7 @@ def test_normalize_pdf_model_list_keeps_other_types_and_valid_text_order() -> No}model_list = [[equation, first_text, invalid_text, header, second_text]]- analyze._normalize_pdf_model_list(model_list)+ normalization._normalize_pdf_model_list(model_list)assert model_list == [[equation, first_text, header, second_text]]@@ -923,15 +930,15 @@ def test_doc_analyze_office_returns_model_list_without_pdf_processing(image_loader = MagicMock()visual_image_attacher = MagicMock()model_list_normalizer = MagicMock()- monkeypatch.setattr(analyze, "_OFFICE_MODEL_MAP", model_factories)- monkeypatch.setattr(analyze, "PDFDocument", pdf_document)- monkeypatch.setattr(analyze, "HybridLocalModelContextSingleton", hybrid_model_factory)- monkeypatch.setattr(analyze, "get_processing_window_size", window_size_reader)- monkeypatch.setattr(analyze, "_build_processing_windows", window_builder)- monkeypatch.setattr(analyze, "load_images_from_pdf_bytes_range", image_loader)- monkeypatch.setattr(analyze, "_attach_visual_block_images", visual_image_attacher)- monkeypatch.setattr(analyze, "_normalize_pdf_model_list", model_list_normalizer)- monkeypatch.setattr(analyze.time, "perf_counter", fake_perf_counter)+ monkeypatch.setattr(office, "_OFFICE_MODEL_MAP", model_factories)+ monkeypatch.setattr(pipeline, "PDFDocument", pdf_document)+ monkeypatch.setattr(pipeline, "HybridLocalModelContextSingleton", hybrid_model_factory)+ monkeypatch.setattr(window, "get_processing_window_size", window_size_reader)+ monkeypatch.setattr(window, "_build_processing_windows", window_builder)+ monkeypatch.setattr(window, "load_images_from_pdf_bytes_range", image_loader)+ monkeypatch.setattr(window, "_attach_visual_block_images", visual_image_attacher)+ monkeypatch.setattr(pipeline, "_normalize_pdf_model_list", model_list_normalizer)+ monkeypatch.setattr(office.time, "perf_counter", fake_perf_counter)middle_json, model_list = analyze.doc_analyze(b"office-bytes",@@ -969,8 +976,8 @@ def test_doc_analyze_rejects_unsupported_suffix_before_resource_initialization("""验证非法后缀会在创建 PDF 文档或 Office 模型前直接报错。"""pdf_document = MagicMock()model_factories = {suffix: MagicMock() for suffix in ("docx", "pptx", "xlsx")}- monkeypatch.setattr(analyze, "PDFDocument", pdf_document)- monkeypatch.setattr(analyze, "_OFFICE_MODEL_MAP", model_factories)+ monkeypatch.setattr(pipeline, "PDFDocument", pdf_document)+ monkeypatch.setattr(office, "_OFFICE_MODEL_MAP", model_factories)with pytest.raises(ValueError, match="Unsupported file suffix: 'PDF'"):analyze.doc_analyze(b"unknown", file_suffix="PDF") # type: ignore[arg-type]@@ -980,6 +987,68 @@ def test_doc_analyze_rejects_unsupported_suffix_before_resource_initialization(model_factory.assert_not_called()+ ("effort", "parse_mode", "expected_message"),+ [+ ("turbo", "txt", "Unsupported analyze effort: turbo"),+ ("low", "invalid", "parse_mode invalid is not supported"),+ ],+)+def test_doc_analyze_rejects_invalid_pdf_modes_before_model_initialization(+ monkeypatch: pytest.MonkeyPatch,+ effort: str,+ parse_mode: str,+ expected_message: str,+) -> None:+ """验证非法 PDF effort/parse_mode 统一报 ValueError,且不初始化模型。"""+ fake_document = MagicMock()+ hybrid_model_factory = MagicMock()+ monkeypatch.setattr(pipeline, "PDFDocument", MagicMock(return_value=fake_document))+ monkeypatch.setattr(pipeline, "HybridLocalModelContextSingleton", hybrid_model_factory)++ with pytest.raises(ValueError, match=expected_message):+ analyze.doc_analyze(+ b"invalid-mode-pdf",+ effort=effort, # type: ignore[arg-type]+ parse_mode=parse_mode, # type: ignore[arg-type]+ )++ fake_document.close.assert_called_once_with()+ hybrid_model_factory.assert_not_called()+++def test_pdf_flash_ocr_routes_to_low_hybrid_pipeline(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """验证 Flash 遇到 OCR PDF 时降级为 Low,并把最终路由元数据带回门面。"""+ fake_document = MagicMock()+ hybrid_model = MagicMock()+ hybrid_model.device = "cpu"+ hybrid_singleton = MagicMock()+ hybrid_singleton.get_model.return_value = hybrid_model+ process_pdf_windows = MagicMock(return_value=[])++ monkeypatch.setattr(pipeline, "PDFDocument", MagicMock(return_value=fake_document))+ monkeypatch.setattr(+ pipeline,+ "HybridLocalModelContextSingleton",+ MagicMock(return_value=hybrid_singleton),+ )+ monkeypatch.setattr(pipeline, "process_pdf_windows", process_pdf_windows)+ monkeypatch.setattr(pipeline, "clean_memory", MagicMock())++ result = pipeline.analyze_pdf(+ b"ocr-pdf",+ effort="flash",+ parse_mode="ocr",+ )++ assert result.effort == "low"+ assert result.parse_mode == "ocr"+ assert process_pdf_windows.call_args.kwargs["effort"] == "low"+ assert process_pdf_windows.call_args.kwargs["flash_txt_mode"] is False++def test_pdf_infer_timer_excludes_hybrid_vlm_initialization_and_cleanup(monkeypatch: pytest.MonkeyPatch,) -> None:@@ -1034,20 +1103,20 @@ def test_pdf_infer_timer_excludes_hybrid_vlm_initialization_and_cleanup("""记录设备缓存清理顺序。"""events.append("clean_memory")- monkeypatch.setattr(analyze, "PDFDocument", MagicMock(return_value=fake_document))- monkeypatch.setattr(analyze, "HybridLocalModelContextSingleton", MagicMock(return_value=hybrid_singleton))+ monkeypatch.setattr(pipeline, "PDFDocument", MagicMock(return_value=fake_document))+ monkeypatch.setattr(pipeline, "HybridLocalModelContextSingleton", MagicMock(return_value=hybrid_singleton))monkeypatch.setattr(- analyze,+ pipeline,"_load_vlm_runtime",lambda: {"ModelSingleton": MagicMock(return_value=vlm_singleton),"_maybe_enable_serial_execution": fake_enable_serial_execution,},)- monkeypatch.setattr(analyze, "get_vlm_engine", MagicMock(return_value="transformers"))- monkeypatch.setattr(analyze.time, "perf_counter", fake_perf_counter)- monkeypatch.setattr(analyze, "_normalize_pdf_model_list", fake_normalize_model_list)- monkeypatch.setattr(analyze, "clean_memory", fake_clean_memory)+ monkeypatch.setattr(pipeline, "get_vlm_engine", MagicMock(return_value="transformers"))+ monkeypatch.setattr(pipeline.time, "perf_counter", fake_perf_counter)+ monkeypatch.setattr(pipeline, "_normalize_pdf_model_list", fake_normalize_model_list)+ monkeypatch.setattr(pipeline, "clean_memory", fake_clean_memory)middle_json, model_list = analyze.doc_analyze(b"empty-pdf",@@ -1070,6 +1139,71 @@ def test_pdf_infer_timer_excludes_hybrid_vlm_initialization_and_cleanup(]+def test_pdf_analyze_releases_document_and_model_when_window_processing_fails(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """验证窗口处理异常时仍关闭 PDF 文档并释放已初始化的 Hybrid 模型。"""+ fake_document = MagicMock()+ hybrid_model = MagicMock()+ hybrid_model.device = "cpu"+ hybrid_singleton = MagicMock()+ hybrid_singleton.get_model.return_value = hybrid_model+ clean_memory = MagicMock()++ monkeypatch.setattr(pipeline, "PDFDocument", MagicMock(return_value=fake_document))+ monkeypatch.setattr(+ pipeline,+ "HybridLocalModelContextSingleton",+ MagicMock(return_value=hybrid_singleton),+ )+ monkeypatch.setattr(+ pipeline,+ "process_pdf_windows",+ MagicMock(side_effect=RuntimeError("window failed")),+ )+ monkeypatch.setattr(pipeline, "clean_memory", clean_memory)++ with pytest.raises(RuntimeError, match="window failed"):+ pipeline.analyze_pdf(b"broken-pdf", effort="low", parse_mode="txt")++ fake_document.close.assert_called_once_with()+ clean_memory.assert_called_once_with("cpu")+++def test_pdf_window_releases_rendered_images_when_layout_fails(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """验证窗口内布局阶段异常时仍释放该窗口已经渲染的页图。"""+ page_image = Image.new("RGB", (20, 20), "white")+ fake_document = MagicMock()+ fake_document.page_count = 1+ fake_document.__getitem__.return_value = MagicMock()+ hybrid_model = MagicMock()+ hybrid_model.layout_model.batch_predict.side_effect = RuntimeError("layout failed")++ monkeypatch.setattr(window, "get_processing_window_size", lambda default: 1)+ monkeypatch.setattr(+ window,+ "load_images_from_pdf_bytes_range",+ lambda **_kwargs: [{"img_pil": page_image}],+ )++ with pytest.raises(RuntimeError, match="layout failed"):+ window.process_pdf_windows(+ b"broken-pdf",+ fake_document,+ effort="low",+ parse_mode="txt",+ image_analysis=True,+ flash_txt_mode=False,+ hybrid_model=hybrid_model,+ vlm_predictor=None,+ )++ with pytest.raises(ValueError, match="closed image"):+ page_image.getpixel((0, 0))++@pytest.mark.parametrize(("file_suffix", "expected_page_count"),[("docx", 3), ("pptx", 6), ("xlsx", 3)],@@ -1092,17 +1226,9 @@ def test_doc_analyze_office_real_samples(file_suffix: str, expected_page_count:assert all(isinstance(page, list) for page in model_list)if file_suffix == "docx":model_equations = [- block- for page_model_list in model_list- for block in page_model_list- if block.get("type") == BlockType.EQUATION- ]- middle_equations = [- block- for page in middle_json.pages- for block in page.blocks- if block.type == BlockType.EQUATION+ block for page_model_list in model_list for block in page_model_list if block.get("type") == BlockType.EQUATION]+ middle_equations = [block for page in middle_json.pages for block in page.blocks if block.type == BlockType.EQUATION]assert model_equationsassert len(middle_equations) == len(model_equations)assert "interline_equation" not in middle_json.to_json()@@ -1138,17 +1264,9 @@ def test_doc_analyze_flash_demo1_uses_canonical_equation_type() -> None:)model_equations = [- block- for page_model_list in model_list- for block in page_model_list- if block.get("type") == BlockType.EQUATION- ]- middle_equations = [- block- for page in middle_json.pages- for block in page.blocks- if block.type == BlockType.EQUATION+ block for page_model_list in model_list for block in page_model_list if block.get("type") == BlockType.EQUATION]+ middle_equations = [block for page in middle_json.pages for block in page.blocks if block.type == BlockType.EQUATION]assert model_equationsassert len(middle_equations) == len(model_equations)@@ -1162,12 +1280,12 @@ def test_doc_analyze_flash_returns_complete_model_list_and_typed_middle_json(monevents: list[str] = []source_model_list = [[- {- "type": BlockType.TEXT,- "bbox": [0.0, 0.0, 1.0, 1.0],- "content": "第一页 \\(x+y\\)",- "lines": [{"bbox": [0.0, 0.0, 1.0, 1.0]}],- }+ {+ "type": BlockType.TEXT,+ "bbox": [0.0, 0.0, 1.0, 1.0],+ "content": "第一页 \\(x+y\\)",+ "lines": [{"bbox": [0.0, 0.0, 1.0, 1.0]}],+ }],[{@@ -1218,20 +1336,19 @@ def test_doc_analyze_flash_returns_complete_model_list_and_typed_middle_json(monevents.append("render_window")requested_ranges.append((start_page_id, end_page_id))window_images = [- Image.new("RGB", (40, 20), (page_idx * 40, 100, 160))- for page_idx in range(start_page_id, end_page_id + 1)+ Image.new("RGB", (40, 20), (page_idx * 40, 100, 160)) for page_idx in range(start_page_id, end_page_id + 1)]rendered_images.extend(window_images)return [{"img_pil": image} for image in window_images]- original_attach_visual_block_images = analyze._attach_visual_block_images+ original_attach_visual_block_images = visuals._attach_visual_block_imagesdef tracked_attach_visual_block_images(*args: object, **kwargs: object) -> None:"""记录视觉块补图顺序并调用真实实现。"""events.append("attach_visual")original_attach_visual_block_images(*args, **kwargs) # type: ignore[arg-type]- original_normalize_model_list = analyze._normalize_pdf_model_list+ original_normalize_model_list = normalization._normalize_pdf_model_listdef tracked_normalize_model_list(model_list: list[list[dict[str, object]]]) -> None:"""记录 PDF model_list 规范化顺序并调用真实实现。"""@@ -1246,12 +1363,12 @@ def test_doc_analyze_flash_returns_complete_model_list_and_typed_middle_json(monevents.append(f"timer_{value}")return value- monkeypatch.setattr(analyze, "PDFDocument", lambda _: fake_pdf_doc)- monkeypatch.setattr(analyze, "get_processing_window_size", lambda default: 2)- monkeypatch.setattr(analyze, "load_images_from_pdf_bytes_range", fake_load_images_for_window)- monkeypatch.setattr(analyze, "_attach_visual_block_images", tracked_attach_visual_block_images)- monkeypatch.setattr(analyze, "_normalize_pdf_model_list", tracked_normalize_model_list)- monkeypatch.setattr(analyze.time, "perf_counter", fake_perf_counter)+ monkeypatch.setattr(pipeline, "PDFDocument", lambda _: fake_pdf_doc)+ monkeypatch.setattr(window, "get_processing_window_size", lambda default: 2)+ monkeypatch.setattr(window, "load_images_from_pdf_bytes_range", fake_load_images_for_window)+ monkeypatch.setattr(window, "_attach_visual_block_images", tracked_attach_visual_block_images)+ monkeypatch.setattr(pipeline, "_normalize_pdf_model_list", tracked_normalize_model_list)+ monkeypatch.setattr(pipeline.time, "perf_counter", fake_perf_counter)monkeypatch.setattr(flash_model, "PdfModel", MagicMock(return_value=fake_pdf_model))middle_json, model_list = analyze.doc_analyze(diff --git a/tests/unittest/test_magic_model.py b/tests/unittest/test_postprocess_page_blocks.pysimilarity index 66%rename from tests/unittest/test_magic_model.pyrename to tests/unittest/test_postprocess_page_blocks.pyindex 98890f03..16dc727c 100644--- a/tests/unittest/test_magic_model.py+++ b/tests/unittest/test_postprocess_page_blocks.py@@ -1,19 +1,20 @@from __future__ import annotations-from mineru.backend.magic_model import MagicModel, fix_pdf_list_blocks+from mineru.backend.postprocess.lists import fix_pdf_list_blocks+from mineru.backend.postprocess.page_blocks import process_page_blocksfrom mineru.types import BlockType-def test_magic_model_keeps_canonical_equation_type_and_cleans_content() -> None:- """验证 MagicModel 清理行间公式内容时不再改写 equation 类型。"""+def test_page_blocks_keep_canonical_equation_type_and_clean_content() -> None:+ """验证单页后处理清理行间公式内容时不改写 equation 类型。"""equation = {"type": BlockType.EQUATION,"content": r"\[x+1\]",}- magic_model = MagicModel([equation], use_bbox=False)+ blocks = process_page_blocks([equation], use_bbox=False)- assert magic_model.blocks == [+ assert blocks == [{"type": BlockType.EQUATION,"content": "x+1",@@ -52,9 +53,9 @@ def test_fix_pdf_list_blocks_supports_unit_bbox_without_rewrite() -> None:assert text_bbox == [100, 100, 200, 200]-def test_magic_model_groups_bbox_dict_visual_blocks() -> None:- """验证共享 MagicModel 可将带 bbox 的 dict 视觉块完成分组。"""- magic_model = MagicModel(+def test_page_blocks_group_bbox_dict_visual_blocks() -> None:+ """验证单页后处理可将带 bbox 的 dict 视觉块完成分组。"""+ blocks = process_page_blocks([{"type": BlockType.IMAGE_CAPTION,@@ -69,8 +70,9 @@ def test_magic_model_groups_bbox_dict_visual_blocks() -> None:])- assert len(magic_model.image_blocks) == 1- image_block = magic_model.image_blocks[0]+ image_blocks = [block for block in blocks if block["type"] == BlockType.IMAGE]+ assert len(image_blocks) == 1+ image_block = image_blocks[0]assert isinstance(image_block, dict)assert [block["type"] for block in image_block["content"]] == [BlockType.IMAGE_CAPTION,@@ -78,9 +80,9 @@ def test_magic_model_groups_bbox_dict_visual_blocks() -> None:]-def test_magic_model_groups_no_bbox_office_caption_by_prefix() -> None:- """验证共享 MagicModel 使用 Office 前缀规则分组无 bbox 视觉块。"""- magic_model = MagicModel(+def test_page_blocks_group_no_bbox_office_caption_by_prefix() -> None:+ """验证单页后处理使用 Office 前缀规则分组无 bbox 视觉块。"""+ blocks = process_page_blocks([{"type": BlockType.IMAGE,@@ -93,18 +95,19 @@ def test_magic_model_groups_no_bbox_office_caption_by_prefix() -> None:])- assert magic_model.text_blocks == []- assert len(magic_model.image_blocks) == 1- image_block = magic_model.image_blocks[0]+ assert not [block for block in blocks if block["type"] == BlockType.TEXT]+ image_blocks = [block for block in blocks if block["type"] == BlockType.IMAGE]+ assert len(image_blocks) == 1+ image_block = image_blocks[0]assert [block["type"] for block in image_block["content"]] == [BlockType.IMAGE_BODY,BlockType.IMAGE_CAPTION,]-def test_magic_model_groups_no_bbox_chart_and_code_captions() -> None:+def test_page_blocks_group_no_bbox_chart_and_code_captions() -> None:"""验证无 bbox 的 chart/code caption 映射及 code subtype 保留。"""- magic_model = MagicModel(+ blocks = process_page_blocks([{"type": BlockType.CHART_CAPTION, "content": "Chart 1"},{"type": BlockType.CHART, "content": "<div>chart</div>"},@@ -113,11 +116,12 @@ def test_magic_model_groups_no_bbox_chart_and_code_captions() -> None:])- assert [block["type"] for block in magic_model.chart_blocks[0]["content"]] == [+ chart_block = next(block for block in blocks if block["type"] == BlockType.CHART)+ assert [block["type"] for block in chart_block["content"]] == [BlockType.CHART_CAPTION,BlockType.CHART_BODY,]- code_block = magic_model.code_blocks[0]+ code_block = next(block for block in blocks if block["type"] == BlockType.CODE)assert code_block["sub_type"] == "code"assert code_block["guess_lang"]assert [block["type"] for block in code_block["content"]] == [diff --git a/tests/unittest/test_model_list_to_midlle_json.py b/tests/unittest/test_postprocess_pages.pysimilarity index 59%rename from tests/unittest/test_model_list_to_midlle_json.pyrename to tests/unittest/test_postprocess_pages.pyindex e00fdfae..25ca76d6 100644--- a/tests/unittest/test_model_list_to_midlle_json.py+++ b/tests/unittest/test_postprocess_pages.py@@ -2,7 +2,7 @@ from copy import deepcopyimport pytest-from mineru.backend.model_list_to_midlle_json import model_list_to_pages+from mineru.backend.postprocess.pages import model_list_to_pagesfrom mineru.types import (EquationBlock,ImageBlock,@@ -15,15 +15,17 @@ from mineru.types import (def test_model_list_to_pages_keeps_equation_type_without_mutating_input() -> None:- """验证 equation 经 MagicModel 和严格对象化后保持类型、内容与图片载荷。"""- model_list = [[- {- "type": "equation",- "bbox": [0.1, 0.2, 0.9, 0.4],- "content": r"\[x+1\]",- "image_base64": "data:image/jpeg;base64,/9j/2Q==",- }- ]]+ """验证 equation 经单页后处理和严格对象化后保持类型、内容与图片载荷。"""+ model_list = [+ [+ {+ "type": "equation",+ "bbox": [0.1, 0.2, 0.9, 0.4],+ "content": r"\[x+1\]",+ "image_base64": "data:image/jpeg;base64,/9j/2Q==",+ }+ ]+ ]original = deepcopy(model_list)page = model_list_to_pages(model_list)[0]@@ -37,17 +39,19 @@ def test_model_list_to_pages_keeps_equation_type_without_mutating_input() -> Nondef test_model_list_to_pages_returns_typed_pdf_tree_without_mutating_input() -> None:"""验证 PDF raw dict 只在副本上分组,并返回具体 PageInfo/Block 对象。"""- model_list = [[- {"type": "image_caption", "bbox": [0.1, 0.05, 0.9, 0.1], "content": "Figure 1"},- {- "type": "image",- "bbox": [0.1, 0.12, 0.9, 0.45],- "content": None,- "image_base64": "data:image/jpeg;base64,/9j/2Q==",- },- {"type": "list", "bbox": [0.1, 0.5, 0.9, 0.8], "content": ""},- {"type": "text", "bbox": [0.15, 0.55, 0.85, 0.65], "content": "item"},- ]]+ model_list = [+ [+ {"type": "image_caption", "bbox": [0.1, 0.05, 0.9, 0.1], "content": "Figure 1"},+ {+ "type": "image",+ "bbox": [0.1, 0.12, 0.9, 0.45],+ "content": None,+ "image_base64": "data:image/jpeg;base64,/9j/2Q==",+ },+ {"type": "list", "bbox": [0.1, 0.5, 0.9, 0.8], "content": ""},+ {"type": "text", "bbox": [0.15, 0.55, 0.85, 0.65], "content": "item"},+ ]+ ]original = deepcopy(model_list)pages = model_list_to_pages(model_list, page_index_map=[7])@@ -66,35 +70,37 @@ def test_model_list_to_pages_returns_typed_pdf_tree_without_mutating_input() ->def test_model_list_to_pages_preserves_recursive_office_list_and_index() -> None:"""验证 Office list/index 任意深度递归对象化,并删除目录 text 的 anchor。"""- model_list = [[- {- "type": "list",- "attribute": "ordered",- "ilevel": 0,- "start": 1,- "content": [- {"type": "text", "content": "first"},- {- "type": "list",- "attribute": "unordered",- "ilevel": 1,- "content": [- {"type": "text", "content": "child"},- {"type": "list", "content": [{"type": "text", "content": "deep"}]},- ],- },- ],- },- {- "type": "index",- "content": [- {- "type": "index",- "content": [{"type": "text", "content": "section", "anchor": "a1"}],- }- ],- },- ]]+ model_list = [+ [+ {+ "type": "list",+ "attribute": "ordered",+ "ilevel": 0,+ "start": 1,+ "content": [+ {"type": "text", "content": "first"},+ {+ "type": "list",+ "attribute": "unordered",+ "ilevel": 1,+ "content": [+ {"type": "text", "content": "child"},+ {"type": "list", "content": [{"type": "text", "content": "deep"}]},+ ],+ },+ ],+ },+ {+ "type": "index",+ "content": [+ {+ "type": "index",+ "content": [{"type": "text", "content": "section", "anchor": "a1"}],+ }+ ],+ },+ ]+ ]page = model_list_to_pages(model_list)[0]list_block = page.blocks[0]@@ -141,15 +147,17 @@ def test_office_paragraph_numbering_is_document_wide_and_copy_only() -> None:def test_office_paragraph_numbering_clears_deeper_levels() -> None:"""验证标题返回浅层时会清理旧深层计数,后续重新从一开始编号。"""- model_list = [[- {"type": "paragraph_title", "content": "A", "level": 1, "is_numbered_style": True},- {"type": "paragraph_title", "content": "B", "level": 2, "is_numbered_style": True},- {"type": "paragraph_title", "content": "C", "level": 3, "is_numbered_style": True},- {"type": "paragraph_title", "content": "D", "level": 2, "is_numbered_style": True},- {"type": "paragraph_title", "content": "E", "level": 3, "is_numbered_style": True},- {"type": "paragraph_title", "content": "F", "level": 1, "is_numbered_style": True},- {"type": "paragraph_title", "content": "G", "level": 2, "is_numbered_style": True},- ]]+ model_list = [+ [+ {"type": "paragraph_title", "content": "A", "level": 1, "is_numbered_style": True},+ {"type": "paragraph_title", "content": "B", "level": 2, "is_numbered_style": True},+ {"type": "paragraph_title", "content": "C", "level": 3, "is_numbered_style": True},+ {"type": "paragraph_title", "content": "D", "level": 2, "is_numbered_style": True},+ {"type": "paragraph_title", "content": "E", "level": 3, "is_numbered_style": True},+ {"type": "paragraph_title", "content": "F", "level": 1, "is_numbered_style": True},+ {"type": "paragraph_title", "content": "G", "level": 2, "is_numbered_style": True},+ ]+ ]titles = model_list_to_pages(model_list)[0].blocks@@ -166,9 +174,7 @@ def test_office_paragraph_numbering_clears_deeper_levels() -> None:def test_visual_body_drops_empty_parent_subtype() -> None:"""验证 raw visual 的空 subtype 只用于父块判断,不会泄漏到严格 body 模型。"""- page = model_list_to_pages(- [[{"type": "image", "content": None, "sub_type": None}]]- )[0]+ page = model_list_to_pages([[{"type": "image", "content": None, "sub_type": None}]])[0]assert isinstance(page.blocks[0], ImageBlock)assert page.blocks[0].sub_type is None@@ -177,20 +183,22 @@ def test_visual_body_drops_empty_parent_subtype() -> None:def test_pdf_continuation_is_typed_and_line_metadata_is_removed() -> None:"""验证 raw 段落延续在对象化前完成,公开 TextBlock 不保留临时 lines。"""- model_list = [[- {- "type": "text",- "bbox": [0.1, 0.1, 0.9, 0.3],- "content": "previous continuation",- "lines": [{"bbox": [0.1, 0.1, 0.9, 0.15]}, {"bbox": [0.1, 0.2, 0.9, 0.25]}],- },- {- "type": "text",- "bbox": [0.1, 0.25, 0.9, 0.45],- "content": "current continuation",- "lines": [{"bbox": [0.1, 0.25, 0.9, 0.3]}, {"bbox": [0.1, 0.35, 0.9, 0.4]}],- },- ]]+ model_list = [+ [+ {+ "type": "text",+ "bbox": [0.1, 0.1, 0.9, 0.3],+ "content": "previous continuation",+ "lines": [{"bbox": [0.1, 0.1, 0.9, 0.15]}, {"bbox": [0.1, 0.2, 0.9, 0.25]}],+ },+ {+ "type": "text",+ "bbox": [0.1, 0.25, 0.9, 0.45],+ "content": "current continuation",+ "lines": [{"bbox": [0.1, 0.25, 0.9, 0.3]}, {"bbox": [0.1, 0.35, 0.9, 0.4]}],+ },+ ]+ ]page = model_list_to_pages(model_list)[0]@@ -202,10 +210,12 @@ def test_pdf_continuation_is_typed_and_line_metadata_is_removed() -> None:def test_pdf_detection_scans_past_empty_first_page() -> None:"""验证整份文档 bbox 判定不会把 PDF 空白首页误认为 Office。"""- pages = model_list_to_pages([- [],- [{"type": "text", "bbox": [0.1, 0.1, 0.9, 0.3], "content": "later", "lines": []}],- ])+ pages = model_list_to_pages(+ [+ [],+ [{"type": "text", "bbox": [0.1, 0.1, 0.9, 0.3], "content": "later", "lines": []}],+ ]+ )assert pages[0].blocks == []assert isinstance(pages[1].blocks[0], TextBlock)@@ -215,10 +225,12 @@ def test_cross_page_table_continuation_remains_raw_postprocess() -> None:"""验证连续页表格仍在对象化前写入 continues_prev。"""html_a = "<table><tr><td>A</td><td>B</td></tr></table>"html_b = "<table><tr><td>C</td><td>D</td></tr></table>"- pages = model_list_to_pages([- [{"type": "table", "bbox": [0.1, 0.1, 0.9, 0.85], "content": html_a}],- [{"type": "table", "bbox": [0.1, 0.1, 0.9, 0.85], "content": html_b}],- ])+ pages = model_list_to_pages(+ [+ [{"type": "table", "bbox": [0.1, 0.1, 0.9, 0.85], "content": html_a}],+ [{"type": "table", "bbox": [0.1, 0.1, 0.9, 0.85], "content": html_b}],+ ]+ )assert isinstance(pages[0].blocks[0], TableBlock)assert pages[0].blocks[0].continues_prev is Nonediff --git a/tests/unittest/test_para_block_utils.py b/tests/unittest/test_postprocess_paragraphs.pysimilarity index 98%rename from tests/unittest/test_para_block_utils.pyrename to tests/unittest/test_postprocess_paragraphs.pyindex be1f851c..8a98396a 100644--- a/tests/unittest/test_para_block_utils.py+++ b/tests/unittest/test_postprocess_paragraphs.py@@ -1,8 +1,10 @@+"""跨页段落延续规则的聚焦回归测试。"""+from copy import deepcopyimport pytest-from mineru.backend.utils.para_block_utils import can_auto_merge_text_blocks, merge_para_text_blocks+from mineru.backend.postprocess.paragraphs import can_auto_merge_text_blocks, merge_para_text_blocksfrom mineru.types import BlockTypediff --git a/tests/unittest/test_visual_magic_model_utils.py b/tests/unittest/test_postprocess_visual.pysimilarity index 93%rename from tests/unittest/test_visual_magic_model_utils.pyrename to tests/unittest/test_postprocess_visual.pyindex 5d945394..48f70eb1 100644--- a/tests/unittest/test_visual_magic_model_utils.py+++ b/tests/unittest/test_postprocess_visual.py@@ -1,6 +1,8 @@+"""视觉块后处理规则的聚焦回归测试。"""+from __future__ import annotations-from mineru.backend.utils.visual_magic_model_utils import (+from mineru.backend.postprocess.visual import (VISUAL_MAIN_TYPES,_bbox_for_calculation,fallback_inline_caption_fragments,@@ -10,7 +12,7 @@ from mineru.backend.utils.visual_magic_model_utils import (is_block_outside_visual_gap,regroup_visual_blocks,)-from mineru.backend.utils.raw_block_types import RAW_CAPTION, RAW_FOOTNOTE+from mineru.types import RAW_CAPTION, RAW_FOOTNOTEfrom mineru.types import BlockType@@ -79,10 +81,7 @@ def test_normalized_dict_bbox_matches_scaled_visual_parent_without_rewrite() ->following_table = {"index": 2, "type": BlockType.TABLE_BODY, "bbox": [0.1, 0.8, 0.4, 0.95]}normalized_blocks = [previous_table, caption, following_table]original_bboxes = [list(block["bbox"]) for block in normalized_blocks]- scaled_blocks = [- {**block, "bbox": [value * 1000 for value in block["bbox"]]}- for block in normalized_blocks- ]+ scaled_blocks = [{**block, "bbox": [value * 1000 for value in block["bbox"]]} for block in normalized_blocks]normalized_parent = find_best_visual_parent(caption,@@ -109,10 +108,7 @@ def test_normalized_dict_bbox_matches_scaled_visual_gap_geometry() -> None:outside_gap = {"index": 2, "type": BlockType.TEXT, "bbox": [0.8, 0.8, 0.9, 0.9]}main = {"index": 3, "type": BlockType.TABLE_BODY, "bbox": [0.1, 0.6, 0.4, 0.7]}normalized_blocks = [child, inside_gap, outside_gap, main]- scaled_blocks = [- {**block, "bbox": [value * 1000 for value in block["bbox"]]}- for block in normalized_blocks- ]+ scaled_blocks = [{**block, "bbox": [value * 1000 for value in block["bbox"]]} for block in normalized_blocks]assert is_block_outside_visual_gap(inside_gap, child, main) is Falseassert is_block_outside_visual_gap(outside_gap, child, main) is True@@ -235,9 +231,7 @@ def test_regroup_visual_blocks_supports_bbox_dicts() -> None:"lines": [{"bbox": [0.0, 65.0, 80.0, 75.0]}],}- grouped_blocks, unmatched_blocks = regroup_visual_blocks(- [caption, body, footnote]- )+ grouped_blocks, unmatched_blocks = regroup_visual_blocks([caption, body, footnote])assert unmatched_blocks == []assert len(grouped_blocks[BlockType.IMAGE]) == 1@@ -333,14 +327,11 @@ def test_regroup_visual_blocks_without_bbox_prefers_previous_parent() -> None:assert unmatched_blocks == []assert "bbox" not in grouped_blocks[BlockType.IMAGE][0]- assert [- block["type"]- for block in grouped_blocks[BlockType.IMAGE][0]["content"]- ] == [BlockType.IMAGE_BODY, BlockType.IMAGE_CAPTION]- assert [- block["type"]- for block in grouped_blocks[BlockType.TABLE][0]["content"]- ] == [BlockType.TABLE_BODY]+ assert [block["type"] for block in grouped_blocks[BlockType.IMAGE][0]["content"]] == [+ BlockType.IMAGE_BODY,+ BlockType.IMAGE_CAPTION,+ ]+ assert [block["type"] for block in grouped_blocks[BlockType.TABLE][0]["content"]] == [BlockType.TABLE_BODY]def test_regroup_visual_blocks_supports_code_footnote() -> None:@@ -381,10 +372,7 @@ def test_regroup_visual_blocks_without_bbox_keeps_text_as_barrier() -> None:)assert unmatched_blocks == [caption]- assert [- block["type"]- for block in grouped_blocks[BlockType.TABLE][0]["content"]- ] == [BlockType.TABLE_BODY]+ assert [block["type"] for block in grouped_blocks[BlockType.TABLE][0]["content"]] == [BlockType.TABLE_BODY]def test_no_bbox_caption_fallback_uses_office_prefixes() -> None:diff --git a/tests/unittest/test_table_merge.py b/tests/unittest/test_table_merge.pyindex 3e87d75a..288d4eb3 100644--- a/tests/unittest/test_table_merge.py+++ b/tests/unittest/test_table_merge.py@@ -6,7 +6,7 @@ from typing import Anyimport pytestfrom bs4 import BeautifulSoup-from mineru.backend.utils.table_merge import merge_table, merge_table_content+from mineru.backend.postprocess.table_merge import merge_table, merge_table_contentfrom mineru.types import BlockTypediff --git a/tests/unittest/test_table_merge_cell_merge.py b/tests/unittest/test_table_merge_cell_merge.pyindex ae34adf9..4d5f5f30 100644--- a/tests/unittest/test_table_merge_cell_merge.py+++ b/tests/unittest/test_table_merge_cell_merge.py@@ -5,7 +5,7 @@ from typing import Anyfrom bs4 import BeautifulSoup-from mineru.backend.utils.table_merge import merge_table_content+from mineru.backend.postprocess.table_merge import merge_table_contentfrom mineru.types import BlockType