Skip to content

Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.

feat: enhance PDF analysis with layout block construction and normalization functions

myhlolia60b197322a3
diff --git a/docs/superpowers/specs/2026-07-08-hybrid-doc-analyze-refactor-design.md b/docs/superpowers/specs/2026-07-08-hybrid-doc-analyze-refactor-design.md
deleted file mode 100644
index e76dd56f..00000000
--- a/docs/superpowers/specs/2026-07-08-hybrid-doc-analyze-refactor-design.md
+++ /dev/null
@@ -1,309 +0,0 @@
-# Hybrid doc_analyze Refactor Design
-
-## 背景
-
-`mineru/backend/hybrid/hybrid_analyze.py` 的 `doc_analyze` / `aio_doc_analyze` 当前同时承载入口参数归一、VLM runtime 初始化、按窗口加载图片、三档 effort 抽取、OCR det/rec、MFR、title split、append 和 finalize。随着 `medium`、`high`、`extra_high` 的语义逐步收敛,继续在入口函数里增加条件会让 `parse_method` 与 `effort` 的职责混在一起,后续维护时容易重新引入错误路径。
-
-本次重构目标是把 `doc_analyze` 改成清晰的编排层,保留当前 public contract 和输出行为,不新增公开参数,不改变下游 `PageInfo` / `middle_json` schema。
-
-## 目标
-
-- `doc_analyze` 的核心控制维度只保留 `effort` 和规范化后的 `parse_mode`。
-- `parse_method="auto"` 在进入主流程前归一为 `parse_mode="ocr"` 或 `parse_mode="txt"`。
-- 三档 effort 都在每个窗口先运行小模型 layout。
-- 三档 effort 都使用 OCR 小模型 det 生成文本行 sidecar,但候选范围必须由 plan 控制,不能把 `high/extra_high + ocr` 扩大到所有文本类块。
-- 小模型 layout 的行内公式 bbox 可以作为公式位置提示或 OCR-det mask 输入,但 `high/extra_high + ocr` 不对行内公式跑 MFR 或 OCR-rec。
-- 先在 `mineru_vl_utils` 中支持 `doc_title` / `paragraph_title` block type,再让小模型 layout 的 split title subtype 在 Hybrid 内部和 VLM 外部 layout 调用中作为一等类型传递;`high` 不再先归一为 `title` 再用 layout bbox 反向拆分。
-- `medium` 完全不加载 VLM runtime。
-- `high` 使用 `predictor.batch_extract_with_layout`。
-- `extra_high` 使用 `predictor.batch_two_step_extract`。
-- 保持同步 `doc_analyze` 与异步 `aio_doc_analyze` 的策略一致。
-
-## 非目标
-
-- 不拆分公开 API、CLI、Gradio、parser 层的参数 contract。
-- 不恢复 `low` effort,也不增加兼容 alias。
-- 不新增 formula/table 公开开关。
-- 不重写 `HybridMagicModel`、`model_output_to_middle_json.py` 或最终渲染/export 逻辑。
-- 不改变 VLM predictor 的接口。
-- 不改变最终公开输出中的 title schema;`DOC_TITLE` / `PARAGRAPH_TITLE` 仍只作为内部类型,最终继续归一为 `TITLE + level`。
-- 不要求 `extra_high` 的 VLM two-step layout 原生产出 `doc_title` / `paragraph_title`;two-step 能产出的类型仍由 VLM 模型决定。`extra_high` 需要继续用本地 layout 结果对 two-step 返回的泛化 `title` 做 `doc_title` / `paragraph_title` 拆分。
-
-## 术语
-
-`parse_mode` 是 `parse_method` 归一后的内部值,只允许:
-
-- `ocr`: 文档文本来自光学识别。
-- `txt`: 文档文本来自 PDF 原生文本。
-
-`use_vlm_text_content` 表示下游 `MagicModel` 是否信任 VLM 返回的文本内容。它不是“是否运行 OCR 小模型”的含义。
-
-## 决策表
-
-| effort | 主结构来源 | `parse_mode=ocr` 文本来源 | `parse_mode=txt` 文本来源 | 强制 VLM 解析块 | inline formula MFR | OCR det 候选范围 | OCR rec |
-| --- | --- | --- | --- | --- | --- | --- | --- |
-| `medium` | 小模型 layout | 小模型 OCR det + rec | PDF native text | 无 VLM | `ocr/txt` 都需要 | medium 本地回填候选 | 仅 `ocr` |
-| `high` | 小模型 layout 约束 VLM | VLM block OCR | PDF native text + VLM 结构块 | `index` / `code` / 行间公式 / `table` | 仅 `txt` | `ocr`: 仅 `*_title` / `text`; `txt`: native-text 候选 | 不需要 |
-| `extra_high` | VLM two-step 原生结果 | VLM block OCR | PDF native text + VLM 结构块 | `index` / `code` / 行间公式 / `table` | 仅 `txt` | `ocr`: 仅 `*_title` / `text`; `txt`: native-text 候选 | 不需要 |
-
-由表可得:
-
-- `use_vlm_text_content = parse_mode == "ocr" and effort in {"high", "extra_high"}`
-- `needs_mfr = parse_mode == "txt" or effort == "medium"`
-- `needs_ocr_rec = parse_mode == "ocr" and effort == "medium"`
-- `parse_mode == "txt"` 不等于所有内容都走 PDF native text;只有可由 PDF native 回填的文本类块应被 VLM 跳过,强制 VLM 解析块必须继续交给 VLM。
-- `high` 和 `extra_high` 共用同一个 `forced_vlm_block_types`,包含 `index` / `code` / 行间公式 / `table`;`extra_high` 的 two-step extract 通常不会单独产出 `index`,但统一集合可以避免两套策略漂移。
-- `high/extra_high + ocr` 的 OCR det 候选只允许 `text`、`title`、`doc_title`、`paragraph_title`,其中 title 类用于计算标题块行高,text 类用于后续段落跨栏/跨页合并的坐标标识。
-
-## 内部策略对象
-
-新增内部 dataclass:
-
-```python
-@dataclass(frozen=True)
-class _HybridAnalyzePlan:
- """记录 Hybrid 单次解析的规范化策略,避免 effort/parse_method 判断散落在流程中。"""
-
- effort: str
- parse_mode: Literal["ocr", "txt"]
- use_vlm_text_content: bool
- needs_mfr: bool
- needs_ocr_rec: bool
- extractor: Literal["medium_local", "high_with_layout", "extra_high_two_step"]
- forced_vlm_block_types: frozenset[str]
- vlm_not_extract_list: tuple[str, ...] | None
- ocr_det_candidate_profile: Literal["medium_local", "native_text", "vlm_text_title_only"]
-```
-
-该对象只在 `hybrid_analyze.py` 内部使用,不作为公开 API。
-
-## 阶段划分
-
-### 1. 参数归一
-
-`_resolve_parse_mode(pdf_doc, parse_method)`:
-
-- `parse_method == "auto"` 时调用 `pdf_doc.classify()`。
-- `parse_method == "ocr"` 时直接返回 `ocr`。
-- `parse_method == "txt"` 时直接返回 `txt`。
-- 非法值抛出 `ValueError`。
-
-`_build_hybrid_analyze_plan(effort, parse_mode)`:
-
-- 先调用 `validate_effort(effort)`。
-- 按决策表返回 `_HybridAnalyzePlan`。
-- `vlm_not_extract_list` 不能无条件等同于未来可能扩展的 `NOT_EXTRACT_TYPES`;它必须排除当前 plan 的 `forced_vlm_block_types`,避免误把 `index` / `code` / 行间公式 / `table` 交给 PDF native 或空内容回填。
-- `ocr_det_candidate_profile` 必须显式区分 VLM OCR 路径;`high/extra_high + ocr` 只能使用 `vlm_text_title_only`,不能复用 medium 或 native-text 的宽候选集合。
-
-### 2. Runtime 初始化
-
-`medium` 不调用 `_load_vlm_runtime()`,并强制 `predictor=None`。
-
-`high` / `extra_high` 才按需加载 VLM runtime:
-
-- 同步入口继续使用 `ModelSingleton().get_model(...)`。
-- 异步入口继续使用 `_get_model_async(...)`。
-- `predictor_execution_guard` / `aio_predictor_execution_guard` 保持原有边界。
-
-### 3. 每窗口统一前置 layout
-
-每个 `_ProcessingWindow` 都先加载图片并运行本地 layout,产出:
-
-- `images_pil_list`
-- `np_images`
-- `images_layout_res`
-- `local_context`
-
-本地 context 的 `formula_enable` 应由 plan 决定:
-
-- `plan.needs_mfr=True` 时需要加载 MFR。
-- `plan.needs_mfr=False` 时不加载 MFR,避免 high/extra_high OCR 模式多占资源。
-
-### 4. Effort 抽取
-
-`medium_local`:
-
-- 直接基于 `images_layout_res` 构造 medium model list。
-- 保留 medium 的表格、印章 OCR、formula_number OCR-rec 等本地增强逻辑。
-- 不调用 VLM。
-
-`high_with_layout`:
-
-- 使用 `images_layout_res` 构造 `blocks_list`。
-- 在 `mineru_vl_utils` 支持 split title 类型之后,`HYBRID_VLM_LAYOUT_LABEL_MAP` 直接把 `doc_title` 映射为 `DOC_TITLE`,把 `paragraph_title` 映射为 `PARAGRAPH_TITLE`;不再为了 VLM 调用先退化为 `TITLE`。
-- 调用 `predictor.batch_extract_with_layout(...)`。
-- `parse_mode=ocr` 时不传 `not_extract_list`,由 VLM 完成 block OCR。
-- `parse_mode=txt` 时只跳过可由 PDF native 回填的文本类块;`index`、`code`、行间公式、`table` 必须留给 VLM 解析。
-
-`extra_high_two_step`:
-
-- 调用 `predictor.batch_two_step_extract(...)`。
-- `batch_two_step_extract(...)` 的 VLM 原生 layout 不支持稳定区分 `doc_title` / `paragraph_title`,返回的 title 仍按泛化 `TITLE` 处理。
-- two-step 返回后继续执行 `_apply_layout_title_split(...)`,用同窗口的小模型 layout `doc_title` bbox 把 VLM `TITLE` 拆分为 `DOC_TITLE` / `PARAGRAPH_TITLE`。
-- `parse_mode=ocr` 时不传 `not_extract_list`,由 VLM 完成 block OCR。
-- `parse_mode=txt` 时只跳过可由 PDF native 回填的文本类块;`index`、`code`、行间公式、`table` 必须留给 VLM 解析。
-
-`image_analysis` 继续只在 `extra_high` 中生效,`medium` 和 `high` 强制关闭,避免低/中资源路径隐式触发更重的 VLM 图像分析。
-
-### 5. Title subtype 贯通
-
-`mineru_vl_utils` 是 VLM 外部 layout schema 的拥有者。Magic-PDF 不能只在本地把 layout label 改成 `DOC_TITLE` / `PARAGRAPH_TITLE`,否则 `mineru_vl_utils.structs.ContentBlock` 的类型断言、`parse_layout_output(...)` 的 unknown type 过滤、`prepare_for_extract(...)` 的 `not_extract_list` 校验都会把新类型拒绝或忽略。
-
-因此需要先在 `/Users/myhloli/projects/20251028mineru_vl_utils/mineru-vl-utils` 做一层兼容扩展:
-
-- `mineru_vl_utils.structs.BlockType` 增加 `DOC_TITLE = "doc_title"` 和 `PARAGRAPH_TITLE = "paragraph_title"`。
-- `BLOCK_TYPES` 增加这两个类型,保证 `ContentBlock(...)`、`ContentBlock.type` setter、外部 layout dict 归一化、layout output parser 都接受 split title。
-- `mineru_client.prepare_for_extract(...)` 不需要为这两个类型新增专用 prompt;它们默认走 `[default]` 文本识别 prompt,语义上和 `title` 一致。
-- `not_extract_list` 校验应自然支持这两个类型,便于 `parse_mode=txt` 时把 split title 作为可跳过的 native-text title 类块处理。
-- `post_process(...)` 不应把这两个类型归一成 `title`;输出归一仍留给 Magic-PDF 的 `model_output_to_middle_json._normalize_split_title_blocks(...)`。
-
-Hybrid 内部统一把 `{TITLE, DOC_TITLE, PARAGRAPH_TITLE}` 视为 title-like block:
-
-- `high` 的 `blocks_list` 保留 layout subtype,不再依赖 `_apply_layout_title_split(...)` 对 VLM 返回的 `TITLE` 做二次拆分。
-- `extra_high` 仍使用 two-step 原生结果;由于 two-step 不稳定产出 split title,必须保留 `_apply_layout_title_split(...)`,在 VLM 抽取后用本地 layout `doc_title` bbox 对泛化 `TITLE` 做拆分。
-- `para_block_utils`、title leveling、layout/visual debug 等共享 utils 需要使用统一的 title-like 判断,避免只识别 `TITLE` 导致 merge barrier、行高、绘制或调试输出丢失 title subtype。
-- `model_output_to_middle_json._normalize_split_title_blocks(...)` 仍是输出边界,负责把内部 `DOC_TITLE` / `PARAGRAPH_TITLE` 归一为公开 `TITLE` 并补默认 level。
-
-因此,`_apply_layout_title_split(...)` 不再属于 high 主路径,但仍是 extra_high 主路径的一部分。实现时应把它的调用点收窄到 `extra_high_two_step`,避免未来维护者误以为 high 仍需要“先丢 subtype,再根据 bbox 补回 subtype”。
-
-### 6. Sidecar 增强
-
-OCR det 三档都执行,但候选范围不同:
-
-- `medium_local`: 使用 medium 本地 layout 回填候选,服务 OCR 文本回填、空 `index/code/algorithm` 回填和行提示。
-- `native_text`: 用于 `parse_mode=txt` 的 PDF native text 路径,服务 native 文本回填、行内公式匹配和段落合并提示。
-- `vlm_text_title_only`: 仅用于 `high/extra_high + ocr`,候选只能是 `text`、`title`、`doc_title`、`paragraph_title`。
-
-`vlm_text_title_only` 的结果必须是空文本 sidecar,不能覆盖 VLM content。title 类 det 行只用于 `_line_avg_height` / title leveling,text 类 det 行只用于段落跨栏/跨页合并所需的坐标标识。
-
-MFR 只在 `plan.needs_mfr=True` 时执行:
-
-- `medium + ocr/txt` 都执行。
-- `high/extra_high + txt` 执行。
-- `high/extra_high + ocr` 不执行,行内公式由 VLM block OCR 负责。
-
-OCR rec 只在 `plan.needs_ocr_rec=True` 时执行:
-
-- 仅 `medium + ocr` 执行。
-- `high/extra_high + ocr` 不执行,因为 VLM 已提供 block 文本。
-- 所有 `txt` 模式不执行 OCR rec。
-
-`high/extra_high + ocr` 的 OCR det sidecar 只保留 `*_title/text` 空文本行提示,不能覆盖 VLM content,也不能额外扫描 `index`、`code`、行间公式、`table`、caption、footnote、aside、list 等非目标块。
-
-`high/extra_high + txt` 的 inline formula MFR 只为 PDF native 文本类块补行内公式;已经强制 VLM 解析的 `index`、`code`、行间公式、`table` 内容仍以 VLM 输出为准。
-
-### 7. Append 与 finalize
-
-`append_pages(...)` 继续调用 `blocks_to_page_info(...)`,但传入的 `_ocr_enable` 可以保持当前兼容形态,对下游语义更清楚的变量是 `use_vlm_text_content`。
-
-`_finalize_hybrid_middle_json(...)` 保持现有行为:
-
-- `client_side_output_generation=True` 时走 `apply_server_side_postprocess(...)`。
-- 否则走 `finalize_middle_json(...)`。
-
-重构不改变 `finalize_middle_json_from_preproc(...)` 的 merge、跨页表格、title leveling、split-title normalize 行为。
-
-## 同步与异步一致性
-
-同步和异步入口应共享以下纯策略函数:
-
-- `_resolve_parse_mode`
-- `_build_hybrid_analyze_plan`
-- 计算 `batch_ratio` 的规则
-- 每个 effort 的参数选择规则
-
-异步入口可以继续用 `asyncio.to_thread(...)` 包装本地 CPU/GPU 小模型步骤,但不能维护一套独立的 effort/parse 判断。
-
-## 测试策略
-
-### Plan 单测
-
-新增或扩展 focused tests,覆盖 3 effort x 2 parse_mode:
-
-- `medium + ocr`: `use_vlm_text_content=False`, `needs_mfr=True`, `needs_ocr_rec=True`
-- `medium + txt`: `use_vlm_text_content=False`, `needs_mfr=True`, `needs_ocr_rec=False`
-- `high + ocr`: `use_vlm_text_content=True`, `needs_mfr=False`, `needs_ocr_rec=False`
-- `high + txt`: `use_vlm_text_content=False`, `needs_mfr=True`, `needs_ocr_rec=False`
-- `extra_high + ocr`: `use_vlm_text_content=True`, `needs_mfr=False`, `needs_ocr_rec=False`
-- `extra_high + txt`: `use_vlm_text_content=False`, `needs_mfr=True`, `needs_ocr_rec=False`
-- `high/extra_high + ocr`: `ocr_det_candidate_profile="vlm_text_title_only"`
-
-### Runtime 路由单测
-
-沿用 `tests/unittest/test_hybrid_high_extra_high_ocr_routing.py` 的 fake predictor 风格:
-
-- `medium` 不加载 VLM runtime。
-- `high + ocr` 调 `batch_extract_with_layout`,不跑 MFR/rec,`use_vlm_text_content=True`。
-- `high` 构造 `blocks_list` 时保留 `doc_title` / `paragraph_title` subtype,fake predictor 接收到的 layout block type 应分别是 `DOC_TITLE` / `PARAGRAPH_TITLE`,而不是统一的 `TITLE`。
-- `high + ocr` 的 OCR det 候选只接受 `text` / `title` / `doc_title` / `paragraph_title`,拒绝 `index` / `code` / 行间公式 / `table` / caption / footnote / aside / list。
-- `high + txt` 调 `batch_extract_with_layout`,传 `not_extract_list`,跑 MFR,不跑 rec,并断言 `index` / `code` / 行间公式 / `table` 不在跳过列表中。
-- `extra_high + ocr` 调 `batch_two_step_extract`,不跑 MFR/rec,`use_vlm_text_content=True`。
-- `extra_high` fake predictor 返回泛化 `TITLE` 时,流程仍调用 `_apply_layout_title_split(...)`,并能基于本地 layout `doc_title` bbox 产出 `DOC_TITLE` / `PARAGRAPH_TITLE`。
-- `extra_high + ocr` 的 OCR det 候选只接受 `text` / `title` / `doc_title` / `paragraph_title`,拒绝 `index` / `code` / 行间公式 / `table` / caption / footnote / aside / list。
-- `extra_high + txt` 调 `batch_two_step_extract`,传 `not_extract_list`,跑 MFR,不跑 rec,并断言 `index` / `code` / 行间公式 / `table` 不在跳过列表中。
-- `medium + ocr` 跑 OCR det + OCR rec + MFR。
-
-### 回归测试
-
-保留并更新以下测试族:
-
-- `tests/unittest/test_hybrid_analyze_refactor_guards.py`
-- `tests/unittest/test_hybrid_medium_ocr_text_fill.py`
-- `tests/unittest/test_hybrid_medium_formula_model_loading.py`
-- `tests/unittest/test_hybrid_medium_local_layout_memory.py`
-- `tests/unittest/test_hybrid_medium_table_inline_objects.py`
-- `tests/unittest/test_hybrid_high_extra_high_ocr_routing.py`
-
-新增 title subtype focused tests:
-
-- 在 `mineru_vl_utils` 中新增测试,覆盖 `ContentBlock(BlockType.DOC_TITLE, ...)` / `ContentBlock(BlockType.PARAGRAPH_TITLE, ...)` 可构造、`parse_layout_output(...)` 可解析 `<|ref_start|>doc_title<|ref_end|>` / `<|ref_start|>paragraph_title<|ref_end|>`、`batch_extract_with_layout(...)` 可接收外部 layout dict 并使用 `[default]` prompt。
-- 在 `mineru_vl_utils` 中新增测试,覆盖 `not_extract_list=["doc_title", "paragraph_title"]` 会跳过对应 block,但不会影响 `index` / `code` / 行间公式 / `table`。
-- `HYBRID_VLM_LAYOUT_LABEL_MAP` 和 `_layout_item_to_content_block(...)` 在 high 外部 layout 路径对 `doc_title` / `paragraph_title` 保留内部 split title 类型。
-- `_apply_layout_title_split(...)` 在 extra_high two-step 路径继续覆盖 VLM 泛化 `TITLE` 到 `DOC_TITLE` / `PARAGRAPH_TITLE`。
-- layout/visual debug utils 将 `DOC_TITLE` / `PARAGRAPH_TITLE` 与 `TITLE` 归入同一 title bucket,不把它们误画成普通文本或漏画。
-- `finalize_middle_json_from_preproc(...)` 后,内部 `DOC_TITLE` / `PARAGRAPH_TITLE` 仍归一为公开 `TITLE`,并分别得到默认 level 1 / 2。
-
-## 验证命令
-
-实现后至少运行:
-
-```bash
-.venv1/bin/python -m pytest -o addopts='' \
- tests/unittest/test_hybrid_analyze_refactor_guards.py \
- tests/unittest/test_hybrid_medium_ocr_text_fill.py \
- tests/unittest/test_hybrid_medium_formula_model_loading.py \
- tests/unittest/test_hybrid_medium_local_layout_memory.py \
- tests/unittest/test_hybrid_medium_table_inline_objects.py \
- tests/unittest/test_hybrid_high_extra_high_ocr_routing.py -q
-
-.venv1/bin/python -m py_compile mineru/backend/hybrid/hybrid_analyze.py
-git diff --check
-```
-
-如果实现触碰 `model_output_to_middle_json.py` 或 `hybrid_magic_model.py`,还需要补跑相关 focused tests,并明确说明触碰原因。
-
-跨 repo 实现时还需要在 `mineru_vl_utils` 工作区运行:
-
-```bash
-cd /Users/myhloli/projects/20251028mineru_vl_utils/mineru-vl-utils
-/Users/myhloli/projects/20240809magic_pdf/Magic-PDF/.venv1/bin/python -m pytest -q \
- tests/test_formula_number_layout.py \
- tests/test_external_layout_progress.py \
- tests/test_title_block_types.py
-```
-
-`mineru_vl_utils` 发布或本地依赖更新后,Magic-PDF 的 `pyproject.toml` 需要把 `mineru-vl-utils>=...` 的下限提升到包含 split title 支持的版本;在本地 editable 环境验证时可以先不改依赖下限。
-
-## 风险与约束
-
-- `use_vlm_text_content` 的语义必须保持为“文本内容是否来自 VLM”,不能重新被解释为 OCR 开关。
-- `medium` 的低资源边界不能被破坏,任何 VLM import 都不能进入 medium 路径。
-- `high/extra_high + ocr` 不应触发 MFR 或 OCR-rec。
-- `high/extra_high + ocr` 的 OCR det 不能复用宽文本候选,只允许 `text`、`title`、`doc_title`、`paragraph_title`。
-- `high/extra_high + txt` 必须保留 inline formula MFR,否则 PDF native text 路径会丢失行内公式补偿。
-- `high + txt` 必须强制 VLM 解析 `index`、`code`、行间公式和 `table`,不能因 `not_extract_list` 扩展而退化为 PDF native 回填。
-- `extra_high + txt` 必须强制 VLM 解析 `index`、`code`、行间公式和 `table`,不能因 `not_extract_list` 扩展而退化为 PDF native 回填;`index` 在 two-step 输出中通常不存在,但必须和 `high` 使用同一强制集合。
-- `INDEX -> TEXT` 的归一仍应留在 `MagicModel` 内容构造完成之后,不能提前转换。
-- Magic-PDF 不能在 `mineru_vl_utils` 尚未支持 split title 类型时直接把 high 外部 layout 传成 `doc_title` / `paragraph_title`,否则 `ContentBlock` 断言或 layout parser 会拒绝新类型。
-- 不能删除 `_apply_layout_title_split(...)`;它不再服务 high,但仍服务 extra_high 的 two-step title subtype 补偿。
-- 新增函数和方法必须包含中文注释,方便 review。
diff --git a/mineru/backend/hybrid/analyze.py b/mineru/backend/hybrid/analyze.py
index 5d7a6032..66b1b853 100644
--- a/mineru/backend/hybrid/analyze.py
+++ b/mineru/backend/hybrid/analyze.py
@@ -5,14 +5,18 @@ from dataclasses import dataclass
from typing import Any, Literal
import numpy as np
+from PIL import Image
from loguru import logger
from mineru.backend.local_model_runtime import AtomModelSingleton, HybridLocalModelContextSingleton
+from mineru.backend.utils.runtime_utils import exclude_progress_bar_idle_time
from mineru.utils.engine_utils import get_vlm_engine
+from mineru.utils.model_utils import clean_memory
from mineru.utils.pdf_image_tools import load_images_from_pdf_bytes_range
+from tqdm import tqdm
from ...utils.image_payload import ImagePayloadCache
from ...utils.pdf_document import PDFDocument
-from ...types import PageInfo
+from ...types import PageInfo, BlockType, BBox
from ...utils.config_reader import get_processing_window_size
@@ -23,6 +27,31 @@ MFR_BASE_BATCH_SIZE = 16
OCR_DET_BASE_BATCH_SIZE = 8
LAYOUT_TITLE_SPLIT_OVERLAP_THRESHOLD = 0.8
+VLM_LAYOUT_LABEL_MAP = {
+ "abstract": BlockType.TEXT,
+ "algorithm": BlockType.CODE,
+ "aside_text": BlockType.ASIDE_TEXT,
+ "chart": BlockType.CHART,
+ "content": BlockType.INDEX,
+ "display_formula": BlockType.EQUATION,
+ "doc_title": BlockType.DOC_TITLE,
+ "figure_title": BlockType.CAPTION,
+ "footer": BlockType.FOOTER,
+ "footer_image": BlockType.FOOTER,
+ "footnote": BlockType.PAGE_FOOTNOTE,
+ "formula_number": BlockType.FORMULA_NUMBER,
+ "header": BlockType.HEADER,
+ "header_image": BlockType.HEADER,
+ "image": BlockType.IMAGE,
+ "number": BlockType.PAGE_NUMBER,
+ "paragraph_title": BlockType.PARAGRAPH_TITLE,
+ "reference_content": BlockType.REF_TEXT,
+ "seal": BlockType.IMAGE,
+ "table": BlockType.TABLE,
+ "text": BlockType.TEXT,
+ "vertical_text": BlockType.TEXT,
+}
+
def _load_vlm_runtime() -> dict[str, Any]:
"""按需加载 VLM runtime 组件,确保只有 high/extra_high 路径触发 VLM 依赖。"""
@@ -46,7 +75,6 @@ def _load_vlm_runtime() -> dict[str, Any]:
@dataclass(frozen=True)
class _ProcessingWindow:
"""记录单个 Hybrid 处理窗口的页码范围,统一同步和异步入口的窗口计算。"""
-
index: int
total: int
start: int
@@ -88,55 +116,220 @@ def _log_processing_window(window: _ProcessingWindow, page_count: int, image_cou
)
+def _close_images(images_list: list[dict[str, Any]]) -> None:
+ for image_dict in images_list or []:
+ pil_img = image_dict.get("img_pil")
+ if pil_img is not None:
+ try:
+ pil_img.close()
+ except Exception:
+ pass
+
+
+def _normalize_page_size(page_image: Any) -> tuple[int, int]:
+ """从PIL或numpy图像中读取页面宽高,供归一化bbox还原为像素bbox。"""
+ if hasattr(page_image, "size"):
+ return page_image.size
+
+ height, width = page_image.shape[:2]
+ return width, height
+
+
+def _bbox_to_pixel_bbox(bbox: BBox | None, page_size: tuple[int, int]) -> BBox | None:
+ """将归一化或像素bbox统一成像素bbox,异常bbox返回None。"""
+ if bbox is None or len(bbox) != 4:
+ return None
+
+ try:
+ x0, y0, x1, y1 = [float(v) for v in bbox]
+ except (TypeError, ValueError):
+ return None
+
+ width, height = page_size
+ if all(0.0 <= value <= 1.0 for value in [x0, y0, x1, y1]):
+ x0, y0, x1, y1 = x0 * width, y0 * height, x1 * width, y1 * height
+
+ left, right = sorted([x0, x1])
+ top, bottom = sorted([y0, y1])
+ if right <= left or bottom <= top:
+ return None
+ return (left, top, right, bottom)
+
+
+def _normalize_layout_bbox_to_unit(bbox: BBox | None, page_size: tuple[int, int]) -> list[float] | None:
+ """将 layout 像素 bbox 归一化为 VLM ContentBlock 需要的 0-1 坐标。"""
+ pixel_bbox = _bbox_to_pixel_bbox(bbox, page_size)
+ if pixel_bbox is None:
+ return None
+
+ page_width, page_height = page_size
+ if page_width <= 0 or page_height <= 0:
+ return None
+
+ x0, y0, x1, y1 = pixel_bbox
+ unit_bbox = [
+ max(0.0, min(1.0, float(x0) / page_width)),
+ max(0.0, min(1.0, float(y0) / page_height)),
+ max(0.0, min(1.0, float(x1) / page_width)),
+ max(0.0, min(1.0, float(y1) / page_height)),
+ ]
+ if unit_bbox[2] <= unit_bbox[0] or unit_bbox[3] <= unit_bbox[1]:
+ return None
+ return unit_bbox
+
+
+def _layout_item_to_content_block(layout_item: dict[str, Any], page_size: tuple[int, int]) -> dict | None:
+ """将本地 layout 小模型检测项转换为 mineru-vl-utils 的 ContentBlock。"""
+ label = layout_item.get("label") or layout_item.get("type")
+
+ block_type = VLM_LAYOUT_LABEL_MAP.get(str(label))
+ if block_type is None:
+ return None
+
+ bbox = _normalize_layout_bbox_to_unit(layout_item.get("bbox"), page_size)
+ if bbox is None:
+ return None
+
+ content_block = {
+ "type": block_type,
+ "bbox": bbox,
+ "angle": layout_item.get("angle", 0),
+ }
+
+ if label == "seal":
+ content_block["sub_type"] = "seal"
+
+ return content_block
+
+
+def _build_layout_blocks(
+ images_layout_res: list[list[dict[str, Any]]],
+ images_pil_list: list[Image.Image],
+) -> list[list[Any]]:
+ """按页构造 Hybrid high 模式传给 VLM 的外部 layout blocks。"""
+ blocks_list: list[list[Any]] = []
+ for layout_res, image in zip(images_layout_res, images_pil_list):
+ page_size = _normalize_page_size(image)
+ page_blocks = []
+ for layout_item in layout_res:
+ content_block = _layout_item_to_content_block(layout_item, page_size)
+ if content_block is not None:
+ page_blocks.append(content_block)
+ blocks_list.append(page_blocks)
+ return blocks_list
+
+
def doc_analyze(
pdf_bytes: bytes,
effort: Literal["medium", "high", "xhigh"] = "high",
image_analysis: bool = True,
page_index_map: list[int] | None = None,
image_cache: ImagePayloadCache | None = None,
-) -> tuple[list[PageInfo], list[list[dict[str, Any]]], bool]:
+) -> tuple[list[PageInfo], list[list[dict[str, Any]]]]:
batch_ratio = 2
pdf_doc = PDFDocument(pdf_bytes)
parse_mode = pdf_doc.classify()
- page_count = pdf_doc.page_count
- configured_window_size = get_processing_window_size(default=64)
- windows = _build_processing_windows(page_count, configured_window_size)
- _log_processing_window_plan(page_count, configured_window_size, len(windows))
+ middle_json: list[PageInfo] = []
+ model_list: list[list[dict[str, Any]]] = []
+ doc_closed = False
- infer_start = time.time()
- progress_bar = None
- last_append_end_time = None
+ try:
+ page_count = pdf_doc.page_count
+ configured_window_size = get_processing_window_size(default=64)
+ windows = _build_processing_windows(page_count, configured_window_size)
+ _log_processing_window_plan(page_count, configured_window_size, len(windows))
- hybrid_model_singleton = HybridLocalModelContextSingleton()
- hybrid_model = hybrid_model_singleton.get_model()
- atom_model_manager = AtomModelSingleton()
+ hybrid_model_singleton = HybridLocalModelContextSingleton()
+ hybrid_model = hybrid_model_singleton.get_model()
+ atom_model_manager = AtomModelSingleton()
- try:
- for window in windows:
- images_list = load_images_from_pdf_bytes_range(
- pdf_bytes=pdf_bytes,
- start_page_id=window.start,
- end_page_id=window.end,
- image_type="pil_img",
- )
- images_pil_list = [image_dict["img_pil"] for image_dict in images_list]
- _log_processing_window(window, page_count, len(images_pil_list))
+ if effort in ["high", "xhigh"]:
+ vlm_runtime = _load_vlm_runtime()
+ vlm_backend = get_vlm_engine(inference_engine="auto", is_async=False)
+ vlm_predictor = vlm_runtime["ModelSingleton"]().get_model(backend=vlm_backend)
+ vlm_predictor = vlm_runtime["_maybe_enable_serial_execution"](vlm_predictor, vlm_backend)
+ else:
+ vlm_predictor = None
+
+ infer_start = time.time()
+ progress_bar = None
+ last_append_end_time = None
+
+ try:
+ for window in windows:
+ images_list = load_images_from_pdf_bytes_range(
+ pdf_bytes=pdf_bytes,
+ start_page_id=window.start,
+ end_page_id=window.end,
+ image_type="pil_img",
+ )
+ try:
+ images_pil_list = [image_dict["img_pil"] for image_dict in images_list]
+ _log_processing_window(window, page_count, len(images_pil_list))
- np_images = [np.asarray(pil_image).copy() for pil_image in images_pil_list]
- images_layout_res = hybrid_model.layout_model.batch_predict(
- images_pil_list,
- batch_size=min(8, batch_ratio * LAYOUT_BASE_BATCH_SIZE)
+ np_images = [np.asarray(pil_image).copy() for pil_image in images_pil_list]
+ images_layout_res = hybrid_model.layout_model.batch_predict(
+ images_pil_list,
+ batch_size=min(8, batch_ratio * LAYOUT_BASE_BATCH_SIZE)
+ )
+
+ if effort == "medium":
+ pass
+ elif effort == "high":
+ pass
+ elif effort == "xhigh":
+ pass
+ else:
+ raise ValueError(f"Unsupported analyze effort: {effort}")
+
+ model_list.extend(window_model_list)
+ if progress_bar is None:
+ progress_bar = tqdm(total=page_count, desc="Processing pages")
+ else:
+ exclude_progress_bar_idle_time(
+ progress_bar,
+ last_append_end_time,
+ now=time.time(),
+ )
+ append_pages(
+ middle_json,
+ window_model_list,
+ images_list,
+ pdf_doc,
+ page_cvt_fn=blocks_to_page_info,
+ page_start_index=window.start,
+ page_index_map=page_index_map,
+ _ocr_enable=_ocr_enable,
+ use_vlm_text_content=use_vlm_text_content,
+ progress_bar=progress_bar,
+ image_cache=image_cache,
+ )
+ last_append_end_time = time.time()
+ finally:
+ _close_images(images_list)
+ finally:
+ if progress_bar is not None:
+ progress_bar.close()
+ infer_time = round(time.time() - infer_start, 2)
+ if infer_time > 0 and page_count > 0:
+ logger.debug(
+ f"processing-window infer finished, cost: {infer_time}, speed: {round(len(model_list) / infer_time, 3)} page/s"
)
- if effort == "medium":
- pass
- else:
- vlm_runtime = _load_vlm_runtime()
- vlm_backend = get_vlm_engine(inference_engine="auto", is_async=False)
- vlm_predictor = vlm_runtime["ModelSingleton"]().get_model(backend=vlm_backend)
- if effort == "high":
- pass
- elif effort == "xhigh":
- pass
+ pdf_doc.close()
+ doc_closed = True
+ clean_memory(hybrid_model.device)
+ return middle_json, model_list
+ finally:
+ if not doc_closed:
+ pdf_doc.close()
+
+if __name__ == '__main__':
+ pdf_path = "/Users/myhloli/pdf/截断合并/demo1-2.pdf"
+ with open(pdf_path, "rb") as f:
+ pdf_bytes = f.read()
+ middle_json, model_list = doc_analyze(pdf_bytes, effort="medium", image_analysis=True)
+ logger.info(f"middle_json: {middle_json}")
+ logger.info(f"model_list: {model_list}")