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: reorganize module structure by renaming and relocating table_text.py, and add new model_list_to_midlle_json.py
myhloli81525f7e66b9
diff --git a/mineru/backend/pdf/analyze.py b/mineru/backend/analyze.pysimilarity index 88%rename from mineru/backend/pdf/analyze.pyrename to mineru/backend/analyze.pyindex b37b5459..3bb5768b 100644--- a/mineru/backend/pdf/analyze.py+++ b/mineru/backend/analyze.py@@ -7,6 +7,7 @@ import reimport timefrom collections import Counterfrom dataclasses import dataclass+from io import BytesIOfrom typing import Any, Literalimport cv2@@ -14,7 +15,7 @@ import numpy as npfrom PIL import Imagefrom loguru import logger-from mineru.backend.pdf.table_text import project_ocr_table_text, project_pdf_table_text+from mineru.backend.utils.table_text import project_ocr_table_text, project_pdf_table_textfrom mineru.backend.local_model_runtime import (AtomicModel,HybridLocalModelContext,@@ -37,6 +38,7 @@ from mineru.backend.utils.span_pre_proc import (_restore_post_ocr_fallback,txt_spans_extract,)+from mineru.model.flash import DocxModel, PptxModel, XlsxModelfrom mineru.utils.bbox_utils import normalize_to_int_bboxfrom mineru.utils.engine_utils import get_vlm_enginefrom mineru.utils.language import detect_lang@@ -55,10 +57,9 @@ from mineru.utils.ocr_utils import (from mineru.utils.pdf_image_tools import load_images_from_pdf_bytes_range, get_crop_np_imgfrom tqdm import tqdm-from ...utils.image_payload import ImagePayloadCache-from ...utils.pdf_document import PDFDocument, PDFPage, get_lines_from_chars-from ...types import BBox, Block, BlockType, ContentType, Line, NOT_EXTRACT_TYPES, PageInfo, Span-from ...utils.config_reader import get_processing_window_size+from ..types import BBox, Block, BlockType, ContentType, Line, NOT_EXTRACT_TYPES, PageInfo, Span+from ..utils.config_reader import get_processing_window_size+from ..utils.pdf_document import PDFDocument, PDFPage, get_lines_from_charsos.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1" # 让mps可以fallback@@ -72,6 +73,12 @@ TABLE_TEXT_LINE_OVERLAP_THRESHOLD = 0.5TABLE_TEXT_ORIENTATION_MIN_VALID_LINES = 3TABLE_TEXT_ORIENTATION_MIN_DOMINANCE_RATIO = 0.6TABLE_TEXT_ORIENTATION_ANGLES = frozenset({0, 90, 180, 270})+_OFFICE_MODEL_MAP = {+ "docx": DocxModel,+ "pptx": PptxModel,+ "xlsx": XlsxModel,+}+_SUPPORTED_FILE_SUFFIXES = {"pdf", *_OFFICE_MODEL_MAP}TITLE_BLOCK_TYPES = {BlockType.TITLE,BlockType.DOC_TITLE,@@ -150,7 +157,7 @@ class _OcrDetCrop:def _load_vlm_runtime() -> dict[str, Any]:"""按需加载 VLM runtime 组件,确保只有 high/extra_high 路径触发 VLM 依赖。"""- from ...model.vlm.runtime import (+ from ..model.vlm.runtime import (ModelSingleton,_get_model_async,_maybe_enable_serial_execution,@@ -2181,205 +2188,232 @@ def _replace_inline_formula_delimiters(model_list: list[list[dict[str, Any]]]) -)+def _log_infer_performance(file_suffix: str, page_count: int, elapsed: float) -> None:+ """使用未舍入耗时统一记录 model_list 生产阶段的处理速度。"""+ speed = page_count / elapsed if elapsed > 0 else 0.0+ logger.debug(+ f"model_list infer finished, file_suffix={file_suffix}, pages={page_count}, "+ f"cost={elapsed:.6f}s, speed={speed:.3f} page/s"+ )++def doc_analyze(- pdf_bytes: bytes,+ file_bytes: bytes,effort: Literal["flash", "low", "medium", "high", "xhigh"] = "high",parse_mode: Literal["auto", "txt", "ocr"] = "auto",image_analysis: bool = True,page_index_map: list[int] | None = None,- image_cache: ImagePayloadCache | None = None,+ file_suffix: Literal["pdf", "docx", "pptx", "xlsx"] = "pdf",) -> tuple[list[PageInfo], list[list[dict[str, Any]]]]:- pdf_doc = PDFDocument(pdf_bytes)- if parse_mode == "auto":- parse_mode = pdf_doc.classify()- if parse_mode not in ["txt", "ocr"]:- raise ValueError(f"parse_mode {parse_mode} is not supported")-- # Analyze 阶段暂不组装 Middle JSON,仅返回包含完整模型结果的 model_list。- middle_json: list[PageInfo] = []- model_list: list[list[dict[str, Any]]] = []- doc_closed = False-- try:- # Flash 只处理原生文本,OCR 文档继续复用 Hybrid low 流程。- if effort == "flash" and parse_mode == "ocr":- effort = "low"-- flash_txt_mode = effort == "flash" and parse_mode == "txt"- page_count = pdf_doc.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,+ 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+ 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")++ # 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",)- vlm_predictor = vlm_runtime["_maybe_enable_serial_execution"](vlm_predictor, vlm_backend)- else:- vlm_predictor = None-- infer_start = time.time()-- if flash_txt_mode:- # Flash 先对整份 PDF 生成完整 model_list,不依赖页面渲染和处理窗口。- from mineru.model.flash import PdfModel-- infer_start = time.time()- model_list = PdfModel().predict(pdf_doc)-- 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))+ 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)+ )- for window in windows:- pdf_pages = _get_window_pdf_pages(pdf_doc, window)- images_list = load_images_from_pdf_bytes_range(- pdf_bytes=pdf_bytes,- start_page_id=window.start,- end_page_id=window.end,- image_type="pil_img",- )- try:- if len(pdf_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,+ )+ _apply_layout_title_split(+ window_model_list,+ images_layout_res,+ [_normalize_page_size(image) for image in images_pil_list],+ )+ 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,+ )+ _apply_layout_title_split(+ window_model_list,+ images_layout_res,+ [_normalize_page_size(image) for image in images_pil_list],+ )+ else:+ raise ValueError(f"Unsupported analyze effort: {effort}")+ else:+ raise ValueError(f"Unsupported parse mode: {parse_mode}")- # 使用小模型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,- pdf_pages,+ if effort == "low":+ window_model_list = _process_low_text(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,- )- _apply_layout_title_split(+ window_pages,window_model_list,+ parse_mode,+ hybrid_model,images_layout_res,- [_normalize_page_size(image) for image in images_pil_list],)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,- )- _apply_layout_title_split(+ window_model_list = _process_text_and_formulas(+ images_list,+ window_pages,window_model_list,+ parse_mode,+ effort,+ hybrid_model,images_layout_res,- [_normalize_page_size(image) for image in images_pil_list],)- else:- raise ValueError(f"Unsupported analyze effort: {effort}")- else:- raise ValueError(f"Unsupported parse mode: {parse_mode}")-- if effort == "low":- window_model_list = _process_low_text(- images_list,- pdf_pages,- window_model_list,- parse_mode,- hybrid_model,- images_layout_res,- )- else:- window_model_list = _process_text_and_formulas(- images_list,- pdf_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)+ if effort in {"medium", "high"}:+ _apply_seal_ocr(hybrid_model, window_model_list, np_images)- _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)-- # 等全部窗口合并完成后统一替换,确保完整 model_list 的处理语义一致。- _replace_inline_formula_delimiters(model_list)- infer_time = round(time.time() - infer_start, 2)- if infer_time > 0 and page_count > 0:- logger.debug(- f"processing-window infer finished, cost: {infer_time}, speed: {round(len(model_list) / infer_time, 3)} page/s"- )+ _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 模型结果需要将行内公式定界符统一替换为 eq 标签。+ _replace_inline_formula_delimiters(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()- pdf_doc.close()- doc_closed = True- if hybrid_model is not None:- clean_memory(hybrid_model.device)- return middle_json, model_list- finally:- if not doc_closed:- pdf_doc.close()+ _log_infer_performance(file_suffix, len(model_list), infer_elapsed)++ # PDF 与 Office 的 model_list 在此汇合,后续统一生产 Middle JSON。+ middle_json: list[PageInfo] = []+ return middle_json, model_listif __name__ == "__main__":from mineru.cli_old.common import read_fn- # pdf_path = "/Users/myhloli/pdf/截断合并/demo1-3.pdf"- # pdf_path = "/Users/myhloli/pdf/png/seal4.png" # shubiao.png- pdf_path = "/Users/myhloli/pdf/demo1.pdf"- pdf_bytes = read_fn(pdf_path)- middle_json, model_list = doc_analyze(pdf_bytes, effort="flash")- logger.info(f"middle_json: {middle_json}")- logger.info(f"model_list: {model_list}")+++ # 根据当前文件位置定位项目根目录,读取 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", "pdfs", "demo1.pdf"),+ os.path.join(project_root, "demo", "office_docs", "docx_01.docx"),+ ]++ for file_path in demo_file_paths:+ file_bytes = read_fn(file_path)+ file_suffix = os.path.splitext(file_path)[1].lstrip(".").lower()+ middle_json, model_list = doc_analyze(file_bytes, effort="medium", file_suffix=file_suffix)+ logger.info(f"file_path: {file_path}")+ logger.info(f"middle_json: {middle_json}")+ logger.info(f"model_list: {model_list}")diff --git a/mineru/backend/model_list_to_midlle_json.py b/mineru/backend/model_list_to_midlle_json.pynew file mode 100644index 00000000..f64ba567--- /dev/null+++ b/mineru/backend/model_list_to_midlle_json.py@@ -0,0 +1 @@+# Copyright (c) Opendatalab. All rights reserved.\ No newline at end of filediff --git a/mineru/backend/pdf/table_text.py b/mineru/backend/utils/table_text.pysimilarity index 99%rename from mineru/backend/pdf/table_text.pyrename to mineru/backend/utils/table_text.pyindex 2181eed8..14ab4368 100644--- a/mineru/backend/pdf/table_text.py+++ b/mineru/backend/utils/table_text.py@@ -8,7 +8,7 @@ from typing import Anyimport numpy as npfrom pdftext.schema import Char-from ...types import BBox+from mineru.types import BBox# 空间投影思路参考 LiteParse v2.6.0 的字符分段和网格投影;diff --git a/mineru/model/flash/native_pdf/code_blocks.py b/mineru/model/flash/native_pdf/code_blocks.pyindex 4ba08e79..51606f49 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.pdf.table_text import project_pdf_spatial_text+from mineru.backend.utils.table_text import project_pdf_spatial_textfrom mineru.types import BBoxfrom mineru.utils.pdf_document import PDFPathInfodiff --git a/mineru/model/flash/native_pdf/tables.py b/mineru/model/flash/native_pdf/tables.pyindex 47eb94ee..33505feb 100644--- a/mineru/model/flash/native_pdf/tables.py+++ b/mineru/model/flash/native_pdf/tables.py@@ -12,7 +12,7 @@ from typing import Any, Literalfrom loguru import loggerfrom mineru.backend.utils.char_utils import resolve_text_line_boundary-from mineru.backend.pdf.table_text import project_pdf_table_text+from mineru.backend.utils.table_text import project_pdf_table_textfrom mineru.types import BBoxfrom mineru.utils.pdf_document import PDFPathInfofrom mineru.utils.language import detect_langdiff --git a/tests/unittest/test_flash_pdf_code_blocks.py b/tests/unittest/test_flash_pdf_code_blocks.pyindex 05418800..613f0e89 100644--- a/tests/unittest/test_flash_pdf_code_blocks.py+++ b/tests/unittest/test_flash_pdf_code_blocks.py@@ -5,7 +5,7 @@ from typing import Anyimport pytestfrom mineru.model.flash.native_pdf import code_blocks, models, pipeline-from mineru.backend.pdf.table_text import project_pdf_spatial_text+from mineru.backend.utils.table_text import project_pdf_spatial_textfrom mineru.utils.pdf_document import PDFPathInfofrom _flash_pdf_test_utils import _text_linediff --git a/tests/unittest/test_pdf_analyze_visual_blocks.py b/tests/unittest/test_pdf_analyze_visual_blocks.pynew file mode 100644index 00000000..ff4cbe01--- /dev/null+++ b/tests/unittest/test_pdf_analyze_visual_blocks.py@@ -0,0 +1,598 @@+from __future__ import annotations++import base64+from io import BytesIO+from pathlib import Path+from unittest.mock import MagicMock++import numpy as np+import pytest+from PIL import Image, ImageDraw++from mineru.backend import analyze+from mineru.types import BlockType+++JPEG_DATA_URI_PREFIX = "data:image/jpeg;base64,"+RED = (255, 0, 0)+GREEN = (0, 255, 0)+BLUE = (0, 0, 255)+YELLOW = (255, 255, 0)+_PROJECT_ROOT = Path(__file__).resolve().parents[2]+_OFFICE_SAMPLE_DIR = _PROJECT_ROOT / "demo" / "office_docs"+++def _build_quadrant_image(width: int = 80, height: int = 40) -> Image.Image:+ """构造四角颜色不同的非对称测试图,便于验证视觉块回正方向。"""+ image = Image.new("RGB", (width, height), "white")+ draw = ImageDraw.Draw(image)+ middle_x = width // 2+ middle_y = height // 2+ draw.rectangle((0, 0, middle_x - 1, middle_y - 1), fill=RED)+ draw.rectangle((middle_x, 0, width - 1, middle_y - 1), fill=GREEN)+ draw.rectangle((0, middle_y, middle_x - 1, height - 1), fill=BLUE)+ draw.rectangle((middle_x, middle_y, width - 1, height - 1), fill=YELLOW)+ return image+++def _decode_jpeg_data_uri(data_uri: str) -> Image.Image:+ """解码 JPEG data URI 并返回独立的 RGB 图片对象。"""+ assert data_uri.startswith(JPEG_DATA_URI_PREFIX)+ image_bytes = base64.b64decode(data_uri[len(JPEG_DATA_URI_PREFIX) :])+ assert image_bytes.startswith(b"\xff\xd8")+ with Image.open(BytesIO(image_bytes)) as image:+ assert image.format == "JPEG"+ return image.convert("RGB")+++def _sample_quadrant_colors(image: Image.Image) -> tuple[tuple[int, int, int], ...]:+ """读取图片四个象限中心的颜色,避开 JPEG 分区边缘压缩噪声。"""+ width, height = image.size+ sample_points = (+ (width // 4, height // 4),+ (3 * width // 4, height // 4),+ (width // 4, 3 * height // 4),+ (3 * width // 4, 3 * height // 4),+ )+ return tuple(image.getpixel(point) for point in sample_points)+++def _assert_colors_close(+ actual_colors: tuple[tuple[int, int, int], ...],+ expected_colors: tuple[tuple[int, int, int], ...],+) -> None:+ """允许少量 JPEG 压缩误差地比较四个象限颜色。"""+ for actual, expected in zip(actual_colors, expected_colors):+ assert max(abs(actual_channel - expected_channel) for actual_channel, expected_channel in zip(actual, expected)) <= 12+++ ("angle", "expected_size", "expected_colors"),+ [+ (0, (80, 40), (RED, GREEN, BLUE, YELLOW)),+ (90, (40, 80), (GREEN, YELLOW, RED, BLUE)),+ (180, (80, 40), (YELLOW, BLUE, GREEN, RED)),+ (270, (40, 80), (BLUE, RED, YELLOW, GREEN)),+ ],+)+def test_visual_block_crop_rotates_to_upright(+ angle: int,+ expected_size: tuple[int, int],+ expected_colors: tuple[tuple[int, int, int], ...],+) -> None:+ """验证四种合法 angle 会按现有表格语义把视觉块裁图旋转回正。"""+ page_image = _build_quadrant_image()+ block = {+ "type": BlockType.IMAGE,+ "bbox": [0.0, 0.0, 1.0, 1.0],+ "angle": angle,+ "content": "keep-content",+ }++ analyze._attach_visual_block_images([[block]], [{"img_pil": page_image}])++ crop_image = _decode_jpeg_data_uri(block["image_base64"])+ try:+ assert crop_image.size == expected_size+ _assert_colors_close(_sample_quadrant_colors(crop_image), expected_colors)+ finally:+ crop_image.close()+ page_image.close()+ assert block["angle"] == angle+ assert block["content"] == "keep-content"+++def test_medium_table_task_reuses_visual_block_upright_rotation() -> None:+ """验证 Medium 表格任务继续复用视觉块的 270 度回正语义。"""+ page_image = _build_quadrant_image()+ np_image = np.asarray(page_image).copy()+ table_block = {+ "type": BlockType.TABLE,+ "bbox": [0.0, 0.0, 1.0, 1.0],+ "angle": 270,+ }++ table_tasks = analyze._collect_medium_table_tasks(+ [[table_block]],+ [[]],+ [np_image],+ )++ rotated_image = Image.fromarray(table_tasks[0]["table_img"])+ try:+ assert rotated_image.size == (40, 80)+ _assert_colors_close(+ _sample_quadrant_colors(rotated_image),+ (BLUE, RED, YELLOW, GREEN),+ )+ finally:+ rotated_image.close()+ page_image.close()+++def test_visual_block_types_receive_jpeg_data_uri_only() -> None:+ """验证 model.json 的四类视觉块写入裁图,非视觉块及其字段保持不变。"""+ page_image = Image.new("RGB", (100, 60), "white")+ visual_blocks = [+ {+ "type": block_type,+ "bbox": [0.1, 0.2, 0.6, 0.7],+ "angle": 0,+ "content": f"content-{block_type}",+ "image_base64": "stale",+ }+ for block_type in (+ BlockType.IMAGE,+ BlockType.CHART,+ BlockType.TABLE,+ BlockType.EQUATION,+ )+ ]+ text_block = {+ "type": BlockType.TEXT,+ "bbox": [0.0, 0.0, 1.0, 1.0],+ "content": "text",+ "image_base64": "keep-text-field",+ }++ analyze._attach_visual_block_images(+ [[*visual_blocks, text_block]],+ [{"img_pil": page_image}],+ page_start_index=7,+ )++ try:+ for block in visual_blocks:+ assert block["image_base64"] != "stale"+ crop_image = _decode_jpeg_data_uri(block["image_base64"])+ try:+ assert crop_image.size == (50, 30)+ finally:+ crop_image.close()+ assert block["content"] == f"content-{block['type']}"+ assert block["bbox"] == [0.1, 0.2, 0.6, 0.7]+ assert text_block["image_base64"] == "keep-text-field"+ finally:+ page_image.close()+++def test_visual_block_crop_clips_page_boundary_and_skips_invalid_bbox() -> None:+ """验证像素框会裁到页面范围,无效框会清理旧载荷且不影响其他块。"""+ page_image = Image.new("L", (100, 80), 128)+ clipped_block = {+ "type": BlockType.CHART,+ "bbox": [-10, -5, 30, 20],+ "angle": 0,+ }+ invalid_block = {+ "type": BlockType.TABLE,+ "bbox": [0.5, 0.5, 0.5, 0.8],+ "angle": 0,+ "image_base64": "stale",+ }++ analyze._attach_visual_block_images(+ [[clipped_block, invalid_block]],+ [{"img_pil": page_image}],+ )++ crop_image = _decode_jpeg_data_uri(clipped_block["image_base64"])+ try:+ assert crop_image.size == (30, 20)+ finally:+ crop_image.close()+ page_image.close()+ assert "image_base64" not in invalid_block+++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([[]], [])+++def test_replace_inline_formula_delimiters_updates_model_list_in_place() -> None:+ """验证行内公式定界符会在 model JSON 原对象上统一替换为 eq 标签。"""+ model_list = [+ [+ {"type": BlockType.TEXT, "content": "前 \\(a+b\\) 中 \\(c_d\\) 后"},+ {"type": BlockType.TEXT, "content": "已有 <eq>x</eq> 保持不变"},+ {"type": BlockType.TEXT, "content": "未闭合 \\(formula"},+ ],+ [+ {"type": BlockType.TEXT, "content": ""},+ {"type": BlockType.TEXT, "content": None},+ {"type": BlockType.TEXT, "content": ["非字符串"]},+ {"type": BlockType.TEXT, "content": "跨行 \\(a\nb\\)"},+ ],+ ]++ result = analyze._replace_inline_formula_delimiters(model_list)++ assert result is None+ assert 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 model_list[1][0]["content"] == ""+ assert model_list[1][1]["content"] is None+ assert model_list[1][2]["content"] == ["非字符串"]+ assert model_list[1][3]["content"] == "跨行 \\(a\nb\\)"+++ ("page_count", "elapsed", "expected_cost", "expected_speed"),+ [+ (3, 0.004, "cost=0.004000s", "speed=750.000 page/s"),+ (3, 0.0, "cost=0.000000s", "speed=0.000 page/s"),+ ],+)+def test_log_infer_performance_uses_unrounded_elapsed(+ monkeypatch: pytest.MonkeyPatch,+ page_count: int,+ elapsed: float,+ expected_cost: str,+ expected_speed: str,+) -> None:+ """验证性能日志使用原始耗时计算吞吐,并安全处理零耗时。"""+ debug_log = MagicMock()+ monkeypatch.setattr(analyze.logger, "debug", debug_log)++ analyze._log_infer_performance("docx", page_count, elapsed)++ message = debug_log.call_args.args[0]+ assert "file_suffix=docx" in message+ assert f"pages={page_count}" in message+ assert expected_cost in message+ assert expected_speed in message++[email protected]("file_suffix", ["docx", "pptx", "xlsx"])+def test_doc_analyze_office_returns_model_list_without_pdf_processing(+ monkeypatch: pytest.MonkeyPatch,+ file_suffix: str,+) -> None:+ """验证三类 Office 文件直接返回模型结果,且不进入任何 PDF 处理阶段。"""+ source_model_list = [[{"type": BlockType.TEXT, "content": "原始 \\(office\\) 内容"}]]+ events: list[str] = []+ model_factories: dict[str, MagicMock] = {}+ selected_model = MagicMock()++ def fake_office_predict(_file_stream: BytesIO) -> list[list[dict[str, object]]]:+ """记录 Office predict 所处的计时区间并返回固定模型结果。"""+ events.append("office_predict")+ return source_model_list++ selected_model.predict.side_effect = fake_office_predict+ for suffix in ("docx", "pptx", "xlsx"):+ model = selected_model if suffix == file_suffix else MagicMock()+ model_factories[suffix] = MagicMock(return_value=model)++ perf_counter_values = iter([10.0, 12.5])++ def fake_perf_counter() -> float:+ """返回稳定计时值并记录计时调用顺序。"""+ value = next(perf_counter_values)+ events.append(f"timer_{value}")+ return value++ pdf_document = MagicMock()+ hybrid_model_factory = MagicMock()+ window_size_reader = MagicMock()+ window_builder = MagicMock()+ image_loader = MagicMock()+ visual_image_attacher = MagicMock()+ formula_replacer = 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, "_replace_inline_formula_delimiters", formula_replacer)+ monkeypatch.setattr(analyze.time, "perf_counter", fake_perf_counter)++ middle_json, model_list = analyze.doc_analyze(+ b"office-bytes",+ effort="xhigh",+ parse_mode="ocr",+ file_suffix=file_suffix, # type: ignore[arg-type]+ )++ assert middle_json == []+ assert model_list is source_model_list+ assert model_list[0][0]["content"] == "原始 \\(office\\) 内容"+ for suffix, model_factory in model_factories.items():+ assert model_factory.call_count == (1 if suffix == file_suffix else 0)+ file_stream = selected_model.predict.call_args.args[0]+ assert isinstance(file_stream, BytesIO)+ assert file_stream.getvalue() == b"office-bytes"+ assert not file_stream.closed+ assert events == ["timer_10.0", "office_predict", "timer_12.5"]+ pdf_document.assert_not_called()+ hybrid_model_factory.assert_not_called()+ window_size_reader.assert_not_called()+ window_builder.assert_not_called()+ image_loader.assert_not_called()+ visual_image_attacher.assert_not_called()+ formula_replacer.assert_not_called()+++def test_doc_analyze_rejects_unsupported_suffix_before_resource_initialization(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """验证非法后缀会在创建 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)++ with pytest.raises(ValueError, match="Unsupported file suffix: 'PDF'"):+ analyze.doc_analyze(b"unknown", file_suffix="PDF") # type: ignore[arg-type]++ pdf_document.assert_not_called()+ for model_factory in model_factories.values():+ model_factory.assert_not_called()+++def test_pdf_infer_timer_excludes_hybrid_vlm_initialization_and_cleanup(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """验证 High PDF 的基础/VLM 初始化和资源清理位于 model_list 计时区间之外。"""+ events: list[str] = []+ fake_document = MagicMock()+ fake_document.page_count = 0++ def fake_document_close() -> None:+ """记录 PDFDocument 关闭顺序。"""+ events.append("document_close")++ fake_document.close.side_effect = fake_document_close+ hybrid_model = MagicMock()+ hybrid_model.device = "cpu"+ hybrid_singleton = MagicMock()++ def fake_hybrid_get_model() -> MagicMock:+ """记录 Hybrid 基础模型初始化顺序。"""+ events.append("hybrid_init")+ return hybrid_model++ hybrid_singleton.get_model.side_effect = fake_hybrid_get_model+ vlm_predictor = MagicMock()+ vlm_singleton = MagicMock()++ def fake_vlm_get_model(**_kwargs: object) -> MagicMock:+ """记录 VLM predictor 初始化顺序。"""+ events.append("vlm_init")+ return vlm_predictor++ vlm_singleton.get_model.side_effect = fake_vlm_get_model++ def fake_enable_serial_execution(predictor: MagicMock, _backend: str) -> MagicMock:+ """记录 VLM predictor 包装顺序并原样返回。"""+ events.append("vlm_wrap")+ return predictor++ perf_counter_values = iter([20.0, 22.0])++ def fake_perf_counter() -> float:+ """返回稳定计时值并记录计时调用顺序。"""+ value = next(perf_counter_values)+ events.append(f"timer_{value}")+ return value++ def fake_replace_formula(_model_list: list[list[dict[str, object]]]) -> None:+ """记录 PDF model_list 公式规范化顺序。"""+ events.append("formula_replace")++ def fake_clean_memory(_device: str) -> None:+ """记录设备缓存清理顺序。"""+ events.append("clean_memory")++ monkeypatch.setattr(analyze, "PDFDocument", MagicMock(return_value=fake_document))+ monkeypatch.setattr(analyze, "HybridLocalModelContextSingleton", MagicMock(return_value=hybrid_singleton))+ monkeypatch.setattr(+ analyze,+ "_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, "_replace_inline_formula_delimiters", fake_replace_formula)+ monkeypatch.setattr(analyze, "clean_memory", fake_clean_memory)++ middle_json, model_list = analyze.doc_analyze(+ b"empty-pdf",+ effort="high",+ parse_mode="txt",+ )++ assert middle_json == []+ assert model_list == []+ assert events == [+ "hybrid_init",+ "vlm_init",+ "vlm_wrap",+ "timer_20.0",+ "formula_replace",+ "timer_22.0",+ "document_close",+ "clean_memory",+ ]+++ ("file_suffix", "expected_page_count"),+ [("docx", 3), ("pptx", 6), ("xlsx", 3)],+)+def test_doc_analyze_office_real_samples(file_suffix: str, expected_page_count: int) -> None:+ """验证统一入口可直接分析三类真实 Office 样例并返回完整分页结果。"""+ sample_path = _OFFICE_SAMPLE_DIR / f"{file_suffix}_01.{file_suffix}"++ middle_json, model_list = analyze.doc_analyze(+ sample_path.read_bytes(),+ effort="high",+ parse_mode="ocr",+ file_suffix=file_suffix, # type: ignore[arg-type]+ )++ assert middle_json == []+ assert len(model_list) == expected_page_count+ assert all(isinstance(page, list) for page in model_list)+++def test_doc_analyze_flash_returns_complete_model_list_without_middle_json(monkeypatch: pytest.MonkeyPatch) -> None:+ """验证 Flash 多窗口仅补充完整 model list,并固定返回空 Middle JSON。"""+ from mineru.model import flash as flash_model++ events: list[str] = []+ source_model_list = [+ [+ {+ "type": BlockType.TEXT,+ "bbox": [0.0, 0.0, 1.0, 1.0],+ "content": "第一页 \\(x+y\\)",+ }+ ],+ [+ {+ "type": BlockType.IMAGE,+ "bbox": [0.0, 0.0, 1.0, 1.0],+ "angle": 0,+ }+ ],+ [+ {+ "type": BlockType.EQUATION,+ "bbox": [0.0, 0.0, 1.0, 1.0],+ "angle": 90,+ "content": "第三页 \\(z\\)",+ }+ ],+ ]+ fake_pdf_doc = MagicMock()+ fake_pdf_doc.page_count = len(source_model_list)+ fake_pdf_doc.__getitem__.side_effect = lambda page_idx: MagicMock(page_idx=page_idx)++ def fake_document_close() -> None:+ """记录 Flash PDF 文档关闭顺序。"""+ events.append("document_close")++ fake_pdf_doc.close.side_effect = fake_document_close+ fake_pdf_model = MagicMock()++ def fake_pdf_predict(_document: MagicMock) -> list[list[dict[str, object]]]:+ """记录 PdfModel 推理顺序并返回完整模型结果。"""+ events.append("pdf_predict")+ return source_model_list++ fake_pdf_model.predict.side_effect = fake_pdf_predict+ rendered_images: list[Image.Image] = []+ requested_ranges: list[tuple[int, int]] = []++ def fake_load_images_for_window(+ *,+ pdf_bytes: bytes,+ start_page_id: int,+ end_page_id: int,+ image_type: str,+ ) -> list[dict[str, Image.Image]]:+ """按请求范围生成测试页图,并记录窗口以验证分段与释放行为。"""+ assert pdf_bytes == b"fake-pdf"+ assert image_type == "pil_img"+ events.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)+ ]+ rendered_images.extend(window_images)+ return [{"img_pil": image} for image in window_images]++ original_attach_visual_block_images = analyze._attach_visual_block_images++ def 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_replace_formula = analyze._replace_inline_formula_delimiters++ def tracked_replace_formula(model_list: list[list[dict[str, object]]]) -> None:+ """记录 PDF 公式规范化顺序并调用真实实现。"""+ events.append("formula_replace")+ original_replace_formula(model_list) # type: ignore[arg-type]++ perf_counter_values = iter([30.0, 33.0])++ def fake_perf_counter() -> float:+ """返回稳定计时值并记录计时调用顺序。"""+ value = next(perf_counter_values)+ events.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, "_replace_inline_formula_delimiters", tracked_replace_formula)+ monkeypatch.setattr(analyze.time, "perf_counter", fake_perf_counter)+ monkeypatch.setattr(flash_model, "PdfModel", MagicMock(return_value=fake_pdf_model))++ middle_json, model_list = analyze.doc_analyze(+ b"fake-pdf",+ effort="flash",+ parse_mode="txt",+ page_index_map=[9, 8, 7],+ )++ assert middle_json == []+ assert model_list is source_model_list+ assert requested_ranges == [(0, 1), (2, 2)]+ assert model_list[0][0]["content"] == "第一页 <eq>x+y</eq>"+ assert model_list[2][0]["content"] == "第三页 <eq>z</eq>"+ assert "image_base64" not in model_list[0][0]+ for block in (model_list[1][0], model_list[2][0]):+ crop_image = _decode_jpeg_data_uri(block["image_base64"])+ crop_image.close()+ for image in rendered_images:+ with pytest.raises(ValueError, match="closed image"):+ image.getpixel((0, 0))++ fake_pdf_model.predict.assert_called_once_with(fake_pdf_doc)+ fake_pdf_doc.close.assert_called_once_with()+ assert events == [+ "timer_30.0",+ "pdf_predict",+ "render_window",+ "attach_visual",+ "render_window",+ "attach_visual",+ "formula_replace",+ "timer_33.0",+ "document_close",+ ]+ assert not hasattr(analyze, "append_pages")