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: enforce strict paragraph title levels between 2 and 6 and update related tests
myhloli8fdebbd1985a
diff --git a/docs/en/usage/quick_usage.md b/docs/en/usage/quick_usage.mdindex 7ffd8896..662ac8d1 100644--- a/docs/en/usage/quick_usage.md+++ b/docs/en/usage/quick_usage.md@@ -114,6 +114,30 @@ If you need to adjust parsing options through custom parameters, you can also ch> All officially supported `vllm/lmdeploy` parameters can be passed to MinerU through command line arguments, including the following commands: `mineru`, `mineru-openai-server`, `mineru-gradio`, `mineru-api`, `mineru-router`.> We have compiled some commonly used parameters and usage methods for `vllm/lmdeploy`, which can be found in the documentation [Advanced Command Line Parameters](./advanced_cli_parameters.md).+## Configuring LLM-aided post-processing with config.yaml++LLM-aided title leveling and cross-page table cell continuation read `$MINERU_HOME/config.yaml` and support OpenAI-compatible model services:++```yaml+llm_aided:+ api_key: ${MINERU_LLM_API_KEY:-}+ base_url: https://dashscope.aliyuncs.com/compatible-mode/v1+ model: qwen3.5-plus+ enable_thinking: false+ max_concurrency: 16+ features:+ title_leveling: false+ cross_page_table_cell_merge: false+```++- `title_leveling` groups paragraph titles into levels 2 through 6 by document-title boundaries and runs only for whole-PDF input where `page_index_map` is `None`. It is skipped for page-selected input.+- `cross_page_table_cell_merge` asks the LLM whether each pair of boundary-row cells continues after the existing rules identify a cross-page table.+- Table cell merge does not require whole-document input. Both features are disabled by default and share one asynchronous client, one connection configuration, and the `max_concurrency` request limit, which defaults to 16.+- `max_concurrency` must be an integer of at least 1 and can be overridden with `MINERU_LLM_AIDED_MAX_CONCURRENCY`.+- Enabling either feature requires non-empty `api_key`, `base_url`, and `model` values.+- `enable_thinking` is optional. When omitted, the extension parameter is not sent to the model service.+- The legacy `llm-aided-config` section in `mineru.json` is no longer read.+## Extending MinerU Functionality with Configuration FilesMinerU is now ready to use out of the box, but also supports extending functionality through configuration files. You can edit `mineru.json` file in your user directory to add custom configurations.@@ -127,31 +151,6 @@ Here are some available configuration options:* Used to configure LaTeX formula delimiters* Defaults to `$` symbol, can be modified to other symbols or strings as needed.-- `llm-aided-config`:- * Used to configure parameters for LLM-assisted title hierarchy- * Compatible with all LLM models supporting `openai protocol`, defaults to using Alibaba Cloud Bailian's `qwen3-next-80b-a3b-instruct` model.- * You need to configure your own API key and set `enable` to `true` to enable this feature.- * If your API provider does not support the `enable_thinking` parameter, please manually remove it.- * For example, in your configuration file, the `llm-aided-config` section may look like:- ```json- "llm-aided-config": {- "api_key": "your_api_key",- "base_url": "https://dashscope.aliyuncs.com/compatible-mode/v1",- "model": "qwen3-next-80b-a3b-instruct",- "enable_thinking": false,- "enable": false- }- ```- * To remove the `enable_thinking` parameter, simply delete the line containing `"enable_thinking": false`, resulting in:- ```json- "llm-aided-config": {- "api_key": "your_api_key",- "base_url": "https://dashscope.aliyuncs.com/compatible-mode/v1",- "model": "qwen3-next-80b-a3b-instruct",- "enable": false- }- ```-- `models-dir`:* Used to specify local model storage directory* Please specify model directories for the local lightweight model bundle (`models-dir.pipeline`) and the VLM bundle (`models-dir.vlm`) separately.diff --git a/docs/next/config.md b/docs/next/config.mdindex 5663801c..fb15e548 100644--- a/docs/next/config.md+++ b/docs/next/config.md@@ -38,6 +38,34 @@ render:四个 delimiter 必须为非空字符串。缺省值如上;环境变量可按现有字段路径规则覆盖,例如 `MINERU_RENDER_LATEX_DELIMITERS_INLINE_LEFT`。+PDF 的 LLM 辅助后处理同样读取启动前 `config.yaml`:++```yaml+llm_aided:+ api_key: ${MINERU_LLM_API_KEY:-}+ base_url: https://dashscope.aliyuncs.com/compatible-mode/v1+ model: qwen3.5-plus+ enable_thinking: false+ max_concurrency: 16+ features:+ title_leveling: false+ cross_page_table_cell_merge: false+```++两个功能默认关闭并共享同一套 OpenAI-compatible 连接参数。`title_leveling` 在严格+`PageInfo.blocks` 上优化标题层级,但只在 `page_index_map` 为 `None` 的整本 PDF 输入中运行;+抽页输入会跳过标题优化。`cross_page_table_cell_merge` 不受整本输入限制,只消费确定性后处理+已经写入的 `continues_prev`,再把逐单元格的 `0/1` 结果写入后表根块 `cell_merge`。两个功能+通过同一个异步客户端并发请求,`max_concurrency` 是不小于 1 的共享请求上限,默认值为 16。+标题分级结果允许 1 到 6,段落标题的 1 会归一为 2,最终严格标题层级范围为 2 到 6。前置+MinerU VLM 的跨页单元格检测保持关闭。任一功能启用时,`api_key`、`base_url` 和 `model`+均必须为非空字符串;省略 `enable_thinking` 时不会发送该扩展参数。++环境变量可覆盖任意强类型字段,例如 `MINERU_LLM_AIDED_API_KEY`、+`MINERU_LLM_AIDED_MAX_CONCURRENCY`、+`MINERU_LLM_AIDED_FEATURES_TITLE_LEVELING` 和+`MINERU_LLM_AIDED_FEATURES_CROSS_PAGE_TABLE_CELL_MERGE`。+配置必须服务两个产品原则:- 隐私优先:任何配置都不能导致静默上传文档。diff --git a/docs/zh/usage/quick_usage.md b/docs/zh/usage/quick_usage.mdindex 0fc4ff3e..b641c34e 100644--- a/docs/zh/usage/quick_usage.md+++ b/docs/zh/usage/quick_usage.md@@ -114,6 +114,30 @@ mineru -p <input_path> -o <output_path>> 所有`vllm/lmdeploy`官方支持的参数都可用通过命令行参数传递给 MinerU,包括以下命令:`mineru`、`mineru-openai-server`、`mineru-gradio`、`mineru-api`、`mineru-router`,> 我们整理了一些`vllm/lmdeploy`使用中的常用参数和使用方法,可以在文档[命令行进阶参数](./advanced_cli_parameters.md)中获取。+## 使用 config.yaml 配置 LLM 辅助后处理++LLM 辅助标题分级和跨页表格单元格续接读取 `$MINERU_HOME/config.yaml`,兼容 OpenAI 协议的模型服务:++```yaml+llm_aided:+ api_key: ${MINERU_LLM_API_KEY:-}+ base_url: https://dashscope.aliyuncs.com/compatible-mode/v1+ model: qwen3.5-plus+ enable_thinking: false+ max_concurrency: 16+ features:+ title_leveling: false+ cross_page_table_cell_merge: false+```++- `title_leveling`:仅在 `page_index_map` 为 `None` 的整本 PDF 输入中,以文档标题为边界分组优化 2~6 级段落标题;抽页输入会跳过该功能。+- `cross_page_table_cell_merge`:在现有规则确认跨页续表后,通过 LLM 判断边界行中各组相邻单元格是否续接。+- table cell merge 不要求整本输入;两个功能默认关闭,并通过同一个异步客户端共享连接参数和 `max_concurrency` 请求上限,默认值为 16。+- `max_concurrency` 必须是不小于 1 的整数,可通过 `MINERU_LLM_AIDED_MAX_CONCURRENCY` 覆盖。+- 启用任一功能前必须配置非空的 `api_key`、`base_url` 和 `model`。+- `enable_thinking` 可省略;省略后不会向模型服务发送该扩展参数。+- 旧 `mineru.json` 中的 `llm-aided-config` 不再读取。+## 基于配置文件扩展 MinerU 功能MinerU 现已实现开箱即用,但也支持通过配置文件扩展功能。您可通过编辑用户目录下的 `mineru.json` 文件,添加自定义配置。@@ -127,31 +151,6 @@ MinerU 现已实现开箱即用,但也支持通过配置文件扩展功能。* 用于配置 LaTeX 公式的分隔符* 默认为`$`符号,可根据需要修改为其他符号或字符串。-- `llm-aided-config`:- * 用于配置 LLM 辅助标题分级的相关参数,兼容所有支持`openai协议`的 LLM 模型- * 默认使用`阿里云百炼`的`qwen3-next-80b-a3b-instruct`模型- * 您需要自行配置 API 密钥并将`enable`设置为`true`来启用此功能- * 如果您的api供应商不支持`enable_thinking`参数,请手动将该参数删除- * 例如,在您的配置文件中,`llm-aided-config` 部分可能如下所示:- ```json- "llm-aided-config": {- "api_key": "your_api_key",- "base_url": "https://dashscope.aliyuncs.com/compatible-mode/v1",- "model": "qwen3-next-80b-a3b-instruct",- "enable_thinking": false,- "enable": false- }- ```- * 要移除`enable_thinking`参数,只需删除包含`"enable_thinking": false`的那一行,结果如下:- ```json- "llm-aided-config": {- "api_key": "your_api_key",- "base_url": "https://dashscope.aliyuncs.com/compatible-mode/v1",- "model": "qwen3-next-80b-a3b-instruct",- "enable": false- }- ```-- `models-dir`:* 用于指定本地模型存储目录,请分别指定本地小模型 bundle(`models-dir.pipeline`)和 VLM bundle(`models-dir.vlm`)的模型目录,* 指定目录后您可通过配置环境变量`export MINERU_MODEL_SOURCE=local`来使用本地模型。diff --git a/mineru.template.json b/mineru.template.jsonindex a933e799..ecb3b34d 100644--- a/mineru.template.json+++ b/mineru.template.json@@ -13,15 +13,6 @@"right": "$"}},- "llm-aided-config": {- "title_aided": {- "api_key": "your_api_key",- "base_url": "https://dashscope.aliyuncs.com/compatible-mode/v1",- "model": "qwen3.5-plus",- "enable_thinking": false,- "enable": false- }- },"models-dir": {"pipeline": "","vlm": ""diff --git a/mineru/backend/analyze.py b/mineru/backend/analyze.pyindex dcf3e11b..33303ae0 100644--- a/mineru/backend/analyze.py+++ b/mineru/backend/analyze.py@@ -11,7 +11,9 @@ from loguru import loggerfrom mineru.backend.analysis.contracts import AnalyzeEffort, OfficeSuffix, ParseModefrom mineru.backend.analysis.office import analyze_officefrom mineru.backend.analysis.pdf.pipeline import analyze_pdf+from mineru.backend.postprocess.llm_aided import apply_llm_aided_postprocessfrom mineru.backend.postprocess.pages import model_list_to_pages+from mineru.config import configfrom mineru.types import MiddleJsonfrom mineru.version import __version__ as mineru_version@@ -50,8 +52,16 @@ def doc_analyze(result = analyze_office(file_bytes, cast(OfficeSuffix, file_suffix))_log_infer_performance(file_suffix, len(result.model_list), result.elapsed)+ pages = model_list_to_pages(result.model_list, page_index_map)+ if file_suffix == "pdf":+ apply_llm_aided_postprocess(+ pages,+ config.llm_aided,+ page_index_map=page_index_map,+ )+middle_json = MiddleJson(- pages=model_list_to_pages(result.model_list, page_index_map),+ pages=pages,file_suffix=file_suffix,effort=result.effort,parse_mode=result.parse_mode,diff --git a/mineru/backend/postprocess/lists.py b/mineru/backend/postprocess/lists.pyindex e87cbe4e..85e78ee1 100644--- a/mineru/backend/postprocess/lists.py+++ b/mineru/backend/postprocess/lists.py@@ -20,8 +20,8 @@ def fix_office_paragraph_titles(model_list: list[list[dict[str, Any]]]) -> None:if block.get("type") != BlockType.PARAGRAPH_TITLE:continueraw_level = block.get("level")- level_is_valid = isinstance(raw_level, int) and not isinstance(raw_level, bool) and raw_level >= 2- level = raw_level if level_is_valid else 2+ normalized_level = raw_level if type(raw_level) is int else 2+ level = min(max(normalized_level, 2), 6)block["level"] = levelnumbering_depth = level - 1is_numbered_style = block.pop("is_numbered_style", None)diff --git a/mineru/backend/postprocess/llm_aided.py b/mineru/backend/postprocess/llm_aided.pynew file mode 100644index 00000000..d54f709e--- /dev/null+++ b/mineru/backend/postprocess/llm_aided.py@@ -0,0 +1,75 @@+# Copyright (c) Opendatalab. All rights reserved.+"""编排 PDF 的后置 LLM 标题与跨页单元格增强。"""++from __future__ import annotations++import asyncio++from loguru import logger++from mineru.config import LLMAidedConfig+from mineru.types import PageInfo++from .llm_client import LLMAidedClient+from .table_merge.llm_cell_merge import apply_llm_cross_page_cell_merge+from .title_leveling import apply_llm_title_leveling+++def _resolve_enabled_features(+ config: LLMAidedConfig,+ page_index_map: list[int] | None,+) -> tuple[bool, bool]:+ """根据整本输入约束解析本次实际启用的标题与表格功能。"""+ title_enabled = config.features.title_leveling and page_index_map is None+ table_enabled = config.features.cross_page_table_cell_merge+ if config.features.title_leveling and page_index_map is not None:+ logger.info("Skipping LLM title leveling because page_index_map is not None")+ return title_enabled, table_enabled+++async def _apply_llm_aided_postprocess(+ pages: list[PageInfo],+ config: LLMAidedConfig,+ *,+ title_enabled: bool,+ table_enabled: bool,+ client: LLMAidedClient | None,+) -> None:+ """使用同一异步客户端并发执行当前实际启用的 LLM 后处理。"""+ resolved_client = client or LLMAidedClient(config)+ try:+ tasks = []+ if title_enabled:+ tasks.append(apply_llm_title_leveling(pages, resolved_client))+ if table_enabled:+ tasks.append(apply_llm_cross_page_cell_merge(pages, resolved_client))+ await asyncio.gather(*tasks)+ finally:+ if client is None:+ await resolved_client.close()+++def apply_llm_aided_postprocess(+ pages: list[PageInfo],+ config: LLMAidedConfig,+ *,+ page_index_map: list[int] | None = None,+ client: LLMAidedClient | None = None,+) -> None:+ """按配置和整本输入约束同步桥接异步 LLM 后处理。"""+ title_enabled, table_enabled = _resolve_enabled_features(config, page_index_map)+ if not title_enabled and not table_enabled:+ return++ asyncio.run(+ _apply_llm_aided_postprocess(+ pages,+ config,+ title_enabled=title_enabled,+ table_enabled=table_enabled,+ client=client,+ )+ )+++__all__ = ["apply_llm_aided_postprocess"]diff --git a/mineru/backend/postprocess/llm_client.py b/mineru/backend/postprocess/llm_client.pynew file mode 100644index 00000000..095e4ac9--- /dev/null+++ b/mineru/backend/postprocess/llm_client.py@@ -0,0 +1,105 @@+# Copyright (c) Opendatalab. All rights reserved.+"""LLM 辅助后处理共享的 OpenAI-compatible 请求客户端。"""++from __future__ import annotations++import asyncio+import inspect+from collections.abc import Callable+from typing import Any, TypeVar++import json_repair+from loguru import logger+from openai import AsyncOpenAI++from mineru.config import LLMAidedConfig++ValidatedResult = TypeVar("ValidatedResult")++_MAX_LLM_RETRIES = 3+++class LLMAidedClient:+ """复用单个异步 OpenAI-compatible 客户端并提供带校验的 JSON 请求。"""++ def __init__(self, config: LLMAidedConfig, client: Any | None = None) -> None:+ """保存强类型配置,并按需创建带共享并发限制的异步客户端。"""+ self._config = config+ self._client = client or AsyncOpenAI(api_key=config.api_key, base_url=config.base_url)+ self._owns_client = client is None+ self._semaphore = asyncio.Semaphore(config.max_concurrency)++ async def request_validated_json(+ self,+ *,+ operation: str,+ prompt: str,+ validator: Callable[[Any], ValidatedResult | None],+ temperature: float,+ ) -> ValidatedResult | None:+ """异步请求 JSON,并在每次重试中执行调用方提供的结构校验。"""+ request_params: dict[str, Any] = {+ "model": self._config.model,+ "messages": [{"role": "user", "content": prompt}],+ "temperature": temperature,+ }+ if self._config.enable_thinking is not None:+ request_params["extra_body"] = {"enable_thinking": self._config.enable_thinking}++ for attempt in range(1, _MAX_LLM_RETRIES + 1):+ try:+ async with self._semaphore:+ completion = await self._client.chat.completions.create(**request_params)+ content = self._extract_message_content(completion)+ parsed = json_repair.loads(content)+ validated = validator(parsed)+ if validated is not None:+ return validated+ logger.warning(+ "LLM {} response validation failed on attempt {}/{}",+ operation,+ attempt,+ _MAX_LLM_RETRIES,+ )+ except Exception as exc:+ logger.warning(+ "LLM {} request failed on attempt {}/{}: {}",+ operation,+ attempt,+ _MAX_LLM_RETRIES,+ type(exc).__name__,+ )++ logger.error("LLM {} failed after {} attempts", operation, _MAX_LLM_RETRIES)+ return None++ async def close(self) -> None:+ """仅关闭由当前包装器自行创建的底层异步客户端。"""+ if not self._owns_client:+ return+ close = getattr(self._client, "close", None)+ if not callable(close):+ return+ result = close()+ if inspect.isawaitable(result):+ await result++ @staticmethod+ def _extract_message_content(completion: Any) -> str:+ """从非流式 Chat Completions 响应中提取最终文本并移除思考前缀。"""+ choices = getattr(completion, "choices", None)+ if not choices:+ raise ValueError("LLM response does not contain choices")+ message = getattr(choices[0], "message", None)+ content = getattr(message, "content", None)+ if not isinstance(content, str) or not content.strip():+ raise ValueError("LLM response content is empty")+ content = content.strip()+ if "</think>" in content:+ content = content.rsplit("</think>", 1)[1].strip()+ if not content:+ raise ValueError("LLM response content is empty after removing thinking output")+ return content+++__all__ = ["LLMAidedClient"]diff --git a/mineru/backend/postprocess/page_blocks.py b/mineru/backend/postprocess/page_blocks.pyindex ba808da0..b6cd1393 100644--- a/mineru/backend/postprocess/page_blocks.py+++ b/mineru/backend/postprocess/page_blocks.py@@ -86,7 +86,8 @@ def _normalize_raw_blocks(page_model_list: list[BlockDict]) -> list[BlockDict]:block["level"] = 1elif block_type == BlockType.PARAGRAPH_TITLE:raw_level = block.get("level")- block["level"] = raw_level if type(raw_level) is int and raw_level >= 2 else 2+ normalized_level = raw_level if type(raw_level) is int else 2+ block["level"] = min(max(normalized_level, 2), 6)if block_type not in [BlockType.IMAGE_BODY, BlockType.TABLE_BODY, BlockType.CHART_BODY]:if block_content:diff --git a/mineru/backend/postprocess/table_merge/llm_cell_merge.py b/mineru/backend/postprocess/table_merge/llm_cell_merge.pynew file mode 100644index 00000000..b5422730--- /dev/null+++ b/mineru/backend/postprocess/table_merge/llm_cell_merge.py@@ -0,0 +1,175 @@+# Copyright (c) Opendatalab. All rights reserved.+"""使用后置外部 LLM 分析跨页表格边界单元格续接关系。"""++from __future__ import annotations++import asyncio+import json+from dataclasses import dataclass+from typing import Literal, cast++from mineru.types import PageInfo, TableBlock, TableBodyBlock++from .html import build_row_rendered_cell_segments, build_table_state_from_html+from .structure import _expand_header_count_by_rowspan, detect_table_headers+from ..llm_client import LLMAidedClient++CellMergeFlag = Literal[0, 1]+++@dataclass(frozen=True, slots=True)+class _CellMergeCandidate:+ """保存一次后置单元格分析所需的目标块与视觉列映射。"""++ current_table: TableBlock+ prompt: str+ expected_segment_count: int+ expanded_col_count: int+ previous_segment_col_ranges: tuple[tuple[int, int], ...]+++def _table_body_html(table: TableBlock) -> str | None:+ """读取严格 table 根块下唯一主体的 HTML 内容。"""+ for child in table.content:+ if isinstance(child, TableBodyBlock):+ return child.content or None+ return None+++def _find_continued_table_pairs(pages: list[PageInfo]) -> list[tuple[TableBlock, TableBlock]]:+ """按相邻页面查找已由确定性规则标记的跨页续表对。"""+ pairs: list[tuple[TableBlock, TableBlock]] = []+ for previous_page, current_page in zip(pages, pages[1:]):+ if current_page.page_idx != previous_page.page_idx + 1:+ continue+ current_table = next(+ (+ block+ for block in current_page.blocks+ if isinstance(block, TableBlock) and block.continues_prev is True+ ),+ None,+ )+ if current_table is None:+ continue+ previous_table = next(+ (block for block in reversed(previous_page.blocks) if isinstance(block, TableBlock)),+ None,+ )+ if previous_table is not None:+ pairs.append((previous_table, current_table))+ return pairs+++def _build_cell_merge_prompt(previous_texts: list[str], current_texts: list[str]) -> str:+ """构造逐渲染单元格返回零一状态的跨页续接提示。"""+ return f"""请判断跨页表格边界两行中的对应单元格是否属于同一个被分页截断的逻辑单元格。+对每一组对应单元格独立判断:1 表示需要把当前页单元格续接到上一页单元格,0 表示不续接。+必须返回与输入单元格数量相同的 JSON 整数数组;数组元素只能是 0 或 1。+全 0、全 1 和混合结果都允许。不要返回 Markdown、代码块或解释文字。++上一页表格最后一个数据行:+{json.dumps(previous_texts, ensure_ascii=False)}++当前页表格第一个数据行:+{json.dumps(current_texts, ensure_ascii=False)}++输出示例:+[0, 1, 0]+"""+++def _prepare_cell_merge_candidate(+ previous_table: TableBlock,+ current_table: TableBlock,+) -> _CellMergeCandidate | None:+ """从跨页表格 HTML 中提取边界数据行及其渲染单元格段。"""+ previous_html = _table_body_html(previous_table)+ current_html = _table_body_html(current_table)+ if previous_html is None or current_html is None:+ return None++ previous_state = build_table_state_from_html(previous_html)+ current_state = build_table_state_from_html(current_html)+ if previous_state is None or current_state is None:+ return None++ header_count, _, _ = detect_table_headers(previous_state, current_state)+ header_count = _expand_header_count_by_rowspan(current_state.rows, header_count)+ previous_metrics = previous_state.last_data_row_metrics+ current_metrics = current_state.front_first_data_row_metrics.get(header_count)+ if previous_metrics is None or current_metrics is None:+ return None++ previous_segments = build_row_rendered_cell_segments(previous_state.rows, previous_metrics.row_idx)+ current_segments = build_row_rendered_cell_segments(current_state.rows, current_metrics.row_idx)+ if not previous_segments or len(previous_segments) != len(current_segments):+ return None++ expanded_col_count = max((segment.end_col for segment in previous_segments), default=0)+ if expanded_col_count <= 0:+ return None++ return _CellMergeCandidate(+ current_table=current_table,+ prompt=_build_cell_merge_prompt(+ [segment.text for segment in previous_segments],+ [segment.text for segment in current_segments],+ ),+ expected_segment_count=len(previous_segments),+ expanded_col_count=expanded_col_count,+ previous_segment_col_ranges=tuple((segment.start_col, segment.end_col) for segment in previous_segments),+ )+++def _validate_cell_merge(value: object, expected_count: int) -> list[CellMergeFlag] | None:+ """校验 LLM 返回列表长度及每个独立单元格的零一状态。"""+ if not isinstance(value, list) or len(value) != expected_count:+ return None+ if any(type(flag) is not int or flag not in (0, 1) for flag in value):+ return None+ return cast(list[CellMergeFlag], list(value))+++def _expand_cell_merge(+ candidate: _CellMergeCandidate,+ segment_flags: list[CellMergeFlag],+) -> list[CellMergeFlag]:+ """将逐渲染单元格状态按 colspan 覆盖范围展开到视觉列。"""+ expanded: list[CellMergeFlag] = [0] * candidate.expanded_col_count+ for flag, (start_col, end_col) in zip(segment_flags, candidate.previous_segment_col_ranges):+ if flag != 1:+ continue+ for col_idx in range(start_col, min(end_col, candidate.expanded_col_count)):+ expanded[col_idx] = 1+ return expanded+++async def apply_llm_cross_page_cell_merge(pages: list[PageInfo], client: LLMAidedClient) -> None:+ """并发分析已确认的跨页续表,并按候选原始顺序写入 cell_merge。"""+ candidates = [+ candidate+ for previous_table, current_table in _find_continued_table_pairs(pages)+ if (candidate := _prepare_cell_merge_candidate(previous_table, current_table)) is not None+ ]+ if not candidates:+ return++ candidate_flags = await asyncio.gather(+ *(+ client.request_validated_json(+ operation="cross_page_table_cell_merge",+ prompt=candidate.prompt,+ validator=lambda value, count=candidate.expected_segment_count: _validate_cell_merge(value, count),+ temperature=0.1,+ )+ for candidate in candidates+ )+ )+ for candidate, segment_flags in zip(candidates, candidate_flags):+ if segment_flags is None:+ continue+ candidate.current_table.cell_merge = _expand_cell_merge(candidate, segment_flags)+++__all__ = ["apply_llm_cross_page_cell_merge"]diff --git a/mineru/backend/postprocess/title_leveling.py b/mineru/backend/postprocess/title_leveling.pynew file mode 100644index 00000000..85f1a7ea--- /dev/null+++ b/mineru/backend/postprocess/title_leveling.py@@ -0,0 +1,103 @@+# Copyright (c) Opendatalab. All rights reserved.+"""使用后置外部 LLM 优化严格 MiddleJson 的标题层级。"""++from __future__ import annotations++import asyncio+import json+from typing import Any++from mineru.types import DocTitleBlock, PageInfo, ParagraphTitleBlock+from mineru.render._internal.common.inline import inline_plain_text, parse_inline_content++from .llm_client import LLMAidedClient++ParagraphTitleGroup = list[ParagraphTitleBlock]+++def _collect_paragraph_title_groups(pages: list[PageInfo]) -> list[ParagraphTitleGroup]:+ """按文档标题边界把段落标题划分为保持阅读顺序的非空分组。"""+ groups: list[ParagraphTitleGroup] = []+ current_group: ParagraphTitleGroup = []+ for page in pages:+ for block in page.blocks:+ if isinstance(block, DocTitleBlock):+ block.level = 1+ if current_group:+ groups.append(current_group)+ current_group = []+ elif isinstance(block, ParagraphTitleBlock):+ current_group.append(block)+ if current_group:+ groups.append(current_group)+ return groups+++def _plain_title_text(block: ParagraphTitleBlock) -> str:+ """提取标题可见文本供 LLM 使用,不改写原始行内样式内容。"""+ return inline_plain_text(parse_inline_content(block.content))+++def _build_title_prompt(group: ParagraphTitleGroup) -> str:+ """只使用组内序号和段落标题纯文本构造分级提示。"""+ titles = {str(index): _plain_title_text(block) for index, block in enumerate(group)}+ return f"""请优化下列同一文档分组内章节和段落标题的层级,标题层级使用 2 到 6 级。+必须保留所有输入项,并返回键完全相同的 JSON 对象;值只能是 1 到 6 的整数,返回 1 时系统会归一为 2。+不要返回 Markdown、代码块或解释文字。++输入标题:+{json.dumps(titles, ensure_ascii=False)}++输出格式示例:+{{"0": 2, "1": 4, "2": 6}}+"""+++def _validate_title_levels(value: Any, expected_count: int) -> dict[int, int] | None:+ """校验标题层级响应必须覆盖全部索引且值位于一至六级。"""+ if not isinstance(value, dict):+ return None++ levels: dict[int, int] = {}+ try:+ for raw_key, raw_level in value.items():+ if isinstance(raw_key, bool) or isinstance(raw_level, bool):+ return None+ key = int(raw_key)+ level = int(raw_level)+ if str(key) != str(raw_key) or type(raw_level) is not int or not 1 <= level <= 6:+ return None+ levels[key] = level+ except (TypeError, ValueError):+ return None++ if set(levels) != set(range(expected_count)):+ return None+ return levels+++async def apply_llm_title_leveling(pages: list[PageInfo], client: LLMAidedClient) -> None:+ """并发优化各文档标题分组,单组失败时保留该组原始层级。"""+ groups = _collect_paragraph_title_groups(pages)+ if not groups:+ return++ group_levels = await asyncio.gather(+ *(+ client.request_validated_json(+ operation="title_leveling",+ prompt=_build_title_prompt(group),+ validator=lambda value, count=len(group): _validate_title_levels(value, count),+ temperature=0.7,+ )+ for group in groups+ )+ )+ for group, levels in zip(groups, group_levels):+ if levels is None:+ continue+ for index, block in enumerate(group):+ block.level = max(2, levels[index])+++__all__ = ["apply_llm_title_leveling"]diff --git a/mineru/cli_old/client_side_output.py b/mineru/cli_old/client_side_output.pyindex 63dc4b56..b4ea9037 100644--- a/mineru/cli_old/client_side_output.py+++ b/mineru/cli_old/client_side_output.py@@ -8,8 +8,12 @@ from typing import Anyfrom mineru.parser.base import ParseResultfrom mineru.render import render_content_list, render_markdown, render_structured_contentfrom mineru.types import PageInfo-from mineru.utils.backend_options import DEFAULT_HYBRID_EFFORT, normalize_backend, resolve_backend_and_effort-from mineru.utils.title_level_postprocess import finalize_client_side_pages+from mineru.utils.backend_options import (+ DEFAULT_HYBRID_EFFORT,+ normalize_backend,+ resolve_backend_and_effort,+ validate_effort,+)from mineru.version import __version__PDF_BACKENDS = {"hybrid"}@@ -42,6 +46,20 @@ def _stamp_client_side_backend(pages: list[PageInfo], backend: str) -> None:page._backend = backend+def _finalize_client_side_pages(+ pages: list[PageInfo],+ backend: str,+ effort: str = DEFAULT_HYBRID_EFFORT,+) -> None:+ """按调用方传入的后端类型,对 pages 原地执行客户端可完成的 finalize。"""+ if backend == "hybrid":+ from mineru.backend.pdf.model_output_to_middle_json import finalize_middle_json_from_preproc++ finalize_middle_json_from_preproc(pages, effort=validate_effort(effort))+ return+ raise ValueError(f"Unsupported client-side finalize backend '{backend}'")++def regenerate_client_side_outputs(parse_dir: str | Path,doc_stem: str,@@ -68,7 +86,7 @@ def regenerate_client_side_outputs(_stamp_client_side_backend(pages, normalized_backend)if normalized_backend in PDF_BACKENDS:- finalize_client_side_pages(pages, normalized_backend, effort=effort)+ _finalize_client_side_pages(pages, normalized_backend, effort=effort)image_dir = "images"diff --git a/mineru/config.py b/mineru/config.pyindex 6665fab0..bc923859 100644--- a/mineru/config.py+++ b/mineru/config.py@@ -10,7 +10,7 @@ import socketfrom typing import Any, Literalimport yaml-from pydantic import BaseModel, Field+from pydantic import BaseModel, Field, field_validator, model_validatorfrom pydantic_core import to_jsonable_python_logger = logging.getLogger(__name__)@@ -271,6 +271,45 @@ class RenderConfig(BaseModel):latex_delimiters: LatexDelimitersConfig = Field(default_factory=LatexDelimitersConfig)+class LLMAidedFeaturesConfig(BaseModel):+ """LLM 辅助后处理的独立功能开关。"""++ title_leveling: bool = False+ cross_page_table_cell_merge: bool = False+++class LLMAidedConfig(BaseModel):+ """OpenAI-compatible LLM 辅助后处理配置。"""++ api_key: str = Field(default="", repr=False)+ base_url: str = "https://dashscope.aliyuncs.com/compatible-mode/v1"+ model: str = "qwen3.5-plus"+ enable_thinking: bool | None = None+ max_concurrency: int = Field(default=16, ge=1)+ features: LLMAidedFeaturesConfig = Field(default_factory=LLMAidedFeaturesConfig)++ @field_validator("max_concurrency", mode="before")+ @classmethod+ def _reject_boolean_max_concurrency(cls, value: Any) -> Any:+ """拒绝被 Python 视作整数的布尔并发数,同时保留环境变量字符串转换。"""+ if isinstance(value, bool):+ raise ValueError("llm_aided.max_concurrency must be a positive integer")+ return value++ @model_validator(mode="after")+ def _validate_enabled_credentials(self) -> "LLMAidedConfig":+ """任一 LLM 功能启用时要求连接参数均为非空字符串。"""+ enabled = self.features.title_leveling or self.features.cross_page_table_cell_merge+ if not enabled:+ return self++ for field_name in ("api_key", "base_url", "model"):+ value = getattr(self, field_name)+ if not isinstance(value, str) or not value.strip():+ raise ValueError(f"llm_aided.{field_name} must be a non-empty string when an LLM feature is enabled")+ return self++class DoclibConfig(BaseModel):"""Doclib startup configuration.@@ -317,6 +356,7 @@ class Config(BaseModel):doclib: DoclibConfig = Field(default_factory=DoclibConfig)render: RenderConfig = Field(default_factory=RenderConfig)+ llm_aided: LLMAidedConfig = Field(default_factory=LLMAidedConfig)config = _apply_env_overrides(Config(**_read_config()))@@ -332,6 +372,8 @@ __all__ = ["config","Config","DoclibConfig",+ "LLMAidedConfig",+ "LLMAidedFeaturesConfig","LatexDelimiterConfig","LatexDelimitersConfig","RenderConfig",diff --git a/mineru/render/docx.py b/mineru/render/docx.pyindex 4ca26796..414c183f 100644--- a/mineru/render/docx.py+++ b/mineru/render/docx.py@@ -218,7 +218,7 @@ class _DocxRenderer:block: DocTitleBlock | ParagraphTitleBlock,context: InlineRenderContext,) -> None:- """用 Heading 1–9 写标题,并在段落内容外添加 bookmark。"""+ """用 Heading 1–6 写严格标题,并在段落内容外添加 bookmark。"""level = min(max(block.level, 1), 9)paragraph = self.document.add_paragraph(style=f"Heading {level}")append_inline_content(paragraph, block.content, context=context)diff --git a/mineru/types.py b/mineru/types.pyindex adf5b677..e0644afa 100644--- a/mineru/types.py+++ b/mineru/types.py@@ -404,7 +404,7 @@ class DocTitleBlock(TitleBlockBase):class ParagraphTitleBlock(TitleBlockBase):type: Literal[BlockType.PARAGRAPH_TITLE]- level: int = Field(ge=2)+ level: int = Field(ge=2, le=6)class PageAuxTextBlock(StringContentBlock):diff --git a/mineru/utils/config_reader.py b/mineru/utils/config_reader.pyindex 47fc023e..b1cd81ab 100644--- a/mineru/utils/config_reader.py+++ b/mineru/utils/config_reader.py@@ -148,18 +148,6 @@ def get_latex_delimiter_config() -> dict[str, Any] | None:return latex_delimiter_config-def get_llm_aided_config() -> dict[str, Any] | None:- config = read_config()- if config is None:- return None- llm_aided_config = config.get("llm-aided-config", None)- if llm_aided_config is None:- # logger.warning(f"'llm-aided-config' not found in {CONFIG_FILE_NAME}, use 'None' as default")- return None- else:- return llm_aided_config--def get_local_models_dir() -> dict[str, str] | None:config = read_config()if config is None:diff --git a/mineru/utils/llm_aided.py b/mineru/utils/llm_aided.pydeleted file mode 100644index 3b929b89..00000000--- a/mineru/utils/llm_aided.py+++ /dev/null@@ -1,360 +0,0 @@-# Copyright (c) Opendatalab. All rights reserved.-from __future__ import annotations--from collections.abc import Callable-from concurrent.futures import ThreadPoolExecutor-from typing import Any--import json_repair-from loguru import logger-from openai import OpenAI--from ..render.merge import merge_para_text-from ..types import BBox, Block, BlockType, PageInfo--TITLE_BLOCK_TYPES = {- BlockType.DOC_TITLE,- BlockType.PARAGRAPH_TITLE,-}--MAX_TITLE_GROUP_WORKERS = 4---def _get_title_line_avg_height(block: Block) -> float:- if block._line_avg_height > 0:- return block._line_avg_height-- title_block_line_height_list = []- for line in block.lines:- # 标题行高是 LLM prompt 的几何提示,这里只消费有效 bbox,不回写 middle json。- bbox = line.bbox- if not bbox or len(bbox) < 4:- continue- line_height = bbox[3] - bbox[1]- if line_height > 0:- title_block_line_height_list.append(int(line_height))-- if len(title_block_line_height_list) > 0:- return sum(title_block_line_height_list) / len(title_block_line_height_list)-- bbox = block.bbox- if bbox and len(bbox) >= 4:- return max(0, int(bbox[3] - bbox[1]))- return 0---def _collect_title_block_refs(- page_info_list: list[PageInfo],-) -> tuple[list[tuple[PageInfo, Block]], set[Any]]:- title_block_refs = []- title_types = set()-- for page_info in page_info_list:- for block in page_info.para_blocks:- block_type = block.type- if block_type in TITLE_BLOCK_TYPES:- title_block_refs.append((page_info, block))- title_types.add(block_type)-- return title_block_refs, title_types---def _build_title_dict(title_block_refs: list[tuple[PageInfo, Block]]) -> dict[str, list[Any]]:- title_dict = {}-- for i, (page_info, block) in enumerate(title_block_refs):- title_dict[str(i)] = [- merge_para_text(block),- _get_title_line_avg_height(block),- page_info.page_idx + 1,- ]-- return title_dict---def _build_title_optimize_prompt(title_dict: dict[str, list[Any]]) -> str:- return f"""输入的内容是一篇文档中所有标题组成的字典,请根据以下指南优化标题的结果,使结果符合正常文档的层次结构:--1. 字典中每个value均为一个list,包含以下元素:- - 标题文本- - 文本行高是标题所在块的平均行高- - 标题所在的页码--2. 保留原始内容:- - 输入的字典中所有元素都是有效的,不能删除字典中的任何元素- - 请务必保证输出的字典中元素的数量和输入的数量一致--3. 保持字典内key-value的对应关系不变--4. 优化层次结构:- - 根据标题内容的语义为每个标题元素添加适当的层次结构- - 行高较大的标题一般是更高级别的标题- - 标题从前至后的层级必须是连续的,不能跳过层级- - 标题层级最多为4级,不要添加过多的层级- - 优化后的标题只保留代表该标题的层级的整数,不要保留其他信息--5. 合理性检查与微调:- - 在完成初步分级后,仔细检查分级结果的合理性- - 根据上下文关系和逻辑顺序,对不合理的分级进行微调- - 确保最终的分级结果符合文档的实际结构和逻辑--IMPORTANT:-请直接返回优化过的由标题层级组成的字典,格式为{{标题id:标题层级}},如下:-{{- 0:1,- 1:2,- 2:2,- 3:3-}}-不需要对字典格式化,不需要返回任何其他信息。--Input title list:-{title_dict}--Corrected title list:-"""---def _build_relative_title_optimize_prompt(title_dict: dict[str, list[Any]]) -> str:- return f"""输入内容是某一篇文档中除文章标题外的全部章节/段落标题组成的字典。--请注意:-- 文章标题不在本次输入中,已经由系统单独识别并设置为1级标题--1. 字典中每个value均为一个list,包含以下元素:- - 标题文本- - 文本行高是标题所在块的平均行高- - 标题所在的页码--2. 保留原始内容:- - 输入的字典中所有元素都是有效的,不能删除字典中的任何元素- - 请务必保证输出的字典中元素的数量和输入的数量一致--3. 保持字典内key-value的对应关系不变--4. 优化层次结构:- - 根据标题内容的语义为每个标题元素添加适当的层次结构- - 行高较大的标题一般是更高级别的标题- - 标题从前至后的层级必须是连续的,不能跳过层级- - 标题层级最多为4级,不要添加过多的层级- - 优化后的标题只保留代表该标题的层级的整数,不要保留其他信息--5. 合理性检查与微调:- - 在完成初步分级后,仔细检查分级结果的合理性- - 根据上下文关系和逻辑顺序,对不合理的分级进行微调- - 确保最终的分级结果符合文档的实际结构和逻辑--IMPORTANT:-请直接返回优化后的标题层级字典,格式为{{标题id:标题层级}},如下:-{{- 0:1,- 1:2,- 2:2,- 3:3-}}-不要返回 Markdown,不要返回代码块,不要返回任何解释文字。--Input title list:-{title_dict}--Corrected title list:-"""---def _request_title_levels(- title_aided_config: dict[str, Any], title_dict: dict[str, list[Any]], prompt_builder: Callable[..., str] | None = None-) -> dict[int, int] | None:- if len(title_dict) == 0:- return {}-- client = OpenAI(- api_key=title_aided_config["api_key"],- base_url=title_aided_config["base_url"],- )-- retry_count = 0- max_retries = 3- expected_keys = set(range(len(title_dict)))- if prompt_builder is None:- prompt_builder = _build_title_optimize_prompt- title_optimize_prompt = prompt_builder(title_dict)-- logger.debug(f"Requesting LLM for title optimization with prompt: {title_optimize_prompt}")-- api_params = {- "model": title_aided_config["model"],- "messages": [{"role": "user", "content": title_optimize_prompt}],- "temperature": 0.7,- "stream": True,- }- if "enable_thinking" in title_aided_config:- api_params["extra_body"] = {"enable_thinking": title_aided_config["enable_thinking"]}-- while retry_count < max_retries:- try:- completion = client.chat.completions.create(**api_params)- content_pieces = []- for chunk in completion:- if chunk.choices and chunk.choices[0].delta.content is not None:- content_pieces.append(chunk.choices[0].delta.content)-- content = "".join(content_pieces).strip()- if "</think>" in content:- idx = content.index("</think>") + len("</think>")- content = content[idx:].strip()-- logger.debug(f"Raw LLM output for title levels: {content}")- dict_completion = json_repair.loads(content)- dict_completion = {int(k): int(v) for k, v in dict_completion.items()}-- if set(dict_completion.keys()) == expected_keys:- return dict_completion-- logger.warning("The keys in the optimized title result do not match the input titles.")- except Exception as e:- logger.exception(e)-- retry_count += 1-- logger.error("Failed to decode dict after maximum retries.")- return None---def _apply_levels_to_blocks(title_block_refs: list[tuple[PageInfo, Block]], levels_by_index: dict[int, int] | None) -> None:- if levels_by_index is None:- return-- for i, (_, block) in enumerate(title_block_refs):- resolved_level = int(levels_by_index[i])- if block.type == BlockType.DOC_TITLE:- block.level = 1- elif block.type == BlockType.PARAGRAPH_TITLE:- block.level = max(resolved_level, 2)---def _get_title_block_identity(block: Block) -> tuple[str, int] | tuple[str, BBox, str]:- block_index = block.index- if block_index is not None:- return ("index", block_index)-- return ("bbox_text", block.bbox, merge_para_text(block))---def _sync_para_titles_to_preproc(page_info_list: list[PageInfo]) -> None:- for page_info in page_info_list:- para_title_map = {}- for block in page_info.para_blocks:- if block.type in TITLE_BLOCK_TYPES:- para_title_map[_get_title_block_identity(block)] = block-- if len(para_title_map) == 0:- continue-- for block in page_info.preproc_blocks:- if block.type not in TITLE_BLOCK_TYPES:- continue-- para_block = para_title_map.get(_get_title_block_identity(block))- if para_block is None:- continue-- block.type = para_block.type- para_level = getattr(para_block, "level", None)- if para_level is not None:- block.level = para_level---def _run_single_pass_title_leveling(title_block_refs: list[tuple[PageInfo, Block]], title_aided_config: dict[str, Any]) -> None:- title_dict = _build_title_dict(title_block_refs)- levels_by_index = _request_title_levels(title_aided_config, title_dict)- _apply_levels_to_blocks(title_block_refs, levels_by_index)---def _split_paragraph_title_groups(- title_block_refs: list[tuple[PageInfo, Block]],-) -> list[list[tuple[PageInfo, Block]]]:- groups = []- current_group = []-- for title_ref in title_block_refs:- _, block = title_ref- if block.type == BlockType.DOC_TITLE:- if current_group:- groups.append(current_group)- current_group = []- elif block.type == BlockType.PARAGRAPH_TITLE:- current_group.append(title_ref)-- if current_group:- groups.append(current_group)-- return groups---def _offset_paragraph_title_levels(levels_by_index: dict[int, int] | None) -> dict[int, int] | None:- if not levels_by_index:- return levels_by_index-- return {index: max(int(level), 2) for index, level in levels_by_index.items()}---def _request_paragraph_group_levels(- title_block_refs: list[tuple[PageInfo, Block]], title_aided_config: dict[str, Any]-) -> dict[int, int] | None:- title_dict = _build_title_dict(title_block_refs)- levels_by_index = _request_title_levels(- title_aided_config,- title_dict,- prompt_builder=_build_relative_title_optimize_prompt,- )- return _offset_paragraph_title_levels(levels_by_index)---def _run_grouped_title_leveling(title_block_refs: list[tuple[PageInfo, Block]], title_aided_config: dict[str, Any]) -> None:- paragraph_title_groups = _split_paragraph_title_groups(title_block_refs)- group_levels = []-- if len(paragraph_title_groups) > 1:- max_workers = min(len(paragraph_title_groups), MAX_TITLE_GROUP_WORKERS)- with ThreadPoolExecutor(max_workers=max_workers) as executor:- futures = [- executor.submit(- _request_paragraph_group_levels,- title_group,- title_aided_config,- )- for title_group in paragraph_title_groups- ]- group_levels = [future.result() for future in futures]- else:- group_levels = [- _request_paragraph_group_levels(title_group, title_aided_config) for title_group in paragraph_title_groups- ]-- for title_group, levels_by_index in zip(paragraph_title_groups, group_levels):- _apply_levels_to_blocks(title_group, levels_by_index)---def llm_aided_title(page_info_list: list[PageInfo], title_aided_config: dict[str, Any]) -> None:- title_block_refs, title_types = _collect_title_block_refs(page_info_list)- if len(title_block_refs) == 0:- logger.info("No titles detected, skipping LLM-aided title optimization.")- return-- has_doc_title = BlockType.DOC_TITLE in title_types- has_paragraph_title = BlockType.PARAGRAPH_TITLE in title_types- if has_doc_title and has_paragraph_title:- _run_grouped_title_leveling(title_block_refs, title_aided_config)- _sync_para_titles_to_preproc(page_info_list)- return-- title_refs_for_llm = []- for title_ref in title_block_refs:- _, block = title_ref- if block.type != BlockType.DOC_TITLE:- title_refs_for_llm.append(title_ref)-- if len(title_refs_for_llm) > 0:- _run_single_pass_title_leveling(title_refs_for_llm, title_aided_config)-- _sync_para_titles_to_preproc(page_info_list)diff --git a/mineru/utils/title_level_postprocess.py b/mineru/utils/title_level_postprocess.pydeleted file mode 100644index 52f3ed0a..00000000--- a/mineru/utils/title_level_postprocess.py+++ /dev/null@@ -1,48 +0,0 @@-# Copyright (c) Opendatalab. All rights reserved.-from __future__ import annotations--import time-from copy import deepcopy-from typing import Any--from loguru import logger--from ..types import PageInfo-from .backend_options import DEFAULT_HYBRID_EFFORT, validate_effort-from .config_reader import get_llm_aided_config-from .llm_aided import llm_aided_title---def _resolve_title_aided_config() -> dict[str, Any] | None:- """从本地配置解析标题分级开关。"""- llm_aided_config = get_llm_aided_config()- title_aided_config = llm_aided_config.get("title_aided") if isinstance(llm_aided_config, dict) else None- if not isinstance(title_aided_config, dict) or not title_aided_config:- return None- if not title_aided_config.get("enable", False):- return None- return deepcopy(title_aided_config)---def apply_title_leveling_to_pdf_info(pdf_info: list[PageInfo]) -> None:- title_aided_config = _resolve_title_aided_config()- if title_aided_config:- start_time = time.perf_counter()- success = False- try:- llm_aided_title(pdf_info, title_aided_config)- success = True- finally:- elapsed = time.perf_counter() - start_time- status = "finished" if success else "failed"- logger.info(f"title leveling {status}, cost: {elapsed:.2f}s")---def finalize_client_side_pages(pages: list[PageInfo], backend: str, effort: str = DEFAULT_HYBRID_EFFORT) -> None:- """按调用方传入的后端类型,对 pages 原地执行客户端可完成的 finalize。"""- if backend == "hybrid":- from mineru.backend.pdf.model_output_to_middle_json import finalize_middle_json_from_preproc-- finalize_middle_json_from_preproc(pages, effort=validate_effort(effort))- return- raise ValueError(f"Unsupported client-side finalize backend '{backend}'")diff --git a/tests/unittest/test_backend_architecture.py b/tests/unittest/test_backend_architecture.pyindex d2a71ed0..4bdfceb0 100644--- a/tests/unittest/test_backend_architecture.py+++ b/tests/unittest/test_backend_architecture.py@@ -102,6 +102,22 @@ def test_backend_utils_package_is_removed() -> None:assert not utils_path.exists()+def test_llm_postprocess_business_logic_is_not_kept_in_utils() -> None:+ """守卫 LLM 客户端和标题业务统一归属 backend/postprocess。"""+ removed_utils_paths = [+ _PROJECT_ROOT / "mineru/utils/llm_aided.py",+ _PROJECT_ROOT / "mineru/utils/title_level_postprocess.py",+ ]+ expected_backend_paths = [+ _PROJECT_ROOT / "mineru/backend/postprocess/llm_client.py",+ _PROJECT_ROOT / "mineru/backend/postprocess/title_leveling.py",+ _PROJECT_ROOT / "mineru/backend/postprocess/table_merge/llm_cell_merge.py",+ ]++ assert not [path for path in removed_utils_paths if path.exists()]+ assert all(path.is_file() for path in expected_backend_paths)++def test_table_merge_package_keeps_one_way_internal_dependencies() -> None:"""守卫 table_merge 低层模块不反向导入内容合并或文档编排模块。"""package_path = _PROJECT_ROOT / "mineru/backend/postprocess/table_merge"diff --git a/tests/unittest/test_client_side_output.py b/tests/unittest/test_client_side_output.pynew file mode 100644index 00000000..f0867191--- /dev/null+++ b/tests/unittest/test_client_side_output.py@@ -0,0 +1,127 @@+from __future__ import annotations++import importlib.util+import json+import sys+from pathlib import Path+from types import ModuleType+from typing import Any++import pytest++from mineru.types import PageInfo++_PROJECT_ROOT = Path(__file__).resolve().parents[2]+_CLIENT_SIDE_OUTPUT_PATH = _PROJECT_ROOT / "mineru/cli_old/client_side_output.py"+++class _FakeParseResult:+ """为旧客户端输出测试提供最小 ParseResult 行为。"""++ def __init__(+ self,+ pages: list[PageInfo],+ _retained_page_indices: list[int] | None = None,+ _broken_page_indices: list[int] | None = None,+ ) -> None:+ """保存页面和旧客户端会回写的页号元数据。"""+ self.pages = pages+ self._retained_page_indices = _retained_page_indices or []+ self._broken_page_indices = _broken_page_indices or []++ @classmethod+ def from_dict(cls, _payload: dict[str, Any]) -> "_FakeParseResult":+ """从测试 middle json 返回一个空页面结果。"""+ return cls([PageInfo(page_idx=0)])++ def to_dict(self) -> dict[str, Any]:+ """返回旧客户端写文件所需的最小字典。"""+ return {"pages": [page.model_dump(mode="json") for page in self.pages]}+++def _load_client_side_output(monkeypatch: pytest.MonkeyPatch) -> ModuleType:+ """隔离旧 parser/render 基线导入,加载本次迁移的客户端输出模块。"""+ parser_package = ModuleType("mineru.parser")+ parser_package.__path__ = [] # type: ignore[attr-defined]+ parser_base = ModuleType("mineru.parser.base")+ parser_base.ParseResult = _FakeParseResult # type: ignore[attr-defined]+ render_module = ModuleType("mineru.render")+ render_module.render_content_list = lambda *_args, **_kwargs: [] # type: ignore[attr-defined]+ render_module.render_markdown = lambda *_args, **_kwargs: "" # type: ignore[attr-defined]+ render_module.render_structured_content = lambda *_args, **_kwargs: {} # type: ignore[attr-defined]+ monkeypatch.setitem(sys.modules, "mineru.parser", parser_package)+ monkeypatch.setitem(sys.modules, "mineru.parser.base", parser_base)+ monkeypatch.setitem(sys.modules, "mineru.render", render_module)++ spec = importlib.util.spec_from_file_location("_client_side_output_under_test", _CLIENT_SIDE_OUTPUT_PATH)+ if spec is None or spec.loader is None:+ raise RuntimeError("Unable to load client_side_output.py")+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module+++def _install_fake_finalize_module(monkeypatch: pytest.MonkeyPatch, calls: list[str]) -> None:+ """安装旧客户端动态 import 所需的最小 backend.pdf finalize 模块。"""+ pdf_package = ModuleType("mineru.backend.pdf")+ pdf_package.__path__ = [] # type: ignore[attr-defined]+ finalize_module = ModuleType("mineru.backend.pdf.model_output_to_middle_json")++ def finalize_middle_json_from_preproc(_pages: list[PageInfo], effort: str = "medium") -> None:+ """记录旧客户端向动态 finalize 入口转发的 effort。"""+ calls.append(effort)++ finalize_module.finalize_middle_json_from_preproc = finalize_middle_json_from_preproc # type: ignore[attr-defined]+ monkeypatch.setitem(sys.modules, "mineru.backend.pdf", pdf_package)+ monkeypatch.setitem(sys.modules, "mineru.backend.pdf.model_output_to_middle_json", finalize_module)+++def test_finalize_client_side_pages_passes_hybrid_effort(monkeypatch: pytest.MonkeyPatch) -> None:+ """校验迁移后的客户端 Hybrid finalize 继续转发 effort。"""+ module = _load_client_side_output(monkeypatch)+ calls: list[str] = []+ _install_fake_finalize_module(monkeypatch, calls)++ module._finalize_client_side_pages([PageInfo(page_idx=0)], "hybrid", effort="high")++ assert calls == ["high"]+++def test_finalize_client_side_pages_rejects_low_effort(monkeypatch: pytest.MonkeyPatch) -> None:+ """校验迁移后的客户端 Hybrid finalize 仍拒绝 low effort。"""+ module = _load_client_side_output(monkeypatch)+ calls: list[str] = []+ _install_fake_finalize_module(monkeypatch, calls)++ with pytest.raises(ValueError, match="Unsupported effort 'low'"):+ module._finalize_client_side_pages([PageInfo(page_idx=0)], "hybrid", effort="low")++ assert calls == []+++def test_regenerate_client_side_outputs_forwards_hybrid_effort(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ """校验客户端重建输出时继续把 Hybrid effort 传给迁移后的私有 helper。"""+ module = _load_client_side_output(monkeypatch)+ middle_json_path = tmp_path / "demo_middle.json"+ middle_json_path.write_text(json.dumps({"pages": []}), encoding="utf-8")+ calls: list[tuple[str, str]] = []+ monkeypatch.setattr(+ module,+ "_finalize_client_side_pages",+ lambda _pages, backend, effort="medium": calls.append((backend, effort)),+ )++ module.regenerate_client_side_outputs(tmp_path, "demo", "hybrid-engine", effort="high")++ assert calls == [("hybrid", "high")]+++def test_finalize_client_side_pages_uses_explicit_backend(monkeypatch: pytest.MonkeyPatch) -> None:+ """校验迁移后的私有 helper 继续拒绝旧 pipeline backend。"""+ module = _load_client_side_output(monkeypatch)++ with pytest.raises(ValueError, match="Unsupported client-side finalize backend 'pipeline'"):+ module._finalize_client_side_pages([PageInfo(page_idx=0)], "pipeline")diff --git a/tests/unittest/test_doclib_config.py b/tests/unittest/test_doclib_config.pyindex 359026ad..46a3eae9 100644--- a/tests/unittest/test_doclib_config.py+++ b/tests/unittest/test_doclib_config.py@@ -1,9 +1,12 @@from __future__ import annotations+from pathlib import Path+import pytestfrom mineru.config import (Config,+ LLMAidedConfig,LogConfig,PatchedConfig,_apply_env_overrides,@@ -43,7 +46,7 @@ def test_interpolate_env_rejects_missing_required_value(monkeypatch: pytest.Monk_interpolate_env("${MINERU_TEST_MISSING}")-def test_load_config_reads_yaml_and_interpolates_env(tmp_path, monkeypatch: pytest.MonkeyPatch) -> None:+def test_load_config_reads_yaml_and_interpolates_env(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:monkeypatch.setenv("MINERU_TEST_DATA", str(tmp_path / "data"))config_file = tmp_path / "config.yaml"config_file.write_text(@@ -102,7 +105,7 @@ def test_apply_env_overrides_uses_greedy_field_path_matching(monkeypatch: pytestassert cfg.doclib.sqlite.mmap_size == 0-def test_read_config_uses_default_config_under_mineru_home(tmp_path, monkeypatch: pytest.MonkeyPatch) -> None:+def test_read_config_uses_default_config_under_mineru_home(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:mineru_home = tmp_path / "mineru-home"mineru_home.mkdir()monkeypatch.setenv("MINERU_HOME", str(mineru_home))@@ -133,6 +136,115 @@ def test_apply_env_overrides_can_override_doclib_data_dir(monkeypatch: pytest.Moassert cfg.doclib.data_dir == "/tmp/ignored-data-dir"+def test_llm_aided_config_defaults_to_disabled() -> None:+ """验证 LLM 辅助功能缺省关闭且不会要求 API 凭据。"""+ llm_config = Config().llm_aided++ assert llm_config.api_key == ""+ assert llm_config.base_url == "https://dashscope.aliyuncs.com/compatible-mode/v1"+ assert llm_config.model == "qwen3.5-plus"+ assert llm_config.enable_thinking is None+ assert llm_config.max_concurrency == 16+ assert llm_config.features.title_leveling is False+ assert llm_config.features.cross_page_table_cell_merge is False+++def test_llm_aided_config_reads_yaml_shape(tmp_path: Path) -> None:+ """验证 config.yaml 的共享连接参数和独立功能开关进入强类型配置。"""+ config_file = tmp_path / "config.yaml"+ config_file.write_text(+ """+llm_aided:+ api_key: secret+ base_url: https://example.test/v1+ model: test-model+ enable_thinking: false+ max_concurrency: 24+ features:+ title_leveling: true+ cross_page_table_cell_merge: true+""".strip(),+ encoding="utf-8",+ )++ cfg = Config(**_load_config(str(config_file)))++ assert cfg.llm_aided.api_key == "secret"+ assert cfg.llm_aided.base_url == "https://example.test/v1"+ assert cfg.llm_aided.model == "test-model"+ assert cfg.llm_aided.enable_thinking is False+ assert cfg.llm_aided.max_concurrency == 24+ assert cfg.llm_aided.features.title_leveling is True+ assert cfg.llm_aided.features.cross_page_table_cell_merge is True+++def test_llm_aided_config_supports_environment_overrides(monkeypatch: pytest.MonkeyPatch) -> None:+ """验证 LLM 连接参数和深层功能开关均可由环境变量覆盖。"""+ prefix = "TEST_MINERU_"+ monkeypatch.setenv(f"{prefix}LLM_AIDED_API_KEY", "env-secret")+ monkeypatch.setenv(f"{prefix}LLM_AIDED_MODEL", "env-model")+ monkeypatch.setenv(f"{prefix}LLM_AIDED_ENABLE_THINKING", "false")+ monkeypatch.setenv(f"{prefix}LLM_AIDED_MAX_CONCURRENCY", "32")+ monkeypatch.setenv(f"{prefix}LLM_AIDED_FEATURES_TITLE_LEVELING", "true")+ monkeypatch.setenv(f"{prefix}LLM_AIDED_FEATURES_CROSS_PAGE_TABLE_CELL_MERGE", "true")++ cfg = _apply_env_overrides(Config(), prefix=prefix)++ assert cfg.llm_aided.api_key == "env-secret"+ assert cfg.llm_aided.model == "env-model"+ assert cfg.llm_aided.enable_thinking is False+ assert cfg.llm_aided.max_concurrency == 32+ assert cfg.llm_aided.features.title_leveling is True+ assert cfg.llm_aided.features.cross_page_table_cell_merge is True++[email protected]("feature", ["title_leveling", "cross_page_table_cell_merge"])+def test_llm_aided_config_requires_credentials_for_enabled_feature(feature: str) -> None:+ """验证任一 LLM 功能启用时空 API key 会在配置边界报错。"""+ with pytest.raises(ValueError, match="llm_aided.api_key"):+ LLMAidedConfig(features={feature: True})++[email protected]("value", [0, -1, 1.5, "invalid", True])+def test_llm_aided_config_rejects_invalid_max_concurrency(value: object) -> None:+ """验证并发数无论功能是否启用都必须是正整数。"""+ with pytest.raises(ValueError):+ LLMAidedConfig(max_concurrency=value) # type: ignore[arg-type]++[email protected]("field_name", ["api_key", "base_url", "model"])+def test_llm_aided_config_rejects_each_empty_connection_field(field_name: str) -> None:+ """验证启用功能时共享连接参数中的任一空值都会被拒绝。"""+ values = {+ "api_key": "secret",+ "base_url": "https://example.test/v1",+ "model": "test-model",+ }+ values[field_name] = " "++ with pytest.raises(ValueError, match=f"llm_aided.{field_name}"):+ LLMAidedConfig(+ **values,+ features={"title_leveling": True},+ )+++def test_legacy_llm_aided_root_key_is_ignored() -> None:+ """验证旧 llm-aided-config 不会再启用新的 YAML LLM 功能。"""+ cfg = Config.model_validate(+ {+ "llm-aided-config": {+ "title_aided": {+ "api_key": "legacy",+ "enable": True,+ }+ }+ }+ )++ assert cfg.llm_aided.features.title_leveling is False++def test_default_doclib_data_dir_uses_doclib_directory() -> None:cfg = Config()diff --git a/tests/unittest/test_html_render.py b/tests/unittest/test_html_render.pyindex 162133bb..614d2811 100644--- a/tests/unittest/test_html_render.py+++ b/tests/unittest/test_html_render.py@@ -447,7 +447,7 @@ def test_index_uses_real_forward_anchor_and_omits_duplicate_ids() -> None:],)first = ParagraphTitleBlock(type="paragraph_title", index=1, level=2, anchor="sec 1", content="Section")- duplicate = ParagraphTitleBlock(type="paragraph_title", index=2, level=9, anchor="sec 1", content="Duplicate")+ duplicate = ParagraphTitleBlock(type="paragraph_title", index=2, level=6, anchor="sec 1", content="Duplicate")soup = BeautifulSoup(render_html(_middle(_page(0, index, first, duplicate)), standalone=False), "html.parser")assert soup.select_one('.mineru-index a[href="#sec-1"]').get_text() == "Section"@@ -455,7 +455,7 @@ def test_index_uses_real_forward_anchor_and_omits_duplicate_ids() -> None:assert soup.select_one(".mineru-index li ul") is not Noneassert soup.select_one(".mineru-index li ul a") is Noneassert len(soup.select('[id="sec-1"]')) == 1- assert soup.find("h6", attrs={"data-heading-level": "9"}).get_text() == "Duplicate"+ assert soup.find("h6", attrs={"data-heading-level": "6"}).get_text() == "Duplicate"def test_empty_title_does_not_create_a_broken_index_target_and_anchor_controls_are_normalized() -> None:diff --git a/tests/unittest/test_llm_aided_postprocess.py b/tests/unittest/test_llm_aided_postprocess.pynew file mode 100644index 00000000..dce8728d--- /dev/null+++ b/tests/unittest/test_llm_aided_postprocess.py@@ -0,0 +1,717 @@+from __future__ import annotations++import asyncio+from pathlib import Path+from types import SimpleNamespace+from typing import Any++import pytest+from bs4 import BeautifulSoup++from mineru.backend.analysis.contracts import AnalysisResult+from mineru.backend.postprocess.llm_client import LLMAidedClient+from mineru.backend.postprocess.llm_aided import apply_llm_aided_postprocess+from mineru.backend.postprocess.table_merge.llm_cell_merge import apply_llm_cross_page_cell_merge+from mineru.backend.postprocess.title_leveling import apply_llm_title_leveling+from mineru.config import LLMAidedConfig, LLMAidedFeaturesConfig+from mineru.render._internal.common.planner import build_render_plan+from mineru.render.contracts import RenderMode+from mineru.types import (+ BlockType,+ DocTitleBlock,+ MiddleJson,+ PageInfo,+ ParagraphTitleBlock,+ TableBlock,+ TableBodyBlock,+)+++class _QueuedValidatedClient:+ """按队列返回测试响应,并复用生产代码传入的 validator。"""++ def __init__(self, responses: list[Any]) -> None:+ """保存待校验响应及请求记录。"""+ self.responses = list(responses)+ self.operations: list[str] = []+ self.prompts: list[str] = []++ async def request_validated_json(+ self,+ *,+ operation: str,+ prompt: str,+ validator: Any,+ temperature: float,+ ) -> Any:+ """记录操作并把下一项测试响应交给生产 validator。"""+ self.operations.append(operation)+ self.prompts.append(prompt)+ assert prompt+ assert temperature >= 0+ if not self.responses:+ return None+ return validator(self.responses.pop(0))+++class _FakeCompletions:+ """模拟 OpenAI Chat Completions 调用并记录请求参数。"""++ def __init__(self, contents: list[str]) -> None:+ """按顺序保存每次调用应返回的消息文本。"""+ self.contents = list(contents)+ self.calls: list[dict[str, Any]] = []++ async def create(self, **kwargs: Any) -> Any:+ """记录参数并返回最小非流式 completion 对象。"""+ self.calls.append(kwargs)+ content = self.contents.pop(0)+ return SimpleNamespace(choices=[SimpleNamespace(message=SimpleNamespace(content=content))])+++class _ConcurrentValidatedClient:+ """让所有领域请求在返回前汇合,以验证跨功能并发执行。"""++ def __init__(self, expected_calls: int) -> None:+ """保存预期请求数及并发观测状态。"""+ self.expected_calls = expected_calls+ self.operations: list[str] = []+ self.active = 0+ self.peak_active = 0+ self._all_started = asyncio.Event()++ async def request_validated_json(+ self,+ *,+ operation: str,+ prompt: str,+ validator: Any,+ temperature: float,+ ) -> Any:+ """等待全部测试请求进入后再按领域返回合法响应。"""+ assert prompt+ assert temperature >= 0+ self.operations.append(operation)+ self.active += 1+ self.peak_active = max(self.peak_active, self.active)+ if len(self.operations) == self.expected_calls:+ self._all_started.set()+ try:+ await asyncio.wait_for(self._all_started.wait(), timeout=1)+ response = {"0": 3} if operation == "title_leveling" else [1, 0]+ return validator(response)+ finally:+ self.active -= 1+++class _ConcurrencyCompletions:+ """阻塞底层 completion,以观测共享客户端的并发上限。"""++ def __init__(self, expected_limit: int) -> None:+ """初始化请求计数、峰值和释放事件。"""+ self.expected_limit = expected_limit+ self.calls = 0+ self.active = 0+ self.peak_active = 0+ self.limit_reached = asyncio.Event()+ self.release = asyncio.Event()++ async def create(self, **kwargs: Any) -> Any:+ """记录并发请求,并在测试释放前保持占用。"""+ assert kwargs+ self.calls += 1+ self.active += 1+ self.peak_active = max(self.peak_active, self.active)+ if self.active == self.expected_limit:+ self.limit_reached.set()+ try:+ await self.release.wait()+ return SimpleNamespace(choices=[SimpleNamespace(message=SimpleNamespace(content="[0]"))])+ finally:+ self.active -= 1+++def _llm_config(+ *,+ title: bool = False,+ table: bool = False,+ enable_thinking: bool | None = None,+ max_concurrency: int = 16,+) -> LLMAidedConfig:+ """构造已提供测试凭据的强类型 LLM 配置。"""+ return LLMAidedConfig(+ api_key="test-key",+ base_url="https://example.test/v1",+ model="test-model",+ enable_thinking=enable_thinking,+ max_concurrency=max_concurrency,+ features=LLMAidedFeaturesConfig(+ title_leveling=title,+ cross_page_table_cell_merge=table,+ ),+ )+++def _table(index: int, html: str, *, continues_prev: bool = False) -> TableBlock:+ """构造严格的两层表格块。"""+ bbox = (0.1, 0.1, 0.9, 0.9)+ return TableBlock(+ type=BlockType.TABLE,+ index=index,+ bbox=bbox,+ continues_prev=True if continues_prev else None,+ content=[+ TableBodyBlock(+ type=BlockType.TABLE_BODY,+ index=index,+ bbox=bbox,+ content=html,+ )+ ],+ )+++def _cross_page_table_pages(+ *,+ continues_prev: bool = True,+ previous_html: str | None = None,+ current_html: str | None = None,+) -> list[PageInfo]:+ """构造包含重复表头和两个数据行的严格跨页表格页面。"""+ previous_html = previous_html or (+ "<table><tr><th>H1</th><th>H2</th></tr><tr><td>A</td><td>X</td></tr></table>"+ )+ current_html = current_html or (+ "<table><tr><th>H1</th><th>H2</th></tr><tr><td>B</td><td>Y</td></tr></table>"+ )+ return [+ PageInfo(page_idx=0, blocks=[_table(0, previous_html)]),+ PageInfo(page_idx=1, blocks=[_table(0, current_html, continues_prev=continues_prev)]),+ ]+++def _raw_table(html: str, bbox: list[float]) -> dict[str, Any]:+ """构造 doc_analyze 集成测试使用的 raw table model block。"""+ return {+ "type": BlockType.TABLE,+ "bbox": bbox,+ "content": html,+ }+++def _merged_row_texts(middle_json: MiddleJson) -> list[list[str]]:+ """通过真实 render plan 读取跨页合并后的逐行单元格文本。"""+ plan = build_render_plan(middle_json, RenderMode.DEFAULT)+ merged_table = plan[0][0].block+ assert isinstance(merged_table, TableBlock)+ body = next(child for child in merged_table.content if isinstance(child, TableBodyBlock))+ soup = BeautifulSoup(body.content, "html.parser")+ return [[cell.get_text() for cell in row.find_all(["td", "th"])] for row in soup.find_all("tr")]+++def test_llm_client_injects_optional_thinking_parameter() -> None:+ """验证显式 enable_thinking 通过 extra_body 发送且返回经过结构校验。"""+ completions = _FakeCompletions(['</think>{"0": 2}'])+ openai_client = SimpleNamespace(chat=SimpleNamespace(completions=completions))+ client = LLMAidedClient(_llm_config(title=True, enable_thinking=False), client=openai_client)++ result = asyncio.run(+ client.request_validated_json(+ operation="test",+ prompt="prompt",+ validator=lambda value: value if value == {"0": 2} else None,+ temperature=0.1,+ )+ )++ assert result == {"0": 2}+ assert completions.calls[0]["extra_body"] == {"enable_thinking": False}+++def test_llm_client_omits_unspecified_thinking_parameter() -> None:+ """验证未配置 enable_thinking 时不向兼容服务发送供应商参数。"""+ completions = _FakeCompletions(["[0]"])+ openai_client = SimpleNamespace(chat=SimpleNamespace(completions=completions))+ client = LLMAidedClient(_llm_config(table=True), client=openai_client)++ result = asyncio.run(+ client.request_validated_json(+ operation="test",+ prompt="prompt",+ validator=lambda value: value if value == [0] else None,+ temperature=0.1,+ )+ )++ assert result == [0]+ assert "extra_body" not in completions.calls[0]+++def test_llm_client_retries_invalid_json_structure() -> None:+ """验证共享请求层会对结构校验失败的响应重试并返回后续合法结果。"""+ completions = _FakeCompletions(["{}", "[0, 1]"])+ openai_client = SimpleNamespace(chat=SimpleNamespace(completions=completions))+ client = LLMAidedClient(_llm_config(table=True), client=openai_client)++ result = asyncio.run(+ client.request_validated_json(+ operation="test",+ prompt="prompt",+ validator=lambda value: value if value == [0, 1] else None,+ temperature=0.1,+ )+ )++ assert result == [0, 1]+ assert len(completions.calls) == 2++[email protected](("configured_limit", "request_count"), [(3, 4), (16, 17)])+def test_llm_client_uses_configured_shared_concurrency_limit(configured_limit: int, request_count: int) -> None:+ """验证默认和非默认并发数都会控制所有领域共用的底层请求槽。"""+ completions = _ConcurrencyCompletions(configured_limit)+ openai_client = SimpleNamespace(chat=SimpleNamespace(completions=completions))+ client = LLMAidedClient(+ _llm_config(title=True, max_concurrency=configured_limit),+ client=openai_client,+ )++ async def _run() -> list[list[int] | None]:+ """并发发起超过上限的请求,并在额外请求进入前检查限流状态。"""+ tasks = [+ asyncio.create_task(+ client.request_validated_json(+ operation="test",+ prompt=f"prompt-{index}",+ validator=lambda value: value if value == [0] else None,+ temperature=0.1,+ )+ )+ for index in range(request_count)+ ]+ await asyncio.wait_for(completions.limit_reached.wait(), timeout=1)+ await asyncio.sleep(0)+ assert completions.calls == configured_limit+ assert completions.peak_active == configured_limit+ completions.release.set()+ return await asyncio.gather(*tasks)++ assert asyncio.run(_run()) == [[0]] * request_count+++def test_title_leveling_uses_current_page_blocks_and_keeps_global_levels() -> None:+ """验证当前严格标题块可直接分级且文档标题固定为一级。"""+ pages = [+ PageInfo(+ page_idx=0,+ blocks=[+ DocTitleBlock(+ type=BlockType.DOC_TITLE,+ index=0,+ bbox=(0.1, 0.1, 0.9, 0.2),+ content="Document",+ level=1,+ ),+ ParagraphTitleBlock(+ type=BlockType.PARAGRAPH_TITLE,+ index=1,+ bbox=(0.1, 0.3, 0.9, 0.35),+ content="Section",+ level=3,+ ),+ ],+ )+ ]+ client = _QueuedValidatedClient([{"0": 1}])++ asyncio.run(apply_llm_title_leveling(pages, client)) # type: ignore[arg-type]++ assert pages[0].blocks[0].level == 1 # type: ignore[union-attr]+ assert pages[0].blocks[1].level == 2 # type: ignore[union-attr]+ assert client.operations == ["title_leveling"]+++def test_title_leveling_keeps_original_levels_for_invalid_response() -> None:+ """验证单个标题组响应缺项时该组标题层级保持不变。"""+ title = ParagraphTitleBlock(+ type=BlockType.PARAGRAPH_TITLE,+ index=0,+ bbox=(0.1, 0.1, 0.9, 0.2),+ content="Section",+ level=3,+ )+ pages = [PageInfo(page_idx=0, blocks=[title])]+ client = _QueuedValidatedClient([{}])++ asyncio.run(apply_llm_title_leveling(pages, client)) # type: ignore[arg-type]++ assert title.level == 3+++def test_title_leveling_groups_by_doc_title_and_uses_plain_content_only() -> None:+ """验证文档标题切组、组内重新编号,并且提示词只含段落标题纯文本。"""+ styled_content = '<text style="bold">Leading</text>'+ leading = ParagraphTitleBlock(type=BlockType.PARAGRAPH_TITLE, index=0, content=styled_content, level=2)+ first = ParagraphTitleBlock(type=BlockType.PARAGRAPH_TITLE, index=2, content="First", level=2)+ second = ParagraphTitleBlock(+ type=BlockType.PARAGRAPH_TITLE,+ index=3,+ content='<text style="italic">Second</text>',+ level=3,+ )+ third = ParagraphTitleBlock(type=BlockType.PARAGRAPH_TITLE, index=6, content="Third", level=2)+ pages = [+ PageInfo(+ page_idx=0,+ blocks=[+ leading,+ DocTitleBlock(type=BlockType.DOC_TITLE, index=1, content="Document A", level=1),+ first,+ second,+ DocTitleBlock(type=BlockType.DOC_TITLE, index=4, content="Document B", level=1),+ DocTitleBlock(type=BlockType.DOC_TITLE, index=5, content="Document C", level=1),+ third,+ ],+ )+ ]+ client = _QueuedValidatedClient([{"0": 2}, {"0": 3, "1": 5}, {"0": 6}])++ asyncio.run(apply_llm_title_leveling(pages, client)) # type: ignore[arg-type]++ assert [leading.level, first.level, second.level, third.level] == [2, 3, 5, 6]+ assert styled_content == leading.content+ assert len(client.prompts) == 3+ assert '"0": "Leading"' in client.prompts[0]+ assert '"0": "First"' in client.prompts[1]+ assert '"1": "Second"' in client.prompts[1]+ assert '"0": "Third"' in client.prompts[2]+ assert all("Document" not in prompt for prompt in client.prompts)+ assert all("<text" not in prompt for prompt in client.prompts)+ assert all(field not in prompt for prompt in client.prompts for field in ("normalized_height", "page", "current_type"))+ assert all("2 到 6 级" in prompt and "1 到 6 的整数" in prompt for prompt in client.prompts)+++def test_title_leveling_invalid_group_does_not_block_other_groups() -> None:+ """验证一个分组失败不会阻止其他并发分组更新层级。"""+ first = ParagraphTitleBlock(type=BlockType.PARAGRAPH_TITLE, index=1, content="First", level=2)+ second = ParagraphTitleBlock(type=BlockType.PARAGRAPH_TITLE, index=3, content="Second", level=2)+ pages = [+ PageInfo(+ page_idx=0,+ blocks=[+ DocTitleBlock(type=BlockType.DOC_TITLE, index=0, content="A", level=1),+ first,+ DocTitleBlock(type=BlockType.DOC_TITLE, index=2, content="B", level=1),+ second,+ ],+ )+ ]+ client = _QueuedValidatedClient([{}, {"0": 4}])++ asyncio.run(apply_llm_title_leveling(pages, client)) # type: ignore[arg-type]++ assert first.level == 2+ assert second.level == 4++[email protected](("response_level", "expected_level"), [(1, 2), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)])+def test_title_leveling_accepts_levels_one_through_six(response_level: int, expected_level: int) -> None:+ """验证一级归一为二级,并允许二至六级标题写回。"""+ title = ParagraphTitleBlock(type=BlockType.PARAGRAPH_TITLE, index=0, content="Section", level=3)+ pages = [PageInfo(page_idx=0, blocks=[title])]+ client = _QueuedValidatedClient([{"0": response_level}])++ asyncio.run(apply_llm_title_leveling(pages, client)) # type: ignore[arg-type]++ assert title.level == expected_level++[email protected]("response_level", [0, 7, True, 2.0, "6"])+def test_title_leveling_rejects_levels_outside_integer_one_through_six(response_level: Any) -> None:+ """验证越界或非整数层级会让当前标题组保持原层级。"""+ title = ParagraphTitleBlock(type=BlockType.PARAGRAPH_TITLE, index=0, content="Section", level=3)+ pages = [PageInfo(page_idx=0, blocks=[title])]+ client = _QueuedValidatedClient([{"0": response_level}])++ asyncio.run(apply_llm_title_leveling(pages, client)) # type: ignore[arg-type]++ assert title.level == 3+++ ("response", "expected"),+ [+ ([0, 0], [0, 0]),+ ([1, 1], [1, 1]),+ ([1, 0], [1, 0]),+ ([0, 1], [0, 1]),+ ],+)+def test_cell_merge_accepts_independent_zero_one_states(response: list[int], expected: list[int]) -> None:+ """验证全零、全一和混合状态都会新增到后表根块。"""+ pages = _cross_page_table_pages()+ client = _QueuedValidatedClient([response])++ asyncio.run(apply_llm_cross_page_cell_merge(pages, client)) # type: ignore[arg-type]++ current_table = pages[1].blocks[0]+ assert isinstance(current_table, TableBlock)+ assert current_table.cell_merge == expected+++def test_cell_merge_expands_rendered_colspan_segment_to_visual_columns() -> None:+ """验证一个 colspan 渲染单元格的状态会展开到其覆盖的全部视觉列。"""+ pages = _cross_page_table_pages(+ previous_html=(+ "<table><tr><th colspan='2'>H</th></tr><tr><td colspan='2'>A</td></tr></table>"+ ),+ current_html=(+ "<table><tr><th colspan='2'>H</th></tr><tr><td colspan='2'>B</td></tr></table>"+ ),+ )+ client = _QueuedValidatedClient([[1]])++ asyncio.run(apply_llm_cross_page_cell_merge(pages, client)) # type: ignore[arg-type]++ current_table = pages[1].blocks[0]+ assert isinstance(current_table, TableBlock)+ assert current_table.cell_merge == [1, 1]++[email protected]("response", [[], [1], [1, 2], [True, False], "[1, 0]"])+def test_invalid_cell_merge_response_leaves_field_absent(response: Any) -> None:+ """验证非法列表不会在后表新增 cell_merge。"""+ pages = _cross_page_table_pages()+ client = _QueuedValidatedClient([response])++ asyncio.run(apply_llm_cross_page_cell_merge(pages, client)) # type: ignore[arg-type]++ current_table = pages[1].blocks[0]+ assert isinstance(current_table, TableBlock)+ assert current_table.cell_merge is None+ assert "cell_merge" not in current_table.model_fields_set+++def test_unmarked_table_does_not_request_cell_merge() -> None:+ """验证未被确定性规则标记的相邻表格不会触发后置 LLM。"""+ pages = _cross_page_table_pages(continues_prev=False)+ client = _QueuedValidatedClient([[1, 0]])++ asyncio.run(apply_llm_cross_page_cell_merge(pages, client)) # type: ignore[arg-type]++ assert client.operations == []+++def test_mixed_cell_merge_flows_through_strict_middle_json_and_renderer() -> None:+ """验证混合状态经严格 MiddleJson 后由真实 renderer 逐单元格消费。"""+ pages = _cross_page_table_pages()+ client = _QueuedValidatedClient([[1, 0]])+ asyncio.run(apply_llm_cross_page_cell_merge(pages, client)) # type: ignore[arg-type]+ middle_json = MiddleJson(+ pages=pages,+ file_suffix="pdf",+ effort="high",+ parse_mode="txt",+ mineru_version="test",+ )++ assert _merged_row_texts(middle_json) == [["H1", "H2"], ["AB", "X"], ["", "Y"]]+++def test_postprocess_reuses_one_client_for_both_features() -> None:+ """验证标题与表格功能复用同一个后置请求客户端。"""+ table_pages = _cross_page_table_pages()+ previous_table = table_pages[0].blocks[0].model_copy( # type: ignore[union-attr]+ update={+ "index": 1,+ "content": [table_pages[0].blocks[0].content[0].model_copy(update={"index": 1})], # type: ignore[union-attr]+ }+ )+ pages = [+ PageInfo(+ page_idx=0,+ blocks=[+ ParagraphTitleBlock(+ type=BlockType.PARAGRAPH_TITLE,+ index=0,+ bbox=(0.1, 0.01, 0.9, 0.05),+ content="Section",+ level=2,+ ),+ previous_table,+ ],+ ),+ table_pages[1],+ ]+ client = _QueuedValidatedClient([{"0": 3}, [0, 1]])++ apply_llm_aided_postprocess(+ pages,+ _llm_config(title=True, table=True),+ client=client, # type: ignore[arg-type]+ )++ assert client.operations == ["title_leveling", "cross_page_table_cell_merge"]+ assert pages[0].blocks[0].level == 3 # type: ignore[union-attr]+ assert pages[1].blocks[0].cell_merge == [0, 1] # type: ignore[union-attr]+++def test_title_groups_and_table_candidates_run_concurrently() -> None:+ """验证多个标题组和表格候选会跨功能同时请求共享客户端。"""+ first_pair = _cross_page_table_pages()+ second_pair = _cross_page_table_pages()+ first_previous_table = first_pair[0].blocks[0].model_copy( # type: ignore[union-attr]+ update={+ "index": 2,+ "content": [first_pair[0].blocks[0].content[0].model_copy(update={"index": 2})], # type: ignore[union-attr]+ }+ )+ second_previous_table = second_pair[0].blocks[0].model_copy( # type: ignore[union-attr]+ update={+ "index": 2,+ "content": [second_pair[0].blocks[0].content[0].model_copy(update={"index": 2})], # type: ignore[union-attr]+ }+ )+ first_title = ParagraphTitleBlock(type=BlockType.PARAGRAPH_TITLE, index=1, content="First", level=2)+ second_title = ParagraphTitleBlock(type=BlockType.PARAGRAPH_TITLE, index=1, content="Second", level=2)+ pages = [+ PageInfo(+ page_idx=0,+ blocks=[+ DocTitleBlock(type=BlockType.DOC_TITLE, index=0, content="A", level=1),+ first_title,+ first_previous_table,+ ],+ ),+ PageInfo(page_idx=1, blocks=first_pair[1].blocks),+ PageInfo(+ page_idx=2,+ blocks=[+ DocTitleBlock(type=BlockType.DOC_TITLE, index=0, content="B", level=1),+ second_title,+ second_previous_table,+ ],+ ),+ PageInfo(page_idx=3, blocks=second_pair[1].blocks),+ ]+ client = _ConcurrentValidatedClient(expected_calls=4)++ apply_llm_aided_postprocess(+ pages,+ _llm_config(title=True, table=True),+ client=client, # type: ignore[arg-type]+ )++ assert client.peak_active == 4+ assert client.operations.count("title_leveling") == 2+ assert client.operations.count("cross_page_table_cell_merge") == 2+ assert [first_title.level, second_title.level] == [3, 3]+ assert pages[1].blocks[0].cell_merge == [1, 0] # type: ignore[union-attr]+ assert pages[3].blocks[0].cell_merge == [1, 0] # type: ignore[union-attr]+++def test_disabled_postprocess_does_not_construct_client(monkeypatch: pytest.MonkeyPatch) -> None:+ """验证两个功能关闭时不会创建任何外部客户端。"""+ from mineru.backend.postprocess import llm_aided++ monkeypatch.setattr(llm_aided, "LLMAidedClient", lambda _config: pytest.fail("client must not be created"))++ apply_llm_aided_postprocess([], LLMAidedConfig())+++def test_partial_input_skips_title_without_constructing_client(monkeypatch: pytest.MonkeyPatch) -> None:+ """验证抽页输入只启用标题时会正常跳过且不创建外部客户端。"""+ from mineru.backend.postprocess import llm_aided++ monkeypatch.setattr(llm_aided, "LLMAidedClient", lambda _config: pytest.fail("client must not be created"))++ apply_llm_aided_postprocess([], _llm_config(title=True), page_index_map=[])+++def test_partial_input_skips_title_but_keeps_table_cell_merge() -> None:+ """验证抽页输入不会触发标题请求,但仍会执行跨页单元格分析。"""+ pages = _cross_page_table_pages()+ title = ParagraphTitleBlock(type=BlockType.PARAGRAPH_TITLE, index=0, content="Section", level=2)+ pages[0].blocks.insert(0, title)+ client = _QueuedValidatedClient([[0, 1]])++ apply_llm_aided_postprocess(+ pages,+ _llm_config(title=True, table=True),+ page_index_map=[10, 11],+ client=client, # type: ignore[arg-type]+ )++ assert client.operations == ["cross_page_table_cell_merge"]+ assert title.level == 2+ assert pages[1].blocks[0].cell_merge == [0, 1] # type: ignore[union-attr]+++def test_front_vlm_cell_merge_detection_remains_disabled() -> None:+ """守卫前置 MinerUClient 的跨页 cell_merge 生成机制永久关闭。"""+ runtime_path = Path(__file__).resolve().parents[2] / "mineru/model/vlm/runtime.py"++ assert "enable_cross_page_table_merge=False" in runtime_path.read_text(encoding="utf-8")+++def test_doc_analyze_runs_llm_after_deterministic_table_detection(monkeypatch: pytest.MonkeyPatch) -> None:+ """验证 PDF 主链路先产生 continues_prev,再执行后置 LLM 并构造 MiddleJson。"""+ from mineru.backend import analyze++ previous_html = "<table><tr><th>H1</th><th>H2</th></tr><tr><td>A</td><td>X</td></tr></table>"+ current_html = "<table><tr><th>H1</th><th>H2</th></tr><tr><td>B</td><td>Y</td></tr></table>"+ result = AnalysisResult(+ model_list=[+ [_raw_table(previous_html, [0.1, 0.5, 0.9, 0.95])],+ [_raw_table(current_html, [0.1, 0.05, 0.9, 0.5])],+ ],+ effort="high",+ parse_mode="txt",+ elapsed=0.1,+ )+ calls: list[str] = []++ def fake_llm_postprocess(+ pages: list[PageInfo],+ _config: LLMAidedConfig,+ *,+ page_index_map: list[int] | None,+ ) -> None:+ """断言确定性续表标记已存在,并模拟新增 cell_merge。"""+ assert page_index_map is None+ current_table = pages[1].blocks[0]+ assert isinstance(current_table, TableBlock)+ assert current_table.continues_prev is True+ assert current_table.cell_merge is None+ current_table.cell_merge = [1, 0]+ calls.append("llm")++ monkeypatch.setattr(analyze, "analyze_pdf", lambda *_args, **_kwargs: result)+ monkeypatch.setattr(analyze, "apply_llm_aided_postprocess", fake_llm_postprocess)++ middle_json, _ = analyze.doc_analyze(b"pdf")++ current_table = middle_json.pages[1].blocks[0]+ assert isinstance(current_table, TableBlock)+ assert current_table.cell_merge == [1, 0]+ assert calls == ["llm"]+++def test_doc_analyze_does_not_run_llm_for_office(monkeypatch: pytest.MonkeyPatch) -> None:+ """验证 Office 统一入口不会进入仅限 PDF 的 LLM 后处理。"""+ from mineru.backend import analyze++ result = AnalysisResult(+ model_list=[[{"type": BlockType.PARAGRAPH_TITLE, "content": "Slide", "level": 2}]],+ effort="flash",+ parse_mode="txt",+ elapsed=0.1,+ )+ calls: list[str] = []+ monkeypatch.setattr(analyze, "analyze_office", lambda *_args, **_kwargs: result)+ monkeypatch.setattr(analyze, "apply_llm_aided_postprocess", lambda *_args, **_kwargs: calls.append("llm"))++ middle_json, _ = analyze.doc_analyze(b"office", file_suffix="pptx")++ assert middle_json.file_suffix == "pptx"+ assert calls == []diff --git a/tests/unittest/test_markdown_render.py b/tests/unittest/test_markdown_render.pyindex 86a8c251..c26a9e87 100644--- a/tests/unittest/test_markdown_render.py+++ b/tests/unittest/test_markdown_render.py@@ -561,7 +561,7 @@ def test_title_and_index_render_anchor_links_without_heading_leaves() -> None:title = ParagraphTitleBlock(type="paragraph_title",index=1,- level=8,+ level=6,anchor="toc-a",content="Section",)diff --git a/tests/unittest/test_middle_json_block_models.py b/tests/unittest/test_middle_json_block_models.pyindex ad058273..5c83107a 100644--- a/tests/unittest/test_middle_json_block_models.py+++ b/tests/unittest/test_middle_json_block_models.py@@ -109,17 +109,20 @@ def test_shared_models_preserve_all_discriminator_values() -> None:def test_title_levels_follow_global_hierarchy() -> None:- """验证文档标题固定为一级,段落标题必须从二级开始。"""+ """验证文档标题固定为一级,段落标题严格限制在二至六级。"""doc_title = parse_block({"type": "doc_title", "content": "doc", "level": 1})paragraph_title = parse_block({"type": "paragraph_title", "content": "section", "level": 2})+ deepest_title = parse_block({"type": "paragraph_title", "content": "deep", "level": 6})assert doc_title.to_dict()["level"] == 1assert paragraph_title.to_dict()["level"] == 2+ assert deepest_title.to_dict()["level"] == 6for payload in ({"type": "doc_title", "content": "doc"},{"type": "doc_title", "content": "doc", "level": 2},{"type": "paragraph_title", "content": "section"},{"type": "paragraph_title", "content": "section", "level": 1},+ {"type": "paragraph_title", "content": "section", "level": 7},):with pytest.raises(ValidationError):parse_block(payload)diff --git a/tests/unittest/test_postprocess_pages.py b/tests/unittest/test_postprocess_pages.pyindex 8275d4b8..ad708846 100644--- a/tests/unittest/test_postprocess_pages.py+++ b/tests/unittest/test_postprocess_pages.py@@ -360,17 +360,57 @@ def test_chart_none_content_is_normalized_to_empty_string() -> None:def test_raw_title_levels_are_normalized_to_global_hierarchy() -> None:- """验证 raw 标题在严格对象化前补齐全局一级和二级层级。"""+ """验证 raw 标题在严格对象化前归一为全局一至六级层级。"""page = model_list_to_pages([[{"type": "doc_title", "content": "Document"},{"type": "paragraph_title", "content": "Section", "level": 1},+ {"type": "paragraph_title", "content": "Deep", "level": 9},]])[0]- assert [block.level for block in page.blocks] == [1, 2]+ assert [block.level for block in page.blocks] == [1, 2, 6]+++def test_pdf_raw_paragraph_title_level_is_clamped_to_six() -> None:+ """验证带 bbox 的 PDF raw 深层标题在严格对象化前归一为六级。"""+ page = model_list_to_pages(+ [[{"type": "paragraph_title", "content": "Deep", "level": 9, "bbox": [0.1, 0.1, 0.9, 0.2]}]]+ )[0]++ assert isinstance(page.blocks[0], ParagraphTitleBlock)+ assert page.blocks[0].level == 6+++def test_office_title_level_is_clamped_before_numbering_and_index_mapping() -> None:+ """验证 Office 深层标题在编号和目录映射前归一为六级。"""+ model_list = [+ [+ {+ "type": "paragraph_title",+ "content": "Deep",+ "level": 9,+ "anchor": "deep-anchor",+ "is_numbered_style": True,+ },+ {+ "type": "index",+ "content": [{"type": "text", "content": "Deep entry", "anchor": "deep-anchor"}],+ },+ ]+ ]++ page = model_list_to_pages(model_list)[0]+ title = page.blocks[0]+ index = page.blocks[1]++ assert isinstance(title, ParagraphTitleBlock)+ assert title.level == 6+ assert title.content == "1.1.1.1.1 Deep"+ assert isinstance(index.content[0], ParagraphTitleBlock)+ assert index.content[0].level == 6def test_pdf_continuation_is_typed_and_line_metadata_is_removed() -> None:diff --git a/tests/unittest/test_structured_content_render.py b/tests/unittest/test_structured_content_render.pyindex c20ec3d5..7373605a 100644--- a/tests/unittest/test_structured_content_render.py+++ b/tests/unittest/test_structured_content_render.py@@ -66,7 +66,7 @@ def test_structured_content_preserves_document_tree_without_merging_or_mutation(ParagraphTitleBlock(type="paragraph_title",index=0,- level=8,+ level=6,anchor="section-a",content='# <text style="bold">Section</text> <eq>x</eq>',),@@ -94,7 +94,7 @@ def test_structured_content_preserves_document_tree_without_merging_or_mutation(assert result["pages"][0]["blocks"][0] == {"type": "paragraph_title","anchor": "section-a",- "level": 8,+ "level": 6,"content": r"\# **Section** $x$",}assert render_markdown(middle).startswith('<a id="section-a"></a>\n###### # **Section** $x$')diff --git a/tests/unittest/test_title_level_postprocess.py b/tests/unittest/test_title_level_postprocess.pydeleted file mode 100644index bdcbd466..00000000--- a/tests/unittest/test_title_level_postprocess.py+++ /dev/null@@ -1,65 +0,0 @@-import json--import pytest--from mineru.parser.base import ParseResult-from mineru.types import PageInfo-from mineru.utils import title_level_postprocess---def test_finalize_client_side_pages_passes_hybrid_effort(monkeypatch) -> None:- """校验客户端 Hybrid finalize 会沿用请求侧传入的 effort。"""- calls: list[str] = []- pages = [PageInfo(page_idx=0, _backend="hybrid")]- monkeypatch.setattr(- "mineru.backend.hybrid.model_output_to_middle_json.finalize_middle_json_from_preproc",- lambda parsed_pages, effort="medium": calls.append(effort),- )-- title_level_postprocess.finalize_client_side_pages(pages, "hybrid", effort="high")-- assert calls == ["high"]---def test_finalize_client_side_pages_rejects_low_effort(monkeypatch) -> None:- """校验客户端 Hybrid finalize 不再接受 low effort。"""- calls: list[str] = []- pages = [PageInfo(page_idx=0, _backend="hybrid")]- monkeypatch.setattr(- "mineru.backend.hybrid.model_output_to_middle_json.finalize_middle_json_from_preproc",- lambda parsed_pages, effort="medium": calls.append(effort),- )-- with pytest.raises(ValueError, match="Unsupported effort 'low'"):- title_level_postprocess.finalize_client_side_pages(pages, "hybrid", effort="low")-- assert calls == []---def test_regenerate_client_side_outputs_forwards_hybrid_effort(monkeypatch, tmp_path) -> None:- """校验客户端重建输出时继续把 Hybrid effort 传到 finalize 阶段。"""- from mineru.cli_old import client_side_output-- middle_json_path = tmp_path / "demo_middle.json"- middle_json_path.write_text(- json.dumps(ParseResult(pages=[PageInfo(page_idx=0)]).to_dict()),- encoding="utf-8",- )- calls: list[tuple[str, str]] = []- monkeypatch.setattr(- client_side_output,- "finalize_client_side_pages",- lambda pages, backend, effort="medium": calls.append((backend, effort)),- )-- client_side_output.regenerate_client_side_outputs(tmp_path, "demo", "hybrid-engine", effort="high")-- assert calls == [("hybrid", "high")]---def test_finalize_client_side_pages_uses_explicit_backend(monkeypatch) -> None:- legacy_backend = "pipeline"- pages = [PageInfo(page_idx=0, _backend=legacy_backend)]-- with pytest.raises(ValueError, match="Unsupported client-side finalize backend 'pipeline'"):- title_level_postprocess.finalize_client_side_pages(pages, legacy_backend)