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: remove support for low effort analysis and update related documentation
myhlolia343e91891b6
diff --git a/CLAUDE.md b/CLAUDE.mdindex ff7cff4a..34e41e81 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -167,7 +167,7 @@ pr-5415 重构后,Middle JSON 已收敛为 schema 2.0 的统一结构,不再| `pages` | `list[PageInfo]` | 严格按 `page_idx` 升序的页面数组 || `is_full_document` | `bool` | 是否整本文档解析(空 `page_index_map` 时为 `True`) || `file_suffix` | `Literal["pdf", "doc", "docx", "ppt", "pptx", "xls", "xlsx"]` | 输入文件类型 |-| `effort` | `Literal["flash", "low", "medium", "high", "xhigh"]` | 分析强度 |+| `effort` | `Literal["flash", "medium", "high", "xhigh"]` | 分析强度 || `parse_mode` | `Literal["txt", "ocr"]` | 解析模式 || `mineru_version` | `str` | MinerU 版本号 |diff --git a/README_en.md b/README_en.mdindex abfc95ef..682e2185 100644--- a/README_en.md+++ b/README_en.md@@ -71,7 +71,7 @@ MCP Server · LangChain / Dify / FastGPT native integration · 10+ domestic AI c| Inference Backend | Best For ||------------------|---------|-| hybrid-engine --effort low | Fast local parsing, no VLM calls, runs on CPU or GPU |+| Flash tier | Fast local parsing, no VLM calls, runs on CPU or GPU || hybrid-engine | High accuracy, native text extraction, low hallucination, supports VLM acceleration ecosystem |Domestic AI chips: Ascend · Cambricon · Enflame · MetaX · Moore Threads · Kunlunxin · Iluvatar · Hygon · Biren · T-Head@@ -325,9 +325,9 @@ If your device meets the GPU acceleration requirements in the table above, you c```bashmineru -p <input_path> -o <output_path>```-If your device does not meet the GPU acceleration requirements, you can use Hybrid low to run without VLM calls:+If your device does not meet the GPU acceleration requirements, you can explicitly use the Flash tier to run without VLM calls:```bash-mineru -p <input_path> -o <output_path> -b hybrid-engine --effort low+mineru parse "<input_path>" --tier flash -o <output_path>````mineru` currently supports local `PDF`, image, `DOCX`, `PPTX`, and `XLSX` file or directory inputs, and can be used for document parsing through the CLI, API, WebUI, and `mineru-router`. For detailed instructions, please refer to the [Usage Guide](https://opendatalab.github.io/MinerU/usage/).diff --git a/README_zh.md b/README_zh.mdindex a785c259..7d8cce2c 100644--- a/README_zh.md+++ b/README_zh.md@@ -69,7 +69,7 @@ MCP Server · LangChain / Dify / FastGPT 原生集成 · 10+ 国产算力适配| 推理后端 | 适用场景 ||--------------|-----------------------------|-| hybrid-engine --effort low | 本地快速解析,不调用 VLM,CPU / GPU 均可运行 |+| Flash tier | 本地快速解析,不调用 VLM,CPU / GPU 均可运行 || hybrid-engine| 高精度,原生文本提取,低幻觉,支持 VLM 加速生态 |国产算力:昇腾 · 寒武纪 · 燧原 · 沐曦 · 摩尔线程 · 昆仑芯 · 天数智芯 · 瀚博 · 太初元碁 · 海光 · 平头哥@@ -331,9 +331,9 @@ MinerU提供了便捷的docker部署方式,这有助于快速搭建环境并```bashmineru -p <input_path> -o <output_path>```-如果您的设备不满足GPU加速条件,可以使用 Hybrid low,以在不调用 VLM 的模式下运行:+如果您的设备不满足GPU加速条件,可以显式使用 Flash tier,以在不调用 VLM 的模式下运行:```bash-mineru -p <input_path> -o <output_path> -b hybrid-engine --effort low+mineru parse "<input_path>" --tier flash -o <output_path>```当前 `mineru` 支持本地 `PDF / 图片 / DOCX / PPTX / XLSX` 文件或目录输入,并可通过命令行、API、WebUI、`mineru-router` 等多种方式进行文档解析,具体使用方法请参考[使用指南](https://opendatalab.github.io/MinerU/zh/usage/)。diff --git a/docs/en/quick_start/index.md b/docs/en/quick_start/index.mdindex b2db63f6..462a6165 100644--- a/docs/en/quick_start/index.md+++ b/docs/en/quick_start/index.md@@ -143,9 +143,9 @@ If your device meets the GPU acceleration requirements in the table above, you c```bashmineru -p <input_path> -o <output_path>```-If your device does not meet the GPU acceleration requirements, you can use Hybrid low to run without VLM calls:+If your device does not meet the GPU acceleration requirements, you can explicitly use the Flash tier to run without VLM calls:```bash-mineru -p <input_path> -o <output_path> -b hybrid-engine --effort low+mineru parse "<input_path>" --tier flash -o <output_path>````mineru` currently supports local `PDF`, image, `DOCX`, `PPTX`, and `XLSX` file or directory inputs.diff --git a/docs/en/reference/output_files.md b/docs/en/reference/output_files.mdindex 6ba08bdb..7c476350 100644--- a/docs/en/reference/output_files.md+++ b/docs/en/reference/output_files.md@@ -117,7 +117,7 @@ The following sections provide detailed descriptions of each file's purpose and| `pages` | `list[PageInfo]` | Array of parsing results for each page, strictly increasing by `page_idx` || `is_full_document` | `bool` | Whether the input is a full document (empty `page_index_map`) || `file_suffix` | `string` | Input file type: `pdf`, `doc`, `docx`, `ppt`, `pptx`, `xls`, or `xlsx` |-| `effort` | `string` | Analysis effort: `flash`, `low`, `medium`, `high`, or `xhigh` |+| `effort` | `string` | Analysis effort: `flash`, `medium`, `high`, or `xhigh` || `parse_mode` | `string` | Parse mode: `txt` or `ocr` || `mineru_version` | `string` | MinerU version number |diff --git a/docs/next/middle-json/current-medium.md b/docs/next/middle-json/current-medium.mdindex 666338c5..a9641d82 100644--- a/docs/next/middle-json/current-medium.md+++ b/docs/next/middle-json/current-medium.md@@ -32,7 +32,7 @@| `pages` | `list[list[dict]]` | 必填,保存 Analyze 产生的 raw blocks || `page_index_map` | `list[int]` | 必填;空列表表示整本默认顺序,非空时与 pages 等长且唯一递增 || `file_suffix` | `pdf/doc/docx/ppt/pptx/xls/xlsx` | 必填 |-| `effort` | `flash/low/medium/high/xhigh` | 必填,使用分析后实际值 |+| `effort` | `flash/medium/high/xhigh` | 必填,使用公开分析档位 || `parse_mode` | `txt/ocr` | 必填,使用分析后实际值 || `mineru_version` | 非空字符串 | 必填 |@@ -51,7 +51,7 @@ MiddleJson 并执行适用的 PDF 后处理。不再提供裸 model list 加独| `pages` | `list[PageInfo]` | 必填,`page_idx` 唯一且严格递增 || `is_full_document` | `bool` | 必填,保存整本或抽页语义,不提供默认值 || `file_suffix` | `pdf/doc/docx/ppt/pptx/xls/xlsx` | 必填 |-| `effort` | `flash/low/medium/high/xhigh` | 必填 |+| `effort` | `flash/medium/high/xhigh` | 必填 || `parse_mode` | `txt/ocr` | 必填 || `mineru_version` | 非空字符串 | 必填 |diff --git a/docs/zh/quick_start/index.md b/docs/zh/quick_start/index.mdindex 8d9f8709..25869407 100644--- a/docs/zh/quick_start/index.md+++ b/docs/zh/quick_start/index.md@@ -154,9 +154,9 @@ MinerU提供了便捷的docker部署方式,这有助于快速搭建环境并```bashmineru -p <input_path> -o <output_path>```-如果您的设备不满足GPU加速条件,可以使用 Hybrid low,以在不调用 VLM 的模式下运行:+如果您的设备不满足GPU加速条件,可以显式使用 Flash tier,以在不调用 VLM 的模式下运行:```bash-mineru -p <input_path> -o <output_path> -b hybrid-engine --effort low+mineru parse "<input_path>" --tier flash -o <output_path>```当前 `mineru` 支持本地 `PDF / 图片 / DOCX / PPTX / XLSX` 文件或目录输入。diff --git a/docs/zh/reference/output_files.md b/docs/zh/reference/output_files.mdindex 96e85a6b..87f58af7 100644--- a/docs/zh/reference/output_files.md+++ b/docs/zh/reference/output_files.md@@ -117,7 +117,7 @@| `pages` | `list[PageInfo]` | 每一页的解析结果数组,按 `page_idx` 严格升序 || `is_full_document` | `bool` | 是否整本文档解析(`page_index_map` 为空时为 `True`) || `file_suffix` | `string` | 输入文件类型:`pdf`、`doc`、`docx`、`ppt`、`pptx`、`xls` 或 `xlsx` |-| `effort` | `string` | 分析强度:`flash`、`low`、`medium`、`high` 或 `xhigh` |+| `effort` | `string` | 分析强度:`flash`、`medium`、`high` 或 `xhigh` || `parse_mode` | `string` | 解析模式:`txt` 或 `ocr` || `mineru_version` | `string` | MinerU 版本号 |diff --git a/mineru/backend/analysis/contracts.py b/mineru/backend/analysis/contracts.pyindex e47e5774..dd25e9cf 100644--- a/mineru/backend/analysis/contracts.py+++ b/mineru/backend/analysis/contracts.py@@ -6,7 +6,7 @@ from __future__ import annotationsfrom dataclasses import dataclassfrom typing import Any, Literal, TypeAlias-AnalyzeEffort: TypeAlias = Literal["flash", "low", "medium", "high", "xhigh"]+AnalyzeEffort: TypeAlias = Literal["flash", "medium", "high", "xhigh"]# 请求阶段允许自动分类,分析结果中的模式必须已经收敛为 txt 或 ocr。ParseMode: TypeAlias = Literal["auto", "txt", "ocr"]ResolvedParseMode: TypeAlias = Literal["txt", "ocr"]diff --git a/mineru/backend/analysis/pdf/constants.py b/mineru/backend/analysis/pdf/constants.pyindex 3aa4d3e3..02c66b90 100644--- a/mineru/backend/analysis/pdf/constants.py+++ b/mineru/backend/analysis/pdf/constants.py@@ -135,4 +135,3 @@ NOT_EXTRACT_TYPES = {}VLM_TXT_DET_TYPE = NOT_EXTRACT_TYPESVLM_OCR_DET_TYPE = set(LINE_METADATA_BLOCK_TYPES)-_LOW_TXT_VISUAL_RUN_ANGLES = (0.0, 90.0, 180.0, 270.0)diff --git a/mineru/backend/analysis/pdf/pipeline.py b/mineru/backend/analysis/pdf/pipeline.pyindex 5acab184..8ab0e186 100644--- a/mineru/backend/analysis/pdf/pipeline.py+++ b/mineru/backend/analysis/pdf/pipeline.py@@ -5,9 +5,9 @@ from __future__ import annotationsimport osimport time-from typing import Any, Literal, cast+from typing import Any, cast-from mineru.backend.analysis.contracts import AnalysisResult, ResolvedParseMode+from mineru.backend.analysis.contracts import AnalysisResult, AnalyzeEffort, ParseMode, ResolvedParseModefrom mineru.backend.local_model_runtime import HybridLocalModelContextSingletonfrom mineru.utils.engine_utils import get_vlm_enginefrom mineru.utils.model_utils import clean_memory@@ -19,16 +19,19 @@ from .window import process_pdf_windowsos.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1"-_SUPPORTED_PDF_EFFORTS = {"flash", "low", "medium", "high", "xhigh"}+_SUPPORTED_PDF_EFFORTS = {"flash", "medium", "high", "xhigh"}def analyze_pdf(file_bytes: bytes,- effort: Literal["flash", "low", "medium", "high", "xhigh"] = "high",- parse_mode: Literal["auto", "txt", "ocr"] = "auto",+ effort: AnalyzeEffort = "high",+ parse_mode: ParseMode = "auto",image_analysis: bool = True,) -> AnalysisResult:"""生产 PDF model-list,并返回最终路由元数据和精确推理耗时。"""+ if effort not in _SUPPORTED_PDF_EFFORTS:+ raise ValueError(f"Unsupported analyze effort: {effort}")+document = PDFDocument(file_bytes)hybrid_model = Nonetry:@@ -37,13 +40,6 @@ def analyze_pdf(if parse_mode not in ["txt", "ocr"]:raise ValueError(f"parse_mode {parse_mode} is not supported")resolved_parse_mode = cast(ResolvedParseMode, parse_mode)- if effort not in _SUPPORTED_PDF_EFFORTS:- raise ValueError(f"Unsupported analyze effort: {effort}")-- # Flash 只处理原生文本,OCR 文档继续复用 Hybrid low 流程。- if effort == "flash" and resolved_parse_mode == "ocr":- effort = "low"-flash_txt_mode = effort == "flash" and resolved_parse_mode == "txt"vlm_predictor = Nonediff --git a/mineru/backend/analysis/pdf/tables.py b/mineru/backend/analysis/pdf/tables.pyindex 621a4efd..b3aa6550 100644--- a/mineru/backend/analysis/pdf/tables.py+++ b/mineru/backend/analysis/pdf/tables.py@@ -1,5 +1,5 @@# Copyright (c) Opendatalab. All rights reserved.-"""表格方向检测、Medium/Low 表格识别与文本投影。"""+"""表格方向检测、Medium 表格识别与 Flash OCR 文本投影。"""from __future__ import annotations@@ -14,23 +14,14 @@ from loguru import loggerfrom mineru.backend.local_model_runtime import HybridLocalModelContext, run_ocr_inferencefrom mineru.model.model_types import AtomicModelName-from mineru.types import RAW_FORMULA_NUMBER, BBox, BlockType, ContentType+from mineru.types import RAW_FORMULA_NUMBER, BBox, BlockTypefrom mineru.utils.bbox_utils import (calculate_overlap_area_in_bbox1_area_ratio,normalize_to_int_bbox,)-from mineru.utils.native_pdf_table import (- NativeTableInput,- NativeTableRectangle,- NativeTableRule,- coerce_native_table_rectangles,- coerce_native_table_rules,- recover_native_pdf_table,-)from mineru.utils.ocr_utils import mask_formula_regions_for_ocr_detfrom mineru.utils.pdf_document import PDFPage, get_lines_from_chars-from mineru.utils.pdf_text_styles import PDFTextLinkLine, PDFTextStyleLine-from mineru.utils.spatial_text import project_ocr_table_text, project_pdf_table_text+from mineru.utils.spatial_text import project_ocr_table_textfrom .constants import (BATCH_RATIO,@@ -39,7 +30,6 @@ from .constants import (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,@@ -54,9 +44,7 @@ from .geometry import (_sidecar_bbox_to_page_bbox,_table_bbox_center,)-from .text.models import _AnalyzeSpan-from .text.native import __replace_ligatures, __replace_unicode, _is_supported_rotation-from .text.styles import build_pdf_native_visual_lines_and_styles+from .text.native import _is_supported_rotationdef _apply_table_rotate_labels(@@ -70,48 +58,6 @@ def _apply_table_rotate_labels(table_item["layout_item"]["angle"] = int(rotate_label or "0")-def _visual_line_items_to_spans(line_items: list[Any]) -> list[_AnalyzeSpan]:- """把 Flash 视觉 run 转为 Hybrid 文本分配使用的私有 span。"""-- 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 _build_pdf_text_visual_run_data(- pdf_page: PDFPage,-) -> tuple[list[_AnalyzeSpan], list[PDFTextStyleLine], list[PDFTextLinkLine]]:- """一次构造 Low/TXT 视觉 span、文本样式和超链接证据。"""-- _page_chars, line_items, style_lines, link_lines = (- build_pdf_native_visual_lines_and_styles(- pdf_page,- supported_angles=_LOW_TXT_VISUAL_RUN_ANGLES,- )- )- return _visual_line_items_to_spans(line_items), style_lines, link_lines---def _build_pdf_text_visual_run_spans(pdf_page: PDFPage) -> list[_AnalyzeSpan]:- """将 Low/TXT 原生粗行按 Flash 字符间隙拆成可独立分配的视觉 run。"""-- page_spans, _style_lines, _link_lines = _build_pdf_text_visual_run_data(- pdf_page- )- return page_spans--def _detect_table_angle_from_pdf_lines(pdf_lines: list[dict[str, Any]],table_bbox: BBox,@@ -262,7 +208,7 @@ def _select_table_owner(item_bbox: BBox,table_entries: list[dict[str, Any]],) -> dict[str, Any] | None:- """为 low/medium 对象匹配所属表格,多表命中时选择交叠面积最大的表格。"""+ """为本地 layout 对象匹配所属表格,多表命中时选择交叠面积最大的表格。"""center_x, center_y = _table_bbox_center(item_bbox)candidates: list[tuple[float, dict[str, Any]]] = []for table_entry in table_entries:@@ -551,11 +497,11 @@ def _apply_medium_table_recognition(table_task["table_block"]["content"] = html_code-def _remove_low_table_inner_blocks(+def _remove_flash_ocr_table_inner_blocks(images_list: list[dict[str, Any]],model_list: list[list[dict[str, Any]]],) -> None:- """按表格中心点归属规则移除 low 表内图片、公式和公式编号块。"""+ """按表格中心点归属规则移除 Flash OCR 表内图片、公式和公式编号块。"""inner_block_types = {BlockType.IMAGE,BlockType.EQUATION,@@ -585,14 +531,12 @@ def _remove_low_table_inner_blocks(page_model_list[:] = retained_blocks-def _fill_low_table_contents(+def _fill_flash_ocr_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 表格回填高置信原生 HTML 或空间投影文本。"""+ """为 Flash OCR 表格回填 OCR 空间投影文本。"""table_entries: list[dict[str, Any]] = []for page_idx, page_model_list in enumerate(model_list):table_idx = 0@@ -613,101 +557,7 @@ def _fill_low_table_contents(return# 表格一旦认领内部对象便立即从 model_list 删除,后续文本回填失败也不恢复。- _remove_low_table_inner_blocks(images_list, model_list)-- if parse_mode == "txt":- page_chars_cache: dict[int, list[Any]] = {}- page_rules_cache: dict[int, tuple[NativeTableRule, ...]] = {}- page_rectangles_cache: dict[int, tuple[NativeTableRectangle, ...]] = {}- 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()- if page_idx not in page_rules_cache:- try:- page_rules_cache[page_idx] = coerce_native_table_rules(- pdf_page.get_drawing_lines()- )- except Exception as exc:- logger.warning(- "Hybrid low native table drawing extraction failed: "- f"page_idx={page_idx}, error={exc}"- )- page_rules_cache[page_idx] = ()- if page_idx not in page_rectangles_cache:- try:- page_rectangles_cache[page_idx] = (- coerce_native_table_rectangles(- pdf_page.get_path_infos()- )- )- except Exception as exc:- logger.warning(- "Hybrid low native table path extraction failed: "- f"page_idx={page_idx}, error={exc}"- )- page_rectangles_cache[page_idx] = ()-- native_result = None- try:- # PDFPage 字符和 drawing 已应用页面字典旋转;Low 的文本角度仍是- # PDF 字符内禀角,因此仅在原生结构恢复入口补回页面旋转。- native_angle = (- _normalize_visual_block_angle(- table_block.get("angle", 0)- )- + pdf_page.rotation- ) % 360- native_result = recover_native_pdf_table(- NativeTableInput(- table_bbox=table_bbox,- page_size=(float(page_width), float(page_height)),- angle=native_angle,- chars=tuple(page_chars_cache[page_idx]),- drawing_lines=page_rules_cache[page_idx],- rectangles=page_rectangles_cache[page_idx],- )- )- except Exception as exc:- logger.warning(- "Hybrid low native table recovery failed and fell back to projection: "- f"page_idx={page_idx}, table_idx={table_idx}, error={exc}"- )- if native_result is not None:- table_block["content"] = native_result.html- else:- 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}")+ _remove_flash_ocr_table_inner_blocks(images_list, model_list)try:table_ocr_model = local_model_context.get_ocr_model(@@ -718,8 +568,8 @@ def _fill_low_table_contents(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']}, "+ "Flash OCR table text failed: "+ f"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}"@@ -763,13 +613,13 @@ def _fill_low_table_contents()if not table_block["content"]:logger.warning(- "Hybrid low table text is empty: "- f"parse_mode={parse_mode}, page_idx={page_idx}, "+ "Flash OCR table text is empty: "+ f"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}, "+ "Flash OCR table text failed: "+ f"page_idx={page_idx}, "f"table_idx={table_idx}, bbox={table_block.get('bbox')}, error={exc}")diff --git a/mineru/backend/analysis/pdf/window.py b/mineru/backend/analysis/pdf/window.pyindex 01c75dbe..ccbaee18 100644--- a/mineru/backend/analysis/pdf/window.py+++ b/mineru/backend/analysis/pdf/window.py@@ -10,22 +10,19 @@ import numpy as npfrom loguru import loggerfrom mineru.backend.local_model_runtime import HybridLocalModelContext-from mineru.types import RAW_FORMULA_NUMBER, BlockTypefrom mineru.utils.config_reader import get_processing_window_sizefrom mineru.utils.pdf_document import PDFDocument, PDFPagefrom mineru.utils.pdf_image_tools import load_images_from_pdf_bytes_range-from mineru.utils.pdf_text_styles import apply_pdf_text_links, apply_pdf_text_styles-from mineru.utils.spatial_text import project_pdf_spatial_text+from ..contracts import AnalyzeEffortfrom .constants import (BATCH_RATIO,LAYOUT_BASE_BATCH_SIZE,MFR_BASE_BATCH_SIZE,NOT_EXTRACT_TYPES,PIPELINE_DET_TYPE,- TITLE_BLOCK_TYPES,)-from .geometry import _bbox_to_pixel_bbox, _normalize_page_size+from .geometry import _normalize_page_sizefrom .layout import (_build_vl_style_layout_blocks,_collect_table_items,@@ -48,18 +45,15 @@ from .ocr import ()from .tables import (_apply_medium_table_recognition,- _build_pdf_text_visual_run_data,- _fill_low_table_contents,_apply_table_orientations,+ _fill_flash_ocr_table_contents,)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,)@@ -125,60 +119,14 @@ def _close_images(images_list: list[dict[str, Any]]) -> None:pass-def _fill_low_txt_native_formula_contents(- pdf_pages: list[PDFPage],- model_list: list[list[dict[str, Any]]],-) -> None:- """按 Low layout 公式框从 PDF 字符层独立回填公式正文和编号。"""- if len(pdf_pages) != len(model_list):- raise ValueError(- "Low TXT native formula page count mismatch: "- f"pdf_pages={len(pdf_pages)}, model_list={len(model_list)}"- )-- target_block_types = {BlockType.EQUATION, RAW_FORMULA_NUMBER}- for pdf_page, page_model_list in zip(pdf_pages, model_list):- page_size = tuple(float(value) for value in pdf_page.size)- pending_blocks: list[tuple[dict[str, Any], tuple[float, float, float, float]]] = []- for block_item in page_model_list:- if block_item.get("type") not in target_block_types:- continue- block_content = block_item.get("content")- has_nonempty_content = (- bool(block_content.strip())- if isinstance(block_content, str)- else bool(block_content)- )- if has_nonempty_content:- continue- block_bbox = _bbox_to_pixel_bbox(block_item.get("bbox"), page_size)- if block_bbox is not None:- pending_blocks.append((block_item, block_bbox))-- if not pending_blocks:- continue-- page_chars = pdf_page.get_chars()- for block_item, block_bbox in pending_blocks:- native_content = project_pdf_spatial_text(- page_chars,- block_bbox,- block_item.get("angle", 0),- preserve_blank_rows=False,- ).strip()- if native_content:- block_item["content"] = native_content---def _process_low_text(+def _process_flash_ocr(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 填充文本内容。"""+ """使用本地 OCR 为 Flash layout block 填充正文和表格内容。"""_validate_text_formula_window_inputs(images_list,pdf_pages,@@ -186,69 +134,33 @@ def _process_low_text(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)- page_spans, style_lines, link_lines = _build_pdf_text_visual_run_data(- pdf_page- )- block_lines = _group_page_spans_by_block(- page_model_list,- page_spans,- page_size,- target_block_types,- )- _apply_block_content_and_line_metadata(- page_model_list,- block_lines,- page_size,- )- apply_pdf_text_links(- page_model_list,- link_lines,- page_size,- )- apply_pdf_text_styles(- page_model_list,- style_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_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,- parse_mode,+ empty_formula_list,+ ocr_res_list,+ "ocr",+ PIPELINE_DET_TYPE,+ local_model_context,+ )+ _fill_flash_ocr_table_contents(+ images_list,+ model_list,local_model_context,)- if parse_mode == "txt":- _fill_low_txt_native_formula_contents(pdf_pages, model_list)return model_list@@ -351,7 +263,7 @@ def process_pdf_windows(file_bytes: bytes,document: PDFDocument,*,- effort: Literal["flash", "low", "medium", "high", "xhigh"],+ effort: AnalyzeEffort,parse_mode: Literal["txt", "ocr"],image_analysis: bool,flash_txt_mode: bool,@@ -389,13 +301,16 @@ def process_pdf_windows(# Flash 仅切割当前窗口的外层列表,用于页图释放前原地补充视觉块裁图。window_model_list = model_list[window.start : window.end + 1]else:+ local_model_context = hybrid_model+ if local_model_context is None:+ raise ValueError("Hybrid local model context is required outside Flash TXT mode")np_images = [np.asarray(pil_image).copy() for pil_image in images_pil_list]- images_layout_res = hybrid_model.layout_model.batch_predict(+ images_layout_res = local_model_context.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"]:+ if effort in ["flash", "medium", "high"]:table_items = _collect_table_items(images_layout_res, np_images)if table_items:_apply_table_orientations(@@ -403,13 +318,13 @@ def process_pdf_windows(parse_mode,window_pages,images_list,- hybrid_model,+ local_model_context,)vl_style_layout_blocks = _build_vl_style_layout_blocks(images_layout_res, images_pil_list)if parse_mode == "txt":- if effort in ["low", "medium"]:+ if effort == "medium":window_model_list = vl_style_layout_blockselif effort == "high":window_model_list = vlm_predictor.batch_extract_with_layout(@@ -427,7 +342,7 @@ def process_pdf_windows(else:raise ValueError(f"Unsupported analyze effort: {effort}")elif parse_mode == "ocr":- if effort in ["low", "medium"]:+ if effort in ["flash", "medium"]:window_model_list = vl_style_layout_blockselif effort == "high":window_model_list = vlm_predictor.batch_extract_with_layout(@@ -455,16 +370,15 @@ def process_pdf_windows([_normalize_page_size(image) for image in images_pil_list],)- if effort == "low":- window_model_list = _process_low_text(+ if effort == "flash":+ window_model_list = _process_flash_ocr(images_list,window_pages,window_model_list,- parse_mode,- hybrid_model,+ local_model_context,images_layout_res,)- # low 在表内对象清理后复用统一公式编号合并,确保视觉裁图包含编号区域。+ # Flash OCR 在表内对象清理后复用统一公式编号合并,确保视觉裁图包含编号区域。for page_model_list in window_model_list:page_model_list[:] = optimize_hybrid_formula_number_blocks(page_model_list)else:@@ -474,12 +388,12 @@ def process_pdf_windows(window_model_list,parse_mode,effort,- hybrid_model,+ local_model_context,images_layout_res,)if effort in {"medium", "high"}:- _apply_seal_ocr(hybrid_model, window_model_list, np_images)+ _apply_seal_ocr(local_model_context, window_model_list, np_images)elif effort == "xhigh":_supplement_missing_image_block_containers(window_model_list,diff --git a/mineru/backend/analyze.py b/mineru/backend/analyze.pyindex b243b479..da2714c1 100644--- a/mineru/backend/analyze.py+++ b/mineru/backend/analyze.py@@ -17,6 +17,7 @@ from mineru.types import MiddleJson, ModelJsonfrom mineru.version import __version__ as mineru_version_SUPPORTED_FILE_SUFFIXES = {"pdf", "doc", "docx", "ppt", "pptx", "xls", "xlsx"}+_SUPPORTED_ANALYZE_EFFORTS = {"flash", "medium", "high", "xhigh"}def _log_infer_performance(file_suffix: str, page_count: int, elapsed: float) -> None:@@ -30,8 +31,8 @@ def _log_infer_performance(file_suffix: str, page_count: int, elapsed: float) ->def doc_analyze(file_bytes: bytes,- effort: Literal["flash", "low", "medium", "high", "xhigh"] = "high",- parse_mode: Literal["auto", "txt", "ocr"] = "auto",+ effort: AnalyzeEffort = "high",+ parse_mode: ParseMode = "auto",image_analysis: bool = True,page_index_map: list[int] | None = None,file_suffix: Literal["pdf", "doc", "docx", "ppt", "pptx", "xls", "xlsx"] = "pdf",@@ -39,12 +40,14 @@ def doc_analyze("""生产严格 ModelJson,并在统一边界构造严格 MiddleJson。"""if file_suffix not in _SUPPORTED_FILE_SUFFIXES:raise ValueError(f"Unsupported file suffix: {file_suffix!r}")+ if effort not in _SUPPORTED_ANALYZE_EFFORTS:+ raise ValueError(f"Unsupported analyze effort: {effort}")if file_suffix == "pdf":result = analyze_pdf(file_bytes,- effort=cast(AnalyzeEffort, effort),- parse_mode=cast(ParseMode, parse_mode),+ effort=effort,+ parse_mode=parse_mode,image_analysis=image_analysis,)else:@@ -68,8 +71,8 @@ def doc_analyze(async def aio_doc_analyze(file_bytes: bytes,- effort: Literal["flash", "low", "medium", "high", "xhigh"] = "high",- parse_mode: Literal["auto", "txt", "ocr"] = "auto",+ effort: AnalyzeEffort = "high",+ parse_mode: ParseMode = "auto",image_analysis: bool = True,page_index_map: list[int] | None = None,file_suffix: Literal["pdf", "doc", "docx", "ppt", "pptx", "xls", "xlsx"] = "pdf",diff --git a/mineru/parser/base.py b/mineru/parser/base.pyindex d620332a..46d93e16 100644--- a/mineru/parser/base.py+++ b/mineru/parser/base.py@@ -19,7 +19,7 @@ from ..utils.pdf_document import PDFDocumentMIDDLE_JSON_SCHEMA_VERSION: str = "2.0"_LEGACY_SCHEMA_VERSION: str = "1.0"_LEGACY_DEFAULT_FILE_SUFFIX: Literal["pdf", "doc", "docx", "ppt", "pptx", "xls", "xlsx"] = "pdf"-_LEGACY_DEFAULT_EFFORT: Literal["flash", "low", "medium", "high", "xhigh"] = "medium"+_LEGACY_DEFAULT_EFFORT: Literal["flash", "medium", "high", "xhigh"] = "medium"_LEGACY_DEFAULT_PARSE_MODE: Literal["txt", "ocr"] = "txt"_PDF_RETAINED_PAGE_INDICES_KEY = "_pdf_retained_page_indices"_PDF_BROKEN_PAGE_INDICES_KEY = "_pdf_broken_page_indices"diff --git a/mineru/parser/mineru_parser.py b/mineru/parser/mineru_parser.pyindex 75d0e775..c03eb125 100644--- a/mineru/parser/mineru_parser.py+++ b/mineru/parser/mineru_parser.py@@ -18,7 +18,7 @@ from .base import DocumentParser, ParseResultlogger = logging.getLogger(__name__)-_Effort = Literal["flash", "low", "medium", "high", "xhigh"]+_Effort = Literal["flash", "medium", "high", "xhigh"]_ParseMode = Literal["auto", "txt", "ocr"]_FileSuffix = Literal["pdf", "doc", "docx", "ppt", "pptx", "xls", "xlsx"]_SUPPORTED_SUFFIXES: frozenset[str] = frozenset({"pdf", "doc", "docx", "ppt", "pptx", "xls", "xlsx"})diff --git a/mineru/types.py b/mineru/types.pyindex c0e46fb2..20a593a7 100644--- a/mineru/types.py+++ b/mineru/types.py@@ -743,7 +743,7 @@ class ModelJson(_StrictMiddleModel):pages: list[list[dict[str, Any]]]page_index_map: list[int]file_suffix: Literal["pdf", "doc", "docx", "ppt", "pptx", "xls", "xlsx"]- effort: Literal["flash", "low", "medium", "high", "xhigh"]+ effort: Literal["flash", "medium", "high", "xhigh"]parse_mode: Literal["txt", "ocr"]mineru_version: str = Field(min_length=1)@@ -809,7 +809,7 @@ class MiddleJson(_StrictMiddleModel):pages: list[PageInfo]is_full_document: boolfile_suffix: Literal["pdf", "doc", "docx", "ppt", "pptx", "xls", "xlsx"]- effort: Literal["flash", "low", "medium", "high", "xhigh"]+ effort: Literal["flash", "medium", "high", "xhigh"]parse_mode: Literal["txt", "ocr"]mineru_version: str = Field(min_length=1)diff --git a/tests/fixtures/evaluate_native_pdf_table_manifest.py b/tests/fixtures/evaluate_native_pdf_table_manifest.pyindex 76eced9f..58183582 100644--- a/tests/fixtures/evaluate_native_pdf_table_manifest.py+++ b/tests/fixtures/evaluate_native_pdf_table_manifest.py@@ -81,8 +81,8 @@ def _evaluate_entry(point_bbox = tuple(float(value) for value in entry["bbox_points"])else:bbox = entry["bbox"]- # Low TXT 使用整数化 PDFPage 尺寸还原归一化 layout bbox;评测必须复现- # 同一生产坐标边界,避免亚点级外缘生成幽灵轨道。+ # layout bbox 使用整数化 PDFPage 尺寸还原;评测必须复现同一生产坐标边界,+ # 避免亚点级外缘生成幽灵轨道。production_page_size = (int(page_size[0]), int(page_size[1]))point_bbox = tuple(bbox[index] * (production_page_size[0] if index % 2 == 0 else production_page_size[1]) for index in range(4)diff --git a/tests/unittest/test_model_json.py b/tests/unittest/test_model_json.pyindex fa8dc92e..ab856ec6 100644--- a/tests/unittest/test_model_json.py+++ b/tests/unittest/test_model_json.py@@ -121,6 +121,33 @@ def test_model_json_requires_page_index_map_and_forbids_extra_fields() -> None:ModelJson.model_validate({**payload, "page_index_map": [], "unexpected": True})+def test_strict_document_models_reject_removed_low_effort() -> None:+ """验证 ModelJson 与 MiddleJson 的 schema 2.0 均不再接受 Low effort。"""+ with pytest.raises(ValidationError, match="literal_error"):+ ModelJson.model_validate(+ {+ "pages": [],+ "page_index_map": [],+ "file_suffix": "pdf",+ "effort": "low",+ "parse_mode": "ocr",+ "mineru_version": "3.4.0",+ }+ )++ with pytest.raises(ValidationError, match="literal_error"):+ MiddleJson.model_validate(+ {+ "pages": [],+ "is_full_document": True,+ "file_suffix": "pdf",+ "effort": "low",+ "parse_mode": "ocr",+ "mineru_version": "3.4.0",+ }+ )++def test_middle_json_requires_and_serializes_full_document_flag() -> None:"""验证 MiddleJson 将整本语义作为必填字段稳定序列化并往返。"""middle_json = MiddleJson(diff --git a/tests/unittest/test_native_pdf_table_pipeline.py b/tests/unittest/test_native_pdf_table_pipeline.pyindex 49b4e518..9edcd5f8 100644--- a/tests/unittest/test_native_pdf_table_pipeline.py+++ b/tests/unittest/test_native_pdf_table_pipeline.py@@ -1,5 +1,5 @@# Copyright (c) Opendatalab. All rights reserved.-"""验证 Native PDF 表格结构恢复在 Flash/Low pipeline 中的采用与回退。"""+"""验证 Native PDF 表格结构恢复和 Flash OCR 表格投影。"""from __future__ import annotations@@ -9,24 +9,10 @@ from unittest.mock import MagicMockimport pytestfrom PIL import Image-from mineru.backend.analysis.pdf import tables as low_tables+from mineru.backend.analysis.pdf import tables as pdf_tablesfrom mineru.model.flash.native_pdf import models as flash_modelsfrom mineru.model.flash.native_pdf import tables as flash_tablesfrom mineru.types import BlockType-from mineru.utils.native_pdf_table import NativeTableResult---def _native_result(html: str) -> NativeTableResult:- """构造 pipeline 采用分支需要的最小原生结构结果。"""-- return NativeTableResult(- html=html,- rows=2,- cols=2,- cells=(),- source="vector_grid",- confidence=1.0,- )def test_flash_materialization_prefers_native_html_and_keeps_claims(@@ -73,138 +59,24 @@ def test_flash_materialization_prefers_native_html_and_keeps_claims(projection.assert_not_called()-def test_low_txt_prefers_native_html_and_caches_page_primitives(+def test_flash_ocr_projects_table_text(monkeypatch: pytest.MonkeyPatch,) -> None:- """验证 Low TXT 采用原生 HTML,并按页只读取一次字符、drawing 和 Path。"""+ """验证 Flash OCR 保持现有 OCR 空间投影路径。"""- html = "<table><tbody><tr><td>A</td><td>B</td></tr></tbody></table>"- recover = MagicMock(return_value=_native_result(html))- projection = MagicMock(return_value="fallback")- monkeypatch.setattr(low_tables, "recover_native_pdf_table", recover)- monkeypatch.setattr(low_tables, "project_pdf_table_text", projection)- pdf_page = MagicMock()- pdf_page.size = (100.0, 100.0)- pdf_page.rotation = 0- pdf_page.get_chars.return_value = []- pdf_page.get_drawing_lines.return_value = []- pdf_page.get_path_infos.return_value = []- model_list = [- [- {"type": BlockType.TABLE, "bbox": [0.1, 0.1, 0.9, 0.9], "angle": 0},- {"type": BlockType.TABLE, "bbox": [0.2, 0.2, 0.8, 0.8], "angle": 0},- ]- ]- image = Image.new("RGB", (100, 100), "white")- try:- low_tables._fill_low_table_contents(- [{"img_pil": image}],- [pdf_page],- model_list,- "txt",- MagicMock(),- )- finally:- image.close()-- assert [block["content"] for block in model_list[0]] == [html, html]- assert all("cell_merge" not in block for block in model_list[0])- assert recover.call_count == 2- projection.assert_not_called()- pdf_page.get_chars.assert_called_once_with()- pdf_page.get_drawing_lines.assert_called_once_with()- pdf_page.get_path_infos.assert_called_once_with()---def test_low_txt_rejection_keeps_existing_projection(- monkeypatch: pytest.MonkeyPatch,-) -> None:- """验证 Low TXT 原生候选主动放弃后仍逐字采用旧空间投影。"""-- monkeypatch.setattr(low_tables, "recover_native_pdf_table", MagicMock(return_value=None))- projection = MagicMock(return_value="A B")- monkeypatch.setattr(low_tables, "project_pdf_table_text", projection)- pdf_page = MagicMock()- pdf_page.size = (100.0, 100.0)- pdf_page.rotation = 0- pdf_page.get_chars.return_value = []- pdf_page.get_drawing_lines.return_value = []- pdf_page.get_path_infos.return_value = []- model_list = [[{"type": BlockType.TABLE, "bbox": [0.1, 0.1, 0.9, 0.9]}]]- image = Image.new("RGB", (100, 100), "white")- try:- low_tables._fill_low_table_contents(- [{"img_pil": image}],- [pdf_page],- model_list,- "txt",- MagicMock(),- )- finally:- image.close()-- assert model_list[0][0]["content"] == "A B"- projection.assert_called_once()---def test_low_ocr_never_invokes_native_structure_recovery(- monkeypatch: pytest.MonkeyPatch,-) -> None:- """验证 Low OCR 保持现有 OCR 空间投影路径且不调用原生结构器。"""-- recover = MagicMock(side_effect=AssertionError("native recovery must not run"))- monkeypatch.setattr(low_tables, "recover_native_pdf_table", recover)- monkeypatch.setattr(low_tables, "run_ocr_inference", MagicMock(return_value=[[]]))- monkeypatch.setattr(low_tables, "project_ocr_table_text", MagicMock(return_value="OCR TABLE"))+ monkeypatch.setattr(pdf_tables, "run_ocr_inference", MagicMock(return_value=[[]]))+ monkeypatch.setattr(pdf_tables, "project_ocr_table_text", MagicMock(return_value="OCR TABLE"))context = MagicMock()context.get_ocr_model.return_value = SimpleNamespace(ocr=object())model_list = [[{"type": BlockType.TABLE, "bbox": [0.1, 0.1, 0.9, 0.9]}]]image = Image.new("RGB", (100, 100), "white")try:- low_tables._fill_low_table_contents(+ pdf_tables._fill_flash_ocr_table_contents([{"img_pil": image}],- [MagicMock()],model_list,- "ocr",context,)finally:image.close()- recover.assert_not_called()assert model_list[0][0]["content"] == "OCR TABLE"---def test_low_txt_compensates_pdf_page_dictionary_rotation(- monkeypatch: pytest.MonkeyPatch,-) -> None:- """验证 Low 原生结构器使用视觉角度而不改变表块原始角度字段。"""-- recover = MagicMock(return_value=_native_result("<table></table>"))- monkeypatch.setattr(low_tables, "recover_native_pdf_table", recover)- pdf_page = MagicMock()- pdf_page.size = (100.0, 80.0)- pdf_page.rotation = 90- pdf_page.get_chars.return_value = []- pdf_page.get_drawing_lines.return_value = []- pdf_page.get_path_infos.return_value = []- table_block = {- "type": BlockType.TABLE,- "bbox": [0.1, 0.1, 0.9, 0.9],- "angle": 270,- }- image = Image.new("RGB", (100, 80), "white")- try:- low_tables._fill_low_table_contents(- [{"img_pil": image}],- [pdf_page],- [[table_block]],- "txt",- MagicMock(),- )- finally:- image.close()-- native_input = recover.call_args.args[0]- assert native_input.angle == 0- assert table_block["angle"] == 270diff --git a/tests/unittest/test_parse_result_contract.py b/tests/unittest/test_parse_result_contract.pyindex c60c77af..f9c260ea 100644--- a/tests/unittest/test_parse_result_contract.py+++ b/tests/unittest/test_parse_result_contract.py@@ -3,6 +3,7 @@ from dataclasses import fieldsimport jsonimport pytest+from pydantic import ValidationErrorfrom mineru.parser.base import ParseResultfrom mineru.parser import MIDDLE_JSON_SCHEMA_VERSION@@ -86,7 +87,16 @@ def test_parse_result_from_dict_restores_pages() -> None:def test_parse_result_to_dict_includes_schema_version_without_meta() -> None:- result = ParseResult(middle_json=MiddleJson(pages=[PageInfo(page_idx=0)], is_full_document=True, file_suffix="pdf", effort="medium", parse_mode="txt", mineru_version=__version__))+ result = ParseResult(+ middle_json=MiddleJson(+ pages=[PageInfo(page_idx=0)],+ is_full_document=True,+ file_suffix="pdf",+ effort="medium",+ parse_mode="txt",+ mineru_version=__version__,+ )+ )payload = result.to_dict()@@ -95,6 +105,22 @@ def test_parse_result_to_dict_includes_schema_version_without_meta() -> None:assert "_meta" not in payload+def test_parse_result_rejects_schema_v2_low_effort() -> None:+ """验证 schema 版本保持 2.0 时,旧 Low effort 载荷仍按新严格枚举失败。"""+ with pytest.raises(ValidationError, match="literal_error"):+ ParseResult.from_dict(+ {+ "schema_version": MIDDLE_JSON_SCHEMA_VERSION,+ "pages": [],+ "is_full_document": True,+ "file_suffix": "pdf",+ "effort": "low",+ "parse_mode": "ocr",+ "mineru_version": __version__,+ }+ )++def test_parse_result_from_dict_rejects_missing_pages() -> None:with pytest.raises(ValueError, match="pages"):ParseResult.from_dict({"pdf_info": []})@@ -132,7 +158,17 @@ def test_parse_result_from_json_restores_pages() -> None:def test_parse_result_export_pages_returns_defensive_copy_from_cache() -> None:img_bytes = b"defensive-table-image"page, image_cache, inline_image = _table_page_with_cached_inline_image(img_bytes)- result = ParseResult(middle_json=MiddleJson(pages=[page], is_full_document=True, file_suffix="pdf", effort="medium", parse_mode="txt", mineru_version=__version__), _image_cache=image_cache)+ result = ParseResult(+ middle_json=MiddleJson(+ pages=[page],+ is_full_document=True,+ file_suffix="pdf",+ effort="medium",+ parse_mode="txt",+ mineru_version=__version__,+ ),+ _image_cache=image_cache,+ )first_export = result.export_pages()first_export[0].blocks[0].content[0].content = "mutated by caller"@@ -151,7 +187,17 @@ def test_parse_result_export_rewrites_inline_table_base64_images() -> None:img_bytes = b"table-image"page, image_cache, inline_image = _table_page_with_cached_inline_image(img_bytes)- result = ParseResult(middle_json=MiddleJson(pages=[page], is_full_document=True, file_suffix="pdf", effort="medium", parse_mode="txt", mineru_version=__version__), _image_cache=image_cache)+ result = ParseResult(+ middle_json=MiddleJson(+ pages=[page],+ is_full_document=True,+ file_suffix="pdf",+ effort="medium",+ parse_mode="txt",+ mineru_version=__version__,+ ),+ _image_cache=image_cache,+ )images = result.images()exported_page = result.export_pages()[0]exported_body = exported_page.blocks[0].content[0]diff --git a/tests/unittest/test_pdf_analyze_block_content.py b/tests/unittest/test_pdf_analyze_block_content.pyindex c6fb516f..5ae182d0 100644--- a/tests/unittest/test_pdf_analyze_block_content.py+++ b/tests/unittest/test_pdf_analyze_block_content.py@@ -1,6 +1,5 @@from __future__ import annotations-from pathlib import Pathfrom unittest.mock import MagicMockimport numpy as np@@ -10,26 +9,15 @@ from mineru_vl_utils.structs import ContentBlock as VlmContentBlockfrom mineru_vl_utils.structs import ExtractResultfrom mineru.backend import analyze-from mineru.backend.analysis.pdf import constants, formulas, layout, normalization, ocr, pipeline, tables, window+from mineru.backend.analysis.pdf import constants, layout, normalization, ocr, pipeline, windowfrom mineru.backend.analysis.pdf.text import content as text_content-from mineru.backend.analysis.pdf.text import styles as text_stylesfrom mineru.backend.analysis.pdf.text.models import _AnalyzeLine, _AnalyzeSpan-from mineru.types import RAW_ALGORITHM, RAW_CAPTION, RAW_FOOTNOTE, RAW_FORMULA_NUMBER+from mineru.types import RAW_ALGORITHM, RAW_CAPTION, RAW_FOOTNOTEfrom mineru.backend.analysis.pdf.text.native import (POST_OCR_FALLBACK_CONTENT_KEY,POST_OCR_FALLBACK_SCORE_KEY,)-from mineru.model.flash import PdfModel-from mineru.render._internal.common.inline import (- inline_plain_text,- parse_inline_content,-)from mineru.types import BlockType, ContentType, MiddleJson, ModelJson-from mineru.utils.pdf_document import PDFDocument---_PROJECT_ROOT = Path(__file__).resolve().parents[2]-_SYNTHETIC_CJK_PDF_PATH = _PROJECT_ROOT / "tests" / "unittest" / "pdfs" / "native_cjk_layout_synthetic.pdf"def _build_text_lines(*contents: str) -> list[_AnalyzeLine]:@@ -592,188 +580,53 @@ def test_existing_index_content_is_not_overwritten() -> None:assert "lines" not in block-def test_low_txt_visual_runs_split_distant_text_before_layout_matching(+def test_process_flash_ocr_runs_detection_recognition_content_and_tables(monkeypatch: pytest.MonkeyPatch,) -> None:- """验证 Low/TXT 在版面匹配前按 Flash 字符间隙拆开同一粗行。"""-- chars = [- {"char": "L", "bbox": (5.0, 10.0, 9.0, 20.0)},- {"char": "e", "bbox": (9.0, 10.0, 13.0, 20.0)},- {"char": "f", "bbox": (13.0, 10.0, 17.0, 20.0)},- {"char": "t", "bbox": (17.0, 10.0, 21.0, 20.0)},- {"char": " ", "bbox": (21.0, 10.0, 25.0, 20.0)},- {"char": "R", "bbox": (70.0, 10.0, 74.0, 20.0)},- {"char": "i", "bbox": (74.0, 10.0, 78.0, 20.0)},- {"char": "g", "bbox": (78.0, 10.0, 82.0, 20.0)},- {"char": "h", "bbox": (82.0, 10.0, 86.0, 20.0)},- {"char": "t", "bbox": (86.0, 10.0, 90.0, 20.0)},- ]- pdf_lines = [- {- "bbox": (5.0, 10.0, 90.0, 20.0),- "rotation": 0.0,- "spans": [- {- "text": "Left Right",- "bbox": (5.0, 10.0, 90.0, 20.0),- "rotation": 0.0,- "chars": chars,- }- ],- }- ]- pdf_page = MagicMock()- pdf_page.size = (100.0, 100.0)- pdf_page.rotation = 0- pdf_page.get_chars.return_value = []- pdf_page.get_drawing_lines.return_value = []- monkeypatch.setattr(text_styles, "get_lines_from_chars", lambda _chars: pdf_lines)-- 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)),- ("Right", (70.0, 10.0, 90.0, 20.0)),- ]---def test_low_txt_native_formula_contents_extract_body_and_number_independently() -> None:- """验证 Low/TXT 按独立 layout 框提取多行公式和编号,再复用统一合并逻辑。"""- chars = []- char_idx = 0- for text, top, left in (("x=1", 12.0, 12.0), ("y=2", 28.0, 12.0), ("(1)", 20.0, 76.0)):- for offset, char in enumerate(text):- chars.append(- {- "char": char,- "bbox": (- left + offset * 4.0,- top,- left + (offset + 1) * 4.0,- top + 8.0,- ),- "char_idx": char_idx,- }- )- char_idx += 1-- pdf_page = MagicMock(size=(100.0, 100.0))- pdf_page.get_chars.return_value = chars- model_list = [- [- {- "type": BlockType.EQUATION,- "bbox": [0.1, 0.1, 0.6, 0.4],- "angle": 0,- },- {- "type": RAW_FORMULA_NUMBER,- "bbox": [0.74, 0.18, 0.9, 0.3],- "angle": 0,- },- ]- ]-- window._fill_low_txt_native_formula_contents([pdf_page], model_list)-- pdf_page.get_chars.assert_called_once_with()- assert model_list[0][0]["content"] == "x=1\ny=2"- assert model_list[0][1]["content"] == "(1)"-- optimized = formulas.optimize_hybrid_formula_number_blocks(model_list[0])-- assert optimized == [- {- "type": BlockType.EQUATION,- "bbox": [0.1, 0.1, 0.9, 0.4],- "angle": 0,- "content": "x=1\ny=2\\tag{1}",- }- ]---def test_low_txt_native_formula_contents_preserve_existing_and_skip_invalid_or_empty() -> None:- """验证已有公式内容不覆盖,无效框或空字符区域不会写入伪内容。"""- pdf_page = MagicMock(size=(100.0, 100.0))- pdf_page.get_chars.return_value = [- {- "char": "X",- "bbox": (12.0, 12.0, 20.0, 20.0),- "char_idx": 0,- }- ]- model_list = [- [- {- "type": BlockType.EQUATION,- "bbox": [0.1, 0.1, 0.3, 0.3],- "content": "existing",- },- {- "type": RAW_FORMULA_NUMBER,- "bbox": [0.8, 0.2, 0.7, 0.3],- },- {- "type": BlockType.EQUATION,- "bbox": [0.6, 0.6, 0.8, 0.8],- },- ]- ]-- window._fill_low_txt_native_formula_contents([pdf_page], model_list)-- pdf_page.get_chars.assert_called_once_with()- assert model_list[0][0]["content"] == "existing"- assert "content" not in model_list[0][1]- assert "content" not in model_list[0][2]---def test_process_low_txt_fills_native_formulas_after_table_cleanup(- monkeypatch: pytest.MonkeyPatch,-) -> None:- """验证 Low/TXT 先清理表内公式,再只为剩余 layout 公式回填原生内容。"""+ """验证 Flash OCR 依次执行检测、识别、正文回填和表格投影。"""events: list[str] = []- pdf_page = MagicMock(size=(100.0, 100.0))- model_list = [[{"type": BlockType.EQUATION, "bbox": [0.1, 0.1, 0.5, 0.2]}]]-- monkeypatch.setattr(- window,- "_build_pdf_text_visual_run_data",- lambda _page: ([], [], []),- )-- def fake_fill_low_table_contents(*_args: object) -> None:- """模拟表格阶段认领并清理当前公式。"""- events.append("fill_tables")- model_list[0].clear()-- def fake_fill_native_formulas(- _pdf_pages: object,- current_model_list: list[list[dict[str, object]]],- ) -> None:- """确认原生公式回填收到的是表格清理后的块列表。"""- events.append("fill_formulas")- assert current_model_list == [[]]+ image = Image.new("RGB", (10, 10), "white")+ images_list = [{"img_pil": image, "scale": 1.0}]+ pdf_pages = [MagicMock(size=(10.0, 10.0))]+ model_list = [[{"type": BlockType.TEXT, "bbox": [0.1, 0.1, 0.9, 0.9]}]]+ ocr_res_list = [[{"text": "Flash OCR"}]]+ local_model_context = MagicMock()+ validate_inputs = MagicMock(side_effect=lambda *_args: events.append("validate"))+ ocr_det = MagicMock(side_effect=lambda *_args: events.append("det") or ocr_res_list)+ apply_ocr_rec = MagicMock(side_effect=lambda *_args: events.append("rec"))+ fill_content = MagicMock(side_effect=lambda *_args: events.append("content") or model_list)+ fill_tables = MagicMock(side_effect=lambda *_args: events.append("tables"))+ monkeypatch.setattr(window, "_validate_text_formula_window_inputs", validate_inputs)+ monkeypatch.setattr(window, "_ocr_det", ocr_det)+ monkeypatch.setattr(window, "_apply_ocr_rec_results", apply_ocr_rec)+ monkeypatch.setattr(window, "_fill_window_block_content_and_lines", fill_content)+ monkeypatch.setattr(window, "_fill_flash_ocr_table_contents", fill_tables)- monkeypatch.setattr(window, "_fill_low_table_contents", fake_fill_low_table_contents)- monkeypatch.setattr(window, "_fill_low_txt_native_formula_contents", fake_fill_native_formulas)+ try:+ result = window._process_flash_ocr(+ images_list,+ pdf_pages,+ model_list,+ local_model_context,+ [[]],+ )+ finally:+ image.close()- result = window._process_low_text(- [{"img_pil": object(), "scale": 1.0}],- [pdf_page],+ assert result is model_list+ assert events == ["validate", "det", "rec", "content", "tables"]+ assert ocr_det.call_args.args[4] is True+ assert ocr_det.call_args.args[5] == constants.PIPELINE_DET_TYPE+ assert fill_content.call_args.args[5] == "ocr"+ fill_tables.assert_called_once_with(+ images_list,model_list,- "txt",- MagicMock(),- [[]],+ local_model_context,)- assert result == [[]]- assert events == ["fill_tables", "fill_formulas"]-def test_existing_text_content_is_preserved_while_lines_are_refreshed() -> None:- """验证 Low/TXT 只补空正文,已有 VLM 内容不覆盖但仍写入真实行框。"""+ """验证文本回填只补空正文,已有内容不覆盖但仍写入真实行框。"""block = {"type": BlockType.TEXT, "content": "existing content"}@@ -785,45 +638,3 @@ def test_existing_text_content_is_preserved_while_lines_are_refreshed() -> None:assert block["content"] == "existing content"assert block["lines"] == [{"bbox": [0.0, 0.0, 0.5, 0.01]}]---def test_synthetic_cjk_low_visual_runs_keep_index_line_structure() -> None:- """验证 Low/TXT 的 Flash visual run 拆分不会破坏合成 PDF 的 24 行目录。"""-- document = PDFDocument(_SYNTHETIC_CJK_PDF_PATH.read_bytes())- try:- page = document[1]- page_size = tuple(float(value) for value in page.size)- index_block = {- "type": BlockType.INDEX,- "bbox": [0.109, 0.11, 0.874, 0.832],- "angle": 0,- "content": "",- }- block_lines = text_content._group_page_spans_by_block(- [index_block],- tables._build_pdf_text_visual_run_spans(page),- page_size,- {BlockType.INDEX},- )-- assert len(block_lines[0]) == 24- text_content._apply_block_content_and_line_metadata(- [index_block],- block_lines,- page_size,- )-- flash_index_block = next(block for block in PdfModel().predict(document)[1] if block.get("type") == BlockType.INDEX)- flash_content = inline_plain_text(- parse_inline_content(str(flash_index_block["content"]))- )- assert index_block["content"] == flash_content- assert len(str(index_block["content"]).splitlines()) == 24- assert str(index_block["content"]).splitlines()[0] == "1 合成章节 1 1"- assert str(index_block["content"]).splitlines()[-1] == "24 合成章节 24 24"- assert index_block["type"] == BlockType.INDEX- assert index_block["bbox"] == [0.109, 0.11, 0.874, 0.832]- assert index_block["angle"] == 0- finally:- document.close()diff --git a/tests/unittest/test_pdf_analyze_visual_blocks.py b/tests/unittest/test_pdf_analyze_visual_blocks.pyindex 981e8c86..dddefeea 100644--- a/tests/unittest/test_pdf_analyze_visual_blocks.py+++ b/tests/unittest/test_pdf_analyze_visual_blocks.py@@ -6,6 +6,7 @@ import inspectimport threadingfrom io import BytesIOfrom pathlib import Path+from typing import get_args, get_type_hintsfrom unittest.mock import MagicMockimport numpy as np@@ -948,10 +949,10 @@ def test_formula_number_optimizer_does_not_accept_legacy_interline_equation() ->]-def test_low_formula_number_merge_runs_before_visual_crop(+def test_flash_ocr_formula_number_merge_runs_before_visual_crop(monkeypatch: pytest.MonkeyPatch,) -> None:- """验证 low 在文本与表格处理后合并公式编号,并把扩框结果交给视觉裁图。"""+ """验证 Flash OCR 在正文和表格处理后合并公式编号,并把扩框结果交给视觉裁图。"""fake_document = MagicMock()fake_document.page_count = 1fake_document.__getitem__.return_value = MagicMock(size=(100.0, 100.0))@@ -976,20 +977,19 @@ def test_low_formula_number_merge_runs_before_visual_crop(optimize_call_count = 0original_optimizer = formulas.optimize_hybrid_formula_number_blocks- def fake_process_low_text(+ def fake_process_flash_ocr(_images_list: object,_pdf_pages: object,model_list: list[list[dict[str, object]]],- _parse_mode: object,_hybrid_model: object,_images_layout_res: object,) -> list[list[dict[str, object]]]:- """记录 low 文本与表格处理完成,并原样返回 layout block。"""- events.append("process_low")+ """记录 Flash OCR 正文与表格处理完成,并原样返回 layout block。"""+ events.append("process_flash_ocr")return model_listdef tracked_optimizer(page_model_list: list[dict[str, object]]) -> list[dict[str, object]]:- """记录 low 公式编号合并次数,并调用真实合并实现。"""+ """记录 Flash OCR 公式编号合并次数,并调用真实合并实现。"""nonlocal optimize_call_countoptimize_call_count += 1events.append("optimize_formula_number")@@ -1020,15 +1020,15 @@ def test_low_formula_number_merge_runs_before_visual_crop("load_images_from_pdf_bytes_range",MagicMock(return_value=[{"img_pil": page_image}]),)- monkeypatch.setattr(window, "_process_low_text", fake_process_low_text)+ monkeypatch.setattr(window, "_process_flash_ocr", fake_process_flash_ocr)monkeypatch.setattr(window, "optimize_hybrid_formula_number_blocks", tracked_optimizer)monkeypatch.setattr(window, "_attach_visual_block_images", fake_attach_visual_blocks)model_list = window.process_pdf_windows(b"fake-pdf",fake_document,- effort="low",- parse_mode="txt",+ effort="flash",+ parse_mode="ocr",image_analysis=True,flash_txt_mode=False,hybrid_model=hybrid_model,@@ -1045,7 +1045,7 @@ def test_low_formula_number_merge_runs_before_visual_crop(]]assert optimize_call_count == 1- assert events == ["process_low", "optimize_formula_number", "attach_visual"]+ assert events == ["process_flash_ocr", "optimize_formula_number", "attach_visual"]with pytest.raises(ValueError, match="closed image"):page_image.getpixel((0, 0))@@ -1196,6 +1196,13 @@ def test_aio_doc_analyze_matches_sync_signature() -> None:assert async_signature.return_annotation == sync_signature.return_annotation+def test_doc_analyze_effort_annotation_exposes_only_supported_values() -> None:+ """验证同步和异步 Analyze 门面仅公开四个有效 effort。"""+ expected_efforts = ("flash", "medium", "high", "xhigh")+ assert get_args(get_type_hints(analyze.doc_analyze)["effort"]) == expected_efforts+ assert get_args(get_type_hints(analyze.aio_doc_analyze)["effort"]) == expected_efforts++def test_aio_doc_analyze_runs_sync_entrypoint_in_thread_and_forwards_arguments(monkeypatch: pytest.MonkeyPatch,) -> None:@@ -1353,11 +1360,49 @@ def test_doc_analyze_rejects_unsupported_suffix_before_resource_initialization(model_factory.assert_not_called()+def test_doc_analyze_rejects_low_before_office_initialization(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """验证已移除的 Low effort 在创建 Office 模型前直接报错。"""+ model_factories = {+ suffix: MagicMock() for suffix in ("doc", "docx", "ppt", "pptx", "xls", "xlsx")+ }+ monkeypatch.setattr(office, "_OFFICE_MODEL_MAP", model_factories)++ with pytest.raises(ValueError, match="Unsupported analyze effort: low"):+ analyze.doc_analyze(+ b"office-bytes",+ effort="low", # type: ignore[arg-type]+ file_suffix="docx",+ )++ for model_factory in model_factories.values():+ model_factory.assert_not_called()+++def test_analyze_pdf_rejects_low_before_document_initialization(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """验证 PDF 内部入口也会在创建文档前拒绝已移除的 Low effort。"""+ pdf_document = MagicMock()+ monkeypatch.setattr(pipeline, "PDFDocument", pdf_document)++ with pytest.raises(ValueError, match="Unsupported analyze effort: low"):+ pipeline.analyze_pdf(+ b"pdf-bytes",+ effort="low", # type: ignore[arg-type]+ parse_mode="ocr",+ )++ pdf_document.assert_not_called()++@pytest.mark.parametrize(- ("effort", "parse_mode", "expected_message"),+ ("effort", "parse_mode", "expected_message", "document_created"),[- ("turbo", "txt", "Unsupported analyze effort: turbo"),- ("low", "invalid", "parse_mode invalid is not supported"),+ ("turbo", "txt", "Unsupported analyze effort: turbo", False),+ ("low", "txt", "Unsupported analyze effort: low", False),+ ("flash", "invalid", "parse_mode invalid is not supported", True),],)def test_doc_analyze_rejects_invalid_pdf_modes_before_model_initialization(@@ -1365,11 +1410,13 @@ def test_doc_analyze_rejects_invalid_pdf_modes_before_model_initialization(effort: str,parse_mode: str,expected_message: str,+ document_created: bool,) -> None:"""验证非法 PDF effort/parse_mode 统一报 ValueError,且不初始化模型。"""fake_document = MagicMock()+ pdf_document = MagicMock(return_value=fake_document)hybrid_model_factory = MagicMock()- monkeypatch.setattr(pipeline, "PDFDocument", MagicMock(return_value=fake_document))+ monkeypatch.setattr(pipeline, "PDFDocument", pdf_document)monkeypatch.setattr(pipeline, "HybridLocalModelContextSingleton", hybrid_model_factory)with pytest.raises(ValueError, match=expected_message):@@ -1379,20 +1426,30 @@ def test_doc_analyze_rejects_invalid_pdf_modes_before_model_initialization(parse_mode=parse_mode, # type: ignore[arg-type])- fake_document.close.assert_called_once_with()+ if document_created:+ pdf_document.assert_called_once_with(b"invalid-mode-pdf")+ fake_document.close.assert_called_once_with()+ else:+ pdf_document.assert_not_called()+ fake_document.close.assert_not_called()hybrid_model_factory.assert_not_called()-def test_pdf_flash_ocr_routes_to_low_hybrid_pipeline([email protected]("parse_mode", ["ocr", "auto"])+def test_pdf_flash_ocr_uses_local_ocr_without_vlm(monkeypatch: pytest.MonkeyPatch,+ parse_mode: str,) -> None:- """验证 Flash 遇到 OCR PDF 时降级为 Low,并把最终路由元数据带回门面。"""+ """验证 Flash OCR 保持 Flash 元数据,复用本地 OCR 且不加载 VLM。"""fake_document = MagicMock()+ fake_document.classify.return_value = "ocr"hybrid_model = MagicMock()hybrid_model.device = "cpu"hybrid_singleton = MagicMock()hybrid_singleton.get_model.return_value = hybrid_modelprocess_pdf_windows = MagicMock(return_value=[])+ load_vlm_runtime = MagicMock()+ get_vlm_engine = MagicMock()monkeypatch.setattr(pipeline, "PDFDocument", MagicMock(return_value=fake_document))monkeypatch.setattr(@@ -1402,17 +1459,67 @@ def test_pdf_flash_ocr_routes_to_low_hybrid_pipeline()monkeypatch.setattr(pipeline, "process_pdf_windows", process_pdf_windows)monkeypatch.setattr(pipeline, "clean_memory", MagicMock())+ monkeypatch.setattr(pipeline, "_load_vlm_runtime", load_vlm_runtime)+ monkeypatch.setattr(pipeline, "get_vlm_engine", get_vlm_engine)result = pipeline.analyze_pdf(b"ocr-pdf",effort="flash",- parse_mode="ocr",+ parse_mode=parse_mode, # type: ignore[arg-type])- assert result.effort == "low"+ assert result.effort == "flash"assert result.parse_mode == "ocr"- assert process_pdf_windows.call_args.kwargs["effort"] == "low"+ assert process_pdf_windows.call_args.kwargs["effort"] == "flash"+ assert process_pdf_windows.call_args.kwargs["parse_mode"] == "ocr"assert process_pdf_windows.call_args.kwargs["flash_txt_mode"] is False+ if parse_mode == "auto":+ fake_document.classify.assert_called_once_with()+ else:+ fake_document.classify.assert_not_called()+ load_vlm_runtime.assert_not_called()+ get_vlm_engine.assert_not_called()++[email protected]("parse_mode", ["txt", "auto"])+def test_pdf_flash_txt_skips_all_neural_model_loading(+ monkeypatch: pytest.MonkeyPatch,+ parse_mode: str,+) -> None:+ """验证显式或自动 TXT 的 Flash 全流程均不初始化 Hybrid、OCR、layout 或 VLM 模型。"""+ fake_document = MagicMock()+ fake_document.classify.return_value = "txt"+ hybrid_model_factory = MagicMock()+ load_vlm_runtime = MagicMock()+ get_vlm_engine = MagicMock()+ clean_memory = MagicMock()+ process_pdf_windows = MagicMock(return_value=[])+ monkeypatch.setattr(pipeline, "PDFDocument", MagicMock(return_value=fake_document))+ monkeypatch.setattr(pipeline, "HybridLocalModelContextSingleton", hybrid_model_factory)+ monkeypatch.setattr(pipeline, "_load_vlm_runtime", load_vlm_runtime)+ monkeypatch.setattr(pipeline, "get_vlm_engine", get_vlm_engine)+ monkeypatch.setattr(pipeline, "clean_memory", clean_memory)+ monkeypatch.setattr(pipeline, "process_pdf_windows", process_pdf_windows)++ result = pipeline.analyze_pdf(+ b"txt-pdf",+ effort="flash",+ parse_mode=parse_mode, # type: ignore[arg-type]+ )++ assert result.effort == "flash"+ assert result.parse_mode == "txt"+ assert process_pdf_windows.call_args.kwargs["effort"] == "flash"+ assert process_pdf_windows.call_args.kwargs["parse_mode"] == "txt"+ assert process_pdf_windows.call_args.kwargs["flash_txt_mode"] is True+ if parse_mode == "auto":+ fake_document.classify.assert_called_once_with()+ else:+ fake_document.classify.assert_not_called()+ hybrid_model_factory.assert_not_called()+ load_vlm_runtime.assert_not_called()+ get_vlm_engine.assert_not_called()+ clean_memory.assert_not_called()def test_pdf_infer_timer_excludes_hybrid_vlm_initialization_and_cleanup(@@ -1534,7 +1641,7 @@ def test_pdf_analyze_releases_document_and_model_when_window_processing_fails(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")+ pipeline.analyze_pdf(b"broken-pdf", effort="flash", parse_mode="ocr")fake_document.close.assert_called_once_with()clean_memory.assert_called_once_with("cpu")@@ -1562,8 +1669,8 @@ def test_pdf_window_releases_rendered_images_when_layout_fails(window.process_pdf_windows(b"broken-pdf",fake_document,- effort="low",- parse_mode="txt",+ effort="flash",+ parse_mode="ocr",image_analysis=True,flash_txt_mode=False,hybrid_model=hybrid_model,diff --git a/tests/unittest/test_pdf_text_styles.py b/tests/unittest/test_pdf_text_styles.pyindex 57989130..2275fad3 100644--- a/tests/unittest/test_pdf_text_styles.py+++ b/tests/unittest/test_pdf_text_styles.py@@ -10,7 +10,6 @@ from zipfile import ZipFileimport pytest-from mineru.backend.analysis.pdf import windowfrom mineru.backend.analysis.pdf.text import content as text_contentfrom mineru.backend.analysis.pdf.text.models import _AnalyzeLine, _AnalyzeSpanfrom mineru.backend.analysis.pdf.text.native import txt_spans_extract@@ -2052,132 +2051,6 @@ def test_hybrid_txt_efforts_apply_dehyphenated_links()-def test_low_txt_applies_styles_after_native_content_fill(- monkeypatch: pytest.MonkeyPatch,-) -> None:- """验证 Low/TXT 在 block content 完成后应用相同的组合样式策略。"""-- span = _AnalyzeSpan(- type=ContentType.TEXT,- bbox=(10.0, 10.0, 52.0, 20.0),- content="deleted",- score=1.0,- )- style_line = PDFTextStyleLine(- (10.0, 10.0, 52.0, 20.0),- "deleted",- (- PDFTextStyleRange(- 0,- 7,- ("bold", "italic", "underline", "strikethrough"),- ),- ),- 0,- )- link_line = PDFTextLinkLine(- (10.0, 10.0, 52.0, 20.0),- "deleted",- (PDFTextLinkRange(0, 7, "https://low.example.test"),),- 0,- )- monkeypatch.setattr(- window,- "_build_pdf_text_visual_run_data",- lambda _page: ([span], [style_line], [link_line]),- )- monkeypatch.setattr(window, "_fill_low_table_contents", lambda *_args: None)- monkeypatch.setattr(- window,- "_fill_low_txt_native_formula_contents",- lambda *_args: None,- )- model_list = [[{"type": BlockType.TEXT, "bbox": [0.1, 0.1, 0.52, 0.2], "content": ""}]]-- window._process_low_text(- [{"img_pil": object(), "scale": 1.0}],- [MagicMock(size=(100.0, 100.0))],- model_list,- "txt",- MagicMock(),- [[]],- )-- assert model_list[0][0]["content"] == (- '<hyperlink><text style="bold,strikethrough">deleted</text>'- "<url>https://low.example.test</url></hyperlink>"- )---def test_low_txt_applies_dehyphenated_links_after_native_content_fill(- monkeypatch: pytest.MonkeyPatch,-) -> None:- """验证 Low/TXT 在删除物理行断词符后恢复完整链接。"""-- target = "https://low.example.test/dehyphenated"- spans = [- _AnalyzeSpan(- type=ContentType.TEXT,- bbox=(10.0, 10.0, 52.0, 20.0),- content="inter-",- score=1.0,- ),- _AnalyzeSpan(- type=ContentType.TEXT,- bbox=(10.0, 30.0, 52.0, 40.0),- content="national",- score=1.0,- ),- ]- link_lines = [- PDFTextLinkLine(- spans[0].bbox,- "inter-",- (PDFTextLinkRange(0, 6, target),),- 0,- ),- PDFTextLinkLine(- spans[1].bbox,- "national",- (PDFTextLinkRange(0, 8, target),),- 1,- ),- ]- monkeypatch.setattr(- window,- "_build_pdf_text_visual_run_data",- lambda _page: (spans, [], link_lines),- )- monkeypatch.setattr(window, "_fill_low_table_contents", lambda *_args: None)- monkeypatch.setattr(- window,- "_fill_low_txt_native_formula_contents",- lambda *_args: None,- )- model_list = [- [- {- "type": BlockType.TEXT,- "bbox": [0.1, 0.1, 0.52, 0.4],- "content": "",- }- ]- ]-- window._process_low_text(- [{"img_pil": object(), "scale": 1.0}],- [MagicMock(size=(100.0, 100.0))],- model_list,- "txt",- MagicMock(),- [[]],- )-- assert model_list[0][0]["content"] == (- f"<hyperlink>international<url>{target}</url></hyperlink>"- )--def test_ocr_path_does_not_collect_or_apply_pdf_styles(monkeypatch: pytest.MonkeyPatch,) -> None: