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
Merge branch 'next' into pr-5415-merge
jinzhenj32d90209bd02
diff --cc docs/en/usage/cli_tools.mdindex cd26f425,dbc3d2bf..b37afb03--- a/docs/en/usage/cli_tools.md+++ b/docs/en/usage/cli_tools.md@@@ -109,11 -109,10 +109,11 @@@ Here are the environment variables and* Used to specify configuration file path* defaults to `mineru.json` in user directory, can specify other configuration file paths through environment variables.-- `MINERU_TABLE_MERGE_ENABLE`:- * Used to enable table merging functionality- * Default is `true`, can be set to `false` via environment variable to disable table merging functionality.+- `MINERU_FORMULA_CH_SUPPORT`:+ * Used to enable Chinese formula parsing optimization (experimental feature)+ * Default is `false`, can be set to `true` via environment variable to enable Chinese formula parsing optimization.+ * Only effective for local Hybrid model execution.-+- `MINERU_PDF_RENDER_TIMEOUT`:* Used to set the timeout (in seconds) for rendering PDFs to images.* Default is `300` seconds; you can set a different value via an environment variable to adjust the rendering timeout.diff --cc docs/en/usage/quick_usage.mdindex 662ac8d1,488ebc18..3f476ebb--- a/docs/en/usage/quick_usage.md+++ b/docs/en/usage/quick_usage.md@@@ -114,44 -114,38 +114,37 @@@ If you need to adjust parsing options t> 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 Files- MinerU 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.-- >[!IMPORTANT]- >The `mineru.json` file will be automatically generated when you use the built-in model download command `mineru-kit models download all`, or you can create it by copying the [configuration template file](https://github.com/opendatalab/MinerU/blob/master/mineru.template.json) to your user directory and renaming it to `mineru.json`.+ MinerU is now ready to use out of the box, but also supports extending functionality through configuration files. Legacy tool options such as LaTeX delimiters and LLM-aided title hierarchy still use `mineru.json` in your user directory. Model storage and model source settings use `config.yaml`; see [Model Source Documentation](./model_source.md).Here are some available configuration options:--- `latex-delimiter-config`:-- * 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.+ * After specifying the directory, you can use local models by configuring the environment variable `export MINERU_MODEL_SOURCE=local`.diff --cc docs/next/open-questions.mdindex 0abf80a7,bce4bb89..eec27717--- a/docs/next/open-questions.md+++ b/docs/next/open-questions.md@@@ -33,12 -33,11 +33,12 @@@| SDK tier 参数 | 普通 parser 入口应支持 `tier` 语义;`backend` 只作为专家层或过渡参数暴露。 || 错误映射 | `quality_tier_unavailable` 应进入稳定错误体系。 || JSON 输出格式 | 不把 `json` 作为正式产物名;正式格式为 `middle_json`、`content_list`、`structured_content`,详见 [ADR-0001](decisions/0001-json-output-formats.md)。 |+| Middle JSON 行间公式 | Block discriminator 统一为 `equation`;Legacy Span 的 `ContentType.INTERLINE_EQUATION` 暂时保留。 || Force 与 invalidate | `--force` 跳过 done cache,可复用 active parse,只为未覆盖页创建新 parse;invalidate 才改变旧缓存可用性,详见 [ADR-0002](decisions/0002-force-vs-invalidate.md)。 || doclib HTTP API | 本地 doclib HTTP API 使用 `/docs`、`/parses`、`/search` 和 `POST /invalidate`,详见 [ADR-0004](decisions/0004-doclib-http-api-resources.md)。 |- | 本地 `high` | `high` 本地运行是正式支持能力,不是实验能力;当前代码基本 ready。 |- | mineru.net tier | `mineru.net/api` 在相当长时间内只提供最高等级的 `high` 解析。 |- | api-server tier | `mineru-kit api-server --tier` 可重复;未传时当前暴露 `flash`、`medium`、`high`、`extra_high`。 |+ | 本地 `standard` | `standard` 本地运行是正式支持能力,不是实验能力;当前代码基本 ready。 |+ | mineru.net tier | `mineru.net/api` 在相当长时间内默认提供 `standard` 解析;`standard` 是绝大多数场景足够好的高质量档位,但不是最高档。 |+ | api-server tier | `mineru-kit api-server --tier` 是单值能力上限,只接受 `flash`、`basic`、`standard`;未传时按 `standard` 暴露四个请求 tier。 || managed 生命周期 | managed 模式下,模型下载、预热、重试和退避由 `mineru-kit api-server` 负责。 || 本地 api-server 安全 | 本地 api-server 默认监听 loopback;可通过 `--api-key` 设置固定 API Key,默认不设置。 || P0 主链路 | P0 包含完整 watch、rules、search,不再把它们标为可选主链路。 |diff --cc docs/zh/usage/quick_usage.mdindex b641c34e,ce01ef1c..8626386d--- a/docs/zh/usage/quick_usage.md+++ b/docs/zh/usage/quick_usage.md@@@ -114,43 -114,38 +114,36 @@@ 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` 文件,添加自定义配置。-- >[!IMPORTANT]- >`mineru.json` 文件会在您使用内置模型下载命令 `mineru-kit models download all` 时自动生成,也可以通过将[配置模板文件](https://github.com/opendatalab/MinerU/blob/master/mineru.template.json)复制到用户目录下并重命名为 `mineru.json` 来创建。+ MinerU 现已实现开箱即用,但也支持通过配置文件扩展功能。LaTeX 分隔符、LLM 辅助标题分级等旧工具配置仍使用用户目录下的 `mineru.json`。模型存储目录和模型源配置使用 `config.yaml`,详见[模型源说明](./model_source.md)。以下是一些可用的配置选项:--- `latex-delimiter-config`:-- * 用于配置 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 --cc mineru/backend/local_model_runtime.pyindex 9d0c40db,451ba751..fb6f8ed7--- a/mineru/backend/local_model_runtime.py+++ b/mineru/backend/local_model_runtime.py@@@ -6,28 -6,39 +6,29 @@@ from __future__ import annotationimport osimport threadingfrom collections.abc import Callable+from functools import cached_property- from typing import Any+ from typing import TYPE_CHECKING, Any- import torchfrom loguru import logger- from ..model.model_types import AtomicModelName- from ..model.layout.pp_doclayoutv2 import PPDocLayoutV2LayoutModel+from ..model.mfr.pp_formulanet_plus_m.predict_formula import FormulaRecognizer- from ..model.mfr.unimernet.Unimernet import UnimernetModel- from ..model.ocr.pytorch_paddle import PytorchPaddleOCR++from ..model.model_types import AtomicModelNamefrom ..model.table.cls.mineru_table_ori_cls import MineruTableOrientationClsModelfrom ..model.table.cls.paddle_table_cls import PaddleTableClsModelfrom ..model.table.rec.slanet_plus.main import PaddleTableModelfrom ..model.table.rec.unet_table.main import UnetTableModel- from ..utils.config_reader import get_device- from ..utils.enum_class import ModelPath- from ..utils.models_download_utils import auto_download_and_get_model_root_path++ if TYPE_CHECKING:+ from ..model.layout.pp_doclayoutv2 import PPDocLayoutV2LayoutModel+ from ..model.mfr.unimernet.Unimernet import UnimernetModel+ from ..model.ocr.pytorch_paddle import PytorchPaddleOCR+++ from ..utils.config_reader import get_device, get_model_stack+ from ..utils.model_registry import PDF_EXTRACT_KIT, ModelPathfrom ..utils.ocr_language import normalize_ocr_model_lang--class AtomicModel:- """本地原子模型名称集合,供 Hybrid medium 和共享模型单例统一索引。"""-- Layout = "layout"- MFD = "mfd"- MFR = "mfr"- OCR = "ocr"- WirelessTable = "wireless_table"- WiredTable = "wired_table"- TableCls = "table_cls"- TableOrientationCls = "table_ori_cls"--LOCAL_MODEL_INIT_LOCK = threading.RLock()- # 这些锁保护 Hybrid medium/high/extra_high 共享的 atom model/native 模型推理调用,避免多线程同时进入同一个模型对象。+ # 这些锁保护 Hybrid medium/high/xhigh 共享的 atom model/native 模型推理调用,避免多线程同时进入同一个模型对象。LOCAL_MODEL_LAYOUT_INFERENCE_LOCK = threading.RLock()LOCAL_MODEL_MFR_INFERENCE_LOCK = threading.RLock()LOCAL_MODEL_OCR_INFERENCE_LOCK = threading.RLock()@@@ -144,21 -128,18 +130,20 @@@ def wireless_table_model_init(lang: streturn table_model- def mfr_model_init(weight_dir: str, device: str | torch.device = "cpu") -> UnimernetModel | FormulaRecognizer:- """根据公式模型配置和权重目录初始化对应的公式识别器。"""- if MFR_MODEL == "unimernet_small":- mfr_model = UnimernetModel(weight_dir, device)- elif MFR_MODEL == "pp_formulanet_plus_m":- mfr_model = FormulaRecognizer(weight_dir, device)- else:- logger.error("MFR model name not allow")- exit(1)- return mfr_model+ def mfr_model_init(weight_dir: str, device: str = "cpu") -> "UnimernetModel":+ from ..model.mfr.unimernet.Unimernet import UnimernetModel++ return UnimernetModel(weight_dir, device)- def pp_doclayout_v2_model_init(weight: str, device: str | torch.device = "cpu") -> PPDocLayoutV2LayoutModel:+ def pp_doclayout_v2_model_init(weight: str, device: str = "cpu") -> "PPDocLayoutV2LayoutModel":+ """在指定设备上初始化 PP-DocLayoutV2 版面分析模型。"""+++ from ..model.layout.pp_doclayoutv2 import PPDocLayoutV2LayoutModel+if str(device).startswith("npu"):+ import torch+device = torch.device(device)model = PPDocLayoutV2LayoutModel(weight, device)return model@@@ -169,8 -150,9 +154,11 @@@ def ocr_model_initlang: str | None = None,det_db_unclip_ratio: float = 1.5,enable_merge_det_boxes: bool = True,- ) -> PytorchPaddleOCR:+ ) -> "PytorchPaddleOCR":+ """按语言和检测阈值初始化本地 Paddle OCR 模型。"""+++ from ..model.ocr.pytorch_paddle import PytorchPaddleOCR+ocr_kwargs = {"lang": normalize_ocr_model_lang(lang),"det_db_box_thresh": det_db_box_thresh,@@@ -224,20 -202,53 +212,54 @@@ class AtomModelSingletondef atom_model_init(model_name: str, **kwargs: Any) -> Any:+ """将原子模型名称分派到具体初始化函数,并校验初始化结果。"""+ stack = get_model_stack()atom_model = None- if model_name == AtomicModel.Layout:+ if model_name == AtomicModelName.Layout:- atom_model = pp_doclayout_v2_model_init(kwargs.get("pp_doclayout_v2_weights"), kwargs.get("device"))+ if stack == "light":+ from ..model.layout.pp_doclayout_v2_onnx import PPDocLayoutV2LayoutModelONNX+ from ..utils.model_registry import PP_DOCLAYOUT_V2_ONNX++ atom_model = PPDocLayoutV2LayoutModelONNX(+ weight=str(PP_DOCLAYOUT_V2_ONNX.onnx.ensure()),+ device=kwargs.get("device"),+ )+ else:+ atom_model = pp_doclayout_v2_model_init(kwargs.get("pp_doclayout_v2_weights"), kwargs.get("device"))- elif model_name == AtomicModel.MFR:+ elif model_name == AtomicModelName.MFR:- atom_model = mfr_model_init(kwargs.get("mfr_weight_dir"), kwargs.get("device"))+ if stack == "light":+ from ..model.mfr.pp_formulanet_plus_m_onnx import PPFormulaNetPlusMONNX+ from ..utils.model_registry import PP_FORMULANET_PLUS_M_ONNX++ atom_model = PPFormulaNetPlusMONNX(+ model_path=str(PP_FORMULANET_PLUS_M_ONNX.onnx.ensure()),+ config_path=str(PP_FORMULANET_PLUS_M_ONNX.config.ensure()),+ device=kwargs.get("device"),+ )+ else:+ atom_model = mfr_model_init(kwargs.get("mfr_weight_dir"), kwargs.get("device"))- elif model_name == AtomicModel.OCR:+ elif model_name == AtomicModelName.OCR:- atom_model = ocr_model_init(- kwargs.get("det_db_box_thresh", 0.5),- kwargs.get("lang"),- kwargs.get("det_db_unclip_ratio", 1.5),- kwargs.get("enable_merge_det_boxes", True),- )+ if stack == "light":+ from ..model.ocr.pp_ocr_v6_onnx import PPOCRv6ONNX+ from ..utils.model_registry import PP_OCR_V6_SMALL_DET_ONNX, PP_OCR_V6_SMALL_REC_ONNX++ atom_model = PPOCRv6ONNX(+ det_model_path=str(PP_OCR_V6_SMALL_DET_ONNX.onnx.ensure()),+ rec_model_path=str(PP_OCR_V6_SMALL_REC_ONNX.onnx.ensure()),+ dict_path=str(PP_OCR_V6_SMALL_REC_ONNX.config.ensure()),+ device=kwargs.get("device"),+ det_db_box_thresh=kwargs.get("det_db_box_thresh", 0.5),+ det_db_unclip_ratio=kwargs.get("det_db_unclip_ratio", 1.5),+ enable_merge_det_boxes=kwargs.get("enable_merge_det_boxes", True),+ )+ else:+ atom_model = ocr_model_init(+ kwargs.get("det_db_box_thresh", 0.5),+ kwargs.get("lang"),+ kwargs.get("det_db_unclip_ratio", 1.5),+ kwargs.get("enable_merge_det_boxes", True),+ )- elif model_name == AtomicModel.WirelessTable:+ elif model_name == AtomicModelName.WirelessTable:atom_model = wireless_table_model_init(kwargs.get("lang"),)@@@ -285,9 -298,11 +307,13 @@@ class HybridLocalModelContextSingletondef ocr_det_batch_setting() -> bool:+ """根据运行设备和 PyTorch 版本确定是否启用 OCR 检测批处理。"""- import torch as _torch- from packaging import version+++ try:+ import torch as _torch+ from packaging import version+ except ImportError:+ return Truedevice_type = os.getenv("MINERU_LMDEPLOY_DEVICE", "")if device_type.lower() in ["corex"]:@@@ -370,26 -360,23 +396,21 @@@ class HybridLocalModelContextdet_db_box_thresh: float = 0.5,det_db_unclip_ratio: float = 1.5,enable_merge_det_boxes: bool = True,- ) -> PytorchPaddleOCR:+ ) -> "PytorchPaddleOCR":"""获取 OCR 原子模型,默认使用当前 Hybrid 本地上下文语言并复用 singleton 缓存。"""return self.atom_model_manager.get_atom_model(- atom_model_name=AtomicModel.OCR,+ atom_model_name=AtomicModelName.OCR,det_db_box_thresh=det_db_box_thresh,- lang=self.lang if lang is None else lang,+ lang="ch",det_db_unclip_ratio=det_db_unclip_ratio,enable_merge_det_boxes=enable_merge_det_boxes,)- def get_layout_model(self) -> PPDocLayoutV2LayoutModel:+ def get_layout_model(self) -> "PPDocLayoutV2LayoutModel":"""获取 Layout 原子模型,供 Hybrid 本地 layout、标题拆分和公式框检测复用。"""return self.atom_model_manager.get_atom_model(- atom_model_name=AtomicModel.Layout,+ atom_model_name=AtomicModelName.Layout,- pp_doclayout_v2_weights=str(- os.path.join(- auto_download_and_get_model_root_path(ModelPath.pp_doclayout_v2),- ModelPath.pp_doclayout_v2,- )- ),+ pp_doclayout_v2_weights=str(PDF_EXTRACT_KIT.pp_doclayout_v2.ensure()),device=self.device,)@@@ -397,40 -384,7 +418,40 @@@"""获取公式识别原子模型,统一复用当前公式模型配置和设备。"""mfr_model_path = _resolve_mfr_model_path()return self.atom_model_manager.get_atom_model(- atom_model_name=AtomicModel.MFR,+ atom_model_name=AtomicModelName.MFR,- mfr_weight_dir=str(os.path.join(auto_download_and_get_model_root_path(mfr_model_path), mfr_model_path)),+ mfr_weight_dir=str(mfr_model_path.ensure()),device=self.device,)++ def get_wireless_table_model(self) -> PaddleTableModel:+ """获取无线表格识别原子模型。"""+ return self.atom_model_manager.get_atom_model(+ atom_model_name=AtomicModelName.WirelessTable,+ lang="ch",+ )++ def get_wired_table_model(self) -> UnetTableModel:+ """获取有线表格识别原子模型。"""+ return self.atom_model_manager.get_atom_model(+ atom_model_name=AtomicModelName.WiredTable,+ lang="ch",+ )++ def get_table_cls_model(self) -> PaddleTableClsModel:+ """获取表格分类原子模型。"""+ return self.atom_model_manager.get_atom_model(+ atom_model_name=AtomicModelName.TableCls,+ )++ def get_table_orientation_cls_model(self) -> MineruTableOrientationClsModel:+ """获取表格方向分类原子模型。"""+ return self.atom_model_manager.get_atom_model(+ atom_model_name=AtomicModelName.TableOrientationCls,+ )++ def get_seal_ocr_model(self) -> PytorchPaddleOCR:+ """获取印章识别 OCR 原子模型"""+ return self.atom_model_manager.get_atom_model(+ atom_model_name=AtomicModelName.OCR,+ lang="seal",+ )diff --cc mineru/cli_old/common.pyindex 3e5e1101,5cf2ec05..24923a16--- a/mineru/cli_old/common.py+++ b/mineru/cli_old/common.py@@@ -12,21 -12,23 +12,21 @@@ from typing import Any, Callable, Sequefrom loguru import logger- from mineru.backend.office.analyze import analyze as office_analyze- from mineru.cli_old.visualization import select_pages_for_pdf_visualization- from mineru.parser.base import ParseResult- from mineru.render import render_content_list, render_markdown, render_structured_content- from mineru.render.writer import FileBasedDataWriter- from mineru.utils.backend_options import DEFAULT_BACKEND, DEFAULT_HYBRID_EFFORT, LOCAL_HYBRID_EFFORT, resolve_backend_and_effort- from mineru.utils.draw_bbox import draw_layout_bbox, draw_span_bbox- from mineru.utils.engine_utils import get_vlm_engine- from mineru.utils.guess_suffix_or_lang import guess_suffix_by_bytes- from mineru.utils.image_payload import ImagePayloadCache- from mineru.utils.pdf_image_tools import images_bytes_to_pdf_bytes- from mineru.utils.pdfium_guard import safe_rewrite_pdf_bytes_with_pdfium, safe_rewrite_pdf_bytes_with_pdfium_result--from ..backend.office.docx_analyze import office_docx_analyze-from ..backend.office.pptx_analyze import office_pptx_analyze-from ..backend.office.xlsx_analyze import office_xlsx_analyze++from ..backend.office.analyze import analyze as office_analyze+ from ..filetypes import IMAGE_EXTENSIONS, OFFICE_EXTENSIONS, PDF_EXTENSIONS+ from ..parser.base import ParseResult-from ..render import render_content_list, render_markdown, render_structured_content++from ..render import render_markdown, render_structured_content+ from ..render.writer import FileBasedDataWriterfrom ..types import PageInfo+ from ..utils.backend_options import DEFAULT_BACKEND, DEFAULT_HYBRID_EFFORT, LOCAL_HYBRID_EFFORT, resolve_backend_and_effort+ from ..utils.draw_bbox import draw_layout_bbox, draw_span_bbox+ from ..utils.engine_utils import get_vlm_engine+ from ..utils.guess_suffix_or_lang import guess_suffix_by_bytes+ from ..utils.image_payload import ImagePayloadCache+ from ..utils.pdf_image_tools import images_bytes_to_pdf_bytes+ from ..utils.pdfium_guard import safe_rewrite_pdf_bytes_with_pdfium, safe_rewrite_pdf_bytes_with_pdfium_resultfrom ..version import __version__+ from .visualization import select_pages_for_pdf_visualizationos.environ["TORCH_CUDNN_V8_API_DISABLED"] = "1"if os.getenv("MINERU_LMDEPLOY_DEVICE", "") == "maca":@@@ -314,12 -317,12 +315,6 @@@ def _process_output)if f_dump_content_list:-- content_list = render_content_list(get_public_render_pages(), image_dir)-- md_writer.write_string(-- f"{pdf_file_name}_content_list.json",-- json.dumps(content_list, ensure_ascii=False, indent=4),-- )--structured_content = render_structured_content(get_public_render_pages(), image_dir)md_writer.write_string(f"{pdf_file_name}_structured_content.json",diff --cc mineru/config.pyindex bc923859,b08fd33b..bd74d577--- a/mineru/config.py+++ b/mineru/config.py@@@ -7,10 -7,14 +7,14 @@@ import logginimport osimport reimport socket- from typing import Any, Literal+ import tempfile+ from collections.abc import Sequence+ from dataclasses import dataclass+ from typing import Any, Literal, get_args, get_originimport yaml+ from filelock import FileLock-from pydantic import BaseModel, Field+from pydantic import BaseModel, Field, field_validator, model_validatorfrom pydantic_core import to_jsonable_python_logger = logging.getLogger(__name__)@@@ -241,75 -353,12 +353,81 @@@ class ManagedParseServerConfig(BaseModeport_probe_count: int = Field(default=100, ge=1)+class LatexDelimiterConfig(BaseModel):+ """单组 LaTeX 左右定界符配置。"""++ left: str = Field(min_length=1)+ right: str = Field(min_length=1)+++def _default_display_latex_delimiter() -> LatexDelimiterConfig:+ """构造缺省行间公式定界符。"""+ return LatexDelimiterConfig(left="$$", right="$$")+++def _default_inline_latex_delimiter() -> LatexDelimiterConfig:+ """构造缺省行内公式定界符。"""+ return LatexDelimiterConfig(left="$", right="$")+++class LatexDelimitersConfig(BaseModel):+ """Markdown 行内与行间公式定界符配置。"""++ display: LatexDelimiterConfig = Field(default_factory=_default_display_latex_delimiter)+ inline: LatexDelimiterConfig = Field(default_factory=_default_inline_latex_delimiter)+++class RenderConfig(BaseModel):+ """MiddleJson 输出渲染配置。"""++ 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 ModelConfig(BaseModel):+ base_dir: str = _default_path("models")+ source: str = "auto"+ stack: str = "auto" # "auto" | "light" | "full"++class DoclibConfig(BaseModel):"""Doclib startup configuration.@@@ -355,11 -405,12 +474,13 @@@ class Config(BaseModel)"""Top-level MinerU startup configuration."""doclib: DoclibConfig = Field(default_factory=DoclibConfig)+ render: RenderConfig = Field(default_factory=RenderConfig)+ llm_aided: LLMAidedConfig = Field(default_factory=LLMAidedConfig)+ model: ModelConfig = Field(default_factory=ModelConfig)- # render: RenderConfig- config = _apply_env_overrides(Config(**_read_config()))+ _loaded_config = _load_effective_config()+ config = _loaded_config.configdef PatchedConfig(**kwargs: Any) -> Config:diff --cc mineru/doclib/services/parse_svc.pyindex 7c7b47c9,f1c29973..8839e34c--- a/mineru/doclib/services/parse_svc.py+++ b/mineru/doclib/services/parse_svc.py@@@ -14,17 -14,19 +14,19 @@@ from typing import Literal, casfrom urllib.parse import urlparsefrom ...errors import InvalidRequestError, MineruError- from ...parser.api_client import _V1APIError- from ...parser.base import ParseResult- from ...types import TIER_ORDER, PageInfo, Tier- from ..constants import (+ from ...filetypes import (IMAGE_EXTENSIONS,++ INGESTIBLE_EXTENSIONS,LEGACY_OFFICE_EXTENSION_UPGRADES,OFFICE_EXTENSIONS,- PARSEABLE_EXTENSIONS,- INGESTIBLE_EXTENSIONS,TEXT_EXTENSIONS,+ TIERED_PARSE_EXTENSIONS,+ file_type_for_extension,is_office_temp_lock_file,)+ from ...parser.api_client import _APITransportError, _V1APIError+ from ...parser.base import ParseResult+ from ...types import QUALITY_TIERS, TIER_ORDER, PageInfo, Tier, select_default_quality_tier, select_parsing_rule_tierfrom ..core.db import DatabaseManagerfrom ..core.file_io import FileStat, MetadataExtractionError, compute_sha256, extract_metadata, get_file_statfrom ..core.fts import FTSManager@@@ -64,15 -67,6 +67,7 @@@ class ParseFailure(MineruError)MAX_FTS_CHARS = 30_000FTS_HEAD_HALF = 15_000- DOC_TYPE_BY_EXT = {- "md": "markdown",- "markdown": "markdown",- **dict.fromkeys(IMAGE_EXTENSIONS, "image"),- }-- QUALITY_TIER_EXTENSIONS: set[str] = {"pdf", *IMAGE_EXTENSIONS}-+FileRefreshStatus = Literal["known", "new", "changed", "missing", "deleted", "unreachable", "unsupported", "error"]diff --cc mineru/kit/common.pyindex 3635898b,626d7996..d8f0111e--- a/mineru/kit/common.py+++ b/mineru/kit/common.py@@@ -13,24 -12,10 +12,11 @@@ from ..render.writer import FileBasedDafrom ..types import Tierfrom ..utils.image_payload import validate_image_sidecar_path- SupportedBundle = Literal["pipeline", "vlm", "all"]KitFormat = Literal["markdown", "middle_json", "zip"]- LocalTier = Literal["flash", "medium", "high", "extra_high"]-- SUPPORTED_SUFFIXES = {- ".pdf",- ".png",- ".jpeg",- ".jp2",- ".webp",- ".gif",- ".bmp",- ".jpg",- ".tiff",- ".docx",- ".pptx",- ".xlsx",- }+ LocalTier: TypeAlias = Tier++++ PARSEABLE_SUFFIXES = frozenset(f".{ext}" for ext in PARSEABLE_EXTENSIONS)OUTPUT_FILE_SUFFIXES = {"markdown": ".md","middle_json": ".json",diff --cc mineru/model/layout/pp_doclayoutv2.pyindex 6b0e06a9,4ca9d72d..9914bf47--- a/mineru/model/layout/pp_doclayoutv2.py+++ b/mineru/model/layout/pp_doclayoutv2.py@@@ -1044,630 -903,6 +903,586 @@@ class PPDocLayoutV2LayoutModel(PPDocLay)return layout_res+ @staticmethod+ def _calculate_bbox_area(box: Sequence[float]) -> float:+ xmin, ymin, xmax, ymax = [float(v) for v in box]+ return max(0.0, xmax - xmin) * max(0.0, ymax - ymin)++ @classmethod+ def _calculate_intersection_area(cls, box1: Sequence[float], box2: Sequence[float]) -> float:+ x1_min, y1_min, x1_max, y1_max = [float(v) for v in box1]+ x2_min, y2_min, x2_max, y2_max = [float(v) for v in box2]+ inter_xmin = max(x1_min, x2_min)+ inter_ymin = max(y1_min, y2_min)+ inter_xmax = min(x1_max, x2_max)+ inter_ymax = min(y1_max, y2_max)+ return cls._calculate_bbox_area((inter_xmin, inter_ymin, inter_xmax, inter_ymax))++ @classmethod+ def _calculate_overlap_ratio(cls, box1: Sequence[float], box2: Sequence[float]) -> float:+ inter_area = cls._calculate_intersection_area(box1, box2)+ ref_area = min(cls._calculate_bbox_area(box1), cls._calculate_bbox_area(box2))+ if ref_area <= 0.0:+ return 0.0+ return inter_area / ref_area++ @classmethod+ def _calculate_iou(cls, box1: Sequence[float], box2: Sequence[float]) -> float:+ inter_area = cls._calculate_intersection_area(box1, box2)+ union_area = cls._calculate_bbox_area(box1) + cls._calculate_bbox_area(box2) - inter_area+ if union_area <= 0.0:+ return 0.0+ return inter_area / union_area++ @classmethod+ def _calculate_cover_ratio(cls, box1: Sequence[float], box2: Sequence[float]) -> float:+ box1_area = cls._calculate_bbox_area(box1)+ if box1_area <= 0.0:+ return 0.0+ return cls._calculate_intersection_area(box1, box2) / box1_area++ @staticmethod+ def _calculate_x_overlap_ratio(box1: Sequence[float], box2: Sequence[float]) -> float:+ """计算两个 bbox 在横向上的重叠比例,用于判断是否属于同一栏。"""+ box1_xmin, _, box1_xmax, _ = [float(v) for v in box1]+ box2_xmin, _, box2_xmax, _ = [float(v) for v in box2]+ box1_width = max(0.0, box1_xmax - box1_xmin)+ box2_width = max(0.0, box2_xmax - box2_xmin)+ ref_width = min(box1_width, box2_width)+ if ref_width <= 0.0:+ return 0.0+ overlap_width = max(0.0, min(box1_xmax, box2_xmax) - max(box1_xmin, box2_xmin))+ return overlap_width / ref_width++ @staticmethod+ def _calculate_x_cover_ratio(anchor_box: Sequence[float], candidate_box: Sequence[float]) -> float:+ """计算 anchor 在横向上覆盖 candidate 的比例。"""+ anchor_xmin, _, anchor_xmax, _ = [float(v) for v in anchor_box]+ candidate_xmin, _, candidate_xmax, _ = [float(v) for v in candidate_box]+ candidate_width = max(0.0, candidate_xmax - candidate_xmin)+ if candidate_width <= 0.0:+ return 0.0+ overlap_width = max(+ 0.0,+ min(anchor_xmax, candidate_xmax) - max(anchor_xmin, candidate_xmin),+ )+ return overlap_width / candidate_width++ @classmethod+ def _is_footer_x_scope(+ cls,+ anchor_box: Dict,+ candidate_box: Dict,+ image_size: Optional[Tuple[int, int]],+ full_width_threshold: float = 0.7,+ x_overlap_threshold: float = 0.3,+ ) -> bool:+ """判断候选块是否在页脚文本锚点的横向作用范围内。"""+ anchor_bbox = anchor_box.get("bbox")+ candidate_bbox = candidate_box.get("bbox")+ if not anchor_bbox or not candidate_bbox:+ return False++ if image_size is not None and len(image_size) >= 2:+ page_width = float(image_size[1])+ anchor_width = max(0.0, float(anchor_bbox[2]) - float(anchor_bbox[0]))+ if page_width > 0.0 and anchor_width / page_width >= full_width_threshold:+ return True++ return cls._calculate_x_overlap_ratio(anchor_bbox, candidate_bbox) >= x_overlap_threshold++ @classmethod+ def _is_covered_by_footnote(+ cls,+ footnote_box: Dict,+ candidate_box: Dict,+ x_cover_threshold: float = 0.7,+ ) -> bool:+ """判断候选块是否位于 footnote 区域内或其下方,并被其横向覆盖。"""+ footnote_bbox = footnote_box.get("bbox")+ candidate_bbox = candidate_box.get("bbox")+ if not footnote_bbox or not candidate_bbox:+ return False+ if candidate_bbox[1] < footnote_bbox[1]:+ return False+ return cls._calculate_x_cover_ratio(footnote_bbox, candidate_bbox) >= x_cover_threshold++ @classmethod+ def _is_header_footer_boundary_candidate(cls, box: Dict, anchor_labels: set[str]) -> bool:+ """判断普通块是否可被页眉/页脚/页码边界规则改标。"""+ label = box.get("label")+ # 未被明确页眉页脚父框覆盖的公式仍保留公式身份,避免仅按页边位置误改标。+ if cls._is_formula_box(box):+ return False+ if label in cls.HEADER_FOOTER_BOUNDARY_EXEMPT_LABELS:+ return False+ return label not in anchor_labels++ @classmethod+ def _is_footnote_relabel_candidate(cls, box: Dict) -> bool:+ """排除页眉、页脚、页码、页边注等非正文区域块,保留正文内容块。"""+ return box.get("label") not in cls.PAGE_REGION_LABELS++ @staticmethod+ def _is_reference_box(box: Dict) -> bool:+ return box.get("label") == "reference" or int(box.get("cls_id", -1)) == 18++ @staticmethod+ def _is_display_formula_box(box: Dict) -> bool:+ return box.get("label") == "display_formula" or int(box.get("cls_id", -1)) == 5++ @staticmethod+ def _is_inline_formula_box(box: Dict) -> bool:+ return box.get("label") == "inline_formula" or int(box.get("cls_id", -1)) == 15++ @staticmethod+ def _is_formula_box(box: Dict) -> bool:- return (- PPDocLayoutV2LayoutModel._is_display_formula_box(box)- or PPDocLayoutV2LayoutModel._is_inline_formula_box(box)- )++ return PPDocLayoutV2LayoutModel._is_display_formula_box(box) or PPDocLayoutV2LayoutModel._is_inline_formula_box(box)++ @staticmethod+ def _is_formula_number_box(box: Dict) -> bool:+ return box.get("label") == "formula_number" or int(box.get("cls_id", -1)) == 11++ @staticmethod+ def _set_box_label(box: Dict, label: str) -> None:+ """统一同步设置 layout 检测框的标签名和类别编号。"""+ if label not in PP_DOCLAYOUT_V2_LABEL_TO_ID:+ raise ValueError(f"Unsupported PP-DocLayoutV2 label: {label}")+ box["label"] = label+ box["cls_id"] = PP_DOCLAYOUT_V2_LABEL_TO_ID[label]++ @staticmethod+ def _set_formula_label(box: Dict, label: str) -> None:+ if label not in {"inline_formula", "display_formula"}:+ raise ValueError(f"Unsupported formula label: {label}")+ PPDocLayoutV2LayoutModel._set_box_label(box, label)++ @staticmethod+ def _set_header_footer_label(box: Dict, label: str) -> None:+ """同步设置页眉/页脚相关标签及其类别编号。"""+ if label not in {"footer", "footer_image", "header", "header_image"}:+ raise ValueError(f"Unsupported header/footer label: {label}")+ PPDocLayoutV2LayoutModel._set_box_label(box, label)++ @staticmethod+ def _set_footnote_label(box: Dict) -> None:+ """同步设置 page footnote 标签及其类别编号。"""+ PPDocLayoutV2LayoutModel._set_box_label(box, "footnote")++ @classmethod+ def _filter_internal_visual_caption_boxes(+ cls,+ boxes: List[Dict],+ cover_threshold: float = 0.8,+ ) -> List[Dict]:+ """过滤落在图、表、印章等视觉主体内部的 figure_title。++ 这类块通常是图内的 (a)/(b) 标号,不应作为外部 caption 参与后续视觉分组。+ """+ visual_boxes = [box for box in boxes if box.get("label") in cls.VISUAL_BODY_LABELS]+ if not visual_boxes:+ return boxes++ filtered_boxes = []+ for box in boxes:+ if box.get("label") != "figure_title":+ filtered_boxes.append(box)+ continue++ caption_bbox = box.get("bbox")+ if not caption_bbox or len(caption_bbox) < 4:+ filtered_boxes.append(box)+ continue++ caption_center_x = (float(caption_bbox[0]) + float(caption_bbox[2])) / 2+ caption_center_y = (float(caption_bbox[1]) + float(caption_bbox[3])) / 2+ is_internal_caption = False+ for visual_box in visual_boxes:+ visual_bbox = visual_box.get("bbox")+ if not visual_bbox or len(visual_bbox) < 4:+ continue++ visual_xmin, visual_ymin, visual_xmax, visual_ymax = [float(v) for v in visual_bbox]- if not (- visual_xmin <= caption_center_x <= visual_xmax- and visual_ymin <= caption_center_y <= visual_ymax- ):++ if not (visual_xmin <= caption_center_x <= visual_xmax and visual_ymin <= caption_center_y <= visual_ymax):+ continue++ if cls._calculate_cover_ratio(caption_bbox, visual_bbox) >= cover_threshold:+ is_internal_caption = True+ break++ if not is_internal_caption:+ filtered_boxes.append(box)++ return filtered_boxes++ @classmethod+ def _reclassify_header_footer_by_page_half(+ cls,+ boxes: List[Dict],+ image_size: Optional[Tuple[int, int]],+ ) -> List[Dict]:+ """按页面上下半区重新校正页眉/页脚锚点,避免跨半页误触发边界规则。"""+ if image_size is None:+ return boxes++ page_height = float(image_size[0])+ if page_height <= 0:+ return boxes++ page_middle = page_height * 0.5+ upper_half_labels = {+ "footer": "header",+ "footer_image": "header_image",+ }+ lower_half_labels = {+ "header": "footer",+ "header_image": "footer_image",+ }+ for box in boxes:+ bbox = box.get("bbox")+ if not bbox or len(bbox) < 4:+ continue+ label = box.get("label")+ y_mid = (float(bbox[1]) + float(bbox[3])) / 2+ if y_mid < page_middle and label in upper_half_labels:+ cls._set_header_footer_label(box, upper_half_labels[label])+ elif y_mid >= page_middle and label in lower_half_labels:+ cls._set_header_footer_label(box, lower_half_labels[label])++ return boxes++ @staticmethod+ def _union_bbox(box1: Sequence[float], box2: Sequence[float]) -> List[int]:+ x1_min, y1_min, x1_max, y1_max = [float(v) for v in box1]+ x2_min, y2_min, x2_max, y2_max = [float(v) for v in box2]+ return [+ math.floor(min(x1_min, x2_min)),+ math.floor(min(y1_min, y2_min)),+ math.ceil(max(x1_max, x2_max)),+ math.ceil(max(y1_max, y2_max)),+ ]++ @staticmethod+ def _renumber_indices(boxes: List[Dict]) -> List[Dict]:+ for index, box in enumerate(boxes, start=1):+ box["index"] = index+ return boxes++ @classmethod+ def _deduplicate_boxes_by_iou(+ cls,+ boxes: List[Dict],+ iou_threshold: float = 0.9,+ ) -> List[Dict]:+ if len(boxes) <= 1:+ return boxes++ sorted_candidates = sorted(+ enumerate(boxes),+ key=lambda item: (-float(item[1].get("score", 0.0)), item[0]),+ )+ suppressed_indexes = set()+ kept_indexes = []++ for candidate_pos, (current_index, current_box) in enumerate(sorted_candidates):+ if current_index in suppressed_indexes:+ continue+ kept_indexes.append(current_index)+ for other_index, other_box in sorted_candidates[candidate_pos + 1 :]:+ if other_index in suppressed_indexes:+ continue+ if cls._calculate_iou(current_box["bbox"], other_box["bbox"]) > iou_threshold:+ suppressed_indexes.add(other_index)++ kept_indexes.sort()+ return [boxes[index] for index in kept_indexes]++ @classmethod+ def _merge_nested_formula_boxes(+ cls,+ boxes: List[Dict],+ overlap_threshold: float = 0.7,+ ) -> List[Dict]:+ if len(boxes) <= 1:+ return boxes++ changed = True+ while changed:+ changed = False+ formula_indexes = [index for index, box in enumerate(boxes) if cls._is_formula_box(box)]+ for formula_pos, left_index in enumerate(formula_indexes):+ for right_index in formula_indexes[formula_pos + 1 :]:+ left_box = boxes[left_index]+ right_box = boxes[right_index]+ if cls._calculate_overlap_ratio(left_box["bbox"], right_box["bbox"]) < overlap_threshold:+ continue++ left_area = cls._calculate_bbox_area(left_box["bbox"])+ right_area = cls._calculate_bbox_area(right_box["bbox"])+ if left_area > right_area:+ keep_index, drop_index = left_index, right_index+ elif right_area > left_area:+ keep_index, drop_index = right_index, left_index+ else:+ left_score = float(left_box.get("score", 0.0))+ right_score = float(right_box.get("score", 0.0))+ keep_index, drop_index = (- (left_index, right_index)- if left_score >= right_score- else (right_index, left_index)++ (left_index, right_index) if left_score >= right_score else (right_index, left_index)+ )++ keep_box = boxes[keep_index]+ drop_box = boxes[drop_index]+ keep_box["bbox"] = cls._union_bbox(keep_box["bbox"], drop_box["bbox"])+ keep_box["score"] = round(+ max(float(keep_box.get("score", 0.0)), float(drop_box.get("score", 0.0))),+ 4,+ )+ del boxes[drop_index]+ changed = True+ break+ if changed:+ break++ return boxes++ @classmethod+ def _relabel_formula_boxes(+ cls,+ boxes: List[Dict],+ overlap_threshold: float = 0.7,+ ) -> List[Dict]:+ parent_candidates = [+ box+ for box in boxes- if (- not cls._is_formula_box(box)- and not cls._is_formula_number_box(box)- and not cls._is_reference_box(box)- )++ if (not cls._is_formula_box(box) and not cls._is_formula_number_box(box) and not cls._is_reference_box(box))+ ]++ for box in boxes:+ if not cls._is_formula_box(box):+ continue+ target_label = "display_formula"+ for parent_box in parent_candidates:+ if cls._calculate_cover_ratio(box["bbox"], parent_box["bbox"]) >= overlap_threshold:+ target_label = "inline_formula"+ break+ cls._set_formula_label(box, target_label)++ return boxes++ @classmethod+ def _filter_formula_boxes_inside_page_marginals(+ cls,+ boxes: List[Dict],+ cover_threshold: float = 0.8,+ ) -> List[Dict]:+ """删除被明确页眉页脚父框覆盖的公式框,避免页边小公式生成重叠文本 span。"""++ marginal_labels = {"header", "header_image", "footer", "footer_image"}- marginal_parents = [- box- for box in boxes- if box.get("label") in marginal_labels- ]++ marginal_parents = [box for box in boxes if box.get("label") in marginal_labels]+ if not marginal_parents:+ return boxes++ filtered_boxes = []+ for box in boxes:+ if not cls._is_formula_box(box):+ filtered_boxes.append(box)+ continue+ # 仅按公式自身被明确父框覆盖的比例过滤,不使用页面上下坐标带猜测归属。- if any(- cls._calculate_cover_ratio(box["bbox"], parent["bbox"])- >= cover_threshold- for parent in marginal_parents- ):++ if any(cls._calculate_cover_ratio(box["bbox"], parent["bbox"]) >= cover_threshold for parent in marginal_parents):+ continue+ filtered_boxes.append(box)+ return filtered_boxes++ @classmethod+ def _relabel_header_footer_boundary_blocks(+ cls,+ boxes: List[Dict],+ image_size: Optional[Tuple[int, int]] = None,+ ) -> List[Dict]:+ """按视觉坐标用页眉/页脚锚点修正边界区域的普通块标签。"""+ if len(boxes) <= 1:+ return boxes++ header_labels = {"header", "header_image"}+ footer_labels = {"footer", "footer_image"}+ ordered_boxes = sorted(boxes, key=lambda box: box["index"])+ ordered_boxes = cls._reclassify_header_footer_by_page_half(+ ordered_boxes,+ image_size=image_size,+ )+ boundary_anchor_ids = {- id(box)- for box in ordered_boxes- if box.get("label") in header_labels or box.get("label") in footer_labels++ id(box) for box in ordered_boxes if box.get("label") in header_labels or box.get("label") in footer_labels+ }++ header_anchor = max(+ (box for box in ordered_boxes if box.get("label") in header_labels),+ key=lambda box: (box["bbox"][3], box["index"]),+ default=None,+ )+ footer_anchor = min(+ (box for box in ordered_boxes if box.get("label") in footer_labels),+ key=lambda box: (box["bbox"][1], box["index"]),+ default=None,+ )++ # 先按最后一个页眉锚点的下边界修正,后续页脚修正可覆盖重叠区间。+ if header_anchor is not None:+ header_boundary = header_anchor["bbox"][3]+ for box in ordered_boxes:+ if not cls._is_header_footer_boundary_candidate(box, header_labels):+ continue+ if box["bbox"][3] <= header_boundary:+ cls._set_box_label(box, "header")++ footnote_anchors = [box for box in ordered_boxes if box.get("label") == "footnote"]+ if footnote_anchors:+ for box in ordered_boxes:+ if not cls._is_footnote_relabel_candidate(box):+ continue+ for footnote_anchor in footnote_anchors:+ if cls._is_covered_by_footnote(footnote_anchor, box):+ cls._set_footnote_label(box)+ break++ if footer_anchor is not None:+ footer_boundary = footer_anchor["bbox"][1]+ for box in ordered_boxes:+ if not cls._is_header_footer_boundary_candidate(box, footer_labels):+ continue- if (- box["bbox"][1] >= footer_boundary- and cls._is_footer_x_scope(footer_anchor, box, image_size)- ):++ if box["bbox"][1] >= footer_boundary and cls._is_footer_x_scope(footer_anchor, box, image_size):+ cls._set_box_label(box, "footer")++ if image_size is None:+ return ordered_boxes++ page_height = float(image_size[0])+ if page_height <= 0:+ return ordered_boxes++ top_boundary = page_height * 0.3+ bottom_boundary = page_height * 0.7+ top_numbers = []+ bottom_numbers = []+ for box in ordered_boxes:+ if box.get("label") != "number":+ continue+ y_mid = (float(box["bbox"][1]) + float(box["bbox"][3])) / 2+ if y_mid <= top_boundary:+ top_numbers.append(box)+ elif y_mid >= bottom_boundary:+ bottom_numbers.append(box)++ top_number_anchor = max(+ top_numbers,+ key=lambda box: (box["bbox"][3], box["index"]),+ default=None,+ )+ bottom_number_anchor = min(+ bottom_numbers,+ key=lambda box: (box["bbox"][1], box["index"]),+ default=None,+ )++ # number 自身不改标签,仅用上下 30% 区域中的 number 作为辅助分割线。+ if top_number_anchor is not None:+ header_boundary = top_number_anchor["bbox"][1]+ for box in ordered_boxes:- if (- id(box) in boundary_anchor_ids- or not cls._is_header_footer_boundary_candidate(box, set())- ):++ if id(box) in boundary_anchor_ids or not cls._is_header_footer_boundary_candidate(box, set()):+ continue+ if box["bbox"][3] <= header_boundary:+ cls._set_box_label(box, "header")++ if bottom_number_anchor is not None:+ footer_boundary = bottom_number_anchor["bbox"][3]+ for box in ordered_boxes:- if (- id(box) in boundary_anchor_ids- or not cls._is_header_footer_boundary_candidate(box, set())- ):++ if id(box) in boundary_anchor_ids or not cls._is_header_footer_boundary_candidate(box, set()):+ continue+ if box["bbox"][1] >= footer_boundary:+ cls._set_box_label(box, "footer")++ return ordered_boxes++ @classmethod+ def _apply_layout_post_process(+ cls,+ boxes: List[Dict],+ image_size: Optional[Tuple[int, int]] = None,+ ) -> List[Dict]:+ processed_boxes = [{**box, "bbox": list(box["bbox"])} for box in boxes]+ processed_boxes = cls._deduplicate_boxes_by_iou(processed_boxes, iou_threshold=0.9)+ processed_boxes = cls._merge_nested_formula_boxes(processed_boxes, overlap_threshold=0.7)+ processed_boxes = cls._relabel_formula_boxes(processed_boxes, overlap_threshold=0.7)+ processed_boxes = cls._filter_formula_boxes_inside_page_marginals(+ processed_boxes,+ cover_threshold=0.8,+ )+ processed_boxes = cls._relabel_header_footer_boundary_blocks(+ processed_boxes,+ image_size=image_size,+ )+ processed_boxes = cls._filter_internal_visual_caption_boxes(+ processed_boxes,+ cover_threshold=0.8,+ )+ return cls._renumber_indices(processed_boxes)++ @classmethod+ def _apply_paddlex_filter_boxes(+ cls,+ boxes: List[Dict],+ drop_inline_formula: bool = True,+ ) -> List[Dict]:+ filtered_boxes = [dict(box) for box in boxes if not cls._is_reference_box(box)]+ dropped_indexes = set()++ for i in range(len(filtered_boxes)):+ if i in dropped_indexes:+ continue+ x1, y1, x2, y2 = filtered_boxes[i]["bbox"]+ width = float(x2) - float(x1)+ height = float(y2) - float(y1)- if (- (width < 6.0 or height < 6.0)- and (drop_inline_formula or not cls._is_inline_formula_box(filtered_boxes[i]))- ):++ if (width < 6.0 or height < 6.0) and (drop_inline_formula or not cls._is_inline_formula_box(filtered_boxes[i])):+ dropped_indexes.add(i)+ continue++ for j in range(i + 1, len(filtered_boxes)):+ if i in dropped_indexes or j in dropped_indexes:+ continue+- if (- not drop_inline_formula- and (- cls._is_inline_formula_box(filtered_boxes[i])- or cls._is_inline_formula_box(filtered_boxes[j])- )++ if not drop_inline_formula and (++ cls._is_inline_formula_box(filtered_boxes[i]) or cls._is_inline_formula_box(filtered_boxes[j])+ ):+ continue++ overlap_ratio = cls._calculate_overlap_ratio(+ filtered_boxes[i]["bbox"],+ filtered_boxes[j]["bbox"],+ )- if (- drop_inline_formula- and (- cls._is_inline_formula_box(filtered_boxes[i])- or cls._is_inline_formula_box(filtered_boxes[j])- )++ if drop_inline_formula and (++ cls._is_inline_formula_box(filtered_boxes[i]) or cls._is_inline_formula_box(filtered_boxes[j])+ ):+ if overlap_ratio > 0.5:+ if cls._is_inline_formula_box(filtered_boxes[i]):+ dropped_indexes.add(i)+ if cls._is_inline_formula_box(filtered_boxes[j]):+ dropped_indexes.add(j)+ continue++ if overlap_ratio > 0.7:+ box_area_i = cls._calculate_bbox_area(filtered_boxes[i]["bbox"])+ box_area_j = cls._calculate_bbox_area(filtered_boxes[j]["bbox"])+ labels = {filtered_boxes[i]["label"], filtered_boxes[j]["label"]}+ if labels & {"image", "table", "seal", "chart"} and len(labels) > 1:+ if "table" not in labels or labels <= {"table", "image", "seal", "chart"}:+ continue+ if box_area_i >= box_area_j:+ dropped_indexes.add(j)+ else:+ dropped_indexes.add(i)+- kept_boxes = [- box for index, box in enumerate(filtered_boxes) if index not in dropped_indexes- ]++ kept_boxes = [box for index, box in enumerate(filtered_boxes) if index not in dropped_indexes]+ return cls._renumber_indices(kept_boxes)+def predict(self,image: Union[np.ndarray, Image.Image],diff --cc mineru/model/mfr/post_process.pyindex 00000000,f740419d..2d11e7f0mode 000000,100644..100644--- a/mineru/model/mfr/post_process.py+++ b/mineru/model/mfr/post_process.py@@@ -1,0 -1,59 +1,39 @@@+ # Copyright (c) Opendatalab. All rights reserved.+ """公式识别后处理的公共逻辑。++ 从 ``pp_formulanet_plus_m/processors.py`` 的 ``UniMERNetDecode`` 类中提取,+ 供 torch 版和 ONNX 版共同复用,避免代码重复。+ """+++ from __future__ import annotations++ import re++ from ftfy import fix_text+-from .utils import (- fix_latex_environments,- fix_latex_left_right,- remove_unsupported_commands,- remove_up_commands,-)++from .utils import fix_pp_formulanet_latex+-_CHINESE_TEXT_WRAPPING_PATTERN = re.compile(r"\\text\s*{\s*([^}]*?[一-鿿]+[^}]*?)\s*}")++_CHINESE_TEXT_WRAPPING_PATTERN = re.compile(r"\\text\s*{\s*([^}]*?[\u4e00-\u9fff]+[^}]*?)\s*}")+++ def remove_chinese_text_wrapping(formula: str) -> str:+ """去掉中文文字外的 ``\\text{}`` 包裹。++ 与 ``UniMERNetDecode.remove_chinese_text_wrapping`` 行为一致。+ """+ replaced = _CHINESE_TEXT_WRAPPING_PATTERN.sub(lambda m: m.group(1), formula)+ return replaced.replace('"', "")++-def fix_latex(text: str) -> str:- """修复 LaTeX 格式。-- 与 ``UniMERNetDecode.fix_latex`` 行为一致:- 1. 平衡 ``\\left`` / ``\\right``- 2. 补全 ``\\begin{}`` / ``\\end{}``- 3. 移除 ``\\up`` 前缀- 4. 移除不支持的命令- """- text = fix_latex_left_right(text, fix_delimiter=False)- text = fix_latex_environments(text)- text = remove_up_commands(text)- text = remove_unsupported_commands(text)- return text--+ def post_process_formula(text: str) -> str:+ """公式文本的完整后处理流程。++ 与 ``UniMERNetDecode.post_process`` 行为一致:+ 1. 去掉中文 ``\\text{}`` 包裹+ 2. ftfy 修复 Unicode+ 3. 修复 LaTeX 格式+ """+ text = remove_chinese_text_wrapping(text)+ text = fix_text(text)- text = fix_latex(text)++ text = fix_pp_formulanet_latex(text)+ return textdiff --cc mineru/model/mfr/pp_formulanet_plus_m/processors.pyindex 18d90e06,e574519c..bd42c071--- a/mineru/model/mfr/pp_formulanet_plus_m/processors.py+++ b/mineru/model/mfr/pp_formulanet_plus_m/processors.py@@@ -1,14 -1,13 +1,12 @@@# Copyright (c) Opendatalab. All rights reserved.import json--import numpy as np--import cv2import mathimport re++from typing import Any, Dict, List, Optional, Tuple, Union++import cv2++import numpy as npfrom PIL import Image, ImageOps--from typing import List, Optional, Tuple, Union, Dict, Any--- from loguru import loggerfrom tokenizers import AddedTokenfrom tokenizers import Tokenizer as TokenizerFast@@@ -18,9 -17,9 +16,7 @@@ from mineru.model.mfr.post_process impoclass UniMERNetImgDecode(object):"""Class for decoding images for UniMERNet, including cropping margins, resizing, and padding."""-- def __init__(-- self, input_size: Tuple[int, int], random_padding: bool = False, **kwargs-- ) -> None:++ def __init__(self, input_size: Tuple[int, int], random_padding: bool = False, **kwargs) -> None:"""Initializes the UniMERNetImgDecode class with input size and random padding options.Args:@@@ -66,10 -65,10 +62,10 @@@return [channels, height, width]def _compute_resized_output_size(-- self,-- image_size: Tuple[int, int],-- size: Union[int, Tuple[int, int]],-- max_size: Optional[int] = None,++ self,++ image_size: Tuple[int, int],++ size: Union[int, Tuple[int, int]],++ max_size: Optional[int] = None,) -> List[int]:"""Computes the resized output size of the image.@@@ -85,9 -84,9 +81,7 @@@short, long = (w, h) if w <= h else (h, w)requested_new_short = size if isinstance(size, int) else size[0]-- new_short, new_long = requested_new_short, int(-- requested_new_short * long / short-- )++ new_short, new_long = requested_new_short, int(requested_new_short * long / short)if max_size is not None:if max_size <= requested_new_short:@@@ -103,9 -102,9 +97,7 @@@new_w, new_h = size[1], size[0]return [new_h, new_w]-- def resize(-- self, img: Image.Image, size: Union[int, Tuple[int, int]]-- ) -> Image.Image:++ def resize(self, img: Image.Image, size: Union[int, Tuple[int, int]]) -> Image.Image:"""Resizes the image to the specified size.Args:@@@ -118,9 -117,9 +110,7 @@@if isinstance(size, int):size = [size]max_size = None-- output_size = self._compute_resized_output_size(-- (image_height, image_width), size, max_size-- )++ output_size = self._compute_resized_output_size((image_height, image_width), size, max_size)img = img.resize(tuple(output_size[::-1]), resample=2)return img@@@ -234,9 -233,9 +224,7 @@@ class LatexImageFormatdivide_h = math.ceil(im_h / 16) * 16divide_w = math.ceil(im_w / 16) * 16img = img[:, :, 0]-- img = np.pad(-- img, ((0, divide_h - im_h), (0, divide_w - im_w)), constant_values=(1, 1)-- )++ img = np.pad(img, ((0, divide_h - im_h), (0, divide_w - im_w)), constant_values=(1, 1))img_expanded = img[:, :, np.newaxis].transpose(2, 0, 1)return img_expanded[np.newaxis, :]@@@ -307,9 -306,9 +295,9 @@@ class UniMERNetDecode(object)]def __init__(-- self,-- character_list: Dict[str, Any],-- **kwargs,++ self,++ character_list: Dict[str, Any],++ **kwargs,) -> None:"""Initializes the UniMERNetDecode class.@@@ -340,11 -339,11 +328,7 @@@fast_tokenizer_str = json.dumps(character_list["fast_tokenizer_file"])fast_tokenizer_buffer = fast_tokenizer_str.encode("utf-8")self.tokenizer = TokenizerFast.from_buffer(fast_tokenizer_buffer)-- tokenizer_config = (-- character_list["tokenizer_config_file"]-- if "tokenizer_config_file" in character_list-- else None-- )++ tokenizer_config = character_list["tokenizer_config_file"] if "tokenizer_config_file" in character_list else Noneadded_tokens_decoder = {}added_tokens_map = {}if tokenizer_config is not None:@@@ -364,19 -363,19 +348,13 @@@added_tokens_decoder = init_kwargs.pop("added_tokens_decoder", {})tokens_to_add = [token-- for index, token in sorted(-- added_tokens_decoder.items(), key=lambda x: x[0]-- )++ for index, token in sorted(added_tokens_decoder.items(), key=lambda x: x[0])if token not in added_tokens_decoder]added_tokens_encoder = self.added_tokens_encoder(added_tokens_decoder)-- encoder = list(added_tokens_encoder.keys()) + [-- str(token) for token in tokens_to_add-- ]++ encoder = list(added_tokens_encoder.keys()) + [str(token) for token in tokens_to_add]tokens_to_add += [-- token-- for token in self.all_special_tokens_extended-- if token not in encoder and token not in tokens_to_add++ token for token in self.all_special_tokens_extended if token not in encoder and token not in tokens_to_add]if len(tokens_to_add) > 0:is_last_special = None@@@ -398,7 -397,7 +376,7 @@@self._add_tokens(tokens, special_tokens=is_last_special)def _add_tokens(-- self, new_tokens: "List[Union[AddedToken, str]]", special_tokens: bool = False++ self, new_tokens: "List[Union[AddedToken, str]]", special_tokens: bool = False) -> "List[Union[AddedToken, str]]":"""Adds new tokens to the tokenizer.@@@ -414,9 -413,9 +392,7 @@@return self.tokenizer.add_tokens(new_tokens)-- def added_tokens_encoder(-- self, added_tokens_decoder: "Dict[int, AddedToken]"-- ) -> Dict[str, int]:++ def added_tokens_encoder(self, added_tokens_decoder: "Dict[int, AddedToken]") -> Dict[str, int]:"""Creates an encoder dictionary from added tokens.Args:@@@ -425,10 -424,10 +401,7 @@@Returns:Dict[str, int]: Dictionary mapping token strings to IDs."""-- return {-- k.content: v-- for v, k in sorted(added_tokens_decoder.items(), key=lambda item: item[0])-- }++ return {k.content: v for v, k in sorted(added_tokens_decoder.items(), key=lambda item: item[0])}@propertydef all_special_tokens(self) -> List[str]:@@@ -472,9 -471,9 +445,7 @@@set_attr[attr] = attr_valuereturn set_attr-- def convert_ids_to_tokens(-- self, ids: Union[int, List[int]], skip_special_tokens: bool = False-- ) -> Union[str, List[str]]:++ def convert_ids_to_tokens(self, ids: Union[int, List[int]], skip_special_tokens: bool = False) -> Union[str, List[str]]:"""Converts token IDs to token strings.Args:@@@ -513,11 -512,11 +484,11 @@@toks[b][i] = ""toks[b][i] = toks[b][i].replace("Ġ", " ").strip()if toks[b][i] in (-- [-- self.tokenizer.bos_token,-- self.tokenizer.eos_token,-- self.tokenizer.pad_token,-- ]++ [++ self.tokenizer.bos_token,++ self.tokenizer.eos_token,++ self.tokenizer.pad_token,++ ]):del toks[b][i]return toks@@@ -537,10 -536,10 +508,8 @@@if len(end_idx) > 0:end_idx = int(end_idx[0][0])tok_id = tok_id[: end_idx + 1]-- generated_text.append(-- self.tokenizer.decode(tok_id, skip_special_tokens=True)-- )- generated_text = [self.post_process(text) for text in generated_text]++ generated_text.append(self.tokenizer.decode(tok_id, skip_special_tokens=True))+ generated_text = [post_process_formula(text) for text in generated_text]return generated_textdef normalize(self, s: str) -> str:@@@ -561,14 -560,14 +530,14 @@@matches = re.findall(pattern, x[0])for m in matches:if (-- m-- not in [-- "\\operatorname",-- "\\mathrm",-- "\\text",-- "\\mathbf",-- ]-- and m.strip() != ""++ m++ not in [++ "\\operatorname",++ "\\mathrm",++ "\\text",++ "\\mathbf",++ ]++ and m.strip() != ""):s = s.replace(m, m + "XXXXXXX")s = s.replace(" ", "")@@@ -585,51 -584,13 +554,13 @@@breakreturn s.replace("XXXXXXX", " ")- def remove_chinese_text_wrapping(self, formula):- pattern = re.compile(r"\\text\s*{\s*([^}]*?[\u4e00-\u9fff]+[^}]*?)\s*}")-- def replacer(match):- return match.group(1)-- replaced_formula = pattern.sub(replacer, formula)- return replaced_formula.replace('"', "")-- def post_process(self, text: str) -> str:- """Post-processes a string by fixing text and normalizing it.-- Args:- text (str): String to post-process.-- Returns:- str: Post-processed string.- """- from ftfy import fix_text-- text = self.remove_chinese_text_wrapping(text)- text = fix_text(text)- # logger.debug(f"Text after ftfy fix: {text}")- text = self.fix_latex(text)- # logger.debug(f"Text after LaTeX fix: {text}")- return text-- def fix_latex(self, text: str) -> str:- """Fixes LaTeX formatting in a string.-- Args:- text (str): String to fix.-- Returns:- str: Fixed string.- """- return fix_pp_formulanet_latex(text)-def __call__(-- self,-- preds: np.ndarray,-- label: Optional[np.ndarray] = None,-- mode: str = "eval",-- *args,-- **kwargs,++ self,++ preds: np.ndarray,++ label: Optional[np.ndarray] = None,++ mode: str = "eval",++ *args,++ **kwargs,) -> Union[List[str], tuple]:"""Processes predictions and optionally labels, returning the decoded text.diff --cc mineru/model/table/cls/paddle_table_cls.pyindex 42eff60f,a470837c..2259e41b--- a/mineru/model/table/cls/paddle_table_cls.py+++ b/mineru/model/table/cls/paddle_table_cls.py@@@ -14,11 -10,9 +10,9 @@@ from ...utils.onnxruntime_provider impoclass PaddleTableClsModel:def __init__(self):- from mineru.backend.local_model_runtime import AtomicModel+ from mineru.model.model_types import AtomicModelName- self.sess = onnxruntime.InferenceSession(- os.path.join(auto_download_and_get_model_root_path(ModelPath.paddle_table_cls), ModelPath.paddle_table_cls)- )+ self.sess = ort_session(str(PDF_EXTRACT_KIT.paddle_table_cls.ensure()))self.less_length = 256self.cw, self.ch = 224, 224self.std = [0.229, 0.224, 0.225]diff --cc mineru/parser/__init__.pyindex 3882d59d,01e0c0b5..a046792f--- a/mineru/parser/__init__.py+++ b/mineru/parser/__init__.py@@@ -3,10 -3,11 +3,11 @@@ from __future__ import annotationfrom pathlib import Path-from ..filetypes import HTML_EXTENSIONS, OFFICE_EXTENSIONS, TIERED_PARSE_EXTENSIONS, ensure_tier_supported_for_parse_extension++from ..filetypes import OFFICE_EXTENSIONS, TIERED_PARSE_EXTENSIONS, ensure_tier_supported_for_parse_extensionfrom ..types import Tier+from ..utils.backend_options import DEFAULT_HYBRID_EFFORTfrom .api_client import MinerUApiParserfrom .base import MIDDLE_JSON_SCHEMA_VERSION, DocumentParser, ParseResult-from .html import HtmlParserfrom .office import DocxParser, PptxParser, XlsxParserfrom .pdf import PdfFlashParser, PdfHybridParser, PdfPipelineParser, PdfVlmParserfrom .tier import PARSER_BACKENDS, backend_for_tier, resolve_runtime_options, resolve_tier_and_backend@@@ -30,9 -33,7 +31,7 @@@ __all__ ="resolve_tier_and_backend",]- _OFFICE_SUFFIXES = frozenset({"docx", "pptx", "xlsx"})- _PDF_INPUT_SUFFIXES = frozenset({"pdf", "png", "jpeg", "jp2", "webp", "gif", "bmp", "jpg", "tiff"})- _PATH_PRIORITY_SUFFIXES = _OFFICE_SUFFIXES | _PDF_INPUT_SUFFIXES-_PATH_PRIORITY_SUFFIXES = OFFICE_EXTENSIONS | HTML_EXTENSIONS | TIERED_PARSE_EXTENSIONS++_PATH_PRIORITY_SUFFIXES = OFFICE_EXTENSIONS | TIERED_PARSE_EXTENSIONSdef _resolve_input_suffix(path: Path) -> str:@@@ -73,10 -76,16 +74,11 @@@ def _build_parser"xlsx": XlsxParser,}[suffix]return parser_cls()- elif suffix in HTML_EXTENSIONS:- if tier is not None or backend is not None:- runtime = resolve_runtime_options(tier=tier, backend=backend, effort=effort)- ensure_tier_supported_for_parse_extension(runtime.tier, suffix)- return HtmlParser()- if suffix not in _PDF_INPUT_SUFFIXES:+ if suffix not in TIERED_PARSE_EXTENSIONS:raise ValueError(f"Unsupported file type: {suffix or path.suffix or 'unknown'}")+ runtime = resolve_runtime_options(tier=tier, backend=backend, effort=effort)if runtime.backend.startswith("hybrid-"):return PdfHybridParser(backend=runtime.backend,diff --cc mineru/parser/api_server.pyindex c77e9b2f,99e36575..b1c63522--- a/mineru/parser/api_server.py+++ b/mineru/parser/api_server.py@@@ -988,29 -971,14 +971,14 @@@ def _get_job_store(request: Request) -def _resolve_access_level(request: Request) -> AccessLevel:"""Return ``"registered"`` when the server has an API key configured(the middleware already validated it), ``"anonymous"`` otherwise."""-- return (-- "registered" if request.app.state.api_key else "anonymous"-- ) # ═══════════════════════════════════════════════════════════════════════++ return "registered" if request.app.state.api_key else "anonymous"++# ═══════════════════════════════════════════════════════════════════════# JOB STORE# ═══════════════════════════════════════════════════════════════════════- _SUPPORTED_SUFFIXES: dict[str, str] = {- ".pdf": "pdf",- ".png": "image",- ".jpg": "image",- ".jpeg": "image",- ".jp2": "image",- ".webp": "image",- ".gif": "image",- ".bmp": "image",- ".tiff": "image",- ".docx": "docx",- ".pptx": "pptx",- ".xlsx": "xlsx",- }+_OUTPUT_FORMATS_LOCAL = set(_LOCAL_PARSE_OUTPUT_FORMATS)@@@ -2000,20 -2033,67 +2033,69 @@@ def _preflight_tier_dependencies(tier:raise ParseServerStartupError(str(exc)) from exc- def _dependency_tier_for_runtime(runtime: ParserRuntimeOptions) -> Tier:- """根据实际 runtime 判断依赖预检 tier。"""- return runtime.tier+ @dataclass(frozen=True)+ class _ModelPreloadResult:+ tier: DeploymentTier+ engine: str- def _preflight_runtime_dependencies(runtime_options: dict[Tier, ParserRuntimeOptions]) -> None:- """对多 tier server 的 runtime 依赖做去重预检,避免重复导入检查。"""- checked_tiers: set[Tier] = set()- for runtime in runtime_options.values():- dependency_tier = _dependency_tier_for_runtime(runtime)- if dependency_tier in checked_tiers:- continue- checked_tiers.add(dependency_tier)- _preflight_tier_dependencies(dependency_tier)+ @dataclass(frozen=True)+ class _ModelPreloadError:+ code: str+ message: str+++ _MODEL_PRELOAD_DEVICE_ERROR_PATTERNS = (+ "cuda is not available",+ "device is not available",+ "failed to infer device type",+ "no available accelerator",+ "no available gpu",+ "unsupported device",+ "only supported on macos",+ )+++ def _classify_model_preload_error(exc: Exception) -> tuple[str, str]:+ message = str(exc).strip() or type(exc).__name__+ if isinstance(exc, (ModuleNotFoundError, ImportError)):+ return "model_preload_dependency_missing", message+ if isinstance(exc, FileNotFoundError):+ return "model_preload_files_missing", message++ normalized_message = message.lower()+ if any(pattern in normalized_message for pattern in _MODEL_PRELOAD_DEVICE_ERROR_PATTERNS):+ return "model_preload_device_unavailable", message+ return "model_preload_failed", message+++ def _preload_local_models(language: str) -> None:- from ..backend.local_model_runtime import AtomicModel, HybridLocalModelContextSingleton++ # TODO: fix import++ from ..backend.local_model_runtime import HybridLocalModelContextSingleton++ from ..model.model_types import AtomicModelName++ context = HybridLocalModelContextSingleton().get_model(lang=language, formula_enable=True)+ manager = context.atom_model_manager- manager.get_atom_model(atom_model_name=AtomicModel.TableOrientationCls)- manager.get_atom_model(atom_model_name=AtomicModel.TableCls)- manager.get_atom_model(atom_model_name=AtomicModel.WirelessTable, lang=language)- manager.get_atom_model(atom_model_name=AtomicModel.WiredTable, lang=language)- manager.get_atom_model(atom_model_name=AtomicModel.OCR, lang="seal")++ manager.get_atom_model(atom_model_name=AtomicModelName.TableOrientationCls)++ manager.get_atom_model(atom_model_name=AtomicModelName.TableCls)++ manager.get_atom_model(atom_model_name=AtomicModelName.WirelessTable, lang=language)++ manager.get_atom_model(atom_model_name=AtomicModelName.WiredTable, lang=language)++ manager.get_atom_model(atom_model_name=AtomicModelName.OCR, lang="seal")+++ def _preload_server_models(tier: DeploymentTier, *, language: str) -> _ModelPreloadResult:+ if tier == "basic":+ _preload_local_models(language)+ return _ModelPreloadResult(tier=tier, engine="hybrid-local")++ from ..utils.engine_utils import get_vlm_engine++ engine = get_vlm_engine("auto", is_async=True)+ from ..model.vlm.runtime import ModelSingleton++ ModelSingleton().get_model(engine, None, None) # type: ignore[arg-type]+ _preload_local_models(language)+ return _ModelPreloadResult(tier=tier, engine=engine)def create_app(diff --cc mineru/render/__init__.pyindex e5bea943,df5aa296..75156600--- a/mineru/render/__init__.py+++ b/mineru/render/__init__.py@@@ -1,38 -1,12 +1,43 @@@+# Copyright (c) Opendatalab. All rights reserved.+++from .api import render+from .contracts import (+ AssetResolver,+ DocxRenderOptions,+ HtmlRenderOptions,+ MarkdownRenderMode,+ MarkdownRenderOptions,+ RenderFormat,+ RenderMode,+ RenderOptions,+ RenderOutput,+ StructuredContentRenderOptions,+)+from .docx import DocxRenderError, render_docx+from .html import render_html+ from .image import ImageRenderer, image_path_renderer+from .markdown import render_markdown+ from .markdown_table import to_markdown_table-from .union_make import render_content_list, render_markdown, render_structured_content+from .structured_content import render_structured_content- from .api import render__all__ = [+ "AssetResolver",+ "DocxRenderError",+ "DocxRenderOptions",+ "HtmlRenderOptions",+ "MarkdownRenderMode",+ "MarkdownRenderOptions",+ "RenderFormat",+ "RenderMode",+ "RenderOptions",+ "RenderOutput",+ "StructuredContentRenderOptions",+ "render",+ "render_docx",+ "render_html",+ "to_markdown_table",+ "ImageRenderer",+ "image_path_renderer",- "render_content_list","render_markdown","render_structured_content",]diff --cc mineru/render/markdown.pyindex 0ddf7c96,7936d095..16023a5d--- a/mineru/render/markdown.py+++ b/mineru/render/markdown.py@@@ -1,63 -1,123 +1,191 @@@-from ..types import Block, BlockType, ContentType-from .image import ImageRenderer, strip_embedded_image_tags-from .markdown_table import to_markdown_table-from .merge import merge_para_text-from .merge_visual import _build_media_path, merge_visual_para_text+# Copyright (c) Opendatalab. All rights reserved.+"""严格 MiddleJson 到 Markdown 的公共渲染实现。"""+from __future__ import annotations-def blocks_to_markdown(- para_blocks: list[Block],- img_bucket_path: str = "",- table_as_image: bool = False,- formula_as_image: bool = False,- no_rich_content: bool = False,- prefer_markdown_table: bool = False,- image_renderer: ImageRenderer | None = None,-) -> list[str]:- para_texts: list[str] = []- for para_block in para_blocks:- para_text = _block_to_markdown(- para_block=para_block,- img_bucket_path=img_bucket_path,- table_as_image=table_as_image,- formula_as_image=formula_as_image,- no_rich_content=no_rich_content,- prefer_markdown_table=prefer_markdown_table,- image_renderer=image_renderer,- )- if para_text := (para_text or "").strip():- para_texts.append(para_text)- return para_texts+from mineru.config import LatexDelimitersConfig, config- from mineru.render.contracts import MarkdownRenderMode+from mineru.render._internal.common.planner import PlannedBlock, build_render_plan+from mineru.render._internal.markdown.blocks import render_planned_block++from mineru.render.contracts import MarkdownRenderMode+from mineru.types import PAGE_AUXILIARY_BLOCK_TYPES, MiddleJson++_PAGE_SEPARATOR = "\n\n---\n\n"-def _block_to_markdown(- para_block: Block,- img_bucket_path: str = "",- table_as_image: bool = False,- formula_as_image: bool = False,- no_rich_content: bool = False,- prefer_markdown_table: bool = False,- image_renderer: ImageRenderer | None = None,-) -> str | None:- para_type = para_block.type- if para_type == BlockType.TEXT:- return merge_para_text(para_block)- if para_type == BlockType.TITLE:- title_level = _get_title_level(para_block)- return f"{'#' * title_level} {merge_para_text(para_block)}"- if para_type == BlockType.INDEX:- return merge_para_text(para_block)- if para_type == BlockType.ABSTRACT:- return merge_para_text(para_block)- if para_type == BlockType.REF_TEXT:- return merge_para_text(para_block)- if para_type == BlockType.LIST:- return merge_para_text(para_block)- if para_type == BlockType.PHONETIC:- return merge_para_text(para_block)- if para_type == BlockType.CODE:- return merge_visual_para_text(para_block)+def render_markdown(+ middle_json: MiddleJson,+ *,+ mode: MarkdownRenderMode = MarkdownRenderMode.DEFAULT,+ asset_base_url: str = "",+) -> str:+ """把严格 MiddleJson 纯函数式渲染为 Markdown 字符串。"""+ if not isinstance(middle_json, MiddleJson):+ raise TypeError("render_markdown expects a MiddleJson instance")+ if not isinstance(mode, MarkdownRenderMode):+ raise TypeError("mode must be a MarkdownRenderMode value")++ delimiters = config.render.latex_delimiters+ planned_pages = build_render_plan(middle_json, mode)+ rendered_pages = [+ _render_page(+ page,+ mode=mode,+ delimiters=delimiters,+ asset_base_url=asset_base_url,+ )+ for page in planned_pages+ ]+ if mode is MarkdownRenderMode.FULL:+ return _PAGE_SEPARATOR.join(rendered_pages)+ return "\n\n".join(page for page in rendered_pages if page)- if para_type == BlockType.INTERLINE_EQUATION:- if not formula_as_image:- if (para_text := merge_para_text(para_block)).strip():- return para_text- if image_renderer is not None:- return image_renderer(para_block)- return _build_image_link(para_block, ContentType.INTERLINE_EQUATION, img_bucket_path)- if no_rich_content:- return None- if para_type == BlockType.IMAGE:- return merge_visual_para_text(para_block, img_bucket_path, image_renderer=image_renderer)- if para_type == BlockType.TABLE:- if not table_as_image:- if prefer_markdown_table:- return _render_table_block_as_markdown_table(- para_block,- img_bucket_path,- image_renderer=image_renderer,- )- return merge_visual_para_text(para_block, img_bucket_path, image_renderer=image_renderer)- if image_renderer is not None:- return image_renderer(para_block)- return _build_image_link(para_block, ContentType.TABLE, img_bucket_path)- if para_type == BlockType.CHART:- return merge_visual_para_text(para_block, img_bucket_path, image_renderer=image_renderer)- return None+def _render_page(+ planned_blocks: list[PlannedBlock],+ *,+ mode: MarkdownRenderMode,+ delimiters: LatexDelimitersConfig,+ asset_base_url: str,+) -> str:+ """渲染单页逻辑块,并在默认模式中过滤重复页元素。"""+ rendered: list[str] = []+ for planned in planned_blocks:+ if planned.removed:+ continue+ if mode is MarkdownRenderMode.DEFAULT and planned.block.type in PAGE_AUXILIARY_BLOCK_TYPES:+ continue+ text = render_planned_block(planned, delimiters=delimiters, asset_base_url=asset_base_url)+ if text and text.strip():+ rendered.append(text.strip("\n"))+ return "\n\n".join(rendered)-def _get_title_level(block: Block) -> int:- title_level = block.level- if title_level is None:- title_level = 1- if title_level > 6:- title_level = 6- elif title_level < 1:- title_level = 0- return title_level+__all__ = ["MarkdownRenderMode", "render_markdown"]++-def _build_image_link(block: Block, target_span_type: str, img_bucket_path: str) -> str | None:- for line in block.lines:- for span in line.spans:- if span.type != target_span_type or not span.image_path:- continue- if media_path := _build_media_path(img_bucket_path, span.image_path):- return f""- return None++# OLD CODE For reference only:+++# from ..types import Block, BlockType, ContentType++# from .image import ImageRenderer, strip_embedded_image_tags++# from .markdown_table import to_markdown_table++# from .merge import merge_para_text++# from .merge_visual import _build_media_path, merge_visual_para_text++#++#++# def blocks_to_markdown(++# para_blocks: list[Block],++# img_bucket_path: str = "",++# table_as_image: bool = False,++# formula_as_image: bool = False,++# no_rich_content: bool = False,++# prefer_markdown_table: bool = False,++# image_renderer: ImageRenderer | None = None,++# ) -> list[str]:++# para_texts: list[str] = []++# for para_block in para_blocks:++# para_text = _block_to_markdown(++# para_block=para_block,++# img_bucket_path=img_bucket_path,++# table_as_image=table_as_image,++# formula_as_image=formula_as_image,++# no_rich_content=no_rich_content,++# prefer_markdown_table=prefer_markdown_table,++# image_renderer=image_renderer,++# )++# for page in planned_pages++# ]++# if mode is MarkdownRenderMode.FULL:++# return _PAGE_SEPARATOR.join(rendered_pages)++# return "\n\n".join(page for page in rendered_pages if page)+-def _render_table_block_as_markdown_table(- para_block: Block,- img_bucket_path: str,- image_renderer: ImageRenderer | None = None,-) -> str:- for span in para_block.all_spans():- if span.type != ContentType.TABLE or not span.content:- continue- table_html = span.content- if image_renderer is not None:- table_html = strip_embedded_image_tags(table_html)- return to_markdown_table(table_html)- return merge_visual_para_text(para_block, img_bucket_path, image_renderer=image_renderer)++# def _block_to_markdown(++# para_block: Block,++# img_bucket_path: str = "",++# table_as_image: bool = False,++# formula_as_image: bool = False,++# no_rich_content: bool = False,++# prefer_markdown_table: bool = False,++# image_renderer: ImageRenderer | None = None,++# ) -> str | None:++# para_type = para_block.type++# if para_type == BlockType.TEXT:++# return merge_para_text(para_block)++# if para_type == BlockType.TITLE:++# title_level = _get_title_level(para_block)++# return f"{'#' * title_level} {merge_para_text(para_block)}"++# if para_type == BlockType.INDEX:++# return merge_para_text(para_block)++# if para_type == BlockType.ABSTRACT:++# return merge_para_text(para_block)++# if para_type == BlockType.REF_TEXT:++# return merge_para_text(para_block)++# if para_type == BlockType.LIST:++# return merge_para_text(para_block)++# if para_type == BlockType.PHONETIC:++# return merge_para_text(para_block)++# if para_type == BlockType.CODE:++# return merge_visual_para_text(para_block)++#++# if para_type == BlockType.INTERLINE_EQUATION:++# if not formula_as_image:++# if (para_text := merge_para_text(para_block)).strip():++# return para_text++# if image_renderer is not None:++# return image_renderer(para_block)++# return _build_image_link(para_block, ContentType.INTERLINE_EQUATION, img_bucket_path)++#++# if no_rich_content:++# return None++# if para_type == BlockType.IMAGE:++# return merge_visual_para_text(para_block, img_bucket_path, image_renderer=image_renderer)++# if para_type == BlockType.TABLE:++# if not table_as_image:++# if prefer_markdown_table:++# return _render_table_block_as_markdown_table(++# para_block,++# img_bucket_path,++# image_renderer=image_renderer,++# )++# return merge_visual_para_text(para_block, img_bucket_path, image_renderer=image_renderer)++# if image_renderer is not None:++# return image_renderer(para_block)++# return _build_image_link(para_block, ContentType.TABLE, img_bucket_path)++# if para_type == BlockType.CHART:++# return merge_visual_para_text(para_block, img_bucket_path, image_renderer=image_renderer)++# return None++#++#++# def _get_title_level(block: Block) -> int:++# title_level = block.level++# if title_level is None:++# title_level = 1++# if title_level > 6:++# title_level = 6++# elif title_level < 1:++# title_level = 0++# return title_level++#++#++# def _build_image_link(block: Block, target_span_type: str, img_bucket_path: str) -> str | None:++# for line in block.lines:++# for span in line.spans:++# if span.type != target_span_type or not span.image_path:++# continue++# if media_path := _build_media_path(img_bucket_path, span.image_path):++# return f""++# return None++#++#++# def _render_table_block_as_markdown_table(++# para_block: Block,++# img_bucket_path: str,++# image_renderer: ImageRenderer | None = None,++# ) -> str:++# for span in para_block.all_spans():++# if span.type != ContentType.TABLE or not span.content:++# continue++# table_html = span.content++# if image_renderer is not None:++# table_html = strip_embedded_image_tags(table_html)++# return to_markdown_table(table_html)++# return merge_visual_para_text(para_block, img_bucket_path, image_renderer=image_renderer)diff --cc mineru/types.pyindex e0644afa,f64348d3..59ab7131--- a/mineru/types.py+++ b/mineru/types.py@@@ -1,41 -1,12 +1,48 @@@# Copyright (c) Opendatalab. All rights reserved.from __future__ import annotations+import json+import math+import os+ from collections.abc import Iterable-from dataclasses import MISSING, Field, InitVar, dataclass, field, fields-from typing import Any, Iterator, Literal, TypeAlias, TypeVar, get_type_hints+from dataclasses import dataclass+from pathlib import Path+from tempfile import NamedTemporaryFile+from typing import Annotated, Any, ClassVar, Literal, TypeAlias, Union+- from pydantic import BaseModel, ConfigDict, Field, TypeAdapter, field_validator, model_validator-++from pydantic import (++ BaseModel,++ ConfigDict,++ Field,++ TypeAdapter,++ field_validator,++ model_validator,++)-T = TypeVar("T", bound="_DocElement")+# 这些字符串不能作为公开 Block.type discriminator,只用于 raw 阶段或 Block 内部枚举值。+RawBlockType: TypeAlias = Literal[+ "algorithm",+ "caption",+ "footnote",+ "formula_number",+ "phonetic",+]+RAW_ALGORITHM: RawBlockType = "algorithm"+RAW_CAPTION: RawBlockType = "caption"+RAW_FOOTNOTE: RawBlockType = "footnote"+RAW_FORMULA_NUMBER: RawBlockType = "formula_number"+RAW_PHONETIC: RawBlockType = "phonetic"++RAW_ONLY_BLOCK_TYPES = frozenset(+ {+ RAW_ALGORITHM,+ RAW_CAPTION,+ RAW_FOOTNOTE,+ RAW_FORMULA_NUMBER,+ RAW_PHONETIC,+ }+)Tier = Literal["flash",@@@ -288,621 -404,265 +362,624 @@@ BBox: TypeAlias = tuple[float, float, fIntBBox: TypeAlias = tuple[int, int, int, int]-def _is_default_value(f: Field, value: Any) -> bool:- if f.default is not MISSING:- return value == f.default- if f.default_factory is not MISSING:- return value == f.default_factory()- return False+def _remove_block_fields(value: Any, excluded_fields: set[str]) -> Any:+ """递归删除序列化结果中指定的 block 字段,覆盖任意深度的容器。"""+ if isinstance(value, list):+ return [_remove_block_fields(item, excluded_fields) for item in value]+ if not isinstance(value, dict):+ return value++ result = {+ key: _remove_block_fields(item, excluded_fields)+ for key, item in value.items()+ if not ("type" in value and key in excluded_fields)+ }+ return result++class _StrictMiddleModel(BaseModel):+ """Middle JSON 严格模型基类,提供无副作用的统一序列化入口。"""-def _initvar_default(value: Any, default: Any) -> Any:- """修正 InitVar 与同名 property 共存时产生的 property 默认值。"""- return default if isinstance(value, property) else value+ model_config = ConfigDict(extra="forbid", strict=True, validate_assignment=True)+ def to_dict(+ self,+ *,+ skip_defaults: bool = True,+ exclude_none: bool = False,+ exclude_block_fields: set[str] | None = None,+ ) -> dict[str, Any]:+ """序列化对象,并按字段名递归排除任意层级的 block 字段。"""+ payload = self.model_dump(+ mode="json",+ exclude_defaults=skip_defaults,+ exclude_none=exclude_none,+ )+ if exclude_block_fields:+ payload = _remove_block_fields(payload, set(exclude_block_fields))+ return payload++ def to_json(+ self,+ *,+ skip_defaults: bool = True,+ exclude_none: bool = False,+ exclude_block_fields: set[str] | None = None,+ indent: int | None = 4,+ ) -> str:+ """将对象编码为 UTF-8 友好的 JSON 字符串,不执行图片文件写入。"""+ return json.dumps(+ self.to_dict(+ skip_defaults=skip_defaults,+ exclude_none=exclude_none,+ exclude_block_fields=exclude_block_fields,+ ),+ ensure_ascii=False,+ indent=indent,+ )+++class BlockBase(_StrictMiddleModel):+ """所有公开 Middle JSON block 的最小公共字段。"""++ type: BlockTypes+ index: int | None = Field(default=None, ge=0)+ bbox: BBox | None = None++ @field_validator("bbox", mode="before")+ @classmethod+ def _validate_bbox(cls, value: Any) -> BBox | None:+ """接受 JSON 数组形式的 bbox,并严格校验归一化坐标。"""+ if value is None:+ return None+ if not isinstance(value, (list, tuple)) or len(value) != 4:+ raise ValueError("bbox must contain exactly four numbers")+ if any(isinstance(item, bool) or not isinstance(item, (int, float)) for item in value):+ raise ValueError("bbox values must be numbers")+ bbox = tuple(float(item) for item in value)+ if not all(math.isfinite(item) and 0.0 <= item <= 1.0 for item in bbox):+ raise ValueError("bbox values must be finite normalized coordinates")+ if bbox[2] <= bbox[0] or bbox[3] <= bbox[1]:+ raise ValueError("bbox must satisfy x1 > x0 and y1 > y0")+ return bbox # type: ignore[return-value]-EMPTY_BBOX: BBox = (0.0, 0.0, 0.0, 0.0)+class StringContentBlock(BlockBase):+ """所有字符串内容 block 的共享结构。"""-def _origin_is_list(tp: Any) -> bool:- return getattr(tp, "__origin__", None) is list+ content: str-def _list_arg(tp: Any) -> Any | None:- args = getattr(tp, "__args__", None)- return args[0] if args else None+class ContinuableTextBlockBase(StringContentBlock):+ """正文与参考文献共享的跨块续接结构。"""+ continues_prev: bool | None = None-@dataclass-class _DocElement:- """Base class for document-model nodes (Span, Line, Block, PageInfo)."""- def to_dict(self, *, skip_defaults: bool = True) -> dict[str, Any]:- """Serialize to dict, excluding private fields (prefixed with ``_``).+class TextBlock(ContinuableTextBlockBase):+ type: Literal[BlockType.TEXT]- When *skip_defaults* is True, fields whose value equals their- default are also omitted.- """- result: dict[str, Any] = {}- for f in fields(self):- if f.name.startswith("_"):- continue- value = getattr(self, f.name)- if skip_defaults and _is_default_value(f, value):- continue- if isinstance(value, list):- result[f.name] = [v.to_dict(skip_defaults=skip_defaults) if isinstance(v, _DocElement) else v for v in value]- else:- result[f.name] = value- return result+class RefTextBlock(ContinuableTextBlockBase):+ type: Literal[BlockType.REF_TEXT]+++class TitleBlockBase(StringContentBlock):+ """文档标题与段落标题的全局层级公共结构。"""++ anchor: str | None = None+ level: int+++class DocTitleBlock(TitleBlockBase):+ type: Literal[BlockType.DOC_TITLE]+ level: Literal[1]+++class ParagraphTitleBlock(TitleBlockBase):+ type: Literal[BlockType.PARAGRAPH_TITLE]+ level: int = Field(ge=2, le=6)+++class PageAuxTextBlock(StringContentBlock):+ """页眉、页脚、页码、边栏和页脚注释的共享文本结构。"""++ type: Literal[+ BlockType.HEADER,+ BlockType.FOOTER,+ BlockType.PAGE_NUMBER,+ BlockType.ASIDE_TEXT,+ BlockType.PAGE_FOOTNOTE,+ ]+++class ImagePayloadBlock(BlockBase):+ """直接携带图片 data URI 的 block 基类。"""++ image_base64: str | None = Field(default=None, repr=False)+ image_path: str | None = None++ @field_validator("image_path")@classmethod- def from_dict(cls: type[T], d: dict) -> T:- """Reconstruct from dict (inverse of ``to_dict``). Handles nested dataclass lists and list→tuple conversion."""- hints = get_type_hints(cls)- kwargs: dict[str, Any] = {}- for f in fields(cls):- if f.name.startswith("_"):+ def _validate_image_path(cls, value: str | None) -> str | None:+ """校验已记录的图片路径只能是安全的 POSIX 相对路径。"""+ if value is None:+ return None+ from .utils.image_payload import validate_image_sidecar_path++ return validate_image_sidecar_path(value)+++class ImagePayloadContentBlock(ImagePayloadBlock):+ """统一携带字符串内容和图片载荷的 block 结构。"""++ content: str+++class EquationBlock(ImagePayloadContentBlock):+ type: Literal[BlockType.EQUATION]+++class ImageBodyBlock(ImagePayloadContentBlock):+ type: Literal[BlockType.IMAGE_BODY]+++class TableBodyBlock(ImagePayloadContentBlock):+ type: Literal[BlockType.TABLE_BODY]+++class ChartBodyBlock(ImagePayloadContentBlock):+ type: Literal[BlockType.CHART_BODY]+++class CodeBodyBlock(StringContentBlock):+ type: Literal[BlockType.CODE_BODY]+++class ImageAnnotationBlock(StringContentBlock):+ """图片标题与图片脚注的共享结构。"""++ type: Literal[BlockType.IMAGE_CAPTION, BlockType.IMAGE_FOOTNOTE]+++class TableAnnotationBlock(StringContentBlock):+ """表格标题与表格脚注的共享结构。"""++ type: Literal[BlockType.TABLE_CAPTION, BlockType.TABLE_FOOTNOTE]+++class ChartAnnotationBlock(StringContentBlock):+ """图表标题与图表脚注的共享结构。"""++ type: Literal[BlockType.CHART_CAPTION, BlockType.CHART_FOOTNOTE]+++class CodeAnnotationBlock(StringContentBlock):+ """代码标题与代码脚注的共享结构。"""++ type: Literal[BlockType.CODE_CAPTION, BlockType.CODE_FOOTNOTE]+++ListChildBlock: TypeAlias = Annotated[+ Union[TextBlock, RefTextBlock, "ListBlock"],+ Field(discriminator="type"),+]+++class ListBlock(BlockBase):+ type: Literal[BlockType.LIST]+ content: list[ListChildBlock]+ sub_type: Literal[BlockType.TEXT, BlockType.REF_TEXT] | None = None+ continues_prev: bool | None = None+++IndexChildBlock: TypeAlias = Annotated[+ Union[TextBlock, DocTitleBlock, ParagraphTitleBlock, "IndexBlock"],+ Field(discriminator="type"),+]+++class IndexBlock(BlockBase):+ type: Literal[BlockType.INDEX]+ content: list[IndexChildBlock]+++class _VisualBlockBase(BlockBase):+ """视觉父块的共享结构约束。"""++ _body_type: ClassVar[str]++ @model_validator(mode="after")+ def _validate_visual_children(self) -> _VisualBlockBase:+ """校验视觉父块只有一个 body,且父子定位字段保持一致。"""+ children = getattr(self, "content", [])+ bodies = [child for child in children if child.type == self._body_type]+ if len(bodies) != 1:+ raise ValueError(f"{self.type} must contain exactly one {self._body_type}")+ body = bodies[0]+ if self.index is not None and body.index != self.index:+ raise ValueError(f"{self.type} body index must equal parent index")+ if self.bbox is not None and body.bbox is not None and body.bbox != self.bbox:+ raise ValueError(f"{self.type} body bbox must equal parent bbox")+ return self+++ImageChildBlock: TypeAlias = Annotated[+ Union[ImageBodyBlock, ImageAnnotationBlock],+ Field(discriminator="type"),+]+++class ImageBlock(_VisualBlockBase):+ type: Literal[BlockType.IMAGE]+ content: list[ImageChildBlock]+ sub_type: str | None = None+ _body_type: ClassVar[str] = BlockType.IMAGE_BODY+++TableChildBlock: TypeAlias = Annotated[+ Union[TableBodyBlock, TableAnnotationBlock],+ Field(discriminator="type"),+]+++class TableBlock(_VisualBlockBase):+ type: Literal[BlockType.TABLE]+ content: list[TableChildBlock]+ continues_prev: bool | None = None+ cell_merge: list[Literal[0, 1]] | None = None+ _body_type: ClassVar[str] = BlockType.TABLE_BODY+++ChartChildBlock: TypeAlias = Annotated[+ Union[ChartBodyBlock, ChartAnnotationBlock],+ Field(discriminator="type"),+]+++class ChartBlock(_VisualBlockBase):+ type: Literal[BlockType.CHART]+ content: list[ChartChildBlock]+ sub_type: str | None = None+ _body_type: ClassVar[str] = BlockType.CHART_BODY+++CodeChildBlock: TypeAlias = Annotated[+ Union[CodeBodyBlock, CodeAnnotationBlock],+ Field(discriminator="type"),+]+++class CodeBlock(_VisualBlockBase):+ type: Literal[BlockType.CODE]+ content: list[CodeChildBlock]+ sub_type: Literal[BlockType.CODE, RAW_ALGORITHM]+ guess_lang: str | None = None+ _body_type: ClassVar[str] = BlockType.CODE_BODY++ @model_validator(mode="after")+ def _validate_language(self) -> CodeBlock:+ """代码块要求语言,算法块则禁止携带代码语言猜测结果。"""+ if self.sub_type == BlockType.CODE:+ if not isinstance(self.guess_lang, str) or not self.guess_lang.strip():+ raise ValueError("code block must contain a non-empty guess_lang")+ elif self.guess_lang is not None:+ raise ValueError("algorithm block must not contain guess_lang")+ return self+++ListBlock.model_rebuild()+IndexBlock.model_rebuild()+++PageBlock: TypeAlias = Annotated[+ Union[+ TextBlock,+ RefTextBlock,+ DocTitleBlock,+ ParagraphTitleBlock,+ PageAuxTextBlock,+ EquationBlock,+ ListBlock,+ IndexBlock,+ ImageBlock,+ TableBlock,+ ChartBlock,+ CodeBlock,+ ],+ Field(discriminator="type"),+]+++Block: TypeAlias = Annotated[+ Union[+ TextBlock,+ RefTextBlock,+ DocTitleBlock,+ ParagraphTitleBlock,+ PageAuxTextBlock,+ EquationBlock,+ ListBlock,+ IndexBlock,+ ImageBodyBlock,+ ImageAnnotationBlock,+ ImageBlock,+ TableBodyBlock,+ TableAnnotationBlock,+ TableBlock,+ ChartBodyBlock,+ ChartAnnotationBlock,+ ChartBlock,+ CodeBodyBlock,+ CodeAnnotationBlock,+ CodeBlock,+ ],+ Field(discriminator="type"),+]++BLOCK_ADAPTER = TypeAdapter(Block)+++def parse_block(value: Any) -> Block:+ """将字典或已有模型严格解析成对应的具体 Block 类型。"""+ return BLOCK_ADAPTER.validate_python(value)+++def _iter_child_blocks(block: BlockBase) -> list[BlockBase]:+ """返回容器 block 的直接子块,叶子 block 返回空列表。"""+ content = getattr(block, "content", None)+ if not isinstance(content, list):+ return []+ return [child for child in content if isinstance(child, BlockBase)]+++class PageInfo(_StrictMiddleModel):+ """一页的严格 Middle JSON 内容。"""++ page_idx: int = Field(ge=0)+ blocks: list[PageBlock] = Field(default_factory=list)++ @model_validator(mode="after")+ def _validate_page_tree(self) -> PageInfo:+ """校验顶层 index 顺序,并禁止嵌套块携带跨块延续标记。"""+ indices: list[int] = []+ for block in self.blocks:+ if block.index is None:+ raise ValueError("top-level block index is required")+ indices.append(block.index)+ if len(indices) != len(set(indices)):+ raise ValueError("top-level block indices must be unique")+ if any(current <= previous for previous, current in zip(indices, indices[1:])):+ raise ValueError("top-level block indices must be strictly increasing")++ pending = [child for block in self.blocks for child in _iter_child_blocks(block)]+ while pending:+ child = pending.pop()+ if "continues_prev" in child.model_fields_set:+ raise ValueError("nested blocks must not contain continues_prev")+ pending.extend(_iter_child_blocks(child))+ return self+++class MiddleJson(_StrictMiddleModel):+ """Analyze 返回的完整严格 Middle JSON 对象。"""++ pages: list[PageInfo]+ file_suffix: Literal["pdf", "docx", "pptx", "xlsx"]+ effort: Literal["flash", "low", "medium", "high", "xhigh"]+ parse_mode: Literal["txt", "ocr"]+ mineru_version: str = Field(min_length=1)++ @model_validator(mode="after")+ def _validate_document(self) -> MiddleJson:+ """校验页号唯一有序,并要求 PDF 顶层 block 均具有 bbox。"""+ page_indices = [page.page_idx for page in self.pages]+ if len(page_indices) != len(set(page_indices)):+ raise ValueError("page_idx values must be unique")+ if any(current <= previous for previous, current in zip(page_indices, page_indices[1:])):+ raise ValueError("page_idx values must be strictly increasing")+ if self.file_suffix == "pdf":+ for page in self.pages:+ for block in page.blocks:+ if block.bbox is None:+ raise ValueError(f"PDF top-level block requires bbox: page_idx={page.page_idx}, index={block.index}")+ return self++ def export(+ self,+ output_dir: str | Path,+ *,+ json_name: str = "middle_json.json",+ overwrite: bool = False,+ ) -> MiddleJsonExportResult:+ """在副本上外置全部图片,并原子写出不含 base64 的 Middle JSON。"""+ return _export_middle_json(self, Path(output_dir), json_name=json_name, overwrite=overwrite)+++@dataclass(frozen=True, slots=True)+class MiddleJsonExportResult:+ """Middle JSON 图片外置后的对象副本与实际文件路径。"""++ middle_json: MiddleJson+ json_path: Path+ image_paths: tuple[Path, ...]+++def _iter_page_blocks(blocks: list[Block]) -> list[BlockBase]:+ """按深度优先顺序展开页面 block 树,供图片外置统一遍历。"""+ result: list[BlockBase] = []+ pending: list[BlockBase] = list(reversed(blocks))+ while pending:+ block = pending.pop()+ result.append(block)+ pending.extend(reversed(_iter_child_blocks(block)))+ return result+++def _register_export_file(files: dict[str, bytes], relative_path: str, payload: bytes) -> None:+ """登记待写文件,并在同名内容冲突时立即终止导出。"""+ existing = files.get(relative_path)+ if existing is not None and existing != payload:+ raise ValueError(f"Conflicting image payload for path: {relative_path}")+ files[relative_path] = payload+++def _prepare_export_copy(middle_json: MiddleJson) -> tuple[MiddleJson, dict[str, bytes]]:+ """复制对象、解析直接及 HTML 图片,并回填副本中的相对路径。"""- from .utils.image_payload import INLINE_IMAGE_DATA_URI_RE, parse_image_data_uri_strict++ from .utils.image_payload import (++ INLINE_IMAGE_DATA_URI_RE,++ parse_image_data_uri_strict,++ )++ exported = middle_json.model_copy(deep=True)+ image_files: dict[str, bytes] = {}+ for page in exported.pages:+ for block in _iter_page_blocks(page.blocks):+ data_uri = getattr(block, "image_base64", None)+ if data_uri is not None:+ if block.index is None:+ raise ValueError(f"Image carrier requires index: page_idx={page.page_idx}, type={block.type}")+ image_bytes, extension = parse_image_data_uri_strict(data_uri)+ relative_path = f"images/page_{page.page_idx}_{block.type}_{block.index}.{extension}"+ _register_export_file(image_files, relative_path, image_bytes)+ block.image_path = relative_path # type: ignore[attr-defined]+ block.image_base64 = None # type: ignore[attr-defined]++ content = getattr(block, "content", None)+ if not isinstance(content, str) or "data:image/" not in content:continue- if f.name not in d:+ if block.index is None:+ raise ValueError(f"HTML image carrier requires index: page_idx={page.page_idx}, type={block.type}")+ ordinal = 0++ def _replace_data_uri(match: Any) -> str:+ """将当前 HTML data URI 登记为 sidecar,并返回确定性相对路径。"""+ nonlocal ordinal+ ordinal += 1+ image_bytes, extension = parse_image_data_uri_strict(match.group(0))+ relative_path = f"images/page_{page.page_idx}_{block.type}_{block.index}_{ordinal}.{extension}"+ _register_export_file(image_files, relative_path, image_bytes)+ return relative_path++ block.content = INLINE_IMAGE_DATA_URI_RE.sub(_replace_data_uri, content) # type: ignore[assignment]+ return exported, image_files+++def _resolve_export_target(output_root: Path, relative_path: str) -> Path:+ """校验导出相对路径并确保解析后的目标仍位于文档输出目录内。"""+ from .utils.image_payload import validate_image_sidecar_path++ safe_path = validate_image_sidecar_path(relative_path)+ if output_root.is_symlink():+ raise ValueError(f"Export directory must not be a symlink: {output_root}")+ if output_root.exists() and not output_root.is_dir():+ raise ValueError(f"Export directory must be a directory: {output_root}")+ root = output_root.resolve()+ target = root / safe_path+ current_parent = root+ for path_part in Path(safe_path).parts[:-1]:+ current_parent /= path_part+ if current_parent.is_symlink():+ raise ValueError(f"Export path contains a symlink: {relative_path}")+ if current_parent.exists() and not current_parent.is_dir():+ raise ValueError(f"Export path parent is not a directory: {relative_path}")+ try:+ target.parent.resolve(strict=False).relative_to(root)+ except ValueError as exc:+ raise ValueError(f"Export path escapes output directory: {relative_path}") from exc+ return target+++def _commit_export_files(files: dict[Path, bytes], *, overwrite: bool) -> None:+ """预检冲突后以临时文件提交,并在提交失败时恢复已有文件。"""+ pending: dict[Path, bytes] = {}+ originals: dict[Path, bytes | None] = {}+ for target, payload in files.items():+ if target.is_symlink():+ raise ValueError(f"Export target must not be a symlink: {target}")+ if target.exists():+ if not target.is_file():+ raise ValueError(f"Export target is not a regular file: {target}")+ current = target.read_bytes()+ if current == payload:continue- value = d[f.name]- f_type = hints.get(f.name)- if f_type is not None and _origin_is_list(f_type):- elem_type = _list_arg(f_type)- if isinstance(elem_type, type) and issubclass(elem_type, _DocElement):- value = [elem_type.from_dict(v) for v in value]- if f.name in ("bbox", "page_size") and isinstance(value, list):- value = tuple(value)- kwargs[f.name] = value- return cls(**kwargs)---@dataclass-class Span(_DocElement):- """Leaf node of the block tree. Holds text, formula, image, or table content."""-- type: str- bbox: BBox- content: str = ""- score: float = 0.0- image_path: str = ""-- # Internal- _cross_page: bool = False- _np_img: Any = None-- _url: str = ""- _style: list[str] = field(default_factory=list)- _children: list[Span] = field(default_factory=list)-- _extra: dict = field(default_factory=dict)---@dataclass-class Line(_DocElement):- """A line within a block, containing one or more spans."""-- bbox: BBox- spans: list[Span] = field(default_factory=list)-- # Internal- _is_list_start: bool = False- _is_list_end: bool = False-- _code_type: str | None = None- _code_guess_lang: str | None = None---@dataclass-class Block(_DocElement):- """A layout block on a page. May nest child blocks (e.g. list items, image body)."""-- # Required- index: int- type: str- bbox: BBox- lines: list[Line] = field(default_factory=list)- blocks: list[Block] = field(default_factory=list)-- # Optional- level: int | None = None- sub_type: str = ""- guess_lang: str = ""- section_number: str = ""-- # Office- anchor: str = ""- start: int | None = None- ilevel: int | None = None-- # Init-only draft fields. These are accepted for backend conversion- # compatibility, but are not middle_json block fields and never serialize.- angle: InitVar[int | None] = None- score: InitVar[float | None] = None- merge_prev: InitVar[bool] = False- is_numbered_style: InitVar[bool] = False-- # Internal- _cross_page: bool = False- _angle: int | None = None- _layout_score: float | None = None- _merge_prev: bool = False- _is_numbered_style: bool = False- _lines_deleted: bool = False- _ocr_det_lines: list[Line] = field(default_factory=list)- _line_avg_height: int = 0- _cell_merge: list[int] = field(default_factory=list)- _fix_spans: list[Span] = field(default_factory=list)- _list_attribute: str = ""- _page_num: int | None = None- _page_size: tuple[float, float] | None = None- _bbox_fs: BBox | None = None- _sub_images: list[Block] = field(default_factory=list)-- def __post_init__(- self,- angle: int | None,- score: float | None,- merge_prev: bool,- is_numbered_style: bool,- ) -> None:- """接收转换阶段临时字段,但只存入内部属性,避免污染 middle_json 输出。"""- self._angle = _initvar_default(angle, None)- self._layout_score = _initvar_default(score, None)- self._merge_prev = _initvar_default(merge_prev, False)- self._is_numbered_style = _initvar_default(is_numbered_style, False)-- def to_dict(self, *, skip_defaults: bool = True) -> dict[str, Any]:- """仅在 staged middle_json 需要时输出 merge_prev 合并提示。"""- result = super().to_dict(skip_defaults=skip_defaults)- if self.merge_prev or not skip_defaults:- result["merge_prev"] = self.merge_prev- return result+ if not overwrite:+ raise FileExistsError(f"Export target already exists with different content: {target}")+ originals[target] = current+ else:+ originals[target] = None+ pending[target] = payload++ temp_paths: dict[Path, Path] = {}+ committed: list[Path] = []+ try:+ for target, payload in pending.items():+ target.parent.mkdir(parents=True, exist_ok=True)+ with NamedTemporaryFile(+ mode="wb",+ prefix=".mineru-export-",+ dir=target.parent,+ delete=False,+ ) as temp_file:+ temp_file.write(payload)+ temp_paths[target] = Path(temp_file.name)+ for target, temp_path in temp_paths.items():+ os.replace(temp_path, target)+ committed.append(target)+ except Exception:+ for temp_path in temp_paths.values():+ temp_path.unlink(missing_ok=True)+ for target in reversed(committed):+ original = originals[target]+ if original is None:+ target.unlink(missing_ok=True)+ else:+ target.write_bytes(original)+ raise- @classmethod- def from_dict(cls, d: dict) -> Block:- """读取 staged middle_json 中的 merge_prev 合并提示。"""- block = _DocElement.from_dict.__func__(cls, d)- if "merge_prev" in d:- block.merge_prev = bool(d.get("merge_prev", False))- return block-- @property- def angle(self) -> int | None:- """转换阶段读取的原始旋转角,默认不作为 middle_json block 字段输出。"""- return self._angle-- @angle.setter- def angle(self, value: int | None) -> None:- self._angle = value-- @property- def score(self) -> float | None:- """layout 置信度只作为内部调试/传递信息保存,不进入 public block。"""- return self._layout_score-- @score.setter- def score(self, value: float | None) -> None:- self._layout_score = value-- @property- def merge_prev(self) -> bool:- """raw content block 的合并提示,仅供段落合并阶段消费。"""- return self._merge_prev-- @merge_prev.setter- def merge_prev(self, value: bool) -> None:- self._merge_prev = value-- @property- def is_numbered_style(self) -> bool:- """Office 标题编号中间状态,生成 section_number 后不输出。"""- return self._is_numbered_style-- @is_numbered_style.setter- def is_numbered_style(self, value: bool) -> None:- self._is_numbered_style = value-- def all_spans(self) -> Iterator[Span]:- """Depth-first yield every span in this block tree."""- for line in self.lines:- yield from line.spans- for child in self.blocks:- yield from child.all_spans()---@dataclass-class PageInfo(_DocElement):- """Parsed content of a single page."""-- page_idx: int- page_size: tuple[int, int] | None = None- preproc_blocks: list[Block] = field(default_factory=list)- para_blocks: list[Block] = field(default_factory=list)- discarded_blocks: list[Block] = field(default_factory=list)-- # Temporary — will be removed once the render layer converges.- _backend: Literal["hybrid", "office"] | None = None---@dataclass-class ContentItem(_DocElement):- """A single item in the Content List (V1) output format."""-- type: str- page_idx: int = 0- bbox: IntBBox | None = None- text: str | None = None- text_level: int | None = None- text_format: str | None = None- img_path: str | None = None- content: str | None = None- sub_type: str | None = None- list_items: list[str] = field(default_factory=list)- image_caption: list[str] = field(default_factory=list)- image_footnote: list[str] = field(default_factory=list)- table_caption: list[str] = field(default_factory=list)- table_footnote: list[str] = field(default_factory=list)- table_body: str | None = None- chart_caption: list[str] = field(default_factory=list)- chart_footnote: list[str] = field(default_factory=list)- code_caption: list[str] = field(default_factory=list)- code_footnote: list[str] = field(default_factory=list)- code_body: str | None = None++def _validate_export_path_relationships(relative_paths: list[str]) -> None:+ """拒绝任一导出文件占用另一文件的父目录,避免提交阶段才产生冲突。"""+ path_parts = {relative_path: Path(relative_path).parts for relative_path in relative_paths}+ for relative_path, parts in path_parts.items():+ for other_path, other_parts in path_parts.items():+ if relative_path == other_path or len(parts) >= len(other_parts):+ continue+ if other_parts[: len(parts)] == parts:+ raise ValueError(f"Export file path conflicts with a required directory: {relative_path} -> {other_path}")+++def _export_middle_json(+ middle_json: MiddleJson,+ output_dir: Path,+ *,+ json_name: str,+ overwrite: bool,+) -> MiddleJsonExportResult:+ """构造完整导出事务,保证 JSON 与图片使用同一份规范化对象副本。"""+ from .utils.image_payload import validate_image_sidecar_path++ exported, image_files = _prepare_export_copy(middle_json)+ json_text = exported.to_json(+ exclude_block_fields={"image_base64"},+ )+ if "data:image/" in json_text.lower():+ raise ValueError("Exported Middle JSON still contains an inline image data URI")+ json_bytes = json_text.encode("utf-8")+ safe_json_name = validate_image_sidecar_path(json_name)+ relative_files = dict(image_files)+ if safe_json_name in relative_files:+ raise ValueError(f"JSON path conflicts with an exported image: {safe_json_name}")+ relative_files[safe_json_name] = json_bytes+ _validate_export_path_relationships(list(relative_files))+ absolute_files = {+ _resolve_export_target(output_dir, relative_path): payload for relative_path, payload in relative_files.items()+ }+ _commit_export_files(absolute_files, overwrite=overwrite)+ json_path = _resolve_export_target(output_dir, safe_json_name)+ image_paths = tuple(_resolve_export_target(output_dir, relative_path) for relative_path in sorted(image_files))+ return MiddleJsonExportResult(+ middle_json=exported,+ json_path=json_path,+ image_paths=image_paths,+ )diff --cc mineru/utils/pdf_document.pyindex 826beec6,074850ef..ff79644c--- a/mineru/utils/pdf_document.py+++ b/mineru/utils/pdf_document.py@@@ -2,15 -2,12 +2,17 @@@from __future__ import annotationsimport asyncio+import ctypes+import hashlib+ import logging+import mathimport os+ import timefrom contextlib import contextmanager+from dataclasses import dataclassfrom io import BytesIOfrom typing import Any, Iterator, Literal, TypeAlias, cast+from urllib.parse import urlsplitimport numpy as npimport pypdfium2 as pdfium@@@ -530,1317 -405,6 +604,1282 @@@ class PDFDocument_try_close(page)+def _normalize_pdf_page_bbox(bbox: tuple[float, float, float, float]) -> BBox:+ """规范化 PDFium 页面框,兼容上下坐标顺序相反的测试或异常文档。"""+ x0, y0, x1, y1 = (float(value) for value in bbox)+ return min(x0, x1), min(y0, y1), max(x0, x1), max(y0, y1)+++def _drawing_page_size(page_bbox: BBox, page_rotation: int) -> tuple[float, float]:+ """根据未旋转页面框和页面旋转角计算左上坐标系中的页面尺寸。"""+ width = page_bbox[2] - page_bbox[0]+ height = page_bbox[3] - page_bbox[1]+ if page_rotation in (90, 270):+ return height, width+ return width, height+++def _transform_drawing_point(+ point: tuple[float, float],+ page_bbox: BBox,+ page_rotation: int,+) -> tuple[float, float]:+ """把 PDF 底左原点坐标转换为应用页面旋转后的左上原点坐标。"""+ x, y = point+ left, bottom, right, top = page_bbox+ if page_rotation == 90:+ return y - bottom, x - left+ if page_rotation == 180:+ return right - x, y - bottom+ if page_rotation == 270:+ return top - y, right - x+ return x - left, top - y+++def _multiply_pdf_matrices(+ first: tuple[float, float, float, float, float, float],+ second: tuple[float, float, float, float, float, float],+) -> tuple[float, float, float, float, float, float]:+ """按 PDF 行向量约定合并对象矩阵与父 Form 矩阵。"""+ a1, b1, c1, d1, e1, f1 = first+ a2, b2, c2, d2, e2, f2 = second+ return (+ a1 * a2 + b1 * c2,+ a1 * b2 + b1 * d2,+ c1 * a2 + d1 * c2,+ c1 * b2 + d1 * d2,+ e1 * a2 + f1 * c2 + e2,+ e1 * b2 + f1 * d2 + f2,+ )+++def _apply_pdf_matrix(+ point: tuple[float, float],+ matrix: tuple[float, float, float, float, float, float],+) -> tuple[float, float]:+ """将 PDF 仿射矩阵应用到一个路径点。"""+ x, y = point+ a, b, c, d, e, f = matrix+ return a * x + c * y + e, b * x + d * y + f+++def _get_raw_object_matrix(raw_obj: Any) -> tuple[float, float, float, float, float, float] | None:+ """读取一个原始 PDFium 页面对象矩阵,读取失败时返回 None。"""+ matrix = pdfium_c.FS_MATRIX()+ try:+ ok = pdfium_c.FPDFPageObj_GetMatrix(raw_obj, ctypes.byref(matrix))+ except Exception:+ return None+ if not ok:+ return None+ return (+ float(matrix.a),+ float(matrix.b),+ float(matrix.c),+ float(matrix.d),+ float(matrix.e),+ float(matrix.f),+ )+++def _walk_raw_page_objects_with_depth(+ container: Any,+ *,+ is_form: bool,+ parent_matrix: tuple[float, float, float, float, float, float],+ depth: int,+ target_type: int,+) -> Iterator[tuple[Any, tuple[float, float, float, float, float, float], int]]:+ """递归遍历目标对象,并携带累积矩阵及所在 Form 深度。"""+ if depth >= DRAWING_FORM_MAX_DEPTH:+ return++ count_objects = pdfium_c.FPDFFormObj_CountObjects if is_form else pdfium_c.FPDFPage_CountObjects+ get_object = pdfium_c.FPDFFormObj_GetObject if is_form else pdfium_c.FPDFPage_GetObject+ try:+ object_count = int(count_objects(container))+ except Exception:+ return+ if object_count < 0:+ return++ for object_index in range(object_count):+ try:+ raw_obj = get_object(container, object_index)+ if not raw_obj:+ continue+ object_type = int(pdfium_c.FPDFPageObj_GetType(raw_obj))+ object_matrix = _get_raw_object_matrix(raw_obj)+ if object_matrix is None:+ continue+ combined_matrix = _multiply_pdf_matrices(object_matrix, parent_matrix)+ except Exception:+ # 单个损坏页面对象不能中断同页其他目标对象遍历。+ continue++ if object_type == target_type:+ yield raw_obj, combined_matrix, depth+ if object_type == pdfium_c.FPDF_PAGEOBJ_FORM:+ yield from _walk_raw_page_objects_with_depth(+ raw_obj,+ is_form=True,+ parent_matrix=combined_matrix,+ depth=depth + 1,+ target_type=target_type,+ )+++def _walk_raw_page_objects(+ container: Any,+ *,+ is_form: bool,+ parent_matrix: tuple[float, float, float, float, float, float],+ depth: int,+ target_type: int,+) -> Iterator[tuple[Any, tuple[float, float, float, float, float, float]]]:+ """兼容既有调用,仅返回目标对象及累积到页面坐标的矩阵。"""++ for raw_obj, matrix, _form_depth in _walk_raw_page_objects_with_depth(+ container,+ is_form=is_form,+ parent_matrix=parent_matrix,+ depth=depth,+ target_type=target_type,+ ):+ yield raw_obj, matrix+++def _walk_raw_path_objects(+ container: Any,+ *,+ is_form: bool,+ parent_matrix: tuple[float, float, float, float, float, float],+ depth: int,+) -> Iterator[tuple[Any, tuple[float, float, float, float, float, float]]]:+ """递归遍历页面或 Form 中的 Path,并携带累积到页面坐标的矩阵。"""+ yield from _walk_raw_page_objects(+ container,+ is_form=is_form,+ parent_matrix=parent_matrix,+ depth=depth,+ target_type=pdfium_c.FPDF_PAGEOBJ_PATH,+ )+++def _iter_raw_path_objects(+ page: pdfium.PdfPage,+) -> Iterator[tuple[Any, tuple[float, float, float, float, float, float]]]:+ """从页面根对象开始遍历全部 Path,包括嵌套 Form 中的 Path。"""+ identity = (1.0, 0.0, 0.0, 1.0, 0.0, 0.0)+ yield from _walk_raw_path_objects(+ page,+ is_form=False,+ parent_matrix=identity,+ depth=0,+ )+++def _iter_raw_path_objects_with_depth(+ page: pdfium.PdfPage,+) -> Iterator[tuple[Any, tuple[float, float, float, float, float, float], int]]:+ """遍历全部 Path,并保留其所在 Form 深度供上层过滤图标。"""++ identity = (1.0, 0.0, 0.0, 1.0, 0.0, 0.0)+ yield from _walk_raw_page_objects_with_depth(+ page,+ is_form=False,+ parent_matrix=identity,+ depth=0,+ target_type=pdfium_c.FPDF_PAGEOBJ_PATH,+ )+++def _iter_raw_image_objects(+ page: pdfium.PdfPage,+) -> Iterator[tuple[Any, tuple[float, float, float, float, float, float]]]:+ """从页面根对象开始遍历全部点阵图,包括嵌套 Form 中的图片。"""+ identity = (1.0, 0.0, 0.0, 1.0, 0.0, 0.0)+ yield from _walk_raw_page_objects(+ page,+ is_form=False,+ parent_matrix=identity,+ depth=0,+ target_type=pdfium_c.FPDF_PAGEOBJ_IMAGE,+ )+++def _iter_raw_root_form_objects(page: pdfium.PdfPage) -> Iterator[Any]:+ """只遍历页面根层的 Form,避免把同一矢量图的嵌套子 Form 重复输出。"""++ try:+ object_count = int(pdfium_c.FPDFPage_CountObjects(page))+ except Exception:+ return+ if object_count < 0:+ return++ for object_index in range(object_count):+ try:+ raw_obj = pdfium_c.FPDFPage_GetObject(page, object_index)+ if raw_obj and int(pdfium_c.FPDFPageObj_GetType(raw_obj)) == pdfium_c.FPDF_PAGEOBJ_FORM:+ yield raw_obj+ except Exception:+ # 单个损坏对象不能阻断同页其他顶层 Form 的提取。+ continue+++def _get_raw_object_rgba(+ raw_obj: Any,+ color_getter: Any,+) -> tuple[int, int, int, int] | None:+ """读取对象 RGBA;旧 PDFium、不支持的对象或读取失败时返回 None。"""++ red = ctypes.c_uint()+ green = ctypes.c_uint()+ blue = ctypes.c_uint()+ alpha = ctypes.c_uint()+ try:+ ok = color_getter(+ raw_obj,+ ctypes.byref(red),+ ctypes.byref(green),+ ctypes.byref(blue),+ ctypes.byref(alpha),+ )+ except Exception:+ return None+ if not ok:+ return None+ return (+ int(red.value),+ int(green.value),+ int(blue.value),+ int(alpha.value),+ )+++def _get_raw_object_alpha(raw_obj: Any, color_getter: Any) -> int:+ """读取对象颜色 alpha;旧 PDFium 或读取失败时按不透明处理。"""++ rgba = _get_raw_object_rgba(raw_obj, color_getter)+ return rgba[3] if rgba is not None else 255+++def _get_path_visibility(raw_obj: Any) -> tuple[bool, bool]:+ """分别判断 Path 的填充与描边是否实际可见。"""+ fill_mode = ctypes.c_int()+ stroke = ctypes.c_int()+ try:+ ok = pdfium_c.FPDFPath_GetDrawMode(raw_obj, ctypes.byref(fill_mode), ctypes.byref(stroke))+ except Exception:+ return False, False+ if not ok:+ return False, False++ fill_visible = (+ fill_mode.value != pdfium_c.FPDF_FILLMODE_NONE and _get_raw_object_alpha(raw_obj, pdfium_c.FPDFPageObj_GetFillColor) > 0+ )+ stroke_visible = bool(stroke.value) and _get_raw_object_alpha(raw_obj, pdfium_c.FPDFPageObj_GetStrokeColor) > 0+ return fill_visible, stroke_visible+++def _get_raw_stroke_width(raw_obj: Any) -> float:+ """读取 Path 在对象局部坐标中的描边宽度。"""+ stroke_width = ctypes.c_float()+ try:+ ok = pdfium_c.FPDFPageObj_GetStrokeWidth(raw_obj, ctypes.byref(stroke_width))+ except Exception:+ return 0.0+ if not ok:+ return 0.0+ width = abs(float(stroke_width.value))+ return width if math.isfinite(width) else 0.0+++def _get_segment_stroke_width(+ raw_width: float,+ start: tuple[float, float],+ end: tuple[float, float],+ matrix: tuple[float, float, float, float, float, float],+) -> float:+ """按线段局部法向量换算非等比矩阵下的实际描边宽度。"""+ delta_x = end[0] - start[0]+ delta_y = end[1] - start[1]+ segment_length = math.hypot(delta_x, delta_y)+ a, b, c, d, _, _ = matrix+ if segment_length <= 0:+ scale = math.sqrt(abs(a * d - b * c))+ else:+ normal_x = -delta_y / segment_length+ normal_y = delta_x / segment_length+ transformed_x = a * normal_x + c * normal_y+ transformed_y = b * normal_x + d * normal_y+ scale = math.hypot(transformed_x, transformed_y)+ width = raw_width * scale+ return width if math.isfinite(width) else 0.0+++def _read_raw_path_subpaths(raw_obj: Any) -> list[_PathSubpath]:+ """读取 Path 段并拆为子路径,只把 LINETO 与闭合边记录为直线段。"""+ try:+ segment_count = int(pdfium_c.FPDFPath_CountSegments(raw_obj))+ except Exception:+ return []+ if segment_count <= 0:+ return []++ subpaths: list[_PathSubpath] = []+ current_subpath: _PathSubpath | None = None+ current_point: tuple[float, float] | None = None+ subpath_start: tuple[float, float] | None = None++ for segment_index in range(segment_count):+ try:+ segment = pdfium_c.FPDFPath_GetPathSegment(raw_obj, segment_index)+ if not segment:+ continue+ x = ctypes.c_float()+ y = ctypes.c_float()+ if not pdfium_c.FPDFPathSegment_GetPoint(segment, ctypes.byref(x), ctypes.byref(y)):+ continue+ point = (float(x.value), float(y.value))+ segment_type = int(pdfium_c.FPDFPathSegment_GetType(segment))+ segment_closes = bool(pdfium_c.FPDFPathSegment_GetClose(segment))+ except Exception:+ continue++ if segment_type == pdfium_c.FPDF_SEGMENT_MOVETO:+ if current_subpath is not None and current_subpath.points:+ subpaths.append(current_subpath)+ current_subpath = _PathSubpath(points=[point], straight_segments=[])+ current_point = point+ subpath_start = point+ else:+ if current_subpath is None:+ current_subpath = _PathSubpath(points=[point], straight_segments=[])+ current_point = point+ subpath_start = point+ else:+ current_subpath.points.append(point)+ if segment_type == pdfium_c.FPDF_SEGMENT_LINETO and current_point is not None:+ current_subpath.straight_segments.append((current_point, point))+ current_point = point++ if segment_closes and current_subpath is not None and current_point is not None and subpath_start is not None:+ if current_point != subpath_start:+ current_subpath.straight_segments.append((current_point, subpath_start))+ current_subpath.closed = True+ current_point = subpath_start++ if current_subpath is not None and current_subpath.points:+ subpaths.append(current_subpath)+ return subpaths+++def _transform_path_subpath(+ subpath: _PathSubpath,+ matrix: tuple[float, float, float, float, float, float],+ page_bbox: BBox,+ page_rotation: int,+) -> _PathSubpath:+ """将一个子路径从对象局部坐标转换为页面左上坐标。"""++ def transform(point: tuple[float, float]) -> tuple[float, float]:+ """先应用对象/Form 矩阵,再应用页面坐标与旋转转换。"""+ return _transform_drawing_point(_apply_pdf_matrix(point, matrix), page_bbox, page_rotation)++ return _PathSubpath(+ points=[transform(point) for point in subpath.points],+ straight_segments=[(transform(start), transform(end)) for start, end in subpath.straight_segments],+ closed=subpath.closed,+ )+++def _path_info_from_object(+ raw_obj: Any,+ matrix: tuple[float, float, float, float, float, float],+ page_bbox: BBox,+ page_rotation: int,+ form_depth: int,+ source_index: int,+) -> PDFPathInfo | None:+ """将一个原始 Path 转换为页面几何;贝塞尔控制点也纳入保守 bbox。"""++ try:+ segment_count = int(pdfium_c.FPDFPath_CountSegments(raw_obj))+ except Exception:+ return None+ if segment_count <= 0:+ return None++ fill_visible, stroke_visible = _get_path_visibility(raw_obj)+ points = [+ point+ for raw_subpath in _read_raw_path_subpaths(raw_obj)+ for point in _transform_path_subpath(+ raw_subpath,+ matrix,+ page_bbox,+ page_rotation,+ ).points+ ]+ if not points:+ return None+ coordinates = [coordinate for point in points for coordinate in point]+ if not all(math.isfinite(value) for value in coordinates):+ return None++ page_width, page_height = _drawing_page_size(page_bbox, page_rotation)+ stroke_margin = 0.0+ if stroke_visible:+ a, b, c, d, _, _ = matrix+ stroke_scale = max(math.hypot(a, b), math.hypot(c, d))+ stroke_margin = 0.5 * _get_raw_stroke_width(raw_obj) * stroke_scale+ bbox = (+ max(0.0, min(point[0] for point in points) - stroke_margin),+ max(0.0, min(point[1] for point in points) - stroke_margin),+ min(page_width, max(point[0] for point in points) + stroke_margin),+ min(page_height, max(point[1] for point in points) + stroke_margin),+ )+ if bbox[2] <= bbox[0] or bbox[3] <= bbox[1]:+ return None+ return PDFPathInfo(+ bbox=bbox,+ segment_count=segment_count,+ fill_visible=fill_visible,+ stroke_visible=stroke_visible,+ form_depth=form_depth,+ source_index=source_index,+ fill_rgba=(+ _get_raw_object_rgba(+ raw_obj,+ pdfium_c.FPDFPageObj_GetFillColor,+ )+ if fill_visible+ else None+ ),+ )+++def _get_thin_filled_subpath_line(+ subpath: _PathSubpath,+ page_size: tuple[float, float],+) -> PDFDrawingLine | None:+ """把闭合的细长填充子路径折叠为一条中心线,避免把矩形四边重复输出。"""+ if not subpath.closed or len(subpath.points) < 4:+ return None+ x_values = [point[0] for point in subpath.points]+ y_values = [point[1] for point in subpath.points]+ x0, x1 = min(x_values), max(x_values)+ y0, y1 = min(y_values), max(y_values)+ width = x1 - x0+ height = y1 - y0+ long_side = max(width, height)+ short_side = min(width, height)+ if (+ long_side < DRAWING_LINE_MIN_LENGTH+ or short_side > DRAWING_THIN_RECT_MAX_THICKNESS+ or long_side < DRAWING_THIN_RECT_MIN_ASPECT_RATIO * max(short_side, 0.01)+ ):+ return None+ if width >= height:+ return _make_axis_drawing_line((x0, (y0 + y1) / 2), (x1, (y0 + y1) / 2), short_side, page_size)+ return _make_axis_drawing_line(((x0 + x1) / 2, y0), ((x0 + x1) / 2, y1), short_side, page_size)+++def _make_axis_drawing_line(+ start: tuple[float, float],+ end: tuple[float, float],+ width: float,+ page_size: tuple[float, float],+) -> PDFDrawingLine | None:+ """将近水平或近竖直线段吸附到坐标轴、裁剪到页面并生成公开结果。"""+ page_width, page_height = page_size+ x0, y0 = start+ x1, y1 = end+ if not all(math.isfinite(value) for value in (x0, y0, x1, y1, width)):+ return None+ delta_x = abs(x1 - x0)+ delta_y = abs(y1 - y0)++ if delta_x >= delta_y and delta_y <= max(+ DRAWING_LINE_AXIS_ABSOLUTE_TOLERANCE,+ delta_x * DRAWING_LINE_AXIS_RATIO_TOLERANCE,+ ):+ coordinate = (y0 + y1) / 2+ if coordinate < 0 or coordinate > page_height:+ return None+ main_start = max(0.0, min(x0, x1))+ main_end = min(page_width, max(x0, x1))+ if main_end - main_start < DRAWING_LINE_MIN_LENGTH:+ return None+ line_width = max(0.0, width, delta_y)+ half_width = line_width / 2+ bbox = (+ main_start,+ max(0.0, coordinate - half_width),+ main_end,+ min(page_height, coordinate + half_width),+ )+ return PDFDrawingLine(+ start=(main_start, coordinate),+ end=(main_end, coordinate),+ bbox=bbox,+ width=line_width,+ orientation="horizontal",+ )++ if delta_y > delta_x and delta_x <= max(+ DRAWING_LINE_AXIS_ABSOLUTE_TOLERANCE,+ delta_y * DRAWING_LINE_AXIS_RATIO_TOLERANCE,+ ):+ coordinate = (x0 + x1) / 2+ if coordinate < 0 or coordinate > page_width:+ return None+ main_start = max(0.0, min(y0, y1))+ main_end = min(page_height, max(y0, y1))+ if main_end - main_start < DRAWING_LINE_MIN_LENGTH:+ return None+ line_width = max(0.0, width, delta_x)+ half_width = line_width / 2+ bbox = (+ max(0.0, coordinate - half_width),+ main_start,+ min(page_width, coordinate + half_width),+ main_end,+ )+ return PDFDrawingLine(+ start=(coordinate, main_start),+ end=(coordinate, main_end),+ bbox=bbox,+ width=line_width,+ orientation="vertical",+ )+ return None+++def _extract_path_drawing_lines(+ raw_obj: Any,+ matrix: tuple[float, float, float, float, float, float],+ page_bbox: BBox,+ page_rotation: int,+) -> list[PDFDrawingLine]:+ """从单个 Path 提取可见直线,坏 Path 返回空结果且不影响同页其他对象。"""+ fill_visible, stroke_visible = _get_path_visibility(raw_obj)+ if not fill_visible and not stroke_visible:+ return []++ page_size = _drawing_page_size(page_bbox, page_rotation)+ raw_stroke_width = _get_raw_stroke_width(raw_obj) if stroke_visible else 0.0+ drawing_lines: list[PDFDrawingLine] = []+ for raw_subpath in _read_raw_path_subpaths(raw_obj):+ subpath = _transform_path_subpath(raw_subpath, matrix, page_bbox, page_rotation)+ if fill_visible:+ filled_line = _get_thin_filled_subpath_line(subpath, page_size)+ if filled_line is not None:+ drawing_lines.append(filled_line)+ # 细长填充矩形已经折叠为中心线,不再输出其描边四条边。+ continue+ if not stroke_visible:+ continue+ for (raw_start, raw_end), (segment_start, segment_end) in zip(+ raw_subpath.straight_segments,+ subpath.straight_segments,+ ):+ stroke_width = _get_segment_stroke_width(raw_stroke_width, raw_start, raw_end, matrix)+ drawing_line = _make_axis_drawing_line(segment_start, segment_end, stroke_width, page_size)+ if drawing_line is not None:+ drawing_lines.append(drawing_line)+ return drawing_lines+++def _line_axis_coordinate(line: PDFDrawingLine) -> float:+ """返回绘图线在垂直于自身方向的轴坐标。"""+ return line.start[1] if line.orientation == "horizontal" else line.start[0]+++def _line_main_interval(line: PDFDrawingLine) -> tuple[float, float]:+ """返回绘图线沿自身方向的起止区间。"""+ if line.orientation == "horizontal":+ return line.start[0], line.end[0]+ return line.start[1], line.end[1]+++def _combine_collinear_line_group(+ lines: list[PDFDrawingLine],+ page_size: tuple[float, float],+) -> PDFDrawingLine | None:+ """把坐标接近且区间相连的一组线合并为一条稳定中心线。"""+ orientation = lines[0].orientation+ intervals = [_line_main_interval(line) for line in lines]+ lengths = [max(end - start, 0.01) for start, end in intervals]+ coordinates = [_line_axis_coordinate(line) for line in lines]+ total_length = sum(lengths)+ coordinate = sum(value * length for value, length in zip(coordinates, lengths)) / total_length+ coordinate_span = max(coordinates) - min(coordinates)+ width = max(max(line.width for line in lines), coordinate_span + max(line.width for line in lines))+ main_start = min(start for start, _ in intervals)+ main_end = max(end for _, end in intervals)+ if orientation == "horizontal":+ return _make_axis_drawing_line((main_start, coordinate), (main_end, coordinate), width, page_size)+ return _make_axis_drawing_line((coordinate, main_start), (coordinate, main_end), width, page_size)+++def _merge_orientation_lines(+ lines: list[PDFDrawingLine],+ page_size: tuple[float, float],+) -> list[PDFDrawingLine]:+ """按轴坐标聚类,再合并间距不超过约 2pt 的同方向线段。"""+ if not lines:+ return []+ coordinate_clusters: list[list[PDFDrawingLine]] = []+ for line in sorted(lines, key=lambda item: (_line_axis_coordinate(item), _line_main_interval(item)[0])):+ if (+ not coordinate_clusters+ or _line_axis_coordinate(line) - min(_line_axis_coordinate(item) for item in coordinate_clusters[-1])+ > DRAWING_LINE_MERGE_TOLERANCE+ ):+ coordinate_clusters.append([line])+ else:+ coordinate_clusters[-1].append(line)++ merged: list[PDFDrawingLine] = []+ for cluster in coordinate_clusters:+ interval_group: list[PDFDrawingLine] = []+ interval_end = -math.inf+ for line in sorted(cluster, key=lambda item: _line_main_interval(item)[0]):+ line_start, line_end = _line_main_interval(line)+ if interval_group and line_start > interval_end + DRAWING_LINE_MERGE_TOLERANCE:+ combined = _combine_collinear_line_group(interval_group, page_size)+ if combined is not None:+ merged.append(combined)+ interval_group = []+ interval_end = -math.inf+ interval_group.append(line)+ interval_end = max(interval_end, line_end)+ if interval_group:+ combined = _combine_collinear_line_group(interval_group, page_size)+ if combined is not None:+ merged.append(combined)+ return merged+++def _merge_collinear_drawing_lines(+ lines: list[PDFDrawingLine],+ page_size: tuple[float, float],+) -> list[PDFDrawingLine]:+ """合并水平和竖直共线段,并按页面视觉位置稳定排序。"""+ horizontal = _merge_orientation_lines(+ [line for line in lines if line.orientation == "horizontal"],+ page_size,+ )+ vertical = _merge_orientation_lines(+ [line for line in lines if line.orientation == "vertical"],+ page_size,+ )+ return sorted(+ [*horizontal, *vertical],+ key=lambda line: (line.bbox[1], line.bbox[0], line.orientation),+ )+++def _image_bbox_from_matrix(+ matrix: tuple[float, float, float, float, float, float],+ page_bbox: BBox,+ page_rotation: int,+) -> BBox | None:+ """把点阵图单位矩形经对象/Form 矩阵转换并裁剪为页面左上坐标 bbox。"""+ page_points = [+ _transform_drawing_point(+ _apply_pdf_matrix(point, matrix),+ page_bbox,+ page_rotation,+ )+ for point in ((0.0, 0.0), (0.0, 1.0), (1.0, 0.0), (1.0, 1.0))+ ]+ coordinates = [coordinate for point in page_points for coordinate in point]+ if not all(math.isfinite(value) for value in coordinates):+ return None++ page_width, page_height = _drawing_page_size(page_bbox, page_rotation)+ left = max(0.0, min(point[0] for point in page_points))+ top = max(0.0, min(point[1] for point in page_points))+ right = min(page_width, max(point[0] for point in page_points))+ bottom = min(page_height, max(point[1] for point in page_points))+ if right <= left or bottom <= top:+ return None+ return left, top, right, bottom+++def _form_bbox_from_object(+ raw_obj: Any,+ page_bbox: BBox,+ page_rotation: int,+) -> BBox | None:+ """读取顶层 Form 的页面坐标边界,并转换、裁剪到视觉页面范围。"""++ left = ctypes.c_float()+ bottom = ctypes.c_float()+ right = ctypes.c_float()+ top = ctypes.c_float()+ try:+ ok = pdfium_c.FPDFPageObj_GetBounds(+ raw_obj,+ ctypes.byref(left),+ ctypes.byref(bottom),+ ctypes.byref(right),+ ctypes.byref(top),+ )+ except Exception:+ return None+ if not ok:+ return None++ raw_bbox = (float(left.value), float(bottom.value), float(right.value), float(top.value))+ if not all(math.isfinite(value) for value in raw_bbox):+ return None+ page_points = [+ _transform_drawing_point(point, page_bbox, page_rotation)+ for point in (+ (raw_bbox[0], raw_bbox[1]),+ (raw_bbox[0], raw_bbox[3]),+ (raw_bbox[2], raw_bbox[1]),+ (raw_bbox[2], raw_bbox[3]),+ )+ ]+ page_width, page_height = _drawing_page_size(page_bbox, page_rotation)+ visual_left = max(0.0, min(point[0] for point in page_points))+ visual_top = max(0.0, min(point[1] for point in page_points))+ visual_right = min(page_width, max(point[0] for point in page_points))+ visual_bottom = min(page_height, max(point[1] for point in page_points))+ if visual_right <= visual_left or visual_bottom <= visual_top:+ return None+ return visual_left, visual_top, visual_right, visual_bottom+++def _validate_pdf_external_link_target(value: str) -> str | None:+ """校验 PDF URI Action,只保留显式且可安全输出的外部链接。"""++ target = value.strip()- if not target or any(- ord(char) < 0x20- or ord(char) == 0x7F- or 0xD800 <= ord(char) <= 0xDFFF- for char in target- ):++ if not target or any(ord(char) < 0x20 or ord(char) == 0x7F or 0xD800 <= ord(char) <= 0xDFFF for char in target):+ return None+ try:+ parsed = urlsplit(target)+ except ValueError:+ return None+ scheme = parsed.scheme.lower()+ if scheme not in _PDF_EXTERNAL_LINK_SCHEMES:+ return None+ if scheme in {"http", "https"}:+ try:+ if not parsed.netloc or parsed.hostname is None:+ return None+ except ValueError:+ return None+ elif not parsed.path:+ return None+ return target+++def _get_pdfium_uri_path(raw_doc: Any, raw_action: Any) -> str | None:+ """按 PDFium 两阶段缓冲区协议读取 URI Action 的 UTF-8 目标。"""++ try:+ required = int(+ pdfium_c.FPDFAction_GetURIPath(+ raw_doc,+ raw_action,+ None,+ 0,+ )+ )+ except Exception:+ return None+ if required <= 1:+ return None+ try:+ buffer = ctypes.create_string_buffer(required)+ actual = int(+ pdfium_c.FPDFAction_GetURIPath(+ raw_doc,+ raw_action,+ buffer,+ required,+ )+ )+ except Exception:+ return None+ if actual <= 1 or actual > required:+ return None+ raw_value = bytes(buffer.raw[: actual - 1])+ try:+ return raw_value.decode("utf-8")+ except UnicodeDecodeError:+ return None+++def _pdf_link_annotation_is_visible(page: pdfium.PdfPage, raw_link: Any) -> bool:+ """读取 Link 注解可见性;损坏或显式隐藏的注解均不参与文本富化。"""++ raw_annot = None+ try:+ raw_annot = pdfium_c.FPDFLink_GetAnnot(page.raw, raw_link)+ if not raw_annot:+ return False+ flags = int(pdfium_c.FPDFAnnot_GetFlags(raw_annot))+ except Exception:+ return False+ finally:+ if raw_annot:+ try:+ pdfium_c.FPDFPage_CloseAnnot(raw_annot)+ except Exception:+ pass- hidden_flags = (- pdfium_c.FPDF_ANNOT_FLAG_INVISIBLE- | pdfium_c.FPDF_ANNOT_FLAG_HIDDEN- | pdfium_c.FPDF_ANNOT_FLAG_NOVIEW- )++ hidden_flags = pdfium_c.FPDF_ANNOT_FLAG_INVISIBLE | pdfium_c.FPDF_ANNOT_FLAG_HIDDEN | pdfium_c.FPDF_ANNOT_FLAG_NOVIEW+ return not bool(flags & hidden_flags)+++def _visual_bbox_from_pdf_points(+ points: list[tuple[float, float]],+ page_bbox: BBox,+ page_rotation: int,+) -> BBox | None:+ """把 PDF 底左坐标点集转换并裁剪为视觉页面左上坐标 bbox。"""+- if not points or not all(- math.isfinite(coordinate)- for point in points- for coordinate in point- ):++ if not points or not all(math.isfinite(coordinate) for point in points for coordinate in point):+ return None- visual_points = [- _transform_drawing_point(point, page_bbox, page_rotation)- for point in points- ]++ visual_points = [_transform_drawing_point(point, page_bbox, page_rotation) for point in points]+ page_width, page_height = _drawing_page_size(page_bbox, page_rotation)+ visual_bbox = (+ max(0.0, min(point[0] for point in visual_points)),+ max(0.0, min(point[1] for point in visual_points)),+ min(page_width, max(point[0] for point in visual_points)),+ min(page_height, max(point[1] for point in visual_points)),+ )+ if visual_bbox[2] <= visual_bbox[0] or visual_bbox[3] <= visual_bbox[1]:+ return None+ return visual_bbox+++def _pdf_link_region_bboxes(+ raw_link: Any,+ page_bbox: BBox,+ page_rotation: int,+) -> tuple[BBox, ...]:+ """优先读取 Link QuadPoints,并在缺失时回退到注解矩形。"""++ bboxes: list[BBox] = []+ try:+ quad_count = max(0, int(pdfium_c.FPDFLink_CountQuadPoints(raw_link)))+ except Exception:+ quad_count = 0+ for quad_index in range(quad_count):+ quad = pdfium_c.FS_QUADPOINTSF()+ try:+ ok = pdfium_c.FPDFLink_GetQuadPoints(+ raw_link,+ quad_index,+ ctypes.byref(quad),+ )+ except Exception:+ continue+ if not ok:+ continue+ bbox = _visual_bbox_from_pdf_points(+ [+ (float(quad.x1), float(quad.y1)),+ (float(quad.x2), float(quad.y2)),+ (float(quad.x3), float(quad.y3)),+ (float(quad.x4), float(quad.y4)),+ ],+ page_bbox,+ page_rotation,+ )+ if bbox is not None and bbox not in bboxes:+ bboxes.append(bbox)++ if not bboxes:+ rect = pdfium_c.FS_RECTF()+ try:+ ok = pdfium_c.FPDFLink_GetAnnotRect(raw_link, ctypes.byref(rect))+ except Exception:+ ok = False+ if ok:+ bbox = _visual_bbox_from_pdf_points(+ [+ (float(rect.left), float(rect.bottom)),+ (float(rect.left), float(rect.top)),+ (float(rect.right), float(rect.bottom)),+ (float(rect.right), float(rect.top)),+ ],+ page_bbox,+ page_rotation,+ )+ if bbox is not None:+ bboxes.append(bbox)+ return tuple(+ sorted(+ bboxes,+ key=lambda bbox: (bbox[1], bbox[0], bbox[3], bbox[2]),+ )+ )+++def _extract_page_link_annotations(+ page: pdfium.PdfPage,+ raw_doc: Any,+ page_bbox: BBox,+ page_rotation: int,+) -> list[PDFLinkAnnotation]:+ """枚举页面外部 URI Link;单条损坏数据不会中断同页其他链接。"""++ annotations: list[PDFLinkAnnotation] = []+ position = ctypes.c_int(0)+ source_index = 0+ while True:+ raw_link = pdfium_c.FPDF_LINK()+ previous_position = int(position.value)+ try:+ found = pdfium_c.FPDFLink_Enumerate(+ page.raw,+ ctypes.byref(position),+ ctypes.byref(raw_link),+ )+ except Exception:+ break+ if not found:+ break+ current_source_index = source_index+ source_index += 1+ if int(position.value) <= previous_position:+ break+ try:+ if not raw_link or not _pdf_link_annotation_is_visible(page, raw_link):+ continue+ raw_action = pdfium_c.FPDFLink_GetAction(raw_link)+ if not raw_action or int(pdfium_c.FPDFAction_GetType(raw_action)) != pdfium_c.PDFACTION_URI:+ continue+ raw_target = _get_pdfium_uri_path(raw_doc, raw_action)- target = (- _validate_pdf_external_link_target(raw_target)- if raw_target is not None- else None- )++ target = _validate_pdf_external_link_target(raw_target) if raw_target is not None else None+ if target is None:+ continue+ bboxes = _pdf_link_region_bboxes(+ raw_link,+ page_bbox,+ page_rotation,+ )+ if not bboxes:+ continue+ annotations.append(+ PDFLinkAnnotation(+ target=target,+ bboxes=bboxes,+ source_index=current_source_index,+ )+ )+ except Exception:+ continue+ return annotations+++def _get_annotation_string(raw_annot: Any, key: bytes) -> str | None:+ """读取 PDFium 注释字典中的 UTF-16 字符串或名称,异常和空值统一返回 None。"""++ try:+ required = int(pdfium_c.FPDFAnnot_GetStringValue(raw_annot, key, None, 0))+ except Exception:+ return None+ if required <= 2:+ return None+ try:+ buffer = (ctypes.c_ushort * ((required + 1) // 2))()+ actual = int(+ pdfium_c.FPDFAnnot_GetStringValue(+ raw_annot,+ key,+ buffer,+ ctypes.sizeof(buffer),+ )+ )+ except Exception:+ return None+ if actual <= 2 or actual > ctypes.sizeof(buffer):+ return None+ try:+ return bytes(buffer)[: actual - 2].decode("utf-16-le")+ except UnicodeDecodeError:+ return None+++def _signature_bbox_from_annotation(+ raw_annot: Any,+ page_bbox: BBox,+ page_rotation: int,+ form_handle: Any | None,+) -> BBox | None:+ """校验一个可见签名 Widget,并把注释矩形裁剪到视觉页面坐标。"""++ try:+ if int(pdfium_c.FPDFAnnot_GetSubtype(raw_annot)) != pdfium_c.FPDF_ANNOT_WIDGET:+ return None+ flags = int(pdfium_c.FPDFAnnot_GetFlags(raw_annot))+ except Exception:+ return None- hidden_flags = (- pdfium_c.FPDF_ANNOT_FLAG_INVISIBLE- | pdfium_c.FPDF_ANNOT_FLAG_HIDDEN- | pdfium_c.FPDF_ANNOT_FLAG_NOVIEW- )++ hidden_flags = pdfium_c.FPDF_ANNOT_FLAG_INVISIBLE | pdfium_c.FPDF_ANNOT_FLAG_HIDDEN | pdfium_c.FPDF_ANNOT_FLAG_NOVIEW+ if flags & hidden_flags:+ return None+ field_type: int | None = None+ if form_handle is not None:+ try:- field_type = int(- pdfium_c.FPDFAnnot_GetFormFieldType(form_handle, raw_annot)- )++ field_type = int(pdfium_c.FPDFAnnot_GetFormFieldType(form_handle, raw_annot))+ except Exception:+ field_type = None+ if field_type == pdfium_c.FPDF_FORMFIELD_SIGNATURE:+ pass+ elif field_type is None or field_type <= pdfium_c.FPDF_FORMFIELD_UNKNOWN:+ if _get_annotation_string(raw_annot, b"FT") != "Sig":+ return None+ else:+ return None++ # 正常外观长度只有 UTF-16 终止符时等价于无 /AP /N,不能形成可见签名。+ try:+ appearance_length = int(+ pdfium_c.FPDFAnnot_GetAP(+ raw_annot,+ pdfium_c.FPDF_ANNOT_APPEARANCEMODE_NORMAL,+ None,+ 0,+ )+ )+ except Exception:+ return None+ if appearance_length <= 2:+ return None++ rect = pdfium_c.FS_RECTF()+ try:+ if not pdfium_c.FPDFAnnot_GetRect(raw_annot, ctypes.byref(rect)):+ return None+ except Exception:+ return None- raw_bbox = _normalize_pdf_page_bbox(- (float(rect.left), float(rect.bottom), float(rect.right), float(rect.top))- )++ raw_bbox = _normalize_pdf_page_bbox((float(rect.left), float(rect.bottom), float(rect.right), float(rect.top)))+ if not all(math.isfinite(value) for value in raw_bbox):+ return None+ page_points = [+ _transform_drawing_point(point, page_bbox, page_rotation)+ for point in (+ (raw_bbox[0], raw_bbox[1]),+ (raw_bbox[0], raw_bbox[3]),+ (raw_bbox[2], raw_bbox[1]),+ (raw_bbox[2], raw_bbox[3]),+ )+ ]+ page_width, page_height = _drawing_page_size(page_bbox, page_rotation)+ visual_bbox = (+ max(0.0, min(point[0] for point in page_points)),+ max(0.0, min(point[1] for point in page_points)),+ min(page_width, max(point[0] for point in page_points)),+ min(page_height, max(point[1] for point in page_points)),+ )+ if visual_bbox[2] <= visual_bbox[0] or visual_bbox[3] <= visual_bbox[1]:+ return None+ return visual_bbox+++def _extract_page_signature_bboxes(+ page: pdfium.PdfPage,+ page_bbox: BBox,+ page_rotation: int,+ *,+ form_handle: Any | None = None,+) -> list[BBox]:+ """遍历页面签名注释;逐个关闭句柄,并隔离损坏注释造成的异常。"""++ try:+ annot_count = max(0, int(pdfium_c.FPDFPage_GetAnnotCount(page.raw)))+ except Exception:+ return []+ signature_bboxes: list[BBox] = []+ for annot_index in range(annot_count):+ raw_annot = None+ try:+ raw_annot = pdfium_c.FPDFPage_GetAnnot(page.raw, annot_index)+ if not raw_annot:+ continue+ signature_bbox = _signature_bbox_from_annotation(+ raw_annot,+ page_bbox,+ page_rotation,+ form_handle,+ )+ if signature_bbox is not None:+ signature_bboxes.append(signature_bbox)+ except Exception:+ # 单个损坏注释不能影响同页其他有效签名框。+ continue+ finally:+ if raw_annot:+ try:+ pdfium_c.FPDFPage_CloseAnnot(raw_annot)+ except Exception:+ pass+ return sorted(signature_bboxes, key=lambda bbox: (bbox[1], bbox[0], bbox[3], bbox[2]))+++def _extract_page_image_bboxes(+ page: pdfium.PdfPage,+ page_bbox: BBox,+ page_rotation: int,+) -> list[BBox]:+ """在调用方持有 PDFium 锁时提取全部有效点阵图 bbox,并隔离单对象异常。"""+ image_bboxes: list[BBox] = []+ for _raw_obj, matrix in _iter_raw_image_objects(page):+ try:+ image_bbox = _image_bbox_from_matrix(matrix, page_bbox, page_rotation)+ except Exception:+ # 单个损坏 Image 对象不能中断同页其他点阵图提取。+ continue+ if image_bbox is not None:+ image_bboxes.append(image_bbox)+ return sorted(image_bboxes, key=lambda bbox: (bbox[1], bbox[0], bbox[3], bbox[2]))+++def _get_raw_image_fingerprint(raw_obj: Any, page: pdfium.PdfPage) -> str | None:+ """读取受限大小的图片原始流,并结合像素宽高生成 SHA-256 指纹。"""++ metadata = pdfium_c.FPDF_IMAGEOBJ_METADATA()+ try:+ if not pdfium_c.FPDFImageObj_GetImageMetadata(+ raw_obj,+ page.raw,+ ctypes.byref(metadata),+ ):+ return None+ width = int(metadata.width)+ height = int(metadata.height)+ raw_size = int(pdfium_c.FPDFImageObj_GetImageDataRaw(raw_obj, None, 0))+ except Exception:+ return None- if (- width <= 0- or height <= 0- or raw_size <= 0- or raw_size > PDF_IMAGE_FINGERPRINT_MAX_RAW_BYTES- ):++ if width <= 0 or height <= 0 or raw_size <= 0 or raw_size > PDF_IMAGE_FINGERPRINT_MAX_RAW_BYTES:+ return None++ try:+ buffer = ctypes.create_string_buffer(raw_size)+ except (MemoryError, OverflowError):+ return None+ try:+ bytes_read = int(pdfium_c.FPDFImageObj_GetImageDataRaw(raw_obj, buffer, raw_size))+ except Exception:+ return None+ if bytes_read <= 0 or bytes_read > raw_size:+ return None++ digest = hashlib.sha256()+ digest.update(f"{width}:{height}:".encode("ascii"))+ digest.update(buffer.raw[:bytes_read])+ return digest.hexdigest()+++def _extract_page_image_infos(+ page: pdfium.PdfPage,+ page_bbox: BBox,+ page_rotation: int,+) -> list[PDFImageInfo]:+ """提取全部有效点阵图几何;单图指纹失败时保留 bbox 并按放行处理。"""++ image_infos: list[PDFImageInfo] = []+ for raw_obj, matrix in _iter_raw_image_objects(page):+ try:+ image_bbox = _image_bbox_from_matrix(matrix, page_bbox, page_rotation)+ except Exception:+ # 单个损坏 Image 对象不能中断同页其他点阵图提取。+ continue+ if image_bbox is None:+ continue+ image_infos.append(+ PDFImageInfo(+ bbox=image_bbox,+ fingerprint=_get_raw_image_fingerprint(raw_obj, page),+ )+ )+ return sorted(+ image_infos,+ key=lambda info: (info.bbox[1], info.bbox[0], info.bbox[3], info.bbox[2]),+ )+++def _extract_page_form_bboxes(+ page: pdfium.PdfPage,+ page_bbox: BBox,+ page_rotation: int,+) -> list[BBox]:+ """在调用方持有 PDFium 锁时提取顶层 Form bbox,并隔离单对象异常。"""++ form_bboxes: list[BBox] = []+ for raw_obj in _iter_raw_root_form_objects(page):+ try:+ form_bbox = _form_bbox_from_object(raw_obj, page_bbox, page_rotation)+ except Exception:+ # PDFium 遇到个别损坏 Form 时,保留同页其他有效结果。+ continue+ if form_bbox is not None:+ form_bboxes.append(form_bbox)+ return sorted(form_bboxes, key=lambda bbox: (bbox[1], bbox[0], bbox[3], bbox[2]))+++def _extract_page_path_infos(+ page: pdfium.PdfPage,+ page_bbox: BBox,+ page_rotation: int,+) -> list[PDFPathInfo]:+ """在调用方持有 PDFium 锁时提取 Path 信息,并隔离单对象异常。"""++ path_infos: list[PDFPathInfo] = []- for source_index, (raw_obj, matrix, form_depth) in enumerate(- _iter_raw_path_objects_with_depth(page)- ):++ for source_index, (raw_obj, matrix, form_depth) in enumerate(_iter_raw_path_objects_with_depth(page)):+ try:+ path_info = _path_info_from_object(+ raw_obj,+ matrix,+ page_bbox,+ page_rotation,+ form_depth,+ source_index,+ )+ except Exception:+ # PDFium 遇到个别损坏 Path 时,保留同页其他对象的有效结果。+ continue+ if path_info is not None:+ path_infos.append(path_info)+ return path_infos+++def _extract_page_drawing_lines(+ page: pdfium.PdfPage,+ page_bbox: BBox,+ page_rotation: int,+) -> list[PDFDrawingLine]:+ """在调用方持有 PDFium 锁时提取整页绘图线,并隔离单个对象异常。"""+ drawing_lines: list[PDFDrawingLine] = []+ for raw_obj, matrix in _iter_raw_path_objects(page):+ try:+ drawing_lines.extend(+ _extract_path_drawing_lines(+ raw_obj,+ matrix,+ page_bbox,+ page_rotation,+ )+ )+ except Exception:+ # PDFium 遇到个别损坏 Path 时,保留同页其他对象的有效结果。+ continue+ return _merge_collinear_drawing_lines(+ drawing_lines,+ _drawing_page_size(page_bbox, page_rotation),+ )++def _try_close(obj: object) -> None:if callable(close := getattr(obj, "close", None)):try:@@@ -1849,128 -413,10 +1888,118 @@@pass+def _get_visible_char_signature(+ char: Char,+) -> tuple[str, tuple[Any, Any, Any, Any], float]:+ """生成可见字符去重签名,不把 bbox 放入签名以便单独做近重合判断。"""+ font = char.get("font") or {}+ font_key = (+ font.get("name"),+ font.get("flags"),+ font.get("size"),+ font.get("weight"),+ )+ rotation_key = round(float(char.get("rotation") or 0.0), 3)+ return str(char.get("char", "")), font_key, rotation_key+++def _is_near_identical_bbox(+ bbox_a: tuple[float, float, float, float],+ bbox_b: tuple[float, float, float, float],+) -> bool:+ """判断两个字符 bbox 是否属于同一视觉位置的一点内抖动。"""- return all(- abs(coord_a - coord_b) <= NEAR_IDENTICAL_CHAR_BBOX_TOLERANCE- for coord_a, coord_b in zip(bbox_a, bbox_b)- )++ return all(abs(coord_a - coord_b) <= NEAR_IDENTICAL_CHAR_BBOX_TOLERANCE for coord_a, coord_b in zip(bbox_a, bbox_b))+++def _calculate_bbox_overlap_in_smaller_area(+ bbox_a: tuple[float, float, float, float],+ bbox_b: tuple[float, float, float, float],+) -> float:+ """计算两个字符框交集占较小字符框面积的比例。"""+ intersection_width = max(+ 0.0,+ min(bbox_a[2], bbox_b[2]) - max(bbox_a[0], bbox_b[0]),+ )+ intersection_height = max(+ 0.0,+ min(bbox_a[3], bbox_b[3]) - max(bbox_a[1], bbox_b[1]),+ )+ bbox_a_area = max(0.0, bbox_a[2] - bbox_a[0]) * max(+ 0.0,+ bbox_a[3] - bbox_a[1],+ )+ bbox_b_area = max(0.0, bbox_b[2] - bbox_b[0]) * max(+ 0.0,+ bbox_b[3] - bbox_b[1],+ )+ smaller_area = min(bbox_a_area, bbox_b_area)+ if smaller_area == 0:+ return 0.0+ return intersection_width * intersection_height / smaller_area+++def _is_adjacent_offset_duplicate_char(+ previous_char: Char,+ current_char: Char,+) -> bool:+ """识别相邻字符中由对角平移阴影产生的第二个重复字符。"""+ if _get_visible_char_signature(previous_char) != _get_visible_char_signature(current_char):+ return False++ previous_bbox = _char_bbox_values(previous_char.get("bbox"))+ current_bbox = _char_bbox_values(current_char.get("bbox"))+ if previous_bbox is None or current_bbox is None:+ return False++ x_start_offset = current_bbox[0] - previous_bbox[0]+ y_start_offset = current_bbox[1] - previous_bbox[1]+ x_end_offset = current_bbox[2] - previous_bbox[2]+ y_end_offset = current_bbox[3] - previous_bbox[3]++ # 阴影层应是同一字符框的刚性平移,避免把大小不同的相邻同字误判为重复。+ if (+ abs(x_start_offset - x_end_offset) > OFFSET_DUPLICATE_TRANSLATION_TOLERANCE+ or abs(y_start_offset - y_end_offset) > OFFSET_DUPLICATE_TRANSLATION_TOLERANCE+ ):+ return False++ if not (- NEAR_IDENTICAL_CHAR_BBOX_TOLERANCE- < abs(x_start_offset)- <= OFFSET_DUPLICATE_CHAR_BBOX_TOLERANCE- and NEAR_IDENTICAL_CHAR_BBOX_TOLERANCE- < abs(y_start_offset)- <= OFFSET_DUPLICATE_CHAR_BBOX_TOLERANCE++ NEAR_IDENTICAL_CHAR_BBOX_TOLERANCE < abs(x_start_offset) <= OFFSET_DUPLICATE_CHAR_BBOX_TOLERANCE++ and NEAR_IDENTICAL_CHAR_BBOX_TOLERANCE < abs(y_start_offset) <= OFFSET_DUPLICATE_CHAR_BBOX_TOLERANCE+ ):+ return False+- return (- _calculate_bbox_overlap_in_smaller_area(previous_bbox, current_bbox)- >= OFFSET_DUPLICATE_MIN_BBOX_OVERLAP_RATIO- )++ return _calculate_bbox_overlap_in_smaller_area(previous_bbox, current_bbox) >= OFFSET_DUPLICATE_MIN_BBOX_OVERLAP_RATIO+++def _get_near_identical_bbox_bucket_key(+ bbox_coords: tuple[float, float, float, float],+) -> tuple[int, int]:+ """按字符 bbox 左上角生成空间桶 key,缩小近重合判断的候选范围。"""+ return (+ math.floor(bbox_coords[0] / NEAR_IDENTICAL_CHAR_BBOX_TOLERANCE),+ math.floor(bbox_coords[1] / NEAR_IDENTICAL_CHAR_BBOX_TOLERANCE),+ )+++def _iter_neighbor_bbox_bucket_keys(+ bucket_key: tuple[int, int],+) -> Iterator[tuple[int, int]]:+ """遍历当前桶及周围 8 个邻近桶,覆盖 bbox 容差范围内的候选字符。"""+ bucket_x, bucket_y = bucket_key+ for offset_x in (-1, 0, 1):+ for offset_y in (-1, 0, 1):+ yield bucket_x + offset_x, bucket_y + offset_y++def _deduplicate_near_identical_chars(chars: list[Char]) -> list[Char]:- """移除坐标近乎重合的重复可见字符,降低 PDF 叠印文本造成的重复抽取。"""- unique_chars: list[Char] = []- seen_keys: set[tuple[str, int, int, int, int, str, str]] = set()+ """清理 PDFium 文本层边界处同字符、同位置及对角阴影重复字符。"""+ seen_visible_char_bboxes: dict[+ tuple[str, tuple[Any, Any, Any, Any], float],+ dict[tuple[int, int], list[tuple[float, float, float, float]]],+ ] = {}+ deduplicated_chars: list[Char] = []+for char in chars:text = str(char.get("char", ""))if not text or text.isspace():@@@ -2048,84 -483,6 +2077,78 @@@ def _ensure_legacy_chars(chars: Any) -return cast(list[Char], chars)+def _restore_pdfium_surrogate_pairs(+ chars: list[Char],+ textpage: pdfium.PdfTextPage,+) -> list[Char]:+ """利用 PDFium 原始 UTF-16 code unit 恢复 pdftext 丢失的补充平面字符。"""+ if not any(- len(text := str(char.get("char", ""))) == 1- and (text == "\uFFFD" or 0xD800 <= ord(text) <= 0xDFFF)- for char in chars++ len(text := str(char.get("char", ""))) == 1 and (text == "\ufffd" or 0xD800 <= ord(text) <= 0xDFFF) for char in chars+ ):+ return chars++ try:+ textpage_raw = textpage.raw+ char_count = int(textpage.count_chars())+ except Exception:+ textpage_raw = None+ char_count = 0++ restored_chars: list[Char] = []+ consumed_char_indices: set[int] = set()+ get_unicode = pdfium_c.FPDFText_GetUnicode++ for char in chars:+ text = str(char.get("char", ""))+ raw_char_idx = char.get("char_idx")+ try:+ char_idx = int(raw_char_idx) if raw_char_idx is not None else -1+ except (TypeError, ValueError):+ char_idx = -1++ if char_idx in consumed_char_indices:+ continue++ raw_code = None+ if (+ textpage_raw is not None+ and 0 <= char_idx < char_count+ and len(text) == 1- and (text == "\uFFFD" or 0xD800 <= ord(text) <= 0xDFFF)++ and (text == "\ufffd" or 0xD800 <= ord(text) <= 0xDFFF)+ ):+ raw_code = int(get_unicode(textpage_raw, char_idx))++ high_surrogate = None+ low_surrogate = None+ if raw_code is not None and 0xD800 <= raw_code <= 0xDBFF and char_idx + 1 < char_count:+ next_code = int(get_unicode(textpage_raw, char_idx + 1))+ if 0xDC00 <= next_code <= 0xDFFF:+ high_surrogate = raw_code+ low_surrogate = next_code+ consumed_char_indices.add(char_idx + 1)+ elif raw_code is not None and 0xDC00 <= raw_code <= 0xDFFF and char_idx > 0:+ previous_code = int(get_unicode(textpage_raw, char_idx - 1))+ if 0xD800 <= previous_code <= 0xDBFF:+ high_surrogate = previous_code+ low_surrogate = raw_code++ if high_surrogate is not None and low_surrogate is not None:+ restored_char = cast(Char, dict(char))- restored_char["char"] = chr(- 0x10000- + ((high_surrogate - 0xD800) << 10)- + (low_surrogate - 0xDC00)- )++ restored_char["char"] = chr(0x10000 + ((high_surrogate - 0xD800) << 10) + (low_surrogate - 0xDC00))+ restored_chars.append(restored_char)+ continue++ if len(text) == 1 and 0xD800 <= ord(text) <= 0xDFFF:+ restored_char = cast(Char, dict(char))- restored_char["char"] = "\uFFFD"++ restored_char["char"] = "\ufffd"+ restored_chars.append(restored_char)+ continue++ restored_chars.append(char)++ return restored_chars++def _char_bbox_values(bbox: object) -> tuple[float, float, float, float] | None:"""将 tuple/list 或 pdftext Bbox 对象统一转换为四元组坐标。"""if bbox is None:diff --cc pyproject.tomlindex 605366b8,d3165d68..92fce59d--- a/pyproject.toml+++ b/pyproject.toml@@@ -31,6 -31,8 +31,8 @@@ classifiers ="Programming Language :: Python :: 3.13",]dependencies = [- "mineru-vl-utils>=1.1.1,<2",++ "mineru-vl-utils>=1.2.1,<2",+ "mineru-llama-cpp>=0.1.0,<1","click>=8.1.7","loguru>=0.7.2","numpy>=1.21.6",@@@ -45,16 -47,14 +47,16 @@@"reportlab","pdftext>=0.6.3,<0.8.0","modelscope>=1.26.0",- "huggingface-hub>=0.32.4",+ "huggingface-hub[hf_xet]>=0.32.4",+ "filelock>=3.0.0","json-repair>=0.46.2",+ "latex2mathml>=3.81.0,<4","opencv-python>=4.11.0.86","fast-langdetect>=0.2.3,<0.3.0","openai>=1.70.0,<3","beautifulsoup4>=4.13.5,<5",+ "nh3>=0.3.6,<0.4","magika>=0.6.2,<1.1.0",- "mineru-vl-utils>=1.2.1,<2","python-docx>=1.2.0,<2",'pypptx-with-oxml>=1.0.3,<2',"mammoth>=1.11.0,<2",diff --cc tests/unittest/test_doclib_config.pyindex 46a3eae9,00bb4ee4..8a9004a7--- a/tests/unittest/test_doclib_config.py+++ b/tests/unittest/test_doclib_config.py@@@ -6,13 -6,14 +6,15 @@@ import pytesfrom mineru.config import (Config,+ LLMAidedConfig,+ LoadedConfig,LogConfig,PatchedConfig,- _apply_env_overrides,+ _collect_env_overrides,_interpolate_env,_load_config,- _read_config,+ _load_effective_config,+ update_config_file,)from mineru.doclib.config_defaults import CONFIG_DEFAULTS@@@ -136,115 -167,6 +168,116 @@@ def test_apply_env_overrides_can_overriassert 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")+++ # _apply_env_overrides is changed, should fix this test case.+ 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 --cc tests/unittest/test_render_config.pyindex 76d03d62,00000000..055c466fmode 100644,000000..100644--- a/tests/unittest/test_render_config.py+++ b/tests/unittest/test_render_config.py@@@ -1,76 -1,0 +1,77 @@@+from __future__ import annotations++from pathlib import Path++import pytest+from pydantic import ValidationError+- from mineru.config import Config, _apply_env_overrides, _load_config++from mineru.config import Config, _load_config+++def test_render_config_defaults() -> None:+ """验证 config.yaml 缺省时使用美元公式定界符。"""+ delimiters = Config().render.latex_delimiters++ assert delimiters.display.left == "$$"+ assert delimiters.display.right == "$$"+ assert delimiters.inline.left == "$"+ assert delimiters.inline.right == "$"+++def test_render_config_reads_yaml_shape(tmp_path: Path) -> None:+ """验证 render.latex_delimiters YAML 结构能进入 typed Config。"""+ config_file = tmp_path / "config.yaml"+ config_file.write_text(+ """+render:+ latex_delimiters:+ display:+ left: '\\['+ right: '\\]'+ inline:+ left: '\\('+ right: '\\)'+""".strip(),+ encoding="utf-8",+ )++ config = Config(**_load_config(str(config_file)))++ assert config.render.latex_delimiters.display.left == r"\["+ assert config.render.latex_delimiters.inline.right == r"\)"+++def test_render_config_supports_environment_overrides(monkeypatch: pytest.MonkeyPatch) -> None:+ """验证现有环境变量递归覆盖机制可定位 render delimiter。"""+ prefix = "TEST_MINERU_"+ monkeypatch.setenv(f"{prefix}RENDER_LATEX_DELIMITERS_INLINE_LEFT", r"\(")+ monkeypatch.setenv(f"{prefix}RENDER_LATEX_DELIMITERS_INLINE_RIGHT", r"\)")+++ # _apply_env_overrides is changed, should fix this test case.+ config = _apply_env_overrides(Config(), prefix=prefix)++ assert config.render.latex_delimiters.inline.left == r"\("+ assert config.render.latex_delimiters.inline.right == r"\)"++[email protected]("side", ["left", "right"])+def test_render_config_rejects_empty_delimiters(side: str) -> None:+ """验证任一空定界符都会在 typed config 边界报错。"""+ pair = {"left": "$", "right": "$"}+ pair[side] = ""++ with pytest.raises(ValidationError):+ Config(render={"latex_delimiters": {"inline": pair}})+++def test_render_config_does_not_read_legacy_root_key() -> None:+ """验证旧根级 latex-delimiter-config 不影响新 render 配置。"""+ config = Config.model_validate(+ {+ "latex-delimiter-config": {+ "inline": {"left": "OLD", "right": "OLD"},+ }+ }+ )++ assert config.render.latex_delimiters.inline.left == "$"