Skip to content

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

feat: standardize image block key to 'image_base64' and remove unused metadata

myhloli91d9958bccd6
diff --git a/docs/next/middle-json/current-medium.md b/docs/next/middle-json/current-medium.md
index b0e6f514..27c930c8 100644
--- a/docs/next/middle-json/current-medium.md
+++ b/docs/next/middle-json/current-medium.md
@@ -1,166 +1,162 @@
-# 当前事实标准
+# 当前 Middle JSON 事实标准
状态: Draft
+
读者: backend 开发者、SDK 开发者、输出开发者
-范围: 当前 `mineru/types.py` 中 document model 的字段契约和注意事项
-来源: 由根目录旧 Middle JSON 底稿迁移整理而来
+
+范围: `doc_analyze()` 第一返回值及 `mineru/types.py` 中的公开 Middle JSON 对象
## 标准来源
-当前事实标准来自 `mineru/types.py`:
+当前事实标准由以下 Pydantic v2 模型定义:
+- `MiddleJson`
- `PageInfo`
-- `Block`
-- `Line`
-- `Span`
-- `ContentItem`
-- `BlockType`
-- `ContentType`
-- `ContentTypeV2`
+- `Block` discriminated union
+- 各具体 `*Block` 模型
+
+所有模型使用 `extra="forbid"` 和严格校验。反序列化入口是
+`model_validate()` / `model_validate_json()`,序列化入口是 `to_dict()` /
+`to_json()`。不再提供旧 `Block(...)` 通用构造器或 dict-like 兼容接口。
+
+本轮未迁移的 `ParseResult`、renderer、LLM 标题修正和 Structured Content
+不属于本文档描述的对象链路。
-这些类型已具备 `to_dict()` / `from_dict()` 能力,能够递归处理嵌套 dataclass list,并把 JSON 中的 list bbox / page_size 转回 tuple。
+## `MiddleJson`
-当前 `ParseResult.to_dict()` 输出顶层 `schema_version + pages`,并在所有 page backend 一致时保留顶层 `_backend` 作为临时兼容 metadata。`ParseResult.from_dict()` / `from_json()` 已可恢复 `pages` envelope,但不接受旧 `pdf_info` envelope。
+| 字段 | 类型 | 要求 |
+|------|------|------|
+| `pages` | `list[PageInfo]` | 必填,`page_idx` 唯一且严格递增 |
+| `file_suffix` | `pdf/docx/pptx/xlsx` | 必填 |
+| `effort` | `flash/low/medium/high/xhigh` | 必填 |
+| `parse_mode` | `txt/ocr` | 必填 |
+| `mineru_version` | 非空字符串 | 必填 |
+
+当 `file_suffix="pdf"` 时,每个页面顶层 block 必须具有有效 bbox。Office
+顶层 block 可以没有 bbox。
## `PageInfo`
-字段:
+| 字段 | 类型 | 要求 |
+|------|------|------|
+| `page_idx` | 非负整数 | 必填,使用实际页号映射 |
+| `blocks` | `list[Block]` | 必填,默认为空列表 |
-| 字段 | 类型 | 当前要求 | 说明 |
-|------|------|----------|------|
-| `page_idx` | int | 必填 | 0-based 页号。 |
-| `page_size` | tuple[int, int] 或 null | 建议必填 | PDF/VLM/Hybrid 通常有;Office/HTML 可能为空。 |
-| `preproc_blocks` | list[Block] | 默认空 | 预处理 block。Pipeline/VLM/Hybrid 中较常见。 |
-| `para_blocks` | list[Block] | 默认空 | 主阅读流。render 主要消费它。 |
-| `discarded_blocks` | list[Block] | 默认空 | 页眉、页脚、页码等边缘内容。 |
-| `_backend` | internal | 临时 | 当前 render facade 仍依赖它 dispatch。长期应移入 `_meta.backend`。 |
+顶层 block 必须具有非负 `index`。同一页内的 index 必须唯一、严格递增,
+但允许缺号或从非零值开始。数组位置不能替代 index。
-目标要求:
+## Block 公共字段
-- `page_idx` 必须稳定对应原文档页号。
-- `para_blocks` 必须按 reading order 排序。
-- `discarded_blocks` 不应混入主阅读流,但需要保留以支持搜索和引用。
-- `_backend` 不进入长期 public schema。
+所有具体 block 只共享以下定位字段:
-## `Block`
+| 字段 | 类型 | 要求 |
+|------|------|------|
+| `type` | discriminator literal | 必填 |
+| `index` | 非负整数或 null | 顶层必填,嵌套项可省略 |
+| `bbox` | 4 个 float 的 tuple 或 null | PDF 顶层必填,Office/嵌套项可省略 |
-字段:
+bbox 必须是有限的 `[0, 1]` 归一化坐标,并满足 `x1 > x0`、`y1 > y0`。
+每个具体 block 都显式声明必填 `content`,公共基类不再杂糅类型专属字段。
-| 字段 | 类型 | 当前要求 | 说明 |
-|------|------|----------|------|
-| `index` | int | 必填 | 页内排序标识。当前仍有 backend 差异。 |
-| `type` | str | 必填 | 来自 `BlockType`。 |
-| `bbox` | tuple[float, float, float, float] | 必填 | 当前类型必填;未知时常用 `EMPTY_BBOX`。 |
-| `lines` | list[Line] | 默认空 | 叶子内容。 |
-| `blocks` | list[Block] | 默认空 | 嵌套结构,如 list、image/table/code 容器。 |
-| `angle` | int 或 null | 可选 | 文本角度。 |
-| `score` | float 或 null | 可选 | 置信度。 |
-| `level` | int 或 null | 可选 | 标题层级。 |
-| `sub_type` | str | 可选 | 代码等细分类型。 |
-| `guess_lang` | str | 可选 | 语言猜测。 |
-| `merge_prev` | bool | 可选 | 与前一 block 合并。 |
-| `section_number` | str | 可选 | Office 标题编号等。 |
-| `html` | str | 可选 | 表格或富内容。 |
-| `text` | str | 可选 | 兼容字段。 |
-| `latex` | str | 可选 | 公式内容。 |
-| `anchor` | str | Office | 目录/标题 anchor。 |
+公开 discriminator 共 29 个:
-目标要求:
+```text
+aside_text
+chart, chart_body, chart_caption, chart_footnote
+code, code_body, code_caption, code_footnote
+doc_title, paragraph_title
+footer, formula_number, header
+image, image_body, image_caption, image_footnote
+index, interline_equation, list
+page_footnote, page_number, ref_text
+table, table_body, table_caption, table_footnote
+text
+```
-- 一个 block 可以同时有 `lines` 和 `blocks`,但公开消费方应优先按 block type 理解结构。
-- `index` 必须在 normalization 阶段变成 Agent 可依赖的 reading order。
-- `bbox=EMPTY_BBOX` 表示未知,不等于真实页面左上角零面积框。
+仅 raw 阶段允许的 `algorithm/caption/equation/footnote/title/phonetic` 不属于
+公开 union。其它旧 `BlockType` 常量也不会被严格反序列化接受。
-## `Line`
+## 主要具体模型
-字段:
+| 模型 | `content` | 专属字段 |
+|------|-----------|----------|
+| `TextBlock` | `str` | `continues_prev`;不允许 `anchor` |
+| `RefTextBlock` | `str` | 不允许 `continues_prev` |
+| `DocTitleBlock` | `str` | `anchor` |
+| `ParagraphTitleBlock` | `str` | `anchor`、正整数 `level` |
+| `TableBlock` | 有序视觉子块列表 | `continues_prev` |
+| `TableBodyBlock` | `str` | `cell_merge`、图片字段 |
+| `CodeBlock` | 有序视觉子块列表 | `sub_type`、`guess_lang` |
+| `ImageBlock/ChartBlock` | 有序视觉子块列表 | 开放字符串 `sub_type` |
+| `ImageBodyBlock/ChartBodyBlock` | `str` 或 null | 图片字段 |
+| 其它叶子 block | `str` | 仅各自声明的字段 |
-| 字段 | 类型 | 当前要求 | 说明 |
-|------|------|----------|------|
-| `bbox` | tuple[float, float, float, float] | 必填 | 当前类型必填;未知时使用 `EMPTY_BBOX`。 |
-| `spans` | list[Span] | 默认空 | 行内内容。 |
+`CodeBlock(sub_type="code")` 必须有非空 `guess_lang`;
+`sub_type="algorithm"` 禁止 `guess_lang`。`continues_prev` 只允许出现在页面
+顶层 `text/list/table`,任何嵌套项即使显式写成 null 也会被拒绝。
-内部字段:
+`merge_prev`、`is_numbered_style` 和 `section_number` 均不属于公开模型。
+Office 自动标题编号已在对象化前写入 `ParagraphTitleBlock.content`。
-- `_is_list_start`
-- `_is_list_end`
-- `_code_type`
-- `_code_guess_lang`
+## 递归容器
-这些字段不应进入 public schema。
+`ListBlock.content` 是保持原顺序的递归列表:
-## `Span`
+```text
+TextBlock | RefTextBlock | ListBlock
+```
-字段:
+`sub_type` 存在时,只约束当前层直接文本子项;嵌套 ListBlock 独立校验。
-| 字段 | 类型 | 当前要求 | 说明 |
-|------|------|----------|------|
-| `type` | str | 必填 | 来自 `ContentType` 或兼容字符串。 |
-| `bbox` | tuple[float, float, float, float] | 必填 | 当前类型必填;未知时使用 `EMPTY_BBOX`。 |
-| `content` | str | 默认空 | 文本、公式或图表描述。 |
-| `score` | float | 默认 0 | OCR 置信度等。 |
-| `image_path` | str | 默认空 | 图片产物路径。 |
-| `image_base64` | str | 默认空 | 内联图像。 |
-| `html` | str | 默认空 | 表格 HTML。 |
-| `latex` | str | 默认空 | 公式 LaTeX。 |
+`IndexBlock.content` 同样递归:
-内部字段:
+```text
+TextBlock | IndexBlock
+```
-- `_cross_page`
-- `_np_img`
-- `_url`
-- `_style`
-- `_children`
-- `_extra`
+Office 目录规范化会递归移除普通 TextBlock 的 `anchor`。递归结构始终序列化到
+`content`,不产生通用 `blocks` 字段。
-Office 解析已经使用 `_url`、`_style`、`_children` 表达超链接和文本样式。是否公开这些字段需要单独决策。
+## 视觉容器
-## Type 集合
+视觉父块的 `content` 使用上下文限定的有序子 block:
-`BlockType` 已覆盖:
+| 父块 | 允许的子块 |
+|------|------------|
+| `image` | `image_body/image_caption/image_footnote` |
+| `table` | `table_body/table_caption/table_footnote` |
+| `chart` | `chart_body/chart_caption/chart_footnote` |
+| `code` | `code_body/code_caption/code_footnote` |
-- 基础正文: `text`、`title`、`list`、`index`
-- 视觉容器: `image`、`table`、`chart`、`code`
-- 视觉子块: `image_body`、`table_body`、`chart_body`、`code_body` 等
-- 特殊正文: `algorithm`、`ref_text`、`phonetic`、`abstract`
-- 页边内容: `header`、`footer`、`page_number`、`aside_text`、`page_footnote`
-- Pipeline 类型: `doc_title`、`paragraph_title`、`vertical_text`、`header_image`、`footer_image`、`formula_number`
-
-`ContentType` 已覆盖:
-
-- `text`
-- `inline_equation`
-- `interline_equation`
-- `image`
-- `table`
-- `chart`
-- `equation`
-- `hyperlink`
+每个父块必须且只能有一个对应 body;caption 和 footnote 可以有多个。父块有
+index 时 body 必须使用相同 index;父子同时有 bbox 时必须相等。
-当前 `Span` 没有公开 `index` 字段;span 级 locator 不属于 P0 public contract。
+## 图片载荷与导出
-## Validator 现状
+以下 block 可以直接携带 `image_base64` 和 `image_path`:
-生产代码当前不提供 Middle JSON validator。原轻量页面树校验逻辑已退化为单测中的 test-local helper,用于约束当前 dataclass 结构的预期行为。
+- `image_body`
+- `table_body`
+- `chart_body`
+- `interline_equation`
-已覆盖:
+普通 `to_dict()` / `to_json()` 不执行文件 I/O;可通过
+`exclude_block_fields={"image_base64"}` 递归排除图片字段。完整序列化保留
+base64 并支持严格 round-trip。
-- page 的 `page_idx` 与可选 `page_size`。
-- block 的 `index`、`type`、`bbox`、title level。
-- line 的 `bbox`、`spans`。
-- span 的 `type`、`bbox` 和基础内容缺失 warning。
-- `EMPTY_BBOX` 在单测 validator helper 中按 unknown bbox 处理,并作为 warning。
+`MiddleJson.export()` 会在深拷贝上完成图片外置并原子提交 JSON 与 sidecar:
-当前未覆盖完整 envelope 校验、JSON Schema 文件和跨文件 migration。
+```text
+images/page_{page_idx}_{type}_{index}.{ext}
+images/page_{page_idx}_{type}_{index}_{ordinal}.{ext}
+```
-## 当前标准的缺口
+第二种名称用于同一 HTML block 中的多张内嵌图片,ordinal 从 1 开始。导出
+JSON 不包含 `image_base64` 或 `data:image/...`,原始 MiddleJson 对象保持不变。
-当前 dataclass 已经是事实标准,但仍缺少:
+## Analyze 私有对象
-- 顶层 `_meta`。
-- 完整 canonical `_meta`。
-- `file.sha256`。
-- 统一 locator。
-- 旧 `pdf_info` 到 `pages` 的 migration。
-- 对 `EMPTY_BBOX` 和真实 bbox 的正式语义区分。
-- 对内部字段公开策略的决策。
+公开 Block/PageInfo 不引用 `Line` 或 `Span`。Analyze 的文字回填与组行使用
+backend 私有 slotted draft,并只把最终 content 和临时行框写回 raw dict。
+旧 `Line/Span/ContentItem` dataclass 已从 `types.py` 删除;旧 parser、renderer、
+doclib 和 content-list 不属于当前保证可用的 Analyze/MiddleJson 边界。
diff --git a/docs/next/open-questions.md b/docs/next/open-questions.md
index bc0bf8cc..565854d5 100644
--- a/docs/next/open-questions.md
+++ b/docs/next/open-questions.md
@@ -123,11 +123,8 @@
| OQ-M-006 | `equation` 与 `interline_equation` 是否合并为同一公开语义,还是保留 span/block 粒度差异。 | Middle JSON schema |
| OQ-M-007 | `algorithm_caption` 是否应由后端补生产,还是从公开 schema 中删除或降级为普通 caption。 | Middle JSON schema / structured content |
| OQ-M-008 | `DISCARDED` 是否从 `BlockType` enum 拆出,改为 page-level `discarded_blocks` 或 metadata 状态。 | Middle JSON schema |
-| OQ-M-009 | `index` 目录类型是否作为独立公开 block type,还是收敛到 list/tree item 结构。 | Middle JSON schema / structured content |
| OQ-M-010 | `_meta.models` 字段粒度如何定义,是按 layout/OCR/formula/table/VLM 细分,还是仅保留 backend/model 汇总。 | Middle JSON envelope |
-| OQ-M-011 | `merge_prev` 与跨页合并状态是否合并为同一公开机制,或继续作为内部 staged metadata。 | Middle JSON schema |
-| OQ-M-012 | 是否发布 canonical JSON Schema 文件,以及它与未来 Python dataclass validator 的权威关系和存放路径。 | Middle JSON schema |
-| OQ-M-013 | 是否实现 `validate_middle_json(data)` 作为 envelope 级校验入口,并规定其 error/warning 稳定格式。 | Middle JSON validator |
+| OQ-M-012 | 是否发布 canonical JSON Schema 文件,以及它与 Pydantic `model_json_schema()` 的权威关系和存放路径。 | Middle JSON schema |
## 8. Roadmap 与评测
diff --git a/mineru/__init__.py b/mineru/__init__.py
index 8dd46cec..2a76dff1 100644
--- a/mineru/__init__.py
+++ b/mineru/__init__.py
@@ -1,33 +1,6 @@
# Copyright (c) Opendatalab. All rights reserved.
-from .parser import ( # noqa: F401
- DocumentParser,
- DocxParser,
- MinerUApiParser,
- ParseResult,
- PdfFlashParser,
- PdfHybridParser,
- PdfPipelineParser,
- PdfVlmParser,
- PptxParser,
- XlsxParser,
- parse,
-)
-from .types import Block, Line, PageInfo, Span # noqa: F401
+"""MinerU Analyze 与严格 Middle JSON 的最小公开入口。"""
-__all__ = [
- "Block",
- "DocumentParser",
- "DocxParser",
- "Line",
- "MinerUApiParser",
- "PageInfo",
- "ParseResult",
- "PdfFlashParser",
- "PdfHybridParser",
- "PdfPipelineParser",
- "PdfVlmParser",
- "PptxParser",
- "Span",
- "XlsxParser",
- "parse",
-]
+from .types import Block, MiddleJson, PageInfo
+
+__all__ = ["Block", "MiddleJson", "PageInfo"]
diff --git a/mineru/backend/analyze.py b/mineru/backend/analyze.py
index 78bb6216..ac728365 100644
--- a/mineru/backend/analyze.py
+++ b/mineru/backend/analyze.py
@@ -7,6 +7,7 @@ import re
import time
from collections import Counter
from collections.abc import Iterable, Mapping
+from copy import deepcopy
from dataclasses import dataclass
from io import BytesIO
from typing import Any, Literal
@@ -31,7 +32,16 @@ from mineru.backend.utils.boxbase import (
)
from mineru.backend.utils.char_utils import resolve_text_line_boundary
from mineru.backend.utils.formula_number import optimize_hybrid_formula_number_blocks
-from mineru.backend.utils.span_block_fix import fix_text_block
+from mineru.backend.utils.analyze_draft import _AnalyzeLine, _AnalyzeSpan
+from mineru.backend.utils.span_block_fix import group_spans_to_lines
+from mineru.backend.utils.raw_block_types import (
+ RAW_ALGORITHM,
+ RAW_CAPTION,
+ RAW_EQUATION,
+ RAW_FOOTNOTE,
+ RAW_PHONETIC,
+ RAW_TITLE,
+)
from mineru.backend.utils.span_pre_proc import (
SpanBlockMatcher,
__replace_ligatures,
@@ -60,7 +70,7 @@ from mineru.utils.ocr_utils import (
from mineru.utils.pdf_image_tools import load_images_from_pdf_bytes_range, get_crop_np_img
from tqdm import tqdm
-from ..types import BBox, Block, BlockType, ContentType, Line, NOT_EXTRACT_TYPES, Span
+from ..types import BBox, BlockType, ContentType, MiddleJson, NOT_EXTRACT_TYPES
from ..utils.config_reader import get_processing_window_size
from ..utils.pdf_document import PDFDocument, PDFPage, get_lines_from_chars
@@ -86,33 +96,36 @@ _OFFICE_MODEL_MAP = {
}
_SUPPORTED_FILE_SUFFIXES = {"pdf", *_OFFICE_MODEL_MAP}
TITLE_BLOCK_TYPES = {
- BlockType.TITLE,
+ RAW_TITLE,
BlockType.DOC_TITLE,
BlockType.PARAGRAPH_TITLE,
}
CODE_CONTENT_BLOCK_TYPES = {
BlockType.CODE,
- BlockType.ALGORITHM,
+ RAW_ALGORITHM,
}
LINE_METADATA_BLOCK_TYPES = {
BlockType.TEXT,
BlockType.DOC_TITLE,
BlockType.PARAGRAPH_TITLE,
- BlockType.CAPTION,
- BlockType.FOOTNOTE,
+ RAW_CAPTION,
+ RAW_FOOTNOTE,
}
VLM_VISUAL_ANNOTATION_TYPE_MAP = {
- BlockType.TABLE_CAPTION: BlockType.CAPTION,
- BlockType.IMAGE_CAPTION: BlockType.CAPTION,
- BlockType.CODE_CAPTION: BlockType.CAPTION,
- BlockType.TABLE_FOOTNOTE: BlockType.FOOTNOTE,
- BlockType.IMAGE_FOOTNOTE: BlockType.FOOTNOTE,
+ BlockType.TABLE_CAPTION: RAW_CAPTION,
+ BlockType.IMAGE_CAPTION: RAW_CAPTION,
+ BlockType.CODE_CAPTION: RAW_CAPTION,
+ BlockType.TABLE_FOOTNOTE: RAW_FOOTNOTE,
+ BlockType.IMAGE_FOOTNOTE: RAW_FOOTNOTE,
}
+VLM_MODEL_LIST_FIELDS = frozenset(
+ {"type", "bbox", "content", "angle", "score", "sub_type", "cell_merge"}
+)
MODEL_JSON_VISUAL_BLOCK_TYPES = {
BlockType.IMAGE,
BlockType.CHART,
BlockType.TABLE,
- BlockType.EQUATION,
+ RAW_EQUATION,
}
LOCAL_LAYOUT_IMAGE_BLOCK_BODY_TYPES = {
BlockType.IMAGE,
@@ -121,9 +134,9 @@ LOCAL_LAYOUT_IMAGE_BLOCK_BODY_TYPES = {
LOCAL_LAYOUT_IMAGE_BLOCK_AREA_TYPES = {
*LOCAL_LAYOUT_IMAGE_BLOCK_BODY_TYPES,
BlockType.IMAGE_CAPTION,
- BlockType.CAPTION,
+ RAW_CAPTION,
BlockType.IMAGE_FOOTNOTE,
- BlockType.FOOTNOTE,
+ RAW_FOOTNOTE,
}
_INLINE_FORMULA_PATTERN = re.compile(r"\\\((.*?)\\\)")
@@ -133,9 +146,9 @@ VLM_LAYOUT_LABEL_MAP = {
"aside_text": BlockType.ASIDE_TEXT,
"chart": BlockType.CHART,
"content": BlockType.INDEX,
- "display_formula": BlockType.EQUATION,
+ "display_formula": RAW_EQUATION,
"doc_title": BlockType.DOC_TITLE,
- "figure_title": BlockType.CAPTION,
+ "figure_title": RAW_CAPTION,
"footer": BlockType.FOOTER,
"footer_image": BlockType.FOOTER,
"footnote": BlockType.PAGE_FOOTNOTE,
@@ -150,7 +163,7 @@ VLM_LAYOUT_LABEL_MAP = {
"table": BlockType.TABLE,
"text": BlockType.TEXT,
"vertical_text": BlockType.TEXT,
- "vision_footnote": BlockType.FOOTNOTE,
+ "vision_footnote": RAW_FOOTNOTE,
}
PIPELINE_DET_TYPE = {
@@ -159,22 +172,22 @@ PIPELINE_DET_TYPE = {
BlockType.ASIDE_TEXT,
BlockType.INDEX,
BlockType.DOC_TITLE,
- BlockType.CAPTION,
+ RAW_CAPTION,
BlockType.FOOTER,
BlockType.PAGE_FOOTNOTE,
BlockType.HEADER,
BlockType.PAGE_NUMBER,
BlockType.PARAGRAPH_TITLE,
BlockType.REF_TEXT,
- BlockType.FOOTNOTE,
+ RAW_FOOTNOTE,
}
VLM_TXT_DET_TYPE = NOT_EXTRACT_TYPES
VLM_OCR_DET_TYPE = {
BlockType.TEXT,
BlockType.DOC_TITLE,
BlockType.PARAGRAPH_TITLE,
- BlockType.CAPTION,
- BlockType.FOOTNOTE,
+ RAW_CAPTION,
+ RAW_FOOTNOTE,
}
_LOW_TXT_VISUAL_RUN_ANGLES = (0.0, 90.0, 180.0, 270.0)
@@ -410,16 +423,24 @@ def _build_vl_style_layout_blocks(
def _convert_vlm_results_to_model_list(
vlm_results: Iterable[Iterable[Mapping[str, Any]]],
) -> list[list[dict[str, Any]]]:
- """将 VLM 返回的 ExtractResult/ContentBlock 转换为原生 list/dict。"""
- return [[dict(block) for block in page_blocks] for page_blocks in vlm_results]
+ """将 VLM 结果投影为允许进入 Analyze 的字段,丢弃未采用的外部属性。"""
+ return [
+ [
+ {
+ field_name: deepcopy(value)
+ for field_name, value in dict(block).items()
+ if field_name in VLM_MODEL_LIST_FIELDS
+ }
+ for block in page_blocks
+ ]
+ for page_blocks in vlm_results
+ ]
def _normalize_xhigh_vlm_blocks(model_list: list[list[dict[str, Any]]]) -> None:
- """归一化 xhigh VLM 注释类型,并移除正文块的 merge_prev。"""
+ """归一化 xhigh VLM 的视觉注释类型。"""
for page_model_list in model_list:
for block in page_model_list:
- if block.get("type") == BlockType.TEXT:
- block.pop("merge_prev", None)
normalized_type = VLM_VISUAL_ANNOTATION_TYPE_MAP.get(block.get("type"))
if normalized_type is not None:
block["type"] = normalized_type
@@ -474,7 +495,7 @@ def _apply_medium_display_formula_results(
page_size = _normalize_page_size(page_image)
equation_blocks_by_bbox: dict[tuple[float, ...], list[dict[str, Any]]] = {}
for block in page_model_list:
- if block.get("type") != BlockType.EQUATION:
+ if block.get("type") != RAW_EQUATION:
continue
block_bbox = block.get("bbox")
if block_bbox is None or len(block_bbox) != 4:
@@ -751,9 +772,9 @@ def _validate_text_formula_window_inputs(
raise ValueError(f"Hybrid text/formula window image scale must be positive: page_idx={page_idx}")
-def _build_pdf_text_line_spans(pdf_page: PDFPage) -> list[Span]:
- """将标准方向的 pdftext line 转为文本 Span,并复用现有字符清洗规则。"""
- page_spans: list[Span] = []
+def _build_pdf_text_line_spans(pdf_page: PDFPage) -> list[_AnalyzeSpan]:
+ """将标准方向的 pdftext line 转为私有 span,并复用现有字符清洗规则。"""
+ page_spans: list[_AnalyzeSpan] = []
for pdf_line in get_lines_from_chars(pdf_page.get_chars()):
try:
rotation = float(pdf_line.get("rotation", 0.0) or 0.0)
@@ -780,7 +801,7 @@ def _build_pdf_text_line_spans(pdf_page: PDFPage) -> list[Span]:
continue
page_spans.append(
- Span(
+ _AnalyzeSpan(
type=ContentType.TEXT,
bbox=(x0, y0, x1, y1),
content=content,
@@ -790,7 +811,7 @@ def _build_pdf_text_line_spans(pdf_page: PDFPage) -> list[Span]:
return page_spans
-def _build_pdf_text_visual_run_spans(pdf_page: PDFPage) -> list[Span]:
+def _build_pdf_text_visual_run_spans(pdf_page: PDFPage) -> list[_AnalyzeSpan]:
"""将 Low/TXT 原生粗行按 Flash 字符间隙拆成可独立分配的视觉 run。"""
# 延迟导入避免 Hybrid 模块初始化时提前加载完整 Flash PDF 流水线。
@@ -802,13 +823,13 @@ def _build_pdf_text_visual_run_spans(pdf_page: PDFPage) -> list[Span]:
page_rotation=pdf_page.rotation,
supported_angles=_LOW_TXT_VISUAL_RUN_ANGLES,
)
- page_spans: list[Span] = []
+ page_spans: list[_AnalyzeSpan] = []
for line_item in line_items:
content = __replace_ligatures(__replace_unicode(line_item.text)).strip()
if not content:
continue
page_spans.append(
- Span(
+ _AnalyzeSpan(
type=ContentType.TEXT,
bbox=line_item.bbox,
content=content,
@@ -1024,15 +1045,15 @@ def _build_page_text_formula_spans(
page_ocr_res_list: list[dict[str, Any]],
page_size: tuple[float, float],
render_scale: float,
-) -> list[Span]:
- """将当前页行内公式和 OCR 结果转换为统一 Span,正文与公式后续共同组行。"""
- page_spans: list[Span] = []
+) -> list[_AnalyzeSpan]:
+ """将当前页行内公式和 OCR 结果转换为私有 span,供正文与公式共同组行。"""
+ page_spans: list[_AnalyzeSpan] = []
for formula in page_inline_formula_list:
bbox = _sidecar_bbox_to_page_bbox(formula.get("bbox"), page_size, render_scale)
if bbox is None:
continue
page_spans.append(
- Span(
+ _AnalyzeSpan(
type=ContentType.INLINE_EQUATION,
bbox=bbox,
content=str(formula.get("latex", "") or "").strip(),
@@ -1045,7 +1066,7 @@ def _build_page_text_formula_spans(
if bbox is None:
continue
page_spans.append(
- Span(
+ _AnalyzeSpan(
type=ContentType.TEXT,
bbox=bbox,
content=str(ocr_res.get("text", "") or ""),
@@ -1057,11 +1078,11 @@ def _build_page_text_formula_spans(
def _fill_native_pdf_text_spans(
pdf_page: PDFPage,
- page_spans: list[Span],
+ page_spans: list[_AnalyzeSpan],
page_pil_image: Image.Image,
render_scale: float,
page_size: tuple[float, float],
-) -> list[Span]:
+) -> list[_AnalyzeSpan]:
"""复用原生 PDF 字符回填逻辑,并为内容不足的 span 准备后置 OCR 裁图。"""
page_width, page_height = page_size
virtual_block = (0, 0, page_width, page_height, None, None, None, BlockType.TEXT)
@@ -1077,13 +1098,13 @@ def _fill_native_pdf_text_spans(
def _group_page_spans_by_block(
page_model_list: list[dict[str, Any]],
- page_spans: list[Span],
+ page_spans: list[_AnalyzeSpan],
page_size: tuple[float, float],
target_block_types: set[str],
-) -> dict[int, list[Line]]:
+) -> dict[int, list[_AnalyzeLine]]:
"""按 block 原始顺序消费 span,并使用现有文本修复逻辑形成真实行。"""
span_matcher = SpanBlockMatcher(page_spans)
- block_lines: dict[int, list[Line]] = {}
+ block_lines: dict[int, list[_AnalyzeLine]] = {}
for block_idx, block_item in enumerate(page_model_list):
block_type = str(block_item.get("type") or block_item.get("label") or "")
if block_type not in target_block_types:
@@ -1093,32 +1114,28 @@ def _group_page_spans_by_block(
block_lines[block_idx] = []
continue
- fix_block = Block(
- index=block_idx,
- type=block_type,
- bbox=block_bbox,
- _fix_spans=span_matcher.collect_for_block(block_bbox),
+ block_lines[block_idx] = group_spans_to_lines(
+ span_matcher.collect_for_block(block_bbox)
)
- block_lines[block_idx] = fix_text_block(fix_block).lines
return block_lines
def _apply_window_post_ocr(
local_model_context: HybridLocalModelContext,
- page_block_lines_list: list[dict[int, list[Line]]],
+ page_block_lines_list: list[dict[int, list[_AnalyzeLine]]],
) -> None:
"""在当前窗口内识别原生字符不足的 span,保持 finalize 后置 OCR 的回退语义。"""
- need_ocr_spans: list[Span] = []
+ need_ocr_spans: list[_AnalyzeSpan] = []
img_crop_list: list[np.ndarray] = []
for block_lines in page_block_lines_list:
for lines in block_lines.values():
for line in lines:
for span in line.spans:
- if span._np_img is None:
+ if span.image is None:
continue
need_ocr_spans.append(span)
- img_crop_list.append(rotate_vertical_crop_if_needed(span._np_img))
- span._np_img = None
+ img_crop_list.append(rotate_vertical_crop_if_needed(span.image))
+ span.image = None
if not img_crop_list:
return
@@ -1146,7 +1163,7 @@ def _apply_window_post_ocr(
span.score = 0.0
-def _line_content_parts(line: Line) -> list[tuple[str, str]]:
+def _line_content_parts(line: _AnalyzeLine) -> list[tuple[str, str]]:
"""提取一行内可输出的文本与行内公式,公式统一包装为反斜杠圆括号格式。"""
parts: list[tuple[str, str]] = []
for span in line.spans:
@@ -1162,7 +1179,7 @@ def _line_content_parts(line: Line) -> list[tuple[str, str]]:
return parts
-def _lines_to_block_content(lines: list[Line], block_type: str) -> str:
+def _lines_to_block_content(lines: list[_AnalyzeLine], block_type: str) -> str:
"""将真实行折叠为统一 block content,保留目录/代码换行并处理自然语言跨行连接。"""
content_lines = [parts for line in lines if (parts := _line_content_parts(line))]
if not content_lines:
@@ -1193,8 +1210,8 @@ def _lines_to_block_content(lines: list[Line], block_type: str) -> str:
return "".join(content_parts).strip()
-def _build_ocr_det_line_items(lines: list[Line], page_size: tuple[float, float]) -> list[dict[str, Any]]:
- """将内部 Line 转换为归一化行框"""
+def _build_ocr_det_line_items(lines: list[_AnalyzeLine], page_size: tuple[float, float]) -> list[dict[str, Any]]:
+ """将 Analyze 私有行转换为归一化行框。"""
line_items = []
for line in lines:
normalized_bbox = _page_bbox_to_unit_bbox(line.bbox, page_size)
@@ -1205,7 +1222,7 @@ def _build_ocr_det_line_items(lines: list[Line], page_size: tuple[float, float])
def _apply_block_content_and_line_metadata(
page_model_list: list[dict[str, Any]],
- block_lines: dict[int, list[Line]],
+ block_lines: dict[int, list[_AnalyzeLine]],
page_size: tuple[float, float],
) -> None:
"""将组行结果回填到 block,并为正文、视觉标题和视觉脚注保存行框。"""
@@ -1250,7 +1267,9 @@ def _fill_window_block_content_and_lines(
raise ValueError(f"Hybrid block content page count mismatch: {page_counts}")
target_block_types = set(ocr_det_type) | TITLE_BLOCK_TYPES | {BlockType.TEXT}
- page_block_line_results: list[tuple[list[dict[str, Any]], dict[int, list[Line]], tuple[float, float]]] = []
+ page_block_line_results: list[
+ tuple[list[dict[str, Any]], dict[int, list[_AnalyzeLine]], tuple[float, float]]
+ ] = []
for image_dict, pdf_page, page_model_list, page_inline_formula_list, page_ocr_res_list in zip(
images_list,
pdf_pages,
@@ -2067,7 +2086,7 @@ def _remove_low_table_inner_blocks(
"""按表格中心点归属规则移除 low 表内图片、公式和公式编号块。"""
inner_block_types = {
BlockType.IMAGE,
- BlockType.EQUATION,
+ RAW_EQUATION,
BlockType.FORMULA_NUMBER,
}
for image_dict, page_model_list in zip(images_list, model_list):
@@ -2421,7 +2440,7 @@ def _apply_layout_title_split(
for page_model_list, layout_res, page_size in zip(model_list, images_layout_res, page_sizes):
doc_title_bboxes = _collect_layout_doc_title_bboxes(layout_res, page_size)
for block in page_model_list:
- if block.get("type") != BlockType.TITLE:
+ if block.get("type") != RAW_TITLE:
continue
title_bbox = _bbox_to_pixel_bbox(block.get("bbox"), page_size)
if title_bbox is None:
@@ -2467,8 +2486,25 @@ def _is_valid_pdf_text_block(block: dict[str, Any]) -> bool:
def _normalize_pdf_model_list(model_list: list[list[dict[str, Any]]]) -> None:
"""清理 PDF block 元数据、规范公式,并过滤正文或行框无效的文本块。"""
- for page_model_list in model_list:
- for block in page_model_list:
+ for page_idx, page_model_list in enumerate(model_list):
+ for block_idx, block in enumerate(page_model_list):
+ raw_type = block.get("type")
+ if raw_type == RAW_PHONETIC:
+ block["type"] = BlockType.TEXT
+ elif raw_type == RAW_EQUATION:
+ block["type"] = BlockType.INTERLINE_EQUATION
+ equation_content = block.get("content")
+ if isinstance(equation_content, str):
+ if equation_content.startswith("\\["):
+ equation_content = equation_content[2:]
+ if equation_content.endswith("\\]"):
+ equation_content = equation_content[:-2]
+ block["content"] = equation_content.strip()
+ elif raw_type == RAW_TITLE:
+ raise ValueError(
+ "Unclassified PDF title block: "
+ f"page_idx={page_idx}, block_idx={block_idx}"
+ )
block.pop("angle", None)
block.pop("score", None)
content = block.get("content")
@@ -2502,7 +2538,7 @@ def doc_analyze(
image_analysis: bool = True,
page_index_map: list[int] | None = None,
file_suffix: Literal["pdf", "docx", "pptx", "xlsx"] = "pdf",
-) -> tuple[dict[str, Any], list[list[dict[str, Any]]]]:
+) -> tuple[MiddleJson, list[list[dict[str, Any]]]]:
if file_suffix not in _SUPPORTED_FILE_SUFFIXES:
raise ValueError(f"Unsupported file suffix: {file_suffix!r}")
@@ -2697,19 +2733,17 @@ def doc_analyze(
_log_infer_performance(file_suffix, len(model_list), infer_elapsed)
# PDF 与 Office 的 model_list 在此汇合,后续统一生产 Middle JSON。
- middle_json = {
- "pages": [],
- "file_suffix": file_suffix,
- "effort": effort,
- "parse_mode": parse_mode,
- "mineru_version": mineru_version,
- }
- middle_json["pages"] = model_list_to_pages(model_list, page_index_map)
+ middle_json = MiddleJson(
+ pages=model_list_to_pages(model_list, page_index_map),
+ file_suffix=file_suffix,
+ effort=effort,
+ parse_mode=parse_mode,
+ mineru_version=mineru_version,
+ )
return middle_json, model_list
if __name__ == "__main__":
- from mineru.cli_old.common import read_fn
import json
# 根据当前文件位置定位项目根目录,读取 demo 下的 PDF 和 Office 样例。
@@ -2723,7 +2757,7 @@ if __name__ == "__main__":
]
for file_path in demo_file_paths:
- file_bytes = read_fn(file_path)
+ file_bytes = open(file_path, "rb").read()
file_suffix = os.path.splitext(file_path)[1].lstrip(".").lower()
file_suffix = "pdf"
middle_json, model_list = doc_analyze(file_bytes, effort="high", file_suffix=file_suffix)
diff --git a/mineru/backend/magic_model.py b/mineru/backend/magic_model.py
index c280eb9a..6a665c5f 100644
--- a/mineru/backend/magic_model.py
+++ b/mineru/backend/magic_model.py
@@ -2,9 +2,14 @@
import re
from typing import Any
-from loguru import logger
-
from mineru.backend.utils.boxbase import calculate_overlap_area_in_bbox1_area_ratio
+from mineru.backend.utils.raw_block_types import (
+ RAW_ALGORITHM,
+ RAW_CAPTION,
+ RAW_EQUATION,
+ RAW_FOOTNOTE,
+ RAW_TITLE,
+)
from mineru.backend.utils.visual_magic_model_utils import (
code_content_clean,
isolated_formula_clean,
@@ -29,9 +34,15 @@ class MagicModel:
def __init__(
self,
page_model_list: list[dict[str, Any]],
+ *,
+ use_bbox: bool | None = None,
) -> None:
self.blocks = []
- is_block_has_bbox = any(block_info.get("bbox") for block_info in page_model_list)
+ is_block_has_bbox = (
+ any(block_info.get("bbox") for block_info in page_model_list)
+ if use_bbox is None
+ else use_bbox
+ )
# 解析每个块
for index, block_info in enumerate(page_model_list):
code_block_sub_type = None
@@ -44,11 +55,11 @@ class MagicModel:
block_type = BlockType.TABLE_BODY
elif block_type == "chart":
block_type = BlockType.CHART_BODY
- elif block_type in ["code", "algorithm"]:
+ elif block_type in [BlockType.CODE, RAW_ALGORITHM]:
code_block_sub_type = block_type
block_content = code_content_clean(block_content)
block_type = BlockType.CODE_BODY
- elif block_type == "equation":
+ elif block_type == RAW_EQUATION:
block_type = BlockType.INTERLINE_EQUATION
block_content = isolated_formula_clean(block_content)
@@ -57,7 +68,7 @@ class MagicModel:
if block_content:
block_content = clean_content(block_content) or ""
# 对于标题类块,去除换行符和多余空格
- if block_type in [BlockType.TITLE, BlockType.DOC_TITLE, BlockType.PARAGRAPH_TITLE] and block_content:
+ if block_type in [RAW_TITLE, BlockType.DOC_TITLE, BlockType.PARAGRAPH_TITLE] and block_content:
block_content = re.sub(r"\n\s*", " ", block_content).strip()
# 处理 code/algorithm 分类的特殊情况:如果 code 类型的块中包含成对的行内公式标记,则将其分类为 algorithm。
if (
@@ -135,12 +146,20 @@ class MagicModel:
BlockType.REF_TEXT,
BlockType.LIST,
BlockType.INDEX,
- BlockType.CAPTION,
- BlockType.FOOTNOTE,
+ RAW_CAPTION,
+ RAW_FOOTNOTE,
BlockType.IMAGE_BODY,
BlockType.TABLE_BODY,
BlockType.CHART_BODY,
BlockType.CODE_BODY,
+ BlockType.IMAGE_CAPTION,
+ BlockType.IMAGE_FOOTNOTE,
+ BlockType.TABLE_CAPTION,
+ BlockType.TABLE_FOOTNOTE,
+ BlockType.CHART_CAPTION,
+ BlockType.CHART_FOOTNOTE,
+ BlockType.CODE_CAPTION,
+ BlockType.CODE_FOOTNOTE,
}
self.blocks = [
block
@@ -158,10 +177,65 @@ class MagicModel:
+ self.code_blocks
)
+ @staticmethod
+ def fix_office_paragraph_titles(
+ model_list: list[list[dict[str, Any]]],
+ ) -> None:
+ """按文档级标题序列内化 Office 自动编号,并清除私有编号元数据。"""
+ counters: dict[int, int] = {}
+ for page_model_list in model_list:
+ for block in page_model_list:
+ if block.get("type") != BlockType.PARAGRAPH_TITLE:
+ continue
+
+ raw_level = block.get("level")
+ level_is_valid = (
+ isinstance(raw_level, int)
+ and not isinstance(raw_level, bool)
+ and raw_level >= 1
+ )
+ level = raw_level if level_is_valid else 1
+ if not level_is_valid:
+ block.pop("level", None)
+
+ is_numbered_style = block.pop("is_numbered_style", None)
+ block.pop("section_number", None)
+ content = block.get("content")
+ if not isinstance(content, str):
+ continue
+
+ if is_numbered_style is True:
+ for ancestor_level in range(1, level):
+ counters.setdefault(ancestor_level, 1)
+ counters[level] = counters.get(level, 0) + 1
+ _clear_deeper_title_counters(counters, level)
+ section_number = ".".join(
+ str(counters[ancestor_level])
+ for ancestor_level in range(1, level + 1)
+ )
+ block["content"] = f"{section_number} {content}"
+ continue
+
+ if is_numbered_style is False and level_is_valid:
+ number_match = re.match(r"^\s*(\d+(?:\.\d+)*)\b", _visible_text(content))
+ if number_match is None:
+ continue
+ number_parts = [int(part) for part in number_match.group(1).split(".")]
+ if len(number_parts) != level:
+ continue
+ counters.update(
+ (part_level, number)
+ for part_level, number in enumerate(number_parts, start=1)
+ )
+ _clear_deeper_title_counters(counters, level)
+
def fix_pdf_list_blocks(
- list_blocks, text_blocks, ref_text_blocks
-):
+ list_blocks: list[dict[str, Any]],
+ text_blocks: list[dict[str, Any]],
+ ref_text_blocks: list[dict[str, Any]],
+) -> tuple[list[dict[str, Any]], list[dict[str, Any]], list[dict[str, Any]]]:
+ """按 bbox 把 PDF text/ref_text 归入 list,并推断列表子类型。"""
for list_block in list_blocks:
list_block["content"] = []
@@ -204,7 +278,9 @@ def fix_pdf_list_blocks(
return list_blocks, text_blocks, ref_text_blocks
-def fix_pdf_index_blocks(index_blocks):
+def fix_pdf_index_blocks(
+ index_blocks: list[dict[str, Any]],
+) -> list[dict[str, Any]]:
"""将 PDF 目录块的多行内容拆分为多个文本子块。"""
for index_block in index_blocks:
index_block["content"] = [
@@ -215,12 +291,16 @@ def fix_pdf_index_blocks(index_blocks):
return index_blocks
-def fix_office_index_blocks(index_blocks):
- """递归移除 Office 目录块及其子块中的 ilevel 字段。"""
+def fix_office_index_blocks(
+ index_blocks: list[dict[str, Any]],
+) -> list[dict[str, Any]]:
+ """递归移除 Office 目录私有字段,并禁止普通 text 子块携带 anchor。"""
pending_blocks = list(index_blocks)
while pending_blocks:
block = pending_blocks.pop()
block.pop("ilevel", None)
+ if block.get("type") == BlockType.TEXT:
+ block.pop("anchor", None)
content = block.get("content")
if isinstance(content, list):
@@ -233,6 +313,17 @@ def fix_office_index_blocks(index_blocks):
return index_blocks
+def _clear_deeper_title_counters(counters: dict[int, int], level: int) -> None:
+ """删除当前标题层级之后的旧计数,避免返回浅层后错误续接深层编号。"""
+ for counter_level in [value for value in counters if value > level]:
+ del counters[counter_level]
+
+
+def _visible_text(content: str) -> str:
+ """移除简单富文本标签,供显式标题编号识别可见文本开头。"""
+ return re.sub(r"<[^>]+>", "", content)
+
+
def fix_office_list_blocks(
list_blocks: list[dict[str, Any]],
) -> list[dict[str, Any]]:
diff --git a/mineru/backend/model_list_to_midlle_json.py b/mineru/backend/model_list_to_midlle_json.py
index 8bd780ad..9264b396 100644
--- a/mineru/backend/model_list_to_midlle_json.py
+++ b/mineru/backend/model_list_to_midlle_json.py
@@ -1,53 +1,124 @@
# Copyright (c) Opendatalab. All rights reserved.
+from __future__ import annotations
+
from copy import deepcopy
from typing import Any
+from pydantic import TypeAdapter
+
from mineru.backend.magic_model import MagicModel
from mineru.backend.utils.para_block_utils import merge_para_text_blocks
from mineru.backend.utils.table_merge import merge_table
+from mineru.types import PageInfo
+PAGE_INFO_LIST_ADAPTER = TypeAdapter(list[PageInfo])
-def blocks_to_page_info(
- page_model_list: list[dict[str, Any]],
-) -> dict[str, Any]:
- """将blocks转换为页面信息"""
- # Middle JSON 转换允许重写块结构,但不能污染调用方保留的原始 model_list。
- magic_model = MagicModel(
- deepcopy(page_model_list),
+
+def _validate_page_index_map(
+ page_count: int,
+ page_index_map: list[int] | None,
+) -> list[int]:
+ """校验实际页号映射,禁止 zip 截断、重复页号或逆序页号。"""
+ if page_index_map is None:
+ return list(range(page_count))
+ if len(page_index_map) != page_count:
+ raise ValueError(
+ f"page_index_map length mismatch: pages={page_count}, mapping={len(page_index_map)}"
+ )
+ if any(
+ isinstance(page_idx, bool) or not isinstance(page_idx, int) or page_idx < 0
+ for page_idx in page_index_map
+ ):
+ raise ValueError("page_index_map values must be non-negative integers")
+ if len(page_index_map) != len(set(page_index_map)):
+ raise ValueError("page_index_map values must be unique")
+ if any(
+ current <= previous
+ for previous, current in zip(page_index_map, page_index_map[1:])
+ ):
+ raise ValueError("page_index_map values must preserve strictly increasing order")
+ return list(page_index_map)
+
+
+def _document_uses_bbox(model_list: list[list[dict[str, Any]]]) -> bool:
+ """按整份文档是否出现 bbox 判定 PDF/Office,避免空白首页误判。"""
+ return any(
+ block.get("bbox") is not None
+ for page_model_list in model_list
+ for block in page_model_list
+ if isinstance(block, dict)
)
+
+def _remove_private_block_metadata(block: dict[str, Any]) -> None:
+ """递归清除对象化边界之前仅供 Analyze 计算使用的临时字段。"""
+ for field_name in ("lines", "_lines", "angle", "score", "label"):
+ block.pop(field_name, None)
+ content = block.get("content")
+ if isinstance(content, list):
+ for child in content:
+ if isinstance(child, dict):
+ _remove_private_block_metadata(child)
+
+
+def _blocks_to_raw_page_info(
+ page_model_list: list[dict[str, Any]],
+ *,
+ page_idx: int,
+ use_bbox: bool,
+) -> dict[str, Any]:
+ """运行单页 MagicModel 并保留 raw dict,供跨页后处理继续消费。"""
+ magic_model = MagicModel(page_model_list, use_bbox=use_bbox)
page_blocks = magic_model.blocks
- # 对page_blocks根据index的值进行排序
- page_blocks.sort(key=lambda x: x["index"])
+ page_blocks.sort(key=lambda block: block["index"])
+ return {"page_idx": page_idx, "blocks": page_blocks}
- page_info = {
- "blocks": page_blocks,
- }
- return page_info
+
+def blocks_to_page_info(
+ page_model_list: list[dict[str, Any]],
+ *,
+ page_idx: int = 0,
+ use_bbox: bool | None = None,
+) -> PageInfo:
+ """无副作用地把单页 raw blocks 转换为严格 PageInfo 对象。"""
+ copied_blocks = deepcopy(page_model_list)
+ resolved_use_bbox = _document_uses_bbox([copied_blocks]) if use_bbox is None else use_bbox
+ if not resolved_use_bbox:
+ MagicModel.fix_office_paragraph_titles([copied_blocks])
+ raw_page = _blocks_to_raw_page_info(
+ copied_blocks,
+ page_idx=page_idx,
+ use_bbox=resolved_use_bbox,
+ )
+ for block in raw_page["blocks"]:
+ _remove_private_block_metadata(block)
+ return PageInfo.model_validate(raw_page)
def model_list_to_pages(
model_list: list[list[dict[str, Any]]],
page_index_map: list[int] | None = None,
-) -> list[dict[str, Any]]:
- """将 model_list 转换为 pages"""
- if page_index_map is None:
- page_index_map = list(range(len(model_list)))
- pages: list[dict[str, Any]] = []
- for page_model_list, page_index in zip(model_list, page_index_map):
- page_info = blocks_to_page_info(
+) -> list[PageInfo]:
+ """在 raw 后处理结束后,一次性构造严格且可递归序列化的 PageInfo。"""
+ page_indices = _validate_page_index_map(len(model_list), page_index_map)
+ copied_model_list = deepcopy(model_list)
+ use_bbox = _document_uses_bbox(copied_model_list)
+ if not use_bbox:
+ MagicModel.fix_office_paragraph_titles(copied_model_list)
+
+ raw_pages = [
+ _blocks_to_raw_page_info(
page_model_list,
+ page_idx=page_idx,
+ use_bbox=use_bbox,
)
- page_info["page_idx"] = page_index
- pages.append(page_info)
-
- # PDF block 一定带 bbox;扫描全部页面,避免首页为空时误判为 Office。
- has_bbox_block = any(
- isinstance(block, dict) and "bbox" in block
- for page_info in pages
- for block in page_info.get("blocks", [])
- )
- if has_bbox_block:
- merge_para_text_blocks(pages)
- merge_table(pages)
- return pages
+ for page_model_list, page_idx in zip(copied_model_list, page_indices, strict=True)
+ ]
+ if use_bbox:
+ merge_para_text_blocks(raw_pages)
+ merge_table(raw_pages)
+
+ for page in raw_pages:
+ for block in page["blocks"]:
+ _remove_private_block_metadata(block)
+ return PAGE_INFO_LIST_ADAPTER.validate_python(raw_pages)
diff --git a/mineru/backend/utils/analyze_draft.py b/mineru/backend/utils/analyze_draft.py
new file mode 100644
index 00000000..3dbab96f
--- /dev/null
+++ b/mineru/backend/utils/analyze_draft.py
@@ -0,0 +1,27 @@
+# Copyright (c) Opendatalab. All rights reserved.
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from typing import Any
+
+from ...types import BBox
+
+
+@dataclass(slots=True)
+class _AnalyzeSpan:
+ """Analyze 文本回填阶段使用的私有 span,不属于公开 Middle JSON 模型。"""
+
+ type: str
+ bbox: BBox
+ content: str = ""
+ score: float = 0.0
+ image: Any = None
+ metadata: dict[str, Any] = field(default_factory=dict)
+
+
+@dataclass(slots=True)
+class _AnalyzeLine:
+ """Analyze 组行阶段使用的私有 line,只承载 bbox 与私有 span。"""
+
+ bbox: BBox
+ spans: list[_AnalyzeSpan] = field(default_factory=list)
diff --git a/mineru/backend/utils/content_block_draft.py b/mineru/backend/utils/content_block_draft.py
index fe1be49f..0d3d5de7 100644
--- a/mineru/backend/utils/content_block_draft.py
+++ b/mineru/backend/utils/content_block_draft.py
@@ -4,7 +4,7 @@ from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any, Mapping
-from ...types import BBox, OcrDetLineItem
+from ...types import BBox
@dataclass(slots=True)
@@ -15,7 +15,6 @@ class VlmContentBlockDraft:
bbox: BBox
angle: int | None = None
content: str | None = None
- merge_prev: bool = False
sub_type: str | None = None
cell_merge: list[int] = field(default_factory=list)
ocr_det_lines: list[dict] = field(default_factory=list)
@@ -41,8 +40,7 @@ class VlmContentBlockDraft:
bbox=(x_1, y_1, x_2, y_2),
angle=content_block.get("angle", 0),
content=content_block.get("content", ""),
- merge_prev=bool(content_block.get("merge_prev", False)),
sub_type=content_block.get("sub_type"),
cell_merge=list(content_block.get("cell_merge") or []),
- _lines=content_block.get("_lines", []),
+ ocr_det_lines=list(content_block.get("_lines") or []),
)
diff --git a/mineru/backend/utils/formula_number.py b/mineru/backend/utils/formula_number.py
index f903a086..82b23234 100644
--- a/mineru/backend/utils/formula_number.py
+++ b/mineru/backend/utils/formula_number.py
@@ -3,21 +3,11 @@ from __future__ import annotations
from typing import Any
-from ...types import Block, BlockType, ContentType, PageInfo, Span
+from ...types import BlockType
from .char_utils import full_to_half
from .visual_magic_model_utils import isolated_formula_clean
-def extract_text_from_block(block: Block) -> str:
- """从 typed Block 中提取纯文本,用于公式编号归一化。"""
- text_parts = []
- for line in block.lines:
- for span in line.spans:
- if span.type == ContentType.TEXT:
- text_parts.append(span.content)
- return "".join(text_parts).strip()
-
-
def normalize_formula_tag_content(tag_content: str) -> str:
"""归一化公式编号文本,去掉全角字符和包裹括号后用于 \\tag{}。"""
tag_content = full_to_half(str(tag_content or "").strip())
@@ -42,55 +32,6 @@ def build_tagged_formula_content(formula_content: str, tag_content: str) -> str
return f"{formula_content}\\tag{{{tag_content}}}"
-def get_interline_equation_span(block: Block) -> Span | None:
- """查找 typed 公式块中的行间公式 span。"""
- for line in block.lines:
- for span in line.spans:
- if span.type == ContentType.INTERLINE_EQUATION:
- return span
- return None
-
-
-def append_formula_number_tag(equation_block: Block, formula_number_block: Block) -> None:
- """把 typed 公式编号合并进相邻行间公式的 LaTeX 内容。"""
- equation_span = get_interline_equation_span(equation_block)
- if equation_span is None:
- return
- tagged_content = build_tagged_formula_content(equation_span.content, extract_text_from_block(formula_number_block))
- if tagged_content:
- equation_span.content = tagged_content
-
-
-def optimize_pipeline_formula_number_blocks(pages: list[PageInfo]) -> None:
- """合并 Pipeline typed middle-json 中的公式编号块,无法合并时降级为文本块。"""
- for page_info in pages:
- optimized_blocks = []
- blocks = page_info.preproc_blocks
- for index, block in enumerate(blocks):
- if block.type != BlockType.FORMULA_NUMBER:
- optimized_blocks.append(block)
- continue
-
- prev_block = blocks[index - 1] if index > 0 else None
- if prev_block and prev_block.type == BlockType.INTERLINE_EQUATION:
- append_formula_number_tag(prev_block, block)
- continue
-
- next_block = blocks[index + 1] if index + 1 < len(blocks) else None
- next_next_block = blocks[index + 2] if index + 2 < len(blocks) else None
- if (
- next_block
- and next_block.type == BlockType.INTERLINE_EQUATION
- and (next_next_block is None or next_next_block.type != BlockType.FORMULA_NUMBER)
- ):
- append_formula_number_tag(next_block, block)
- continue
-
- block.type = BlockType.TEXT
- optimized_blocks.append(block)
- page_info.preproc_blocks = optimized_blocks
-
-
def _is_hybrid_equation_block(block: dict[str, Any]) -> bool:
"""判断 raw Hybrid/VLM block 是否表示可合并编号的行间公式。"""
return str(block.get("type") or "").lower() in {"equation", "display_formula", BlockType.INTERLINE_EQUATION}
diff --git a/mineru/backend/utils/para_block_utils.py b/mineru/backend/utils/para_block_utils.py
index 0b7f0dea..90746c67 100644
--- a/mineru/backend/utils/para_block_utils.py
+++ b/mineru/backend/utils/para_block_utils.py
@@ -356,7 +356,6 @@ def _remove_line_metadata(block: BlockDict) -> None:
def _cleanup_block_internal_metadata(block: Block) -> None:
"""递归清理只供 finalize 内部流程使用的临时字段。"""
- block.merge_prev = False
block._ocr_det_lines = []
block._line_avg_height = 0
for sub_block in block.blocks:
diff --git a/mineru/backend/utils/raw_block_types.py b/mineru/backend/utils/raw_block_types.py
new file mode 100644
index 00000000..bfba7633
--- /dev/null
+++ b/mineru/backend/utils/raw_block_types.py
@@ -0,0 +1,23 @@
+# Copyright (c) Opendatalab. All rights reserved.
+from typing import Literal, TypeAlias
+
+# 这些类型只允许存在于 Analyze/MagicModel 的 raw dict 阶段。
+RawBlockType: TypeAlias = Literal[
+ "algorithm",
+ "caption",
+ "equation",
+ "footnote",
+ "title",
+ "phonetic",
+]
+
+RAW_ALGORITHM: RawBlockType = "algorithm"
+RAW_CAPTION: RawBlockType = "caption"
+RAW_EQUATION: RawBlockType = "equation"
+RAW_FOOTNOTE: RawBlockType = "footnote"
+RAW_TITLE: RawBlockType = "title"
+RAW_PHONETIC: RawBlockType = "phonetic"
+
+RAW_ONLY_BLOCK_TYPES = frozenset(
+ {RAW_ALGORITHM, RAW_CAPTION, RAW_EQUATION, RAW_FOOTNOTE, RAW_TITLE, RAW_PHONETIC}
+)
diff --git a/mineru/backend/utils/span_block_fix.py b/mineru/backend/utils/span_block_fix.py
index dd97adbd..037a3cbd 100644
--- a/mineru/backend/utils/span_block_fix.py
+++ b/mineru/backend/utils/span_block_fix.py
@@ -1,126 +1,103 @@
# Copyright (c) Opendatalab. All rights reserved.
-from ...types import Block, ContentType, Line, Span
+from __future__ import annotations
+
+from ...types import ContentType
from ...utils.ocr_utils import _is_overlaps_x_exceeds_threshold, _is_overlaps_y_exceeds_threshold
+from .analyze_draft import _AnalyzeLine, _AnalyzeSpan
from .span_orientation import is_vertical_text_block_by_spans
-def fix_text_block(block: Block) -> Block:
- # 文本block中的公式span都应该转换成行内type
- for span in block._fix_spans:
+def group_spans_to_lines(spans: list[_AnalyzeSpan]) -> list[_AnalyzeLine]:
+ """直接把私有 span 分组成有序行,不再构造带临时字段的公开 Block。"""
+ for span in spans:
if span.type == ContentType.INTERLINE_EQUATION:
span.type = ContentType.INLINE_EQUATION
- if is_vertical_text_block_by_spans(block._fix_spans):
- # 如果是纵向文本块,则按纵向lines处理
- block_lines = merge_spans_to_vertical_line(block._fix_spans)
- sort_block_lines = vertical_line_sort_spans_from_top_to_bottom(block_lines)
- else:
- block_lines = merge_spans_to_line(block._fix_spans)
- sort_block_lines = line_sort_spans_by_left_to_right(block_lines)
-
- block.lines = sort_block_lines
- block._fix_spans = []
- return block
+ if is_vertical_text_block_by_spans(spans):
+ return vertical_line_sort_spans_from_top_to_bottom(
+ merge_spans_to_vertical_line(spans)
+ )
+ return line_sort_spans_by_left_to_right(merge_spans_to_line(spans))
-def merge_spans_to_line(spans: list[Span], threshold: float = 0.6) -> list[list[Span]]:
- if len(spans) == 0:
+def merge_spans_to_line(
+ spans: list[_AnalyzeSpan],
+ threshold: float = 0.6,
+) -> list[list[_AnalyzeSpan]]:
+ """按 y 轴重叠关系把横排 span 分组成行。"""
+ if not spans:
return []
- else:
- # 按照y0坐标排序
- spans.sort(key=lambda span: span.bbox[1])
-
- lines = []
- current_line = [spans[0]]
- for span in spans[1:]:
- # 如果当前的span类型为"interline_equation" 或者 当前行中已经有"interline_equation"
- # image和table类型,同上
- if span.type in [ContentType.INTERLINE_EQUATION, ContentType.IMAGE, ContentType.TABLE] or any(
- s.type in [ContentType.INTERLINE_EQUATION, ContentType.IMAGE, ContentType.TABLE] for s in current_line
- ):
- # 则开始新行
- lines.append(current_line)
- current_line = [span]
- continue
-
- # 如果当前的span与当前行的最后一个span在y轴上重叠,则添加到当前行
- if _is_overlaps_y_exceeds_threshold(span.bbox, current_line[-1].bbox, threshold):
- current_line.append(span)
- else:
- # 否则,开始新行
- lines.append(current_line)
- current_line = [span]
-
- # 添加最后一行
- if current_line:
+ spans.sort(key=lambda span: span.bbox[1])
+ lines: list[list[_AnalyzeSpan]] = []
+ current_line = [spans[0]]
+ special_types = {ContentType.INTERLINE_EQUATION, ContentType.IMAGE, ContentType.TABLE}
+ for span in spans[1:]:
+ if span.type in special_types or any(item.type in special_types for item in current_line):
lines.append(current_line)
-
- return lines
+ current_line = [span]
+ elif _is_overlaps_y_exceeds_threshold(span.bbox, current_line[-1].bbox, threshold):
+ current_line.append(span)
+ else:
+ lines.append(current_line)
+ current_line = [span]
+ lines.append(current_line)
+ return lines
-def merge_spans_to_vertical_line(spans: list[Span], threshold: float = 0.6) -> list[list[Span]]:
- """将纵向文本的spans合并成纵向lines(从右向左阅读)"""
- if len(spans) == 0:
+def merge_spans_to_vertical_line(
+ spans: list[_AnalyzeSpan],
+ threshold: float = 0.6,
+) -> list[list[_AnalyzeSpan]]:
+ """按 x 轴重叠关系把竖排 span 从右向左分组成列。"""
+ if not spans:
return []
- else:
- # 按照x2坐标从大到小排序(从右向左)
- spans.sort(key=lambda span: span.bbox[2], reverse=True)
-
- vertical_lines = []
- current_line = [spans[0]]
-
- for span in spans[1:]:
- # 特殊类型元素单独成列
- if span.type in [ContentType.INTERLINE_EQUATION, ContentType.IMAGE, ContentType.TABLE] or any(
- s.type in [ContentType.INTERLINE_EQUATION, ContentType.IMAGE, ContentType.TABLE] for s in current_line
- ):
- vertical_lines.append(current_line)
- current_line = [span]
- continue
-
- # 如果当前的span与当前行的最后一个span在y轴上重叠,则添加到当前行
- if _is_overlaps_x_exceeds_threshold(span.bbox, current_line[-1].bbox, threshold):
- current_line.append(span)
- else:
- vertical_lines.append(current_line)
- current_line = [span]
-
- # 添加最后一列
- if current_line:
- vertical_lines.append(current_line)
-
- return vertical_lines
+ spans.sort(key=lambda span: span.bbox[2], reverse=True)
+ lines: list[list[_AnalyzeSpan]] = []
+ current_line = [spans[0]]
+ special_types = {ContentType.INTERLINE_EQUATION, ContentType.IMAGE, ContentType.TABLE}
+ for span in spans[1:]:
+ if span.type in special_types or any(item.type in special_types for item in current_line):
+ lines.append(current_line)
+ current_line = [span]
+ elif _is_overlaps_x_exceeds_threshold(span.bbox, current_line[-1].bbox, threshold):
+ current_line.append(span)
+ else:
+ lines.append(current_line)
+ current_line = [span]
+ lines.append(current_line)
+ return lines
-# 将每一个line中的span从左到右排序
-def line_sort_spans_by_left_to_right(lines: list[list[Span]]) -> list[Line]:
- line_objects = []
+def line_sort_spans_by_left_to_right(
+ lines: list[list[_AnalyzeSpan]],
+) -> list[_AnalyzeLine]:
+ """将横排行内 span 从左到右排序并计算行框。"""
+ line_objects: list[_AnalyzeLine] = []
for line in lines:
- # 按照x0坐标排序
line.sort(key=lambda span: span.bbox[0])
- line_bbox = (
- min(span.bbox[0] for span in line), # x0
- min(span.bbox[1] for span in line), # y0
- max(span.bbox[2] for span in line), # x1
- max(span.bbox[3] for span in line), # y1
- )
- line_objects.append(Line(bbox=line_bbox, spans=line))
+ line_objects.append(_line_from_spans(line))
return line_objects
-def vertical_line_sort_spans_from_top_to_bottom(vertical_lines: list[list[Span]]) -> list[Line]:
- line_objects = []
+def vertical_line_sort_spans_from_top_to_bottom(
+ vertical_lines: list[list[_AnalyzeSpan]],
+) -> list[_AnalyzeLine]:
+ """将竖排列内 span 从上到下排序并计算列框。"""
+ line_objects: list[_AnalyzeLine] = []
for line in vertical_lines:
- # 按照y0坐标排序(从上到下)
line.sort(key=lambda span: span.bbox[1])
+ line_objects.append(_line_from_spans(line))
+ return line_objects
- # 计算整个列的边界框
- line_bbox = (
- min(span.bbox[0] for span in line), # x0
- min(span.bbox[1] for span in line), # y0
- max(span.bbox[2] for span in line), # x1
- max(span.bbox[3] for span in line), # y1
- )
- line_objects.append(Line(bbox=line_bbox, spans=line))
- return line_objects
+def _line_from_spans(spans: list[_AnalyzeSpan]) -> _AnalyzeLine:
+ """聚合一组 span 的外接矩形并构造私有行对象。"""
+ return _AnalyzeLine(
+ bbox=(
+ min(span.bbox[0] for span in spans),
+ min(span.bbox[1] for span in spans),
+ max(span.bbox[2] for span in spans),
+ max(span.bbox[3] for span in spans),
+ ),
+ spans=spans,
+ )
diff --git a/mineru/backend/utils/span_orientation.py b/mineru/backend/utils/span_orientation.py
index e2dda597..7557596f 100644
--- a/mineru/backend/utils/span_orientation.py
+++ b/mineru/backend/utils/span_orientation.py
@@ -1,11 +1,11 @@
# Copyright (c) Opendatalab. All rights reserved.
-from ...types import Span
+from .analyze_draft import _AnalyzeSpan
VERTICAL_SPAN_HEIGHT_TO_WIDTH_RATIO_THRESHOLD = 2
VERTICAL_SPAN_IN_BLOCK_THRESHOLD = 0.8
-def is_vertical_text_block_by_spans(spans: list[Span]) -> bool:
+def is_vertical_text_block_by_spans(spans: list[_AnalyzeSpan]) -> bool:
"""根据块内文本 span 的高宽比判断文本块是否更像竖排文本。"""
valid_span_count = 0
vertical_span_count = 0
diff --git a/mineru/backend/utils/span_pre_proc.py b/mineru/backend/utils/span_pre_proc.py
index 96361294..a4d5463f 100644
--- a/mineru/backend/utils/span_pre_proc.py
+++ b/mineru/backend/utils/span_pre_proc.py
@@ -12,11 +12,12 @@ import numpy as np
from loguru import logger
from pdftext.schema import Char
-from ...types import BBox, BlockType, ContentType, Span
+from ...types import BBox, BlockType, ContentType
from ...utils.image_utils import calculate_contrast
from ...utils.pdf_document import PDFPage, get_lines_from_chars
from ...utils.pdf_image_tools import get_crop_img
from .boxbase import calculate_overlap_area_in_bbox1_area_ratio
+from .analyze_draft import _AnalyzeSpan
MAX_NATIVE_TEXT_CHARS_PER_PAGE = 65535
PRIVATE_USE_AREA_START = 0xE000
@@ -48,12 +49,12 @@ def __replace_unicode(text: str) -> str:
def txt_spans_extract(
pdf_page: PDFPage,
- spans: list[Span],
+ spans: list[_AnalyzeSpan],
pil_img: Any,
scale: float,
all_bboxes: list[tuple[Any, ...]],
all_discarded_blocks: list[tuple[Any, ...]],
-) -> list[Span]:
+) -> list[_AnalyzeSpan]:
page_char_count = None
try:
page_char_count = pdf_page.get_char_count()
@@ -73,8 +74,8 @@ def txt_spans_extract(
for span in spans:
if span.type in [ContentType.TEXT]:
span_height = span.bbox[3] - span.bbox[1]
- span._extra["height"] = span_height
- span._extra["width"] = span.bbox[2] - span.bbox[0]
+ span.metadata["height"] = span_height
+ span.metadata["width"] = span.bbox[2] - span.bbox[0]
span_height_list.append(span_height)
if len(span_height_list) == 0:
return spans
@@ -91,7 +92,10 @@ def txt_spans_extract(
if block[7] in [BlockType.IMAGE_BODY, BlockType.TABLE_BODY, BlockType.INTERLINE_EQUATION]:
continue
if calculate_overlap_area_in_bbox1_area_ratio(span.bbox, block[0:4]) > 0.5:
- if span._extra["height"] > median_span_height * 2.3 and span._extra["height"] > span._extra["width"] * 2.3:
+ if (
+ span.metadata["height"] > median_span_height * 2.3
+ and span.metadata["height"] > span.metadata["width"] * 2.3
+ ):
vertical_spans.append(span)
elif block in all_bboxes:
useful_spans.append(span)
@@ -118,7 +122,7 @@ def txt_spans_extract(
for span in useful_spans + unuseful_spans:
if span.type in [ContentType.TEXT]:
- span._extra["chars"] = []
+ span.metadata["chars"] = []
new_spans.append(span)
need_ocr_spans = fill_char_in_spans(new_spans, page_all_chars, median_span_height)
@@ -211,11 +215,11 @@ def _get_chars_for_span_fill(page_chars: list[Char] | dict[str, list[Char]]) ->
def _prepare_post_ocr_spans(
- need_ocr_spans: list[Span],
- spans: list[Span],
+ need_ocr_spans: list[_AnalyzeSpan],
+ spans: list[_AnalyzeSpan],
pil_img: Any,
scale: float,
-) -> list[Span]:
+) -> list[_AnalyzeSpan]:
if len(need_ocr_spans) == 0:
return spans
@@ -233,7 +237,7 @@ def _prepare_post_ocr_spans(
span.content = ""
span.score = 1.0
- span._np_img = span_img
+ span.image = span_img
return spans
@@ -241,21 +245,21 @@ def _prepare_post_ocr_spans(
class SpanBlockMatcher:
"""按 block 顺序消费 span,并用 y 方向索引减少无效重叠计算。"""
- def __init__(self, spans: list[Span]) -> None:
+ def __init__(self, spans: list[_AnalyzeSpan]) -> None:
self.spans = list(spans)
self.used_span_indices = set()
self.grid_size = self._get_grid_size(self.spans)
self.grid = self._build_grid(self.spans)
@staticmethod
- def _get_grid_size(spans: list[Span]) -> float:
+ def _get_grid_size(spans: list[_AnalyzeSpan]) -> float:
"""根据 span 高度估算索引网格大小,避免过细或过粗。"""
heights = [span.bbox[3] - span.bbox[1] for span in spans if span.bbox and span.bbox[3] > span.bbox[1]]
if not heights:
return 1
return max(1, statistics.median(heights))
- def _build_grid(self, spans: list[Span]) -> dict[int, list[int]]:
+ def _build_grid(self, spans: list[_AnalyzeSpan]) -> dict[int, list[int]]:
"""将 span 按 y 方向网格登记,后续按 block bbox 快速取候选。"""
grid = collections.defaultdict(list)
for index, span in enumerate(spans):
@@ -284,7 +288,7 @@ class SpanBlockMatcher:
block_bbox: BBox,
overlap_ratio_getter: Callable | None = None,
threshold: float = 0.5,
- ) -> list[Span]:
+ ) -> list[_AnalyzeSpan]:
"""返回当前 block 命中的 span,并标记为已消费以保持旧归属语义。"""
if overlap_ratio_getter is None:
overlap_ratio_getter = self._default_overlap_ratio
@@ -299,21 +303,21 @@ class SpanBlockMatcher:
self.used_span_indices.add(span_idx)
return block_spans
- def remaining_spans(self) -> list[Span]:
+ def remaining_spans(self) -> list[_AnalyzeSpan]:
"""返回尚未归属到任何 block 的 span,方便保持后续兼容。"""
return [span for index, span in enumerate(self.spans) if index not in self.used_span_indices]
@staticmethod
- def _default_overlap_ratio(span: Span, block_bbox: BBox) -> float:
+ def _default_overlap_ratio(span: _AnalyzeSpan, block_bbox: BBox) -> float:
"""默认沿用旧逻辑:计算 span 面积中落入 block 的比例。"""
return calculate_overlap_area_in_bbox1_area_ratio(span.bbox, block_bbox)
def fill_char_in_spans(
- spans: list[Span],
+ spans: list[_AnalyzeSpan],
all_chars: list[Char],
median_span_height: float,
-) -> list[Span]:
+) -> list[_AnalyzeSpan]:
# 简单从上到下排一下序
spans = sorted(spans, key=lambda x: x.bbox[1])
@@ -346,24 +350,24 @@ def fill_char_in_spans(
):
continue
if calculate_char_in_span(char_bbox, span_bbox, char["char"]):
- span._extra["chars"].append(char)
+ span.metadata["chars"].append(char)
break
need_ocr_spans = []
for span in spans:
- private_use_signal = _get_private_use_text_signal(span._extra["chars"])
+ private_use_signal = _get_private_use_text_signal(span.metadata["chars"])
should_post_ocr_private_use = _should_fallback_to_post_ocr_for_private_use_text(private_use_signal)
chars_to_content(span)
# 有的span中虽然没有字但有一两个空的占位符,用宽高和content长度过滤
if should_post_ocr_private_use and span.content:
- span._extra[POST_OCR_FALLBACK_CONTENT_KEY] = span.content
- span._extra[POST_OCR_FALLBACK_SCORE_KEY] = span.score
- span._extra[POST_OCR_REASON_KEY] = POST_OCR_REASON_PRIVATE_USE_TEXT
+ span.metadata[POST_OCR_FALLBACK_CONTENT_KEY] = span.content
+ span.metadata[POST_OCR_FALLBACK_SCORE_KEY] = span.score
+ span.metadata[POST_OCR_REASON_KEY] = POST_OCR_REASON_PRIVATE_USE_TEXT
need_ocr_spans.append(span)
- elif len(span.content) * span._extra["height"] < span._extra["width"] * 0.5:
+ elif len(span.content) * span.metadata["height"] < span.metadata["width"] * 0.5:
# logger.info(f"maybe empty span: {len(span['content'])}, {span['height']}, {span['width']}")
need_ocr_spans.append(span)
- del span._extra["height"], span._extra["width"]
+ del span.metadata["height"], span.metadata["width"]
return need_ocr_spans
@@ -466,22 +470,22 @@ def _should_fallback_to_post_ocr_for_private_use_text(signal: dict[str, float |
)
-def _clear_post_ocr_fallback(span: Span) -> None:
+def _clear_post_ocr_fallback(span: _AnalyzeSpan) -> None:
"""清理后置 OCR 内部兜底字段,避免进入最终 middle-json 输出。"""
- span._extra.pop(POST_OCR_FALLBACK_CONTENT_KEY, None)
- span._extra.pop(POST_OCR_FALLBACK_SCORE_KEY, None)
- span._extra.pop(POST_OCR_REASON_KEY, None)
+ span.metadata.pop(POST_OCR_FALLBACK_CONTENT_KEY, None)
+ span.metadata.pop(POST_OCR_FALLBACK_SCORE_KEY, None)
+ span.metadata.pop(POST_OCR_REASON_KEY, None)
-def _restore_post_ocr_fallback(span: Span) -> bool:
+def _restore_post_ocr_fallback(span: _AnalyzeSpan) -> bool:
"""在后置 OCR 无法使用时恢复原始文本兜底,返回是否已恢复。"""
- if POST_OCR_FALLBACK_CONTENT_KEY not in span._extra:
+ if POST_OCR_FALLBACK_CONTENT_KEY not in span.metadata:
_clear_post_ocr_fallback(span)
return False
- span.content = span._extra[POST_OCR_FALLBACK_CONTENT_KEY]
- if POST_OCR_FALLBACK_SCORE_KEY in span._extra:
- span.score = span._extra[POST_OCR_FALLBACK_SCORE_KEY]
+ span.content = span.metadata[POST_OCR_FALLBACK_CONTENT_KEY]
+ if POST_OCR_FALLBACK_SCORE_KEY in span.metadata:
+ span.score = span.metadata[POST_OCR_FALLBACK_SCORE_KEY]
_clear_post_ocr_fallback(span)
return True
@@ -621,10 +625,10 @@ def _wrap_script_runs(role_text_parts: list[tuple[str, str]]) -> str:
return "".join(wrapped_parts)
-def chars_to_content(span: Span) -> None:
+def chars_to_content(span: _AnalyzeSpan) -> None:
# 检查span中的char是否为空
- if len(span._extra["chars"]) != 0:
- chars = span._extra["chars"]
+ if len(span.metadata["chars"]) != 0:
+ chars = span.metadata["chars"]
# 大多数情况下 char 已按 PDF 原始顺序进入,只有乱序时才排序。
if any(chars[idx]["char_idx"] > chars[idx + 1]["char_idx"] for idx in range(len(chars) - 1)):
chars = sorted(chars, key=lambda x: x["char_idx"])
@@ -660,4 +664,4 @@ def chars_to_content(span: Span) -> None:
content = __replace_ligatures(content)
span.content = content.strip()
- del span._extra["chars"]
+ del span.metadata["chars"]
diff --git a/mineru/backend/utils/visual_magic_model_utils.py b/mineru/backend/utils/visual_magic_model_utils.py
index 558da174..277ac280 100644
--- a/mineru/backend/utils/visual_magic_model_utils.py
+++ b/mineru/backend/utils/visual_magic_model_utils.py
@@ -3,19 +3,20 @@ from __future__ import annotations
import re
from copy import deepcopy
-from typing import Any, cast
+from typing import Any
-from ...types import BBox, Block, BlockType
+from ...types import BBox, BlockType
from .boxbase import bbox_center_distance, bbox_distance
+from .raw_block_types import RAW_CAPTION, RAW_FOOTNOTE
from .table_continuation import is_table_continuation_text
IMAGE_BLOCK_BODY = "image_block_body"
-GENERIC_CHILD_TYPES = (BlockType.CAPTION, BlockType.FOOTNOTE)
-INLINE_CAPTION_FRAGMENT_TYPES = {BlockType.TEXT, BlockType.FOOTNOTE}
+GENERIC_CHILD_TYPES = (RAW_CAPTION, RAW_FOOTNOTE)
+INLINE_CAPTION_FRAGMENT_TYPES = {BlockType.TEXT, RAW_FOOTNOTE}
STACKED_TABLE_CAPTION_CLUSTER_TYPES = {
- BlockType.CAPTION,
+ RAW_CAPTION,
BlockType.TEXT,
- BlockType.FOOTNOTE,
+ RAW_FOOTNOTE,
}
VISUAL_RELATION_IGNORED_TYPES = {
BlockType.HEADER,
@@ -54,8 +55,8 @@ VISUAL_TYPE_MAPPING = {
},
}
VISUAL_CHILD_TYPE_MAPPING: dict[str, tuple[str | None, str]] = {
- BlockType.CAPTION: (None, "caption"),
- BlockType.FOOTNOTE: (None, "footnote"),
+ RAW_CAPTION: (None, "caption"),
+ RAW_FOOTNOTE: (None, "footnote"),
BlockType.IMAGE_CAPTION: (BlockType.IMAGE, "caption"),
BlockType.IMAGE_FOOTNOTE: (BlockType.IMAGE, "footnote"),
BlockType.TABLE_CAPTION: (BlockType.TABLE, "caption"),
@@ -66,30 +67,25 @@ VISUAL_CHILD_TYPE_MAPPING: dict[str, tuple[str | None, str]] = {
BlockType.CODE_FOOTNOTE: (BlockType.CODE, "footnote"),
}
-BlockLike = Block | dict[str, Any]
+BlockDict = dict[str, Any]
-def _get_block_field(block: BlockLike, field_name: str, default: Any = None) -> Any:
- """统一读取 Block 属性或 dict 字段。"""
- if isinstance(block, dict):
- return block.get(field_name, default)
- return getattr(block, field_name, default)
+def _get_block_field(block: BlockDict, field_name: str, default: Any = None) -> Any:
+ """读取 raw dict block 字段。"""
+ return block.get(field_name, default)
-def _set_block_field(block: BlockLike, field_name: str, value: Any) -> None:
- """统一回写 Block 属性或 dict 字段。"""
- if isinstance(block, dict):
- block[field_name] = value
- else:
- setattr(block, field_name, value)
+def _set_block_field(block: BlockDict, field_name: str, value: Any) -> None:
+ """回写 raw dict block 字段。"""
+ block[field_name] = value
-def _block_index(block: BlockLike) -> int:
+def _block_index(block: BlockDict) -> int:
"""读取 block 顺序索引,缺失时沿用原有的零值排序语义。"""
return int(_get_block_field(block, "index", 0) or 0)
-def _block_type(block: BlockLike) -> str:
+def _block_type(block: BlockDict) -> str:
"""读取 block 类型。"""
return str(_get_block_field(block, "type", "") or "")
@@ -102,16 +98,14 @@ def _bbox_for_calculation(bbox: BBox) -> BBox:
return x0, y0, x1, y1
-def _block_bbox(block: BlockLike) -> BBox:
+def _block_bbox(block: BlockDict) -> BBox:
"""读取参与视觉关系判断的 block bbox。"""
- return _bbox_for_calculation(cast(BBox, _get_block_field(block, "bbox")))
+ return _bbox_for_calculation(block["bbox"])
-def _block_line_items(block: BlockLike) -> list[Any]:
- """读取行级元数据,dict 使用 _lines,Block 使用 lines。"""
- if isinstance(block, dict):
- return list(block.get("lines") or [])
- return list(block.lines or [])
+def _block_line_items(block: BlockDict) -> list[Any]:
+ """读取 raw block 的临时行级元数据。"""
+ return list(block.get("lines") or [])
def isolated_formula_clean(txt: str) -> str:
@@ -158,7 +152,7 @@ def clean_content(content: str | None) -> str | None:
def fallback_inline_caption_fragments(
- blocks: list[BlockLike],
+ blocks: list[BlockDict],
visual_main_types: dict[str, str] | set[str],
) -> None:
"""将紧贴视觉主体上方的同行 text/footnote 片段兜底为通用 caption。"""
@@ -176,7 +170,7 @@ def fallback_inline_caption_fragments(
if not (
previous_block
and next_block
- and _block_type(previous_block) == BlockType.CAPTION
+ and _block_type(previous_block) == RAW_CAPTION
and _block_type(next_block) in main_types
):
continue
@@ -184,13 +178,13 @@ def fallback_inline_caption_fragments(
if not is_inline_caption_fragment(previous_block, block, next_block):
continue
- _set_block_field(block, "type", BlockType.CAPTION)
+ _set_block_field(block, "type", RAW_CAPTION)
fallback_stacked_table_caption_fragments(blocks, visual_main_types)
def fallback_no_bbox_caption_fragments(
- blocks: list[BlockLike],
+ blocks: list[BlockDict],
visual_main_types: dict[str, str],
) -> None:
"""将无坐标视觉主体后紧邻且带标题前缀的 text 兜底为 caption。"""
@@ -212,11 +206,11 @@ def fallback_no_bbox_caption_fragments(
content = _block_text_content(next_block).strip().lower()
if any(content.startswith(prefix) for prefix in prefixes):
- _set_block_field(next_block, "type", BlockType.CAPTION)
+ _set_block_field(next_block, "type", RAW_CAPTION)
def fallback_leading_table_continuation_captions(
- blocks: list[BlockLike],
+ blocks: list[BlockDict],
visual_main_types: dict[Any, Any] | set[Any],
) -> None:
"""将页首紧贴表格的续表文本兜底为通用 caption。
@@ -257,10 +251,10 @@ def fallback_leading_table_continuation_captions(
return
for block in leading_blocks:
- _set_block_field(block, "type", BlockType.CAPTION)
+ _set_block_field(block, "type", RAW_CAPTION)
-def _is_leading_continuation_text_block(block: BlockLike) -> bool:
+def _is_leading_continuation_text_block(block: BlockDict) -> bool:
"""判断页首候选块是否是单行续表文本。"""
return (
_block_type(block) in INLINE_CAPTION_FRAGMENT_TYPES
@@ -269,21 +263,19 @@ def _is_leading_continuation_text_block(block: BlockLike) -> bool:
)
-def _block_text_content(block: BlockLike) -> str:
+def _block_text_content(block: BlockDict) -> str:
"""提取视觉块中的可见文本,用于续表 marker 判断。"""
content = _get_block_field(block, "content", "")
return content if isinstance(content, str) else ""
-def is_transparent_visual_relation_block(block: BlockLike) -> bool:
+def is_transparent_visual_relation_block(block: BlockDict) -> bool:
"""判断视觉关系中可忽略的结构性空块。"""
if _block_type(block) != BlockType.LIST:
return False
- nested_blocks = _get_block_field(block, "blocks", [])
- if not nested_blocks and isinstance(block, dict):
- content = block.get("content")
- nested_blocks = content if isinstance(content, list) else []
+ content = block.get("content")
+ nested_blocks = content if isinstance(content, list) else []
if nested_blocks:
return False
@@ -291,8 +283,8 @@ def is_transparent_visual_relation_block(block: BlockLike) -> bool:
def _is_leading_continuation_cluster_near_table(
- leading_blocks: list[BlockLike],
- table_block: BlockLike,
+ leading_blocks: list[BlockDict],
+ table_block: BlockDict,
) -> bool:
"""判断页首续表文本簇是否与后续 table 在几何上相邻。"""
next_top = _block_bbox(table_block)[1]
@@ -317,7 +309,7 @@ def _is_leading_continuation_cluster_near_table(
def fallback_stacked_table_caption_fragments(
- blocks: list[BlockLike],
+ blocks: list[BlockDict],
visual_main_types: dict[str, str] | set[str],
) -> None:
"""将 table 上方紧贴标题簇里的 text/footnote 片段兜底为 caption。"""
@@ -339,7 +331,7 @@ def fallback_stacked_table_caption_fragments(
for block in caption_cluster[last_caption_pos + 1 :]:
if _block_type(block) in INLINE_CAPTION_FRAGMENT_TYPES and is_single_line_caption_fragment(block):
- _set_block_field(block, "type", BlockType.CAPTION)
+ _set_block_field(block, "type", RAW_CAPTION)
def get_table_main_types(visual_main_types: dict[str, str] | set[str]) -> set[str]:
@@ -352,9 +344,9 @@ def get_table_main_types(visual_main_types: dict[str, str] | set[str]) -> set[st
def find_stacked_table_caption_cluster(
- table_block: BlockLike,
- blocks: list[BlockLike],
-) -> list[BlockLike]:
+ table_block: BlockDict,
+ blocks: list[BlockDict],
+) -> list[BlockDict]:
"""按几何位置收集紧贴 table 上方的 caption/text/footnote 标题簇。"""
table_bbox = _block_bbox(table_block)
table_top = table_bbox[1]
@@ -391,15 +383,15 @@ def find_stacked_table_caption_cluster(
return list(reversed(caption_cluster))
-def find_last_caption_position(caption_cluster: list[BlockLike]) -> int | None:
+def find_last_caption_position(caption_cluster: list[BlockDict]) -> int | None:
"""定位标题簇里的最后一个 caption,避免吸收上一张表的尾注。"""
for pos in range(len(caption_cluster) - 1, -1, -1):
- if _block_type(caption_cluster[pos]) == BlockType.CAPTION:
+ if _block_type(caption_cluster[pos]) == RAW_CAPTION:
return pos
return None
-def is_horizontally_near_table(block: BlockLike, table_block: BlockLike) -> bool:
+def is_horizontally_near_table(block: BlockDict, table_block: BlockDict) -> bool:
"""判断标题簇候选块是否横向落在 table 范围附近。"""
table_bbox = _block_bbox(table_block)
block_bbox = _block_bbox(block)
@@ -408,7 +400,7 @@ def is_horizontally_near_table(block: BlockLike, table_block: BlockLike) -> bool
return not (block_bbox[2] < table_bbox[0] - tolerance or block_bbox[0] > table_bbox[2] + tolerance)
-def is_single_line_caption_fragment(block: BlockLike) -> bool:
+def is_single_line_caption_fragment(block: BlockDict) -> bool:
"""判断待兜底片段是否是单行块,避免吞掉多行正文。"""
return len(_block_line_items(block) or [None]) <= 1
@@ -418,7 +410,7 @@ def stacked_caption_max_gap(block_height: float) -> float:
return max(12, block_height * 1.5)
-def find_previous_effective_block(ordered_blocks: list[BlockLike], pos: int) -> BlockLike | None:
+def find_previous_effective_block(ordered_blocks: list[BlockDict], pos: int) -> BlockDict | None:
"""向前查找参与视觉关系判断的有效块,跳过页眉页脚等外围块。"""
for index in range(pos - 1, -1, -1):
block = ordered_blocks[index]
@@ -427,7 +419,7 @@ def find_previous_effective_block(ordered_blocks: list[BlockLike], pos: int) ->
return None
-def find_next_effective_block(ordered_blocks: list[BlockLike], pos: int) -> BlockLike | None:
+def find_next_effective_block(ordered_blocks: list[BlockDict], pos: int) -> BlockDict | None:
"""向后查找参与视觉关系判断的有效块,跳过页眉页脚等外围块。"""
for index in range(pos + 1, len(ordered_blocks)):
block = ordered_blocks[index]
@@ -437,9 +429,9 @@ def find_next_effective_block(ordered_blocks: list[BlockLike], pos: int) -> Bloc
def is_inline_caption_fragment(
- previous_caption: BlockLike,
- text_block: BlockLike,
- next_visual: BlockLike,
+ previous_caption: BlockDict,
+ text_block: BlockDict,
+ next_visual: BlockDict,
) -> bool:
"""判断当前块是否是前一 caption 的同行补充片段。"""
caption_bbox = _block_bbox(previous_caption)
@@ -462,10 +454,10 @@ def is_inline_caption_fragment(
def regroup_visual_blocks(
- blocks: list[BlockLike],
+ blocks: list[BlockDict],
*,
use_bbox: bool = True,
-) -> tuple[dict[Any, list[BlockLike]], list[BlockLike]]:
+) -> tuple[dict[Any, list[BlockDict]], list[BlockDict]]:
"""按 bbox 或纯阅读顺序将通用 caption/footnote 归入视觉主体。"""
ordered_blocks = sorted(blocks, key=_block_index)
if use_bbox:
@@ -491,11 +483,11 @@ def regroup_visual_blocks(
if _block_type(block) in VISUAL_CHILD_TYPE_MAPPING
]
- grouped_children: dict[int, dict[str, list[BlockLike]]] = {
+ grouped_children: dict[int, dict[str, list[BlockDict]]] = {
_block_index(block): {"captions": [], "footnotes": []}
for block in main_blocks
}
- unmatched_child_blocks: list[BlockLike] = []
+ unmatched_child_blocks: list[BlockDict] = []
for child_block in child_blocks:
child_visual_type, child_kind = VISUAL_CHILD_TYPE_MAPPING[
@@ -522,7 +514,7 @@ def regroup_visual_blocks(
child_block
)
- grouped_blocks: dict[str, list[BlockLike]] = {
+ grouped_blocks: dict[str, list[BlockDict]] = {
BlockType.IMAGE: [],
BlockType.TABLE: [],
BlockType.CHART: [],
@@ -536,57 +528,41 @@ def regroup_visual_blocks(
main_sub_type = str(_get_block_field(main_block, "sub_type", "") or "")
body_block = deepcopy(main_block)
_set_block_field(body_block, "type", mapping["body"])
- if main_sub_type:
- if isinstance(body_block, dict):
- body_block.pop("sub_type", None)
- else:
- body_block.sub_type = ""
+ body_block.pop("sub_type", None)
- captions: list[BlockLike] = []
+ captions: list[BlockDict] = []
for caption in sorted(
grouped_children[main_index]["captions"],
key=_block_index,
):
child_block = deepcopy(caption)
_set_block_field(child_block, "type", mapping["caption"])
- if isinstance(child_block, dict):
- child_block.pop("lines", None)
+ child_block.pop("lines", None)
captions.append(child_block)
- footnotes: list[BlockLike] = []
+ footnotes: list[BlockDict] = []
for footnote in sorted(
grouped_children[main_index]["footnotes"],
key=_block_index,
):
child_block = deepcopy(footnote)
_set_block_field(child_block, "type", mapping["footnote"])
- if isinstance(child_block, dict):
- child_block.pop("lines", None)
+ child_block.pop("lines", None)
footnotes.append(child_block)
child_items = sorted(
[body_block, *captions, *footnotes],
key=_block_index,
)
- if isinstance(main_block, dict):
- two_layer_block: BlockLike = {
- "index": main_index,
- "type": visual_type,
- "content": child_items,
- }
- if main_sub_type:
- two_layer_block["sub_type"] = main_sub_type
- if "bbox" in main_block:
- two_layer_block["bbox"] = deepcopy(main_block["bbox"])
- else:
- two_layer_block = Block(
- index=main_index,
- type=visual_type,
- bbox=main_block.bbox,
- content=cast(Any, child_items),
- )
- if main_sub_type:
- two_layer_block.sub_type = main_sub_type
+ two_layer_block: BlockDict = {
+ "index": main_index,
+ "type": visual_type,
+ "content": child_items,
+ }
+ if main_sub_type:
+ two_layer_block["sub_type"] = main_sub_type
+ if "bbox" in main_block:
+ two_layer_block["bbox"] = deepcopy(main_block["bbox"])
grouped_blocks[visual_type].append(two_layer_block)
@@ -597,14 +573,14 @@ def regroup_visual_blocks(
def find_best_visual_parent(
- child_block: BlockLike,
- main_blocks: list[BlockLike],
- ordered_blocks: list[BlockLike],
+ child_block: BlockDict,
+ main_blocks: list[BlockDict],
+ ordered_blocks: list[BlockDict],
position_by_index: dict[int, int],
main_type_to_visual_type: dict[Any, Any] | None = None,
type_by_index: dict[int, str] | None = None,
use_bbox: bool = True,
-) -> BlockLike | None:
+) -> BlockDict | None:
"""为通用 caption/footnote 查找最合适的视觉主体。"""
if main_type_to_visual_type is None:
main_type_to_visual_type = VISUAL_MAIN_TYPES
@@ -700,9 +676,9 @@ def find_best_visual_parent(
def effective_visual_index_diff(
- child_block: BlockLike,
- main_block: BlockLike,
- ordered_blocks: list[BlockLike],
+ child_block: BlockDict,
+ main_block: BlockDict,
+ ordered_blocks: list[BlockDict],
type_by_index: dict[int, str] | None = None,
) -> int:
"""按有效块序列计算视觉子块与主体距离,吸收的 image 子成员视为零成本。"""
@@ -725,9 +701,9 @@ def effective_visual_index_diff(
def is_visual_neighbor(
- child_block: BlockLike,
- main_block: BlockLike,
- ordered_blocks: list[BlockLike],
+ child_block: BlockDict,
+ main_block: BlockDict,
+ ordered_blocks: list[BlockDict],
position_by_index: dict[int, int],
type_by_index: dict[int, str] | None = None,
use_bbox: bool = True,
@@ -765,9 +741,9 @@ def is_visual_neighbor(
def is_block_outside_visual_gap(
- between_block: BlockLike,
- child_block: BlockLike,
- main_block: BlockLike,
+ between_block: BlockDict,
+ child_block: BlockDict,
+ main_block: BlockDict,
) -> bool:
"""判断阅读顺序夹在中间的块是否没有落入视觉父子块的垂直间隔。"""
visual_gap = vertical_gap_between_blocks(child_block, main_block)
@@ -788,8 +764,8 @@ def is_block_outside_visual_gap(
def vertical_gap_between_blocks(
- first_block: BlockLike,
- second_block: BlockLike,
+ first_block: BlockDict,
+ second_block: BlockDict,
) -> tuple[float, float] | None:
"""计算两个块上下分离时的垂直间隔;发生纵向重叠时保持严格阻断。"""
first_bbox = _block_bbox(first_block)
@@ -825,7 +801,7 @@ def are_bboxes_overlapping(first_bbox: BBox, second_bbox: BBox) -> bool:
)
-def block_type(block: BlockLike, type_by_index: dict[int, str] | None = None) -> str:
+def block_type(block: BlockDict, type_by_index: dict[int, str] | None = None) -> str:
"""读取块类型;本地 Hybrid 会传入改写前的原始类型映射。"""
if type_by_index is not None:
return type_by_index[_block_index(block)]
diff --git a/mineru/model/flash/docx/docx_converter.py b/mineru/model/flash/docx/docx_converter.py
index 56be7562..e625346d 100644
--- a/mineru/model/flash/docx/docx_converter.py
+++ b/mineru/model/flash/docx/docx_converter.py
@@ -1529,7 +1529,7 @@ class DocxConverter:
image_block = {
"type": BlockType.IMAGE,
- "_image_base64": img_base64,
+ "image_base64": img_base64,
}
self.cur_page.append(image_block)
diff --git a/mineru/model/flash/pptx/pptx_converter.py b/mineru/model/flash/pptx/pptx_converter.py
index 08b5bcca..86924fcb 100644
--- a/mineru/model/flash/pptx/pptx_converter.py
+++ b/mineru/model/flash/pptx/pptx_converter.py
@@ -719,7 +719,7 @@ class PptxConverter:
if content_type == "image/svg+xml":
image_block = {
"type": BlockType.IMAGE,
- "_image_base64": self._bytes_to_data_uri(image_bytes, content_type),
+ "image_base64": self._bytes_to_data_uri(image_bytes, content_type),
}
self.cur_page.append(image_block)
return
@@ -730,7 +730,7 @@ class PptxConverter:
image_block = {
"type": BlockType.IMAGE,
- "_image_base64": img_base64,
+ "image_base64": img_base64,
}
self.cur_page.append(image_block)
return
diff --git a/mineru/model/flash/xlsx/xlsx_converter.py b/mineru/model/flash/xlsx/xlsx_converter.py
index 03cb0a44..3a232107 100644
--- a/mineru/model/flash/xlsx/xlsx_converter.py
+++ b/mineru/model/flash/xlsx/xlsx_converter.py
@@ -988,7 +988,7 @@ class XlsxConverter:
self.cur_page.append(
{
"type": BlockType.IMAGE,
- "_image_base64": image_info["base64"],
+ "image_base64": image_info["base64"],
}
)
diff --git a/mineru/types.py b/mineru/types.py
index f39e59d9..4e344a5b 100644
--- a/mineru/types.py
+++ b/mineru/types.py
@@ -1,11 +1,15 @@
# Copyright (c) Opendatalab. All rights reserved.
from __future__ import annotations
-from dataclasses import MISSING, Field, InitVar, dataclass, field, fields
-from typing import Any, Iterator, Literal, TypeAlias, TypeVar, get_type_hints, TypedDict
-
-T = TypeVar("T", bound="_DocElement")
+import json
+import math
+import os
+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
Tier = Literal[
"flash",
@@ -135,40 +139,28 @@ BlockTypes = Literal[
BlockType.IMAGE_BODY,
BlockType.TABLE_BODY,
BlockType.CHART_BODY,
- BlockType.CAPTION,
BlockType.IMAGE_CAPTION,
BlockType.TABLE_CAPTION,
BlockType.CHART_CAPTION,
- BlockType.ALGORITHM_CAPTION,
- BlockType.FOOTNOTE,
BlockType.IMAGE_FOOTNOTE,
BlockType.TABLE_FOOTNOTE,
BlockType.CHART_FOOTNOTE,
BlockType.TEXT,
- BlockType.TITLE,
BlockType.INTERLINE_EQUATION,
- BlockType.EQUATION,
BlockType.LIST,
BlockType.INDEX,
- BlockType.DISCARDED,
BlockType.CODE,
BlockType.CODE_BODY,
BlockType.CODE_CAPTION,
BlockType.CODE_FOOTNOTE,
- BlockType.ALGORITHM,
BlockType.REF_TEXT,
- BlockType.PHONETIC,
BlockType.HEADER,
BlockType.FOOTER,
BlockType.PAGE_NUMBER,
BlockType.ASIDE_TEXT,
BlockType.PAGE_FOOTNOTE,
- BlockType.ABSTRACT,
BlockType.DOC_TITLE,
BlockType.PARAGRAPH_TITLE,
- BlockType.VERTICAL_TEXT,
- BlockType.HEADER_IMAGE,
- BlockType.FOOTER_IMAGE,
BlockType.FORMULA_NUMBER,
]
@@ -179,40 +171,28 @@ BLOCK_TYPES = {
BlockType.IMAGE_BODY,
BlockType.TABLE_BODY,
BlockType.CHART_BODY,
- BlockType.CAPTION,
BlockType.IMAGE_CAPTION,
BlockType.TABLE_CAPTION,
BlockType.CHART_CAPTION,
- BlockType.ALGORITHM_CAPTION,
- BlockType.FOOTNOTE,
BlockType.IMAGE_FOOTNOTE,
BlockType.TABLE_FOOTNOTE,
BlockType.CHART_FOOTNOTE,
BlockType.TEXT,
- BlockType.TITLE,
BlockType.INTERLINE_EQUATION,
- BlockType.EQUATION,
BlockType.LIST,
BlockType.INDEX,
- BlockType.DISCARDED,
BlockType.CODE,
BlockType.CODE_BODY,
BlockType.CODE_CAPTION,
BlockType.CODE_FOOTNOTE,
- BlockType.ALGORITHM,
BlockType.REF_TEXT,
- BlockType.PHONETIC,
BlockType.HEADER,
BlockType.FOOTER,
BlockType.PAGE_NUMBER,
BlockType.ASIDE_TEXT,
BlockType.PAGE_FOOTNOTE,
- BlockType.ABSTRACT,
BlockType.DOC_TITLE,
BlockType.PARAGRAPH_TITLE,
- BlockType.VERTICAL_TEXT,
- BlockType.HEADER_IMAGE,
- BlockType.FOOTER_IMAGE,
BlockType.FORMULA_NUMBER,
}
@@ -309,255 +289,661 @@ BBox: TypeAlias = tuple[float, float, float, float]
IntBBox: 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
-def _initvar_default(value: Any, default: Any) -> Any:
- """修正 InitVar 与同名 property 共存时产生的 property 默认值。"""
- return default if isinstance(value, property) else value
+class _StrictMiddleModel(BaseModel):
+ """Middle JSON 严格模型基类,提供无副作用的统一序列化入口。"""
-EMPTY_BBOX: BBox = (0.0, 0.0, 0.0, 0.0)
+ 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]
-def _origin_is_list(tp: Any) -> bool:
- return getattr(tp, "__origin__", None) is list
+class TextBlock(BlockBase):
+ type: Literal[BlockType.TEXT]
+ content: str
+ continues_prev: bool | None = None
-def _list_arg(tp: Any) -> Any | None:
- args = getattr(tp, "__args__", None)
- return args[0] if args else None
+class RefTextBlock(BlockBase):
+ type: Literal[BlockType.REF_TEXT]
+ content: str
-@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 DocTitleBlock(BlockBase):
+ type: Literal[BlockType.DOC_TITLE]
+ content: str
+ anchor: str | None = None
+
+
+class ParagraphTitleBlock(BlockBase):
+ type: Literal[BlockType.PARAGRAPH_TITLE]
+ content: str
+ anchor: str | None = None
+ level: int | None = Field(default=None, ge=1)
+
+
+class AsideTextBlock(BlockBase):
+ type: Literal[BlockType.ASIDE_TEXT]
+ content: str
+
+
+class HeaderBlock(BlockBase):
+ type: Literal[BlockType.HEADER]
+ content: str
+
+
+class FooterBlock(BlockBase):
+ type: Literal[BlockType.FOOTER]
+ content: str
+
+
+class PageNumberBlock(BlockBase):
+ type: Literal[BlockType.PAGE_NUMBER]
+ content: str
- 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 PageFootnoteBlock(BlockBase):
+ type: Literal[BlockType.PAGE_FOOTNOTE]
+ content: str
+
+
+class FormulaNumberBlock(BlockBase):
+ type: Literal[BlockType.FORMULA_NUMBER]
+ content: str
+
+
+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("_"):
- continue
- if f.name not in d:
+ 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 InterlineEquationBlock(ImagePayloadBlock):
+ type: Literal[BlockType.INTERLINE_EQUATION]
+ content: str
+
+
+class ImageBodyBlock(ImagePayloadBlock):
+ type: Literal[BlockType.IMAGE_BODY]
+ content: str | None
+
+
+class TableBodyBlock(ImagePayloadBlock):
+ type: Literal[BlockType.TABLE_BODY]
+ content: str
+ cell_merge: list[Literal[0, 1]] | None = None
+
+
+class ChartBodyBlock(ImagePayloadBlock):
+ type: Literal[BlockType.CHART_BODY]
+ content: str | None
+
+
+class CodeBodyBlock(BlockBase):
+ type: Literal[BlockType.CODE_BODY]
+ content: str
+
+
+class ImageCaptionBlock(BlockBase):
+ type: Literal[BlockType.IMAGE_CAPTION]
+ content: str
+
+
+class ImageFootnoteBlock(BlockBase):
+ type: Literal[BlockType.IMAGE_FOOTNOTE]
+ content: str
+
+
+class TableCaptionBlock(BlockBase):
+ type: Literal[BlockType.TABLE_CAPTION]
+ content: str
+
+
+class TableFootnoteBlock(BlockBase):
+ type: Literal[BlockType.TABLE_FOOTNOTE]
+ content: str
+
+
+class ChartCaptionBlock(BlockBase):
+ type: Literal[BlockType.CHART_CAPTION]
+ content: str
+
+
+class ChartFootnoteBlock(BlockBase):
+ type: Literal[BlockType.CHART_FOOTNOTE]
+ content: str
+
+
+class CodeCaptionBlock(BlockBase):
+ type: Literal[BlockType.CODE_CAPTION]
+ content: str
+
+
+class CodeFootnoteBlock(BlockBase):
+ type: Literal[BlockType.CODE_FOOTNOTE]
+ content: str
+
+
+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
+
+ @model_validator(mode="after")
+ def _validate_sub_type(self) -> ListBlock:
+ """存在 subtype 时,要求当前层直接文本子项与声明类型一致。"""
+ if self.sub_type is None:
+ return self
+ for child in self.content:
+ if isinstance(child, ListBlock):
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
- _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)
-
-
-@dataclass
-class OcrDetLineItem(TypedDict):
- """OCR 检测得到的归一化行框。"""
-
- bbox: list[float]
- type: Literal["line"]
-
-
-@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)
- content: str = ""
-
- # 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
- _ocr_det_lines: list[OcrDetLineItem] = 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 = ""
- _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 child.type != self.sub_type:
+ raise ValueError("list direct text children must match sub_type")
+ return self
- @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
- 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
+
+IndexChildBlock: TypeAlias = Annotated[
+ Union[TextBlock, "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, ImageCaptionBlock, ImageFootnoteBlock],
+ 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, TableCaptionBlock, TableFootnoteBlock],
+ Field(discriminator="type"),
+]
+
+
+class TableBlock(_VisualBlockBase):
+ type: Literal[BlockType.TABLE]
+ content: list[TableChildBlock]
+ continues_prev: bool | None = None
+ _body_type: ClassVar[str] = BlockType.TABLE_BODY
+
+
+ChartChildBlock: TypeAlias = Annotated[
+ Union[ChartBodyBlock, ChartCaptionBlock, ChartFootnoteBlock],
+ Field(discriminator="type"),
+]
+
+
+class ChartBlock(_VisualBlockBase):
+ type: Literal[BlockType.CHART]
+ content: list[ChartChildBlock]
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
+ _body_type: ClassVar[str] = BlockType.CHART_BODY
+
+
+CodeChildBlock: TypeAlias = Annotated[
+ Union[CodeBodyBlock, CodeCaptionBlock, CodeFootnoteBlock],
+ Field(discriminator="type"),
+]
+
+
+class CodeBlock(_VisualBlockBase):
+ type: Literal[BlockType.CODE]
+ content: list[CodeChildBlock]
+ sub_type: Literal[BlockType.CODE, BlockType.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()
+
+
+Block: TypeAlias = Annotated[
+ Union[
+ TextBlock,
+ RefTextBlock,
+ DocTitleBlock,
+ ParagraphTitleBlock,
+ AsideTextBlock,
+ HeaderBlock,
+ FooterBlock,
+ PageNumberBlock,
+ PageFootnoteBlock,
+ FormulaNumberBlock,
+ InterlineEquationBlock,
+ ListBlock,
+ IndexBlock,
+ ImageBodyBlock,
+ ImageCaptionBlock,
+ ImageFootnoteBlock,
+ ImageBlock,
+ TableBodyBlock,
+ TableCaptionBlock,
+ TableFootnoteBlock,
+ TableBlock,
+ ChartBodyBlock,
+ ChartCaptionBlock,
+ ChartFootnoteBlock,
+ ChartBlock,
+ CodeBodyBlock,
+ CodeCaptionBlock,
+ CodeFootnoteBlock,
+ 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[Block] = 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
+
+ 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 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
+ 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
+
+
+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(
+ "Export file path conflicts with a required directory: "
+ f"{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 --git a/mineru/utils/image_payload.py b/mineru/utils/image_payload.py
index f1391f57..0df6827d 100644
--- a/mineru/utils/image_payload.py
+++ b/mineru/utils/image_payload.py
@@ -2,8 +2,10 @@
from __future__ import annotations
import base64
+import binascii
from pathlib import Path, PureWindowsPath
import re
+import xml.etree.ElementTree as ElementTree
from .hash_utils import str_sha256
@@ -36,6 +38,50 @@ def parse_image_data_uri(data_uri: str) -> tuple[bytes, str] | None:
return None
+def parse_image_data_uri_strict(data_uri: str) -> tuple[bytes, str]:
+ """严格解析图片 data URI,并同时校验 MIME 与文件签名是否一致。"""
+ match = re.fullmatch(r"data:image/([^;]+);base64,([A-Za-z0-9+/]*={0,2})", data_uri)
+ if match is None:
+ raise ValueError("Invalid image data URI")
+
+ mime_subtype = match.group(1).lower()
+ extension = normalize_image_extension(mime_subtype)
+ try:
+ payload = base64.b64decode(match.group(2), validate=True)
+ except (binascii.Error, ValueError) as exc:
+ raise ValueError("Invalid base64 image payload") from exc
+ if not payload:
+ raise ValueError("Image payload must not be empty")
+
+ if extension == "svg":
+ if mime_subtype != "svg+xml":
+ raise ValueError(f"Unsupported image MIME subtype: {mime_subtype}")
+ try:
+ svg_root = ElementTree.fromstring(payload)
+ except ElementTree.ParseError as exc:
+ raise ValueError("Invalid SVG image payload") from exc
+ if not isinstance(svg_root.tag, str) or svg_root.tag.rsplit("}", 1)[-1].lower() != "svg":
+ raise ValueError("Image signature does not match MIME subtype: svg+xml")
+ return payload, extension
+
+ signatures: dict[str, tuple[bytes, ...]] = {
+ "jpg": (b"\xff\xd8\xff",),
+ "png": (b"\x89PNG\r\n\x1a\n",),
+ "gif": (b"GIF87a", b"GIF89a"),
+ "webp": (b"RIFF",),
+ "bmp": (b"BM",),
+ "tiff": (b"II*\x00", b"MM\x00*"),
+ }
+ expected = signatures.get(extension)
+ if expected is None:
+ raise ValueError(f"Unsupported image MIME subtype: {mime_subtype}")
+ if not any(payload.startswith(signature) for signature in expected):
+ raise ValueError(f"Image signature does not match MIME subtype: {mime_subtype}")
+ if extension == "webp" and (len(payload) < 12 or payload[8:12] != b"WEBP"):
+ raise ValueError("Image signature does not match MIME subtype: webp")
+ return payload, extension
+
+
def image_path_from_data_uri(data_uri: str) -> str | None:
"""根据 data URI 内容生成稳定图片路径,供没有显式 image_path 的 span 使用。"""
parsed = parse_image_data_uri(data_uri)
@@ -132,6 +178,9 @@ def validate_image_sidecar_path(image_path: str) -> str:
windows_path = PureWindowsPath(image_path)
if (
not image_path
+ or image_path == "."
+ or "\x00" in image_path
+ or "\\" in image_path
or posix_path.is_absolute()
or windows_path.is_absolute()
or windows_path.drive
diff --git a/mineru/utils/pdf_document.py b/mineru/utils/pdf_document.py
index 223f41f7..c6b1dd72 100644
--- a/mineru/utils/pdf_document.py
+++ b/mineru/utils/pdf_document.py
@@ -20,7 +20,6 @@ from pdftext.schema import Bbox, Char, Line
from PIL import Image, ImageOps
from ..types import BBox, PageInfo
-from .draw_bbox import draw_layout_bbox, draw_span_bbox
from .pdf_classify import classify, get_sample_page_indices
from .pdf_image_tools import get_crop_img, load_images_from_pdf_bytes_range
from .pdf_reader import image_to_bytes
@@ -449,11 +448,15 @@ class PDFDocument:
# ------------------------------------------------------------------ #
def draw_layout_bbox(self, pages: list[PageInfo], output_path: str) -> None:
+ from .draw_bbox import draw_layout_bbox
+
out_dir = os.path.dirname(output_path) or "."
filename = os.path.basename(output_path)
draw_layout_bbox(pages, self._pdf_bytes, out_dir, filename)
def draw_span_bbox(self, pages: list[PageInfo], output_path: str) -> None:
+ from .draw_bbox import draw_span_bbox
+
out_dir = os.path.dirname(output_path) or "."
filename = os.path.basename(output_path)
draw_span_bbox(pages, self._pdf_bytes, out_dir, filename)
diff --git a/tests/unittest/test_flash_office_title_types.py b/tests/unittest/test_flash_office_title_types.py
index d92a065d..cf09315e 100644
--- a/tests/unittest/test_flash_office_title_types.py
+++ b/tests/unittest/test_flash_office_title_types.py
@@ -53,8 +53,8 @@ def _set_subtitle(slide: Any, text: str) -> None:
subtitle.text = text
-def test_office_models_store_standalone_images_in_private_image_base64() -> None:
- """验证三类 Office model 的独立图片只通过 _image_base64 输出。"""
+def test_office_models_store_standalone_images_in_image_base64() -> None:
+ """验证三类 Office model 的独立图片统一通过 image_base64 输出。"""
for suffix, model in (
("docx", DocxModel()),
("pptx", PptxModel()),
@@ -69,13 +69,13 @@ def test_office_models_store_standalone_images_in_private_image_base64() -> None
assert image_blocks, suffix
for block in image_blocks:
assert "content" not in block
- assert isinstance(block.get("_image_base64"), str)
- assert block["_image_base64"].startswith("data:image/")
- assert ";base64," in block["_image_base64"]
+ assert isinstance(block.get("image_base64"), str)
+ assert block["image_base64"].startswith("data:image/")
+ assert ";base64," in block["image_base64"]
-def test_pptx_svg_picture_uses_private_image_base64(monkeypatch: Any) -> None:
- """验证 PPTX SVG 图片分支同样使用 _image_base64 字段。"""
+def test_pptx_svg_picture_uses_image_base64(monkeypatch: Any) -> None:
+ """验证 PPTX SVG 图片分支同样使用统一 image_base64 字段。"""
converter = PptxConverter()
def fake_get_shape_image_data(_shape: Any) -> tuple[bytes, str]:
@@ -89,7 +89,7 @@ def test_pptx_svg_picture_uses_private_image_base64(monkeypatch: Any) -> None:
assert converter.cur_page == [
{
"type": BlockType.IMAGE,
- "_image_base64": "data:image/svg+xml;base64,PHN2Zy8+",
+ "image_base64": "data:image/svg+xml;base64,PHN2Zy8+",
}
]
diff --git a/tests/unittest/test_magic_model.py b/tests/unittest/test_magic_model.py
index dd2b4abb..2d62af7c 100644
--- a/tests/unittest/test_magic_model.py
+++ b/tests/unittest/test_magic_model.py
@@ -46,7 +46,7 @@ def test_magic_model_groups_bbox_dict_visual_blocks() -> None:
{
"type": BlockType.IMAGE,
"bbox": [0.0, 15.0, 80.0, 60.0],
- "_image_base64": "data:image/jpeg;base64,image",
+ "image_base64": "data:image/jpeg;base64,image",
},
]
)
@@ -66,7 +66,7 @@ def test_magic_model_groups_no_bbox_office_caption_by_prefix() -> None:
[
{
"type": BlockType.IMAGE,
- "_image_base64": "data:image/jpeg;base64,image",
+ "image_base64": "data:image/jpeg;base64,image",
},
{
"type": BlockType.TEXT,
diff --git a/tests/unittest/test_middle_json_block_models.py b/tests/unittest/test_middle_json_block_models.py
new file mode 100644
index 00000000..6f831827
--- /dev/null
+++ b/tests/unittest/test_middle_json_block_models.py
@@ -0,0 +1,288 @@
+from __future__ import annotations
+
+from copy import deepcopy
+
+import pytest
+from pydantic import ValidationError
+
+import mineru.types as types_module
+from mineru.types import (
+ BLOCK_TYPES,
+ CodeBlock,
+ ListBlock,
+ MiddleJson,
+ PageInfo,
+ TextBlock,
+ parse_block,
+)
+
+
+def _public_block_payloads() -> dict[str, dict[str, object]]:
+ """构造 29 个公开 discriminator 的最小合法载荷。"""
+ text_leaf = {"type": "text", "content": "item"}
+ payloads: dict[str, dict[str, object]] = {
+ "aside_text": {"type": "aside_text", "content": "aside"},
+ "doc_title": {"type": "doc_title", "content": "title"},
+ "footer": {"type": "footer", "content": "footer"},
+ "formula_number": {"type": "formula_number", "content": "(1)"},
+ "header": {"type": "header", "content": "header"},
+ "index": {"type": "index", "content": [text_leaf]},
+ "interline_equation": {"type": "interline_equation", "content": "x=1"},
+ "list": {"type": "list", "content": [text_leaf]},
+ "page_footnote": {"type": "page_footnote", "content": "note"},
+ "page_number": {"type": "page_number", "content": "1"},
+ "paragraph_title": {"type": "paragraph_title", "content": "section"},
+ "ref_text": {"type": "ref_text", "content": "reference"},
+ "text": {"type": "text", "content": "text"},
+ "image_body": {"type": "image_body", "content": None},
+ "image_caption": {"type": "image_caption", "content": "caption"},
+ "image_footnote": {"type": "image_footnote", "content": "note"},
+ "table_body": {"type": "table_body", "content": "<table></table>"},
+ "table_caption": {"type": "table_caption", "content": "caption"},
+ "table_footnote": {"type": "table_footnote", "content": "note"},
+ "chart_body": {"type": "chart_body", "content": None},
+ "chart_caption": {"type": "chart_caption", "content": "caption"},
+ "chart_footnote": {"type": "chart_footnote", "content": "note"},
+ "code_body": {"type": "code_body", "content": "print(1)"},
+ "code_caption": {"type": "code_caption", "content": "caption"},
+ "code_footnote": {"type": "code_footnote", "content": "note"},
+ }
+ payloads.update(
+ {
+ "image": {"type": "image", "content": [payloads["image_body"]]},
+ "table": {"type": "table", "content": [payloads["table_body"]]},
+ "chart": {"type": "chart", "content": [payloads["chart_body"]]},
+ "code": {
+ "type": "code",
+ "content": [payloads["code_body"]],
+ "sub_type": "code",
+ "guess_lang": "python",
+ },
+ }
+ )
+ return payloads
+
+
+def test_all_29_public_discriminators_parse_to_concrete_models() -> None:
+ """验证公开类型集合与 discriminated union 完整一致。"""
+ payloads = _public_block_payloads()
+
+ assert set(payloads) == BLOCK_TYPES
+ assert len(payloads) == 29
+ assert all(parse_block(payload).type == block_type for block_type, payload in payloads.items())
+
+
[email protected]("raw_type", ["algorithm", "caption", "equation", "footnote", "title", "phonetic"])
+def test_raw_only_types_are_rejected(raw_type: str) -> None:
+ """验证 Analyze 私有 raw type 不能越过公开对象边界。"""
+ with pytest.raises(ValidationError):
+ parse_block({"type": raw_type, "content": "raw"})
+
+
+def test_cross_type_fields_and_unknown_fields_are_rejected() -> None:
+ """验证 Text/RefText 的专属字段边界与 extra forbid。"""
+ with pytest.raises(ValidationError):
+ parse_block({"type": "text", "content": "x", "anchor": "a"})
+ with pytest.raises(ValidationError):
+ parse_block({"type": "ref_text", "content": "x", "continues_prev": True})
+ with pytest.raises(ValidationError):
+ parse_block({"type": "text", "content": "x", "unknown": 1})
+
+
+def test_every_public_block_rejects_removed_merge_field() -> None:
+ """验证已废弃合并字段不会被任一公开 block 静默接收。"""
+ for payload in _public_block_payloads().values():
+ invalid_payload = deepcopy(payload)
+ invalid_payload["merge_prev"] = False
+ with pytest.raises(ValidationError):
+ parse_block(invalid_payload)
+
+
+def test_removed_block_classes_are_not_exposed() -> None:
+ """验证未采用的旧 block 类没有重新进入公开对象体系。"""
+ removed_names = (
+ "TitleBlock",
+ "HeaderImageBlock",
+ "FooterImageBlock",
+ "_DocElement",
+ "Span",
+ "Line",
+ "ContentItem",
+ "EMPTY_BBOX",
+ "_is_default_value",
+ "_origin_is_list",
+ "_list_arg",
+ )
+ for removed_name in removed_names:
+ assert not hasattr(types_module, removed_name)
+
+
+ "bbox",
+ [(-0.1, 0.1, 0.8, 0.8), (0.1, 0.1, 1.1, 0.8), (0.5, 0.1, 0.5, 0.8), (0.1, 0.8, 0.5, 0.2)],
+)
+def test_bbox_must_be_normalized_and_positive(bbox: tuple[float, ...]) -> None:
+ """验证 bbox 必须有限、归一化且具有正面积。"""
+ with pytest.raises(ValidationError):
+ parse_block({"type": "text", "content": "x", "bbox": bbox})
+
+
+def test_recursive_list_and_index_round_trip() -> None:
+ """验证四层 List 与递归 Index 的顺序和具体类型可无损恢复。"""
+ list_payload: dict[str, object] = {"type": "text", "content": "leaf"}
+ for _ in range(4):
+ list_payload = {"type": "list", "content": [{"type": "text", "content": "item"}, list_payload]}
+ index_payload = {
+ "type": "index",
+ "content": [{"type": "text", "content": "one"}, {"type": "index", "content": [{"type": "text", "content": "two"}]}],
+ }
+
+ list_block = parse_block(list_payload)
+ index_block = parse_block(index_payload)
+
+ assert isinstance(list_block, ListBlock)
+ assert isinstance(list_block.content[1], ListBlock)
+ assert [child.content for child in index_block.content if isinstance(child, TextBlock)] == ["one"]
+ assert parse_block(list_block.to_dict(skip_defaults=False)) == list_block
+ assert parse_block(index_block.to_dict(skip_defaults=False)) == index_block
+
+
+def test_list_subtype_must_match_direct_text_children() -> None:
+ """验证 List subtype 只约束当前层直接文本子项。"""
+ with pytest.raises(ValidationError, match="match sub_type"):
+ parse_block({"type": "list", "sub_type": "ref_text", "content": [{"type": "text", "content": "x"}]})
+ block = parse_block(
+ {
+ "type": "list",
+ "sub_type": "text",
+ "content": [
+ {"type": "text", "content": "x"},
+ {"type": "list", "sub_type": "ref_text", "content": [{"type": "ref_text", "content": "r"}]},
+ ],
+ }
+ )
+ assert isinstance(block, ListBlock)
+
+
[email protected]("visual_type", ["image", "table", "chart", "code"])
+def test_visual_parent_requires_exactly_one_body(visual_type: str) -> None:
+ """验证视觉父块必须且只能包含一个对应 body。"""
+ payload = deepcopy(_public_block_payloads()[visual_type])
+ payload["content"] = []
+ with pytest.raises(ValidationError, match="exactly one"):
+ parse_block(payload)
+
+
+def test_visual_parent_body_location_contract() -> None:
+ """验证视觉 parent/body 的 index 和同时存在的 bbox 必须一致。"""
+ with pytest.raises(ValidationError, match="index"):
+ parse_block(
+ {
+ "type": "image",
+ "index": 1,
+ "content": [{"type": "image_body", "index": 2, "content": None}],
+ }
+ )
+ with pytest.raises(ValidationError, match="bbox"):
+ parse_block(
+ {
+ "type": "image",
+ "bbox": [0.1, 0.1, 0.9, 0.9],
+ "content": [{"type": "image_body", "bbox": [0.2, 0.2, 0.8, 0.8], "content": None}],
+ }
+ )
+
+
+def test_code_subtype_controls_guess_language() -> None:
+ """验证 code 必须有语言,而 algorithm 禁止语言字段。"""
+ with pytest.raises(ValidationError):
+ parse_block({"type": "code", "sub_type": "code", "content": [{"type": "code_body", "content": "x"}]})
+ with pytest.raises(ValidationError):
+ parse_block(
+ {
+ "type": "code",
+ "sub_type": "algorithm",
+ "guess_lang": "python",
+ "content": [{"type": "code_body", "content": "x"}],
+ }
+ )
+ assert isinstance(
+ parse_block({"type": "code", "sub_type": "algorithm", "content": [{"type": "code_body", "content": "x"}]}),
+ CodeBlock,
+ )
+
+
+def test_page_info_requires_unique_strictly_increasing_top_indices() -> None:
+ """验证顶层 index 必填、唯一、严格递增,但允许缺号。"""
+ page = PageInfo(
+ page_idx=0,
+ blocks=[
+ TextBlock(type="text", index=2, content="a"),
+ TextBlock(type="text", index=8, content="b"),
+ ],
+ )
+ assert [block.index for block in page.blocks] == [2, 8]
+ with pytest.raises(ValidationError):
+ PageInfo(page_idx=0, blocks=[TextBlock(type="text", content="missing")])
+ with pytest.raises(ValidationError):
+ PageInfo(
+ page_idx=0,
+ blocks=[TextBlock(type="text", index=1, content="a"), TextBlock(type="text", index=1, content="b")],
+ )
+
+
+def test_nested_continues_prev_is_rejected_by_page_tree() -> None:
+ """验证 continues_prev 只能出现在页面顶层 text/list/table。"""
+ with pytest.raises(ValidationError, match="nested"):
+ PageInfo.model_validate(
+ {
+ "page_idx": 0,
+ "blocks": [
+ {
+ "type": "list",
+ "index": 0,
+ "content": [{"type": "text", "content": "x", "continues_prev": True}],
+ }
+ ],
+ }
+ )
+
+ with pytest.raises(ValidationError, match="nested"):
+ PageInfo.model_validate(
+ {
+ "page_idx": 0,
+ "blocks": [
+ {
+ "type": "list",
+ "index": 0,
+ "content": [{"type": "text", "content": "x", "continues_prev": None}],
+ }
+ ],
+ }
+ )
+
+
+def test_middle_json_pdf_requires_top_level_bbox_and_round_trips() -> None:
+ """验证 PDF 顶层 bbox 约束及 MiddleJson JSON 往返。"""
+ with pytest.raises(ValidationError, match="requires bbox"):
+ MiddleJson(
+ pages=[PageInfo(page_idx=0, blocks=[TextBlock(type="text", index=0, content="x")])],
+ file_suffix="pdf",
+ effort="flash",
+ parse_mode="txt",
+ mineru_version="test",
+ )
+ middle_json = MiddleJson(
+ pages=[
+ PageInfo(
+ page_idx=0,
+ blocks=[TextBlock(type="text", index=0, bbox=(0.1, 0.1, 0.9, 0.9), content="x")],
+ )
+ ],
+ file_suffix="pdf",
+ effort="flash",
+ parse_mode="txt",
+ mineru_version="test",
+ )
+ restored = MiddleJson.model_validate_json(middle_json.to_json())
+ assert restored == middle_json
diff --git a/tests/unittest/test_middle_json_export.py b/tests/unittest/test_middle_json_export.py
new file mode 100644
index 00000000..d275283c
--- /dev/null
+++ b/tests/unittest/test_middle_json_export.py
@@ -0,0 +1,336 @@
+from __future__ import annotations
+
+import base64
+import json
+import os
+from pathlib import Path
+
+import pytest
+
+from mineru.types import MiddleJson, PageInfo, TableBlock, TableBodyBlock
+
+
+def _data_uri(mime_subtype: str, payload: bytes) -> str:
+ """把测试图片字节编码为 data URI。"""
+ return f"data:image/{mime_subtype};base64,{base64.b64encode(payload).decode('ascii')}"
+
+
+def _middle_json_with_table(body: TableBodyBlock) -> MiddleJson:
+ """构造只包含一个表格载体的最小 Office MiddleJson。"""
+ table = TableBlock(type="table", index=body.index, content=[body])
+ return MiddleJson(
+ pages=[PageInfo(page_idx=3, blocks=[table])],
+ file_suffix="docx",
+ effort="flash",
+ parse_mode="txt",
+ mineru_version="test",
+ )
+
+
+def test_full_serialization_round_trip_and_recursive_field_exclusion() -> None:
+ """验证完整 dump 保留图片,而递归排除不遗漏 visual 子块。"""
+ jpeg_uri = _data_uri("jpeg", b"\xff\xd8\xffpayload\xff\xd9")
+ middle_json = _middle_json_with_table(
+ TableBodyBlock(type="table_body", index=0, content="<table></table>", image_base64=jpeg_uri)
+ )
+
+ full_json = middle_json.to_json(indent=None)
+ excluded = middle_json.to_dict(exclude_block_fields={"image_base64"})
+
+ assert jpeg_uri in full_json
+ assert MiddleJson.model_validate_json(full_json) == middle_json
+ assert "image_base64" not in excluded["pages"][0]["blocks"][0]["content"][0]
+
+
+def test_export_writes_direct_and_multiple_html_images_without_mutating_source(tmp_path: Path) -> None:
+ """验证直接图片与 HTML 多图采用确定性命名,导出副本不污染原对象。"""
+ jpeg_payload = b"\xff\xd8\xffjpeg\xff\xd9"
+ gif_payload = b"GIF89agif"
+ png_payload = b"\x89PNG\r\n\x1a\npng"
+ jpeg_uri = _data_uri("jpeg", jpeg_payload)
+ gif_uri = _data_uri("gif", gif_payload)
+ png_uri = _data_uri("png", png_payload)
+ html = f'<table><img src="{gif_uri}"><img src="{png_uri}"></table>'
+ middle_json = _middle_json_with_table(
+ TableBodyBlock(type="table_body", index=4, content=html, image_base64=jpeg_uri)
+ )
+
+ result = middle_json.export(tmp_path)
+ exported_json = result.json_path.read_text()
+ exported_body = result.middle_json.pages[0].blocks[0].content[0]
+
+ assert {path.name for path in result.image_paths} == {
+ "page_3_table_body_4.jpg",
+ "page_3_table_body_4_1.gif",
+ "page_3_table_body_4_2.png",
+ }
+ assert (tmp_path / "images/page_3_table_body_4.jpg").read_bytes() == jpeg_payload
+ assert (tmp_path / "images/page_3_table_body_4_1.gif").read_bytes() == gif_payload
+ assert (tmp_path / "images/page_3_table_body_4_2.png").read_bytes() == png_payload
+ assert exported_body.image_path == "images/page_3_table_body_4.jpg"
+ assert exported_body.image_base64 is None
+ assert "images/page_3_table_body_4_1.gif" in exported_body.content
+ assert "images/page_3_table_body_4_2.png" in exported_body.content
+ assert "image_base64" not in exported_json
+ assert "data:image/" not in exported_json
+ assert middle_json.pages[0].blocks[0].content[0].image_base64 == jpeg_uri
+ assert "data:image/" in middle_json.pages[0].blocks[0].content[0].content
+
+
+def test_export_supports_strict_svg_payload(tmp_path: Path) -> None:
+ """验证 PPTX 可能产出的 SVG data URI 可按 XML 根元素严格校验并外置。"""
+ svg_payload = b'<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1"></svg>'
+ middle_json = _middle_json_with_table(
+ TableBodyBlock(
+ type="table_body",
+ index=2,
+ content="<table></table>",
+ image_base64=_data_uri("svg+xml", svg_payload),
+ )
+ )
+
+ result = middle_json.export(tmp_path)
+
+ assert (tmp_path / "images/page_3_table_body_2.svg").read_bytes() == svg_payload
+ assert result.middle_json.pages[0].blocks[0].content[0].image_path.endswith(".svg")
+
+
+def test_export_supports_direct_png_and_html_jpeg(tmp_path: Path) -> None:
+ """验证直接 PNG 与 Office 表格 HTML 内嵌 JPEG 都能按各自格式外置。"""
+ png_payload = b"\x89PNG\r\n\x1a\npng"
+ jpeg_payload = b"\xff\xd8\xffjpeg\xff\xd9"
+ jpeg_uri = _data_uri("jpeg", jpeg_payload)
+ middle_json = _middle_json_with_table(
+ TableBodyBlock(
+ type="table_body",
+ index=5,
+ content=f'<table><img src="{jpeg_uri}"></table>',
+ image_base64=_data_uri("png", png_payload),
+ )
+ )
+
+ result = middle_json.export(tmp_path)
+
+ assert (tmp_path / "images/page_3_table_body_5.png").read_bytes() == png_payload
+ assert (tmp_path / "images/page_3_table_body_5_1.jpg").read_bytes() == jpeg_payload
+ assert "images/page_3_table_body_5_1.jpg" in result.middle_json.pages[0].blocks[0].content[0].content
+
+
+ "data_uri",
+ [
+ "data:image/jpeg;base64,not-base64!",
+ _data_uri("png", b"\xff\xd8\xffwrong-mime\xff\xd9"),
+ _data_uri("avif", b"unsupported-format"),
+ _data_uri("svg+xml", b"<html></html>"),
+ ],
+)
+def test_export_rejects_invalid_payload_before_writing(tmp_path: Path, data_uri: str) -> None:
+ """验证非法 base64、MIME 签名不符和不支持格式均不会产生半成品。"""
+ output_dir = tmp_path / "output"
+ middle_json = _middle_json_with_table(
+ TableBodyBlock(type="table_body", index=0, content="<table></table>", image_base64=data_uri)
+ )
+
+ with pytest.raises(ValueError):
+ middle_json.export(output_dir)
+
+ assert not output_dir.exists()
+
+
+def test_export_rejects_unparsed_inline_data_uri_before_writing(tmp_path: Path) -> None:
+ """验证不符合 base64 data URI 语法的 HTML 图片不会原样泄漏到导出 JSON。"""
+ output_dir = tmp_path / "output"
+ middle_json = _middle_json_with_table(
+ TableBodyBlock(
+ type="table_body",
+ index=0,
+ content='<table><img src="data:image/jpeg,raw-payload"></table>',
+ )
+ )
+
+ with pytest.raises(ValueError, match="inline image data URI"):
+ middle_json.export(output_dir)
+
+ assert not output_dir.exists()
+
+
+def test_export_preflights_conflicts_and_supports_explicit_overwrite(tmp_path: Path) -> None:
+ """验证同名同内容可复用、不同内容默认报错且 overwrite 可替换。"""
+ first_payload = b"\xff\xd8\xfffirst\xff\xd9"
+ second_payload = b"\xff\xd8\xffsecond\xff\xd9"
+ first = _middle_json_with_table(
+ TableBodyBlock(
+ type="table_body",
+ index=0,
+ content="<table></table>",
+ image_base64=_data_uri("jpeg", first_payload),
+ )
+ )
+ second = _middle_json_with_table(
+ TableBodyBlock(
+ type="table_body",
+ index=0,
+ content="<table></table>",
+ image_base64=_data_uri("jpeg", second_payload),
+ )
+ )
+
+ first.export(tmp_path)
+ first.export(tmp_path)
+ image_path = tmp_path / "images/page_3_table_body_0.jpg"
+ with pytest.raises(FileExistsError):
+ second.export(tmp_path)
+ assert image_path.read_bytes() == first_payload
+
+ second.export(tmp_path, overwrite=True)
+ assert image_path.read_bytes() == second_payload
+
+
+def test_export_conflicting_json_rolls_back_before_any_image_write(tmp_path: Path) -> None:
+ """验证 JSON 冲突在提交前被发现,不会先留下图片 sidecar。"""
+ (tmp_path / "middle_json.json").write_text("occupied")
+ middle_json = _middle_json_with_table(
+ TableBodyBlock(
+ type="table_body",
+ index=9,
+ content="<table></table>",
+ image_base64=_data_uri("jpeg", b"\xff\xd8\xffpayload\xff\xd9"),
+ )
+ )
+
+ with pytest.raises(FileExistsError):
+ middle_json.export(tmp_path)
+
+ assert not (tmp_path / "images/page_3_table_body_9.jpg").exists()
+ assert (tmp_path / "middle_json.json").read_text() == "occupied"
+
+
+def test_export_restores_existing_files_after_commit_failure(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """验证提交中途失败时会恢复已覆盖文件,并清理全部临时文件。"""
+ image_path = tmp_path / "images/page_3_table_body_0.jpg"
+ image_path.parent.mkdir()
+ image_path.write_bytes(b"old-image")
+ json_path = tmp_path / "middle_json.json"
+ json_path.write_bytes(b"old-json")
+ middle_json = _middle_json_with_table(
+ TableBodyBlock(
+ type="table_body",
+ index=0,
+ content="<table></table>",
+ image_base64=_data_uri("jpeg", b"\xff\xd8\xffnew-image\xff\xd9"),
+ )
+ )
+ original_replace = os.replace
+ replace_count = 0
+
+ def fail_second_replace(source: str | Path, target: str | Path) -> None:
+ """模拟第二个文件提交失败,以覆盖事务回滚分支。"""
+ nonlocal replace_count
+ replace_count += 1
+ if replace_count == 2:
+ raise OSError("simulated commit failure")
+ original_replace(source, target)
+
+ monkeypatch.setattr("mineru.types.os.replace", fail_second_replace)
+
+ with pytest.raises(OSError, match="simulated commit failure"):
+ middle_json.export(tmp_path, overwrite=True)
+
+ assert image_path.read_bytes() == b"old-image"
+ assert json_path.read_bytes() == b"old-json"
+ assert not list(tmp_path.rglob(".mineru-export-*"))
+
+
[email protected]("json_name", ["../middle.json", "/tmp/middle.json", "..\\middle.json"])
+def test_export_rejects_path_escape(tmp_path: Path, json_name: str) -> None:
+ """验证 JSON 输出名不能使用绝对路径或逃逸文档目录。"""
+ middle_json = _middle_json_with_table(
+ TableBodyBlock(type="table_body", index=0, content="<table></table>")
+ )
+ with pytest.raises(ValueError):
+ middle_json.export(tmp_path, json_name=json_name)
+
+
+def test_export_rejects_file_and_directory_path_collision(tmp_path: Path) -> None:
+ """验证 JSON 文件名不能占用图片 sidecar 所需的 images 目录。"""
+ output_dir = tmp_path / "output"
+ middle_json = _middle_json_with_table(
+ TableBodyBlock(
+ type="table_body",
+ index=0,
+ content="<table></table>",
+ image_base64=_data_uri("jpeg", b"\xff\xd8\xffpayload\xff\xd9"),
+ )
+ )
+
+ with pytest.raises(ValueError, match="required directory"):
+ middle_json.export(output_dir, json_name="images")
+
+ assert not output_dir.exists()
+
+
+def test_export_rejects_symlink_output_directory(tmp_path: Path) -> None:
+ """验证导出根目录是符号链接时直接拒绝写入。"""
+ actual_dir = tmp_path / "actual"
+ actual_dir.mkdir()
+ link_dir = tmp_path / "link"
+ os.symlink(actual_dir, link_dir)
+ middle_json = _middle_json_with_table(
+ TableBodyBlock(type="table_body", index=0, content="<table></table>")
+ )
+
+ with pytest.raises(ValueError, match="symlink"):
+ middle_json.export(link_dir)
+
+ assert list(actual_dir.iterdir()) == []
+
+
+def test_export_rejects_symlink_sidecar_directory(tmp_path: Path) -> None:
+ """验证图片子目录是符号链接时不会跟随链接写到文档目录之外。"""
+ outside_dir = tmp_path / "outside"
+ outside_dir.mkdir()
+ output_dir = tmp_path / "output"
+ output_dir.mkdir()
+ os.symlink(outside_dir, output_dir / "images")
+ middle_json = _middle_json_with_table(
+ TableBodyBlock(
+ type="table_body",
+ index=0,
+ content="<table></table>",
+ image_base64=_data_uri("jpeg", b"\xff\xd8\xffpayload\xff\xd9"),
+ )
+ )
+
+ with pytest.raises(ValueError, match="symlink"):
+ middle_json.export(output_dir)
+
+ assert list(outside_dir.iterdir()) == []
+
+
+def test_image_path_is_validated_during_deserialization() -> None:
+ """验证对象边界拒绝绝对路径、目录逃逸和 Windows 反斜杠路径。"""
+ for image_path in ("/tmp/image.jpg", "../image.jpg", "images\\image.jpg"):
+ with pytest.raises(ValueError):
+ TableBodyBlock(
+ type="table_body",
+ index=0,
+ content="<table></table>",
+ image_path=image_path,
+ )
+
+
+def test_exported_json_is_a_pure_middle_json_object(tmp_path: Path) -> None:
+ """验证导出 JSON 可独立严格反序列化且不依赖导出结果包装对象。"""
+ middle_json = _middle_json_with_table(
+ TableBodyBlock(type="table_body", index=0, content="<table></table>")
+ )
+ result = middle_json.export(tmp_path)
+
+ payload = json.loads(result.json_path.read_text())
+ restored = MiddleJson.model_validate(payload)
+
+ assert restored == result.middle_json
diff --git a/tests/unittest/test_model_list_to_midlle_json.py b/tests/unittest/test_model_list_to_midlle_json.py
index 03633793..17bff98c 100644
--- a/tests/unittest/test_model_list_to_midlle_json.py
+++ b/tests/unittest/test_model_list_to_midlle_json.py
@@ -1,287 +1,206 @@
from copy import deepcopy
+import pytest
+
from mineru.backend.model_list_to_midlle_json import model_list_to_pages
-from mineru.types import BlockType
+from mineru.types import ImageBlock, ListBlock, PageInfo, ParagraphTitleBlock, TableBlock, TextBlock
-def test_model_list_to_pages_preserves_pdf_input() -> None:
- """验证 PDF 块完成规范化和分组后不会污染原始 model_list。"""
- model_list = [
- [
- {
- "type": BlockType.IMAGE_CAPTION,
- "bbox": [0, 0, 100, 10],
- "content": "Figure 1",
- },
- {
- "type": BlockType.IMAGE,
- "bbox": [0, 15, 100, 80],
- "image_base64": "data:image/jpeg;base64,image",
- },
- {
- "type": BlockType.EQUATION,
- "bbox": [0, 85, 100, 100],
- "content": r"\[x+1\]",
- },
- {
- "type": BlockType.LIST,
- "bbox": [0, 105, 100, 150],
- "content": "",
- },
- {
- "type": BlockType.TEXT,
- "bbox": [10, 110, 90, 125],
- "content": "list item",
- },
- {
- "type": BlockType.TABLE_CAPTION,
- "bbox": [0, 155, 100, 165],
- "content": "Table 1",
- },
- {
- "type": BlockType.TABLE,
- "bbox": [0, 170, 100, 240],
- "content": "<table></table>",
- },
- ]
- ]
- original_model_list = deepcopy(model_list)
+def test_model_list_to_pages_returns_typed_pdf_tree_without_mutating_input() -> None:
+ """验证 PDF raw dict 只在副本上分组,并返回具体 PageInfo/Block 对象。"""
+ model_list = [[
+ {"type": "image_caption", "bbox": [0.1, 0.05, 0.9, 0.1], "content": "Figure 1"},
+ {
+ "type": "image",
+ "bbox": [0.1, 0.12, 0.9, 0.45],
+ "content": None,
+ "image_base64": "data:image/jpeg;base64,/9j/2Q==",
+ },
+ {"type": "list", "bbox": [0.1, 0.5, 0.9, 0.8], "content": ""},
+ {"type": "text", "bbox": [0.15, 0.55, 0.85, 0.65], "content": "item"},
+ ]]
+ original = deepcopy(model_list)
pages = model_list_to_pages(model_list, page_index_map=[7])
- assert model_list == original_model_list
- assert pages[0]["page_idx"] == 7
- blocks_by_type = {block["type"]: block for block in pages[0]["blocks"]}
-
- image_block = blocks_by_type[BlockType.IMAGE]
- assert [block["type"] for block in image_block["content"]] == [
- BlockType.IMAGE_CAPTION,
- BlockType.IMAGE_BODY,
+ assert model_list == original
+ assert isinstance(pages[0], PageInfo)
+ assert pages[0].page_idx == 7
+ assert isinstance(pages[0].blocks[0], ImageBlock)
+ assert [child.type for child in pages[0].blocks[0].content] == [
+ "image_caption",
+ "image_body",
]
+ assert isinstance(pages[0].blocks[1], ListBlock)
+ assert isinstance(pages[0].blocks[1].content[0], TextBlock)
- equation_block = blocks_by_type[BlockType.INTERLINE_EQUATION]
- assert equation_block["content"] == "x+1"
- assert equation_block is not model_list[0][2]
- list_block = blocks_by_type[BlockType.LIST]
- assert list_block["content"] == [
+def test_model_list_to_pages_preserves_recursive_office_list_and_index() -> None:
+ """验证 Office list/index 任意深度递归对象化,并删除目录 text 的 anchor。"""
+ model_list = [[
{
- "type": BlockType.TEXT,
- "bbox": [10, 110, 90, 125],
- "content": "list item",
- "index": 4,
- }
- ]
- assert list_block["sub_type"] == BlockType.TEXT
-
- table_block = blocks_by_type[BlockType.TABLE]
- assert [block["type"] for block in table_block["content"]] == [
- BlockType.TABLE_CAPTION,
- BlockType.TABLE_BODY,
- ]
-
- equation_block["content"] = "changed"
- assert model_list == original_model_list
-
-
-def test_model_list_to_pages_preserves_office_nested_input() -> None:
- """验证 Office 嵌套列表和目录规范化不会污染原始 model_list。"""
+ "type": "list",
+ "attribute": "ordered",
+ "ilevel": 0,
+ "start": 1,
+ "content": [
+ {"type": "text", "content": "first"},
+ {
+ "type": "list",
+ "attribute": "unordered",
+ "ilevel": 1,
+ "content": [
+ {"type": "text", "content": "child"},
+ {"type": "list", "content": [{"type": "text", "content": "deep"}]},
+ ],
+ },
+ ],
+ },
+ {
+ "type": "index",
+ "content": [
+ {
+ "type": "index",
+ "content": [{"type": "text", "content": "section", "anchor": "a1"}],
+ }
+ ],
+ },
+ ]]
+
+ page = model_list_to_pages(model_list)[0]
+ list_block = page.blocks[0]
+ index_block = page.blocks[1]
+
+ assert isinstance(list_block, ListBlock)
+ assert list_block.content[0].content == "1. first"
+ assert isinstance(list_block.content[1], ListBlock)
+ assert list_block.content[1].content[0].content == "- child"
+ assert isinstance(list_block.content[1].content[1], ListBlock)
+ assert index_block.content[0].content[0].content == "section"
+ assert "anchor" not in index_block.content[0].content[0].model_fields_set
+
+
+def test_office_paragraph_numbering_is_document_wide_and_copy_only() -> None:
+ """验证 Office 标题跨页编号、显式编号同步和 raw 元数据保留。"""
model_list = [
[
- {
- "type": BlockType.IMAGE,
- "_image_base64": "data:image/jpeg;base64,image",
- },
- {
- "type": BlockType.TEXT,
- "content": "Figure 1",
- },
- {
- "type": BlockType.LIST,
- "attribute": "ordered",
- "ilevel": 0,
- "start": 1,
- "content": [
- {"type": BlockType.TEXT, "content": "first"},
- {
- "type": BlockType.LIST,
- "attribute": "unordered",
- "ilevel": 1,
- "content": [
- {"type": BlockType.TEXT, "content": "child"},
- ],
- },
- ],
- },
- {
- "type": BlockType.INDEX,
- "ilevel": 0,
- "content": [
- {
- "type": BlockType.INDEX,
- "ilevel": 1,
- "content": [
- {"type": BlockType.TEXT, "content": "section"},
- ],
- },
- ],
- },
- ]
- ]
- original_model_list = deepcopy(model_list)
-
- pages = model_list_to_pages(model_list)
-
- assert model_list == original_model_list
- assert pages[0]["page_idx"] == 0
- blocks_by_type = {block["type"]: block for block in pages[0]["blocks"]}
-
- image_block = blocks_by_type[BlockType.IMAGE]
- assert [block["type"] for block in image_block["content"]] == [
- BlockType.IMAGE_BODY,
- BlockType.IMAGE_CAPTION,
- ]
-
- list_block = blocks_by_type[BlockType.LIST]
- assert list_block["content"][0]["content"] == "1. first"
- nested_list = list_block["content"][1]
- assert nested_list["content"][0]["content"] == "- child"
- for metadata_key in ("attribute", "ilevel", "start"):
- assert metadata_key not in list_block
- assert metadata_key not in nested_list
- assert list_block is not model_list[0][2]
-
- index_block = blocks_by_type[BlockType.INDEX]
- assert "ilevel" not in index_block
- assert "ilevel" not in index_block["content"][0]
-
- list_block["content"][0]["content"] = "changed"
- assert model_list == original_model_list
-
-
-def test_model_list_to_pages_marks_pdf_continuation_and_removes_lines() -> None:
- """验证统一入口会处理带 bbox 的 PDF,并保持原始 model_list 不变。"""
- model_list = [
+ {"type": "paragraph_title", "content": "<b>A</b>", "level": 1, "is_numbered_style": True},
+ {"type": "paragraph_title", "content": "B", "level": 2, "is_numbered_style": True},
+ ],
[
- {
- "type": BlockType.TEXT,
- "bbox": [0.1, 0.1, 0.9, 0.3],
- "content": "previous continuation",
- "lines": [
- {"bbox": [0.1, 0.1, 0.9, 0.15]},
- {"bbox": [0.1, 0.2, 0.9, 0.25]},
- ],
- },
- {
- "type": BlockType.TEXT,
- "bbox": [0.1, 0.25, 0.9, 0.45],
- "content": "current continuation",
- "lines": [
- {"bbox": [0.1, 0.25, 0.9, 0.3]},
- {"bbox": [0.1, 0.35, 0.9, 0.4]},
- ],
- },
- ]
+ {"type": "paragraph_title", "content": "1.4 Explicit", "level": 2, "is_numbered_style": False},
+ {"type": "paragraph_title", "content": "C", "level": 2, "is_numbered_style": True},
+ {"type": "paragraph_title", "content": "No level", "is_numbered_style": True},
+ ],
]
- original_model_list = deepcopy(model_list)
+ original = deepcopy(model_list)
pages = model_list_to_pages(model_list)
-
- assert model_list == original_model_list
- assert [block["content"] for block in pages[0]["blocks"]] == [
- "previous continuation",
- "current continuation",
+ titles = [block for page in pages for block in page.blocks]
+
+ assert all(isinstance(block, ParagraphTitleBlock) for block in titles)
+ assert [block.content for block in titles] == [
+ "1 <b>A</b>",
+ "1.1 B",
+ "1.4 Explicit",
+ "1.5 C",
+ "2 No level",
]
- assert "continues_prev" not in pages[0]["blocks"][0]
- assert pages[0]["blocks"][1]["continues_prev"] is True
- assert all("lines" not in block for block in pages[0]["blocks"])
- assert [block["bbox"] for block in pages[0]["blocks"]] == [
- [0.1, 0.1, 0.9, 0.3],
- [0.1, 0.25, 0.9, 0.45],
+ assert titles[-1].level is None
+ assert model_list == original
+
+
+def test_office_paragraph_numbering_clears_deeper_levels() -> None:
+ """验证标题返回浅层时会清理旧深层计数,后续重新从一开始编号。"""
+ model_list = [[
+ {"type": "paragraph_title", "content": "A", "level": 1, "is_numbered_style": True},
+ {"type": "paragraph_title", "content": "B", "level": 2, "is_numbered_style": True},
+ {"type": "paragraph_title", "content": "C", "level": 3, "is_numbered_style": True},
+ {"type": "paragraph_title", "content": "D", "level": 2, "is_numbered_style": True},
+ {"type": "paragraph_title", "content": "E", "level": 3, "is_numbered_style": True},
+ {"type": "paragraph_title", "content": "F", "level": 1, "is_numbered_style": True},
+ {"type": "paragraph_title", "content": "G", "level": 2, "is_numbered_style": True},
+ ]]
+
+ titles = model_list_to_pages(model_list)[0].blocks
+
+ assert [title.content for title in titles] == [
+ "1 A",
+ "1.1 B",
+ "1.1.1 C",
+ "1.2 D",
+ "1.2.1 E",
+ "2 F",
+ "2.1 G",
]
-def test_model_list_to_pages_skips_para_merge_for_office_without_bbox() -> None:
- """验证无 bbox 的 Office 不进入段落后处理,也不会删除其 lines。"""
- model_list = [
- [
- {
- "type": BlockType.TEXT,
- "content": "office text",
- "lines": [{"bbox": [0.1, 0.1, 0.9, 0.2]}],
- }
- ]
- ]
-
- pages = model_list_to_pages(model_list)
-
- office_text = pages[0]["blocks"][0]
- assert office_text["lines"] == [{"bbox": [0.1, 0.1, 0.9, 0.2]}]
- assert "continues_prev" not in office_text
-
+def test_visual_body_drops_empty_parent_subtype() -> None:
+ """验证 raw visual 的空 subtype 只用于父块判断,不会泄漏到严格 body 模型。"""
+ page = model_list_to_pages(
+ [[{"type": "image", "content": None, "sub_type": None}]]
+ )[0]
-def test_model_list_to_pages_detects_pdf_after_empty_first_page() -> None:
- """验证 PDF 检测会扫描后续页面,而不是只检查空白首页。"""
- model_list = [
- [],
- [
- {
- "type": BlockType.TEXT,
- "bbox": [0.1, 0.1, 0.9, 0.3],
- "content": "later page",
- "lines": [{"bbox": [0.1, 0.1, 0.9, 0.2]}],
- }
- ],
- ]
-
- pages = model_list_to_pages(model_list)
+ assert isinstance(page.blocks[0], ImageBlock)
+ assert page.blocks[0].sub_type is None
+ assert page.blocks[0].content[0].type == "image_body"
- assert pages[0] == {"blocks": [], "page_idx": 0}
- assert "lines" not in pages[1]["blocks"][0]
+def test_pdf_continuation_is_typed_and_line_metadata_is_removed() -> None:
+ """验证 raw 段落延续在对象化前完成,公开 TextBlock 不保留临时 lines。"""
+ model_list = [[
+ {
+ "type": "text",
+ "bbox": [0.1, 0.1, 0.9, 0.3],
+ "content": "previous continuation",
+ "lines": [{"bbox": [0.1, 0.1, 0.9, 0.15]}, {"bbox": [0.1, 0.2, 0.9, 0.25]}],
+ },
+ {
+ "type": "text",
+ "bbox": [0.1, 0.25, 0.9, 0.45],
+ "content": "current continuation",
+ "lines": [{"bbox": [0.1, 0.25, 0.9, 0.3]}, {"bbox": [0.1, 0.35, 0.9, 0.4]}],
+ },
+ ]]
-def test_model_list_to_pages_marks_only_later_boundary_table() -> None:
- """验证 PDF 统一入口只给连续页的后表写入 continues_prev。"""
- previous_html = "<table><tr><td>A</td><td>B</td></tr></table>"
- current_html = "<table><tr><td>C</td><td>D</td></tr></table>"
- model_list = [
- [
- {"type": BlockType.HEADER, "bbox": [0.1, 0.01, 0.9, 0.03], "content": "header"},
- {"type": BlockType.TABLE, "bbox": [0.1, 0.1, 0.9, 0.85], "content": previous_html},
- {"type": BlockType.PAGE_NUMBER, "bbox": [0.45, 0.95, 0.55, 0.98], "content": "1"},
- ],
- [
- {"type": BlockType.HEADER, "bbox": [0.1, 0.01, 0.9, 0.03], "content": "header"},
- {"type": BlockType.TABLE, "bbox": [0.1, 0.1, 0.9, 0.85], "content": current_html},
- {"type": BlockType.PAGE_NUMBER, "bbox": [0.45, 0.95, 0.55, 0.98], "content": "2"},
- ],
- ]
- original_model_list = deepcopy(model_list)
-
- pages = model_list_to_pages(model_list)
+ page = model_list_to_pages(model_list)[0]
- previous_table = next(block for block in pages[0]["blocks"] if block["type"] == BlockType.TABLE)
- current_table = next(block for block in pages[1]["blocks"] if block["type"] == BlockType.TABLE)
- previous_body = next(block for block in previous_table["content"] if block["type"] == BlockType.TABLE_BODY)
- current_body = next(block for block in current_table["content"] if block["type"] == BlockType.TABLE_BODY)
- assert "continues_prev" not in previous_table
- assert current_table["continues_prev"] is True
- assert "continues_prev" not in current_body
- assert previous_body["content"] == previous_html
- assert current_body["content"] == current_html
- assert previous_table["bbox"] == [0.1, 0.1, 0.9, 0.85]
- assert current_table["bbox"] == [0.1, 0.1, 0.9, 0.85]
- assert model_list == original_model_list
-
-
-def test_model_list_to_pages_does_not_mark_table_across_page_index_gap() -> None:
- """验证统一入口会把 page_index_map 跳页传递给跨页表格判断。"""
- model_list = [
- [{"type": BlockType.TABLE, "bbox": [0.1, 0.1, 0.9, 0.85], "content": "<table><tr><td>A</td></tr></table>"}],
- [{"type": BlockType.TABLE, "bbox": [0.1, 0.1, 0.9, 0.85], "content": "<table><tr><td>B</td></tr></table>"}],
- ]
+ assert all(isinstance(block, TextBlock) for block in page.blocks)
+ assert page.blocks[0].continues_prev is None
+ assert page.blocks[1].continues_prev is True
+ assert all("lines" not in type(block).model_fields for block in page.blocks)
- pages = model_list_to_pages(model_list, page_index_map=[0, 2])
- current_table = next(block for block in pages[1]["blocks"] if block["type"] == BlockType.TABLE)
- assert "continues_prev" not in current_table
+def test_pdf_detection_scans_past_empty_first_page() -> None:
+ """验证整份文档 bbox 判定不会把 PDF 空白首页误认为 Office。"""
+ pages = model_list_to_pages([
+ [],
+ [{"type": "text", "bbox": [0.1, 0.1, 0.9, 0.3], "content": "later", "lines": []}],
+ ])
+
+ assert pages[0].blocks == []
+ assert isinstance(pages[1].blocks[0], TextBlock)
+
+
+def test_cross_page_table_continuation_remains_raw_postprocess() -> None:
+ """验证连续页表格仍在对象化前写入 continues_prev。"""
+ html_a = "<table><tr><td>A</td><td>B</td></tr></table>"
+ html_b = "<table><tr><td>C</td><td>D</td></tr></table>"
+ pages = model_list_to_pages([
+ [{"type": "table", "bbox": [0.1, 0.1, 0.9, 0.85], "content": html_a}],
+ [{"type": "table", "bbox": [0.1, 0.1, 0.9, 0.85], "content": html_b}],
+ ])
+
+ assert isinstance(pages[0].blocks[0], TableBlock)
+ assert pages[0].blocks[0].continues_prev is None
+ assert pages[1].blocks[0].continues_prev is True
+
+
+ ("page_index_map", "message"),
+ [([0], "length mismatch"), ([0, 0], "unique"), ([1, 0], "increasing"), ([0, -1], "non-negative")],
+)
+def test_page_index_map_is_strict(page_index_map: list[int], message: str) -> None:
+ """验证页号映射不允许截断、重复、逆序或负数。"""
+ with pytest.raises(ValueError, match=message):
+ model_list_to_pages([[], []], page_index_map=page_index_map)
diff --git a/tests/unittest/test_parse_result_contract.py b/tests/unittest/test_parse_result_contract.py
index a181829f..6b24e94f 100644
--- a/tests/unittest/test_parse_result_contract.py
+++ b/tests/unittest/test_parse_result_contract.py
@@ -177,42 +177,6 @@ def test_parse_result_from_dict_rejects_legacy_pipeline_backend() -> None:
ParseResult.from_dict({"_backend": legacy_backend, "pages": [{"page_idx": 0}]})
-def test_parse_result_preserves_true_merge_prev_in_staged_middle_json() -> None:
- block = Block(index=0, type="text", bbox=(0.0, 0.0, 10.0, 10.0), merge_prev=True)
- result = ParseResult(pages=[PageInfo(page_idx=0, preproc_blocks=[block])])
-
- payload = result.to_dict()
- restored = ParseResult.from_dict(payload)
-
- serialized_block = payload["pages"][0]["preproc_blocks"][0]
- assert serialized_block["merge_prev"] is True
- assert "angle" not in serialized_block
- assert "score" not in serialized_block
- assert restored.pages[0].preproc_blocks[0].merge_prev is True
-
-
-def test_parse_result_from_dict_restores_merge_prev_from_payload() -> None:
- restored = ParseResult.from_dict(
- {
- "pages": [
- {
- "page_idx": 0,
- "preproc_blocks": [
- {
- "index": 0,
- "type": "text",
- "bbox": [0.0, 0.0, 10.0, 10.0],
- "merge_prev": True,
- }
- ],
- }
- ]
- }
- )
-
- assert restored.pages[0].preproc_blocks[0].merge_prev is True
-
-
def test_parse_result_from_json_restores_pages() -> None:
data = {
"pages": [
diff --git a/tests/unittest/test_pdf_analyze_block_content.py b/tests/unittest/test_pdf_analyze_block_content.py
index da0e451e..bafafce4 100644
--- a/tests/unittest/test_pdf_analyze_block_content.py
+++ b/tests/unittest/test_pdf_analyze_block_content.py
@@ -10,12 +10,13 @@ from mineru_vl_utils.structs import ContentBlock as VlmContentBlock
from mineru_vl_utils.structs import ExtractResult
from mineru.backend import analyze
+from mineru.backend.utils.analyze_draft import _AnalyzeLine, _AnalyzeSpan
from mineru.backend.utils.span_pre_proc import (
POST_OCR_FALLBACK_CONTENT_KEY,
POST_OCR_FALLBACK_SCORE_KEY,
)
from mineru.model.flash import PdfModel
-from mineru.types import BlockType, ContentType, Line, Span
+from mineru.types import BlockType, ContentType, MiddleJson
from mineru.utils.pdf_document import PDFDocument
@@ -23,13 +24,13 @@ _PROJECT_ROOT = Path(__file__).resolve().parents[2]
_NPU_PDF_PATH = _PROJECT_ROOT / "demo" / "pdfs" / "NPU_开发环境部署_参考指南.pdf"
-def _build_text_lines(*contents: str) -> list[Line]:
+def _build_text_lines(*contents: str) -> list[_AnalyzeLine]:
"""按输入文本构造稳定的多行文本结构,供 block content 拼接测试复用。"""
return [
- Line(
+ _AnalyzeLine(
bbox=(0.0, float(line_idx), 100.0, float(line_idx + 1)),
spans=[
- Span(
+ _AnalyzeSpan(
type=ContentType.TEXT,
bbox=(0.0, float(line_idx), 100.0, float(line_idx + 1)),
content=content,
@@ -42,24 +43,24 @@ def _build_text_lines(*contents: str) -> list[Line]:
def _build_post_ocr_page_block_lines(
*page_crop_values: int | tuple[int, ...],
-) -> tuple[list[dict[int, list[Line]]], list[Span]]:
+) -> tuple[list[dict[int, list[_AnalyzeLine]]], list[_AnalyzeSpan]]:
"""按页构造携带待 OCR 裁图的 span,便于验证窗口级批处理和回填顺序。"""
- page_block_lines_list: list[dict[int, list[Line]]] = []
- spans: list[Span] = []
+ page_block_lines_list: list[dict[int, list[_AnalyzeLine]]] = []
+ spans: list[_AnalyzeSpan] = []
for page_idx, crop_values in enumerate(page_crop_values):
normalized_crop_values = (crop_values,) if isinstance(crop_values, int) else crop_values
- page_spans: list[Span] = []
+ page_spans: list[_AnalyzeSpan] = []
for span_idx, crop_value in enumerate(normalized_crop_values):
bbox = (float(span_idx), float(page_idx), float(span_idx + 1), float(page_idx + 1))
- span = Span(
+ span = _AnalyzeSpan(
type=ContentType.TEXT,
bbox=bbox,
- _np_img=np.full((4, 8, 3), crop_value, dtype=np.uint8),
+ image=np.full((4, 8, 3), crop_value, dtype=np.uint8),
)
spans.append(span)
page_spans.append(span)
line_bbox = (0.0, float(page_idx), float(len(page_spans)), float(page_idx + 1))
- page_block_lines_list.append({0: [Line(bbox=line_bbox, spans=page_spans)]})
+ page_block_lines_list.append({0: [_AnalyzeLine(bbox=line_bbox, spans=page_spans)]})
return page_block_lines_list, spans
@@ -79,8 +80,12 @@ def test_convert_vlm_results_to_model_list_uses_builtin_containers() -> None:
assert type(model_list) is list
assert all(type(page) is list for page in model_list)
assert type(model_list[0][0]) is dict
- assert list(model_list[0][0]) == list(source_block)
- assert model_list[0][0] == dict(source_block)
+ assert model_list[0][0] == {
+ "type": BlockType.TEXT,
+ "bbox": [0.1, 0.2, 0.8, 0.4],
+ "angle": 0,
+ "content": "原始文本",
+ }
assert model_list[1] == []
assert model_list[0] is not source_page
assert model_list[0][0] is not source_block
@@ -89,6 +94,22 @@ def test_convert_vlm_results_to_model_list_uses_builtin_containers() -> None:
assert source_block["content"] == "原始文本"
+def test_convert_vlm_results_deep_copies_projected_mutable_fields() -> None:
+ """验证 VLM 投影后的可变字段不会与上游对象共享引用。"""
+ source_cell_merge = [1, 0]
+ source_block = {
+ "type": BlockType.TABLE,
+ "bbox": [0.1, 0.2, 0.8, 0.4],
+ "content": "<table></table>",
+ "cell_merge": source_cell_merge,
+ }
+
+ model_list = analyze._convert_vlm_results_to_model_list([[source_block]])
+ model_list[0][0]["cell_merge"].append(1)
+
+ assert source_cell_merge == [1, 0]
+
+
@pytest.mark.parametrize(
("effort", "parse_mode", "vlm_method_name"),
[
@@ -181,9 +202,10 @@ def test_doc_analyze_converts_vlm_results_before_downstream_processing(
assert type(model_list[0]) is list
assert type(model_list[0][0]) is dict
assert model_list == [[{"type": BlockType.PAGE_NUMBER, "bbox": [0.45, 0.9, 0.55, 0.95], "content": "1"}]]
- assert middle_json["pages"] == []
- assert middle_json["effort"] == effort
- assert middle_json["parse_mode"] == parse_mode
+ assert isinstance(middle_json, MiddleJson)
+ assert middle_json.pages == []
+ assert middle_json.effort == effort
+ assert middle_json.parse_mode == parse_mode
assert type(source_page) is ExtractResult
assert type(source_block) is VlmContentBlock
assert source_block["angle"] == 0
@@ -232,21 +254,6 @@ def test_xhigh_vlm_blocks_normalize_visual_annotation_types() -> None:
]
-def test_xhigh_vlm_blocks_remove_merge_prev_from_all_text_blocks() -> None:
- """验证 xhigh VLM 正文无论 merge_prev 取值如何都移除该字段。"""
- page_blocks = [
- {"type": BlockType.TEXT, "content": "merge", "merge_prev": True},
- {"type": BlockType.TEXT, "content": "do not merge", "merge_prev": False},
- {"type": BlockType.TEXT, "content": "without hint"},
- {"type": BlockType.CAPTION, "content": "caption"},
- ]
-
- analyze._normalize_xhigh_vlm_blocks([page_blocks])
-
- assert all("merge_prev" not in block for block in page_blocks if block["type"] == BlockType.TEXT)
- assert page_blocks[-1] == {"type": BlockType.CAPTION, "content": "caption"}
-
-
def test_five_pdf_text_types_keep_normalized_line_metadata() -> None:
"""验证五类 PDF 文本块统一保留公开的归一化 lines。"""
assert analyze.LINE_METADATA_BLOCK_TYPES == {
@@ -335,7 +342,7 @@ def test_window_post_ocr_batches_all_pages_once() -> None:
assert call_args.kwargs == {"det": False, "tqdm_enable": True}
assert [span.content for span in spans] == ["第一页一", "第一页二", "第二页一", "第二页二"]
assert [span.score for span in spans] == [0.91, 0.82, 0.73, 0.64]
- assert all(span._np_img is None for span in spans)
+ assert all(span.image is None for span in spans)
def test_window_post_ocr_skips_empty_window() -> None:
@@ -362,8 +369,8 @@ def test_window_post_ocr_keeps_low_confidence_fallback_semantics() -> None:
page_block_lines_list, spans = _build_post_ocr_page_block_lines(11, 22)
spans[0].content = "原生文本"
spans[0].score = 0.88
- spans[0]._extra[POST_OCR_FALLBACK_CONTENT_KEY] = spans[0].content
- spans[0]._extra[POST_OCR_FALLBACK_SCORE_KEY] = spans[0].score
+ spans[0].metadata[POST_OCR_FALLBACK_CONTENT_KEY] = spans[0].content
+ spans[0].metadata[POST_OCR_FALLBACK_SCORE_KEY] = spans[0].score
local_model_context = MagicMock()
local_model_context.ocr_model.ocr.return_value = [[("低置信文本", 0.0), ("低置信文本", 0.0)]]
@@ -371,7 +378,7 @@ def test_window_post_ocr_keeps_low_confidence_fallback_semantics() -> None:
assert spans[0].content == "原生文本"
assert spans[0].score == 0.88
- assert spans[0]._extra == {}
+ assert spans[0].metadata == {}
assert spans[1].content == ""
assert spans[1].score == 0.0
diff --git a/tests/unittest/test_pdf_analyze_visual_blocks.py b/tests/unittest/test_pdf_analyze_visual_blocks.py
index a0d06f5e..9ac1d9ed 100644
--- a/tests/unittest/test_pdf_analyze_visual_blocks.py
+++ b/tests/unittest/test_pdf_analyze_visual_blocks.py
@@ -10,7 +10,7 @@ import pytest
from PIL import Image, ImageDraw
from mineru.backend import analyze
-from mineru.types import BlockType
+from mineru.types import BlockType, MiddleJson
JPEG_DATA_URI_PREFIX = "data:image/jpeg;base64,"
@@ -91,7 +91,7 @@ def test_visual_block_crop_rotates_to_upright(
analyze._attach_visual_block_images([[block]], [{"img_pil": page_image}])
- crop_image = _decode_jpeg_data_uri(block["_image_base64"])
+ crop_image = _decode_jpeg_data_uri(block["image_base64"])
try:
assert crop_image.size == expected_size
_assert_colors_close(_sample_quadrant_colors(crop_image), expected_colors)
@@ -139,7 +139,7 @@ def test_visual_block_types_receive_jpeg_data_uri_only() -> None:
"bbox": [0.1, 0.2, 0.6, 0.7],
"angle": 0,
"content": f"content-{block_type}",
- "_image_base64": "stale",
+ "image_base64": "stale",
}
for block_type in (
BlockType.IMAGE,
@@ -152,7 +152,7 @@ def test_visual_block_types_receive_jpeg_data_uri_only() -> None:
"type": BlockType.TEXT,
"bbox": [0.0, 0.0, 1.0, 1.0],
"content": "text",
- "_image_base64": "keep-text-field",
+ "image_base64": "keep-text-field",
}
analyze._attach_visual_block_images(
@@ -163,15 +163,15 @@ def test_visual_block_types_receive_jpeg_data_uri_only() -> None:
try:
for block in visual_blocks:
- assert block["_image_base64"] != "stale"
- crop_image = _decode_jpeg_data_uri(block["_image_base64"])
+ assert block["image_base64"] != "stale"
+ crop_image = _decode_jpeg_data_uri(block["image_base64"])
try:
assert crop_image.size == (50, 30)
finally:
crop_image.close()
assert block["content"] == f"content-{block['type']}"
assert block["bbox"] == [0.1, 0.2, 0.6, 0.7]
- assert text_block["_image_base64"] == "keep-text-field"
+ assert text_block["image_base64"] == "keep-text-field"
finally:
page_image.close()
@@ -195,13 +195,13 @@ def test_visual_block_crop_clips_page_boundary_and_skips_invalid_bbox() -> None:
[{"img_pil": page_image}],
)
- crop_image = _decode_jpeg_data_uri(clipped_block["_image_base64"])
+ crop_image = _decode_jpeg_data_uri(clipped_block["image_base64"])
try:
assert crop_image.size == (30, 20)
finally:
crop_image.close()
page_image.close()
- assert "_image_base64" not in invalid_block
+ assert "image_base64" not in invalid_block
def test_image_block_collapses_contained_blocks_before_visual_crop() -> None:
@@ -284,7 +284,7 @@ def test_image_block_collapses_contained_blocks_before_visual_crop() -> None:
]
assert image_block["type"] == BlockType.IMAGE
assert all(block.get("type") != "image_block" for block in page_model_list)
- crop_image = _decode_jpeg_data_uri(image_block["_image_base64"])
+ crop_image = _decode_jpeg_data_uri(image_block["image_base64"])
try:
assert crop_image.size == (80, 48)
finally:
@@ -371,7 +371,7 @@ def test_xhigh_layout_image_supplements_missing_container_before_crop() -> None:
assert image_block["type"] == BlockType.IMAGE
assert image_block["bbox"] == layout_blocks_list[0][0]["bbox"]
assert external_caption["content"] == "Figure 2: keep external caption"
- crop_image = _decode_jpeg_data_uri(image_block["_image_base64"])
+ crop_image = _decode_jpeg_data_uri(image_block["image_base64"])
try:
assert crop_image.size == (674, 1068)
finally:
@@ -596,6 +596,40 @@ def test_normalize_pdf_model_list_updates_in_place() -> None:
)
+def test_normalize_pdf_model_list_converts_phonetic_and_equation_raw_types() -> None:
+ """验证 phonetic/equation 在正文与 lines 校验前转成公开类型。"""
+ model_list = [[
+ {
+ "type": BlockType.PHONETIC,
+ "bbox": [0.1, 0.1, 0.9, 0.2],
+ "content": "phonetic",
+ "lines": [{"bbox": [0.1, 0.1, 0.9, 0.2]}],
+ },
+ {
+ "type": BlockType.EQUATION,
+ "bbox": [0.1, 0.3, 0.9, 0.4],
+ "content": r"\[x+1\]",
+ },
+ ]]
+
+ analyze._normalize_pdf_model_list(model_list)
+
+ assert model_list[0][0]["type"] == BlockType.TEXT
+ assert model_list[0][1] == {
+ "type": BlockType.INTERLINE_EQUATION,
+ "bbox": [0.1, 0.3, 0.9, 0.4],
+ "content": "x+1",
+ }
+
+
+def test_normalize_pdf_model_list_rejects_unclassified_raw_title() -> None:
+ """验证未被 layout 结果分类的 raw title 以页块位置明确报错。"""
+ with pytest.raises(ValueError, match="page_idx=0, block_idx=0"):
+ analyze._normalize_pdf_model_list(
+ [[{"type": BlockType.TITLE, "bbox": [0.1, 0.1, 0.9, 0.2], "content": "title"}]]
+ )
+
+
@pytest.mark.parametrize(
"block_type",
[
@@ -776,7 +810,11 @@ def test_doc_analyze_office_returns_model_list_without_pdf_processing(
file_suffix=file_suffix, # type: ignore[arg-type]
)
- assert middle_json == []
+ assert isinstance(middle_json, MiddleJson)
+ assert len(middle_json.pages) == 1
+ assert middle_json.file_suffix == file_suffix
+ assert middle_json.effort == "flash"
+ assert middle_json.parse_mode == "txt"
assert model_list is source_model_list
assert model_list[0][0]["content"] == "原始 \\(office\\) 内容"
for suffix, model_factory in model_factories.items():
@@ -887,7 +925,8 @@ def test_pdf_infer_timer_excludes_hybrid_vlm_initialization_and_cleanup(
parse_mode="txt",
)
- assert middle_json == []
+ assert isinstance(middle_json, MiddleJson)
+ assert middle_json.pages == []
assert model_list == []
assert events == [
"hybrid_init",
@@ -916,23 +955,44 @@ def test_doc_analyze_office_real_samples(file_suffix: str, expected_page_count:
file_suffix=file_suffix, # type: ignore[arg-type]
)
- assert middle_json == []
+ assert isinstance(middle_json, MiddleJson)
+ assert len(middle_json.pages) == expected_page_count
+ assert all(page.page_idx == page_idx for page_idx, page in enumerate(middle_json.pages))
assert len(model_list) == expected_page_count
assert all(isinstance(page, list) for page in model_list)
-def test_doc_analyze_flash_returns_complete_model_list_without_middle_json(monkeypatch: pytest.MonkeyPatch) -> None:
- """验证 Flash 多窗口仅补充完整 model list,并固定返回空 Middle JSON。"""
+def test_doc_analyze_flash_real_pdf_returns_typed_middle_json() -> None:
+ """验证一页真实 PDF 经 Flash Analyze 后返回严格对象且 raw 结果无废弃字段。"""
+ sample_path = _PROJECT_ROOT / "demo" / "pdfs" / "2407.00079v4_origi-10.pdf"
+
+ middle_json, model_list = analyze.doc_analyze(
+ sample_path.read_bytes(),
+ effort="flash",
+ parse_mode="txt",
+ file_suffix="pdf",
+ )
+
+ assert isinstance(middle_json, MiddleJson)
+ assert len(middle_json.pages) == len(model_list) == 1
+ assert all(block.bbox is not None for block in middle_json.pages[0].blocks)
+ assert all("merge_prev" not in block for page in model_list for block in page)
+ assert MiddleJson.model_validate_json(middle_json.to_json()) == middle_json
+
+
+def test_doc_analyze_flash_returns_complete_model_list_and_typed_middle_json(monkeypatch: pytest.MonkeyPatch) -> None:
+ """验证 Flash 多窗口补充完整 raw model list,并返回严格 MiddleJson。"""
from mineru.model import flash as flash_model
events: list[str] = []
source_model_list = [
[
- {
- "type": BlockType.TEXT,
- "bbox": [0.0, 0.0, 1.0, 1.0],
- "content": "第一页 \\(x+y\\)",
- }
+ {
+ "type": BlockType.TEXT,
+ "bbox": [0.0, 0.0, 1.0, 1.0],
+ "content": "第一页 \\(x+y\\)",
+ "lines": [{"bbox": [0.0, 0.0, 1.0, 1.0]}],
+ }
],
[
{
@@ -1023,17 +1083,18 @@ def test_doc_analyze_flash_returns_complete_model_list_without_middle_json(monke
b"fake-pdf",
effort="flash",
parse_mode="txt",
- page_index_map=[9, 8, 7],
+ page_index_map=[7, 8, 9],
)
- assert middle_json == []
+ assert isinstance(middle_json, MiddleJson)
+ assert [page.page_idx for page in middle_json.pages] == [7, 8, 9]
assert model_list is source_model_list
assert requested_ranges == [(0, 1), (2, 2)]
assert model_list[0][0]["content"] == "第一页 <eq>x+y</eq>"
assert model_list[2][0]["content"] == "第三页 <eq>z</eq>"
- assert "_image_base64" not in model_list[0][0]
+ assert "image_base64" not in model_list[0][0]
for block in (model_list[1][0], model_list[2][0]):
- crop_image = _decode_jpeg_data_uri(block["_image_base64"])
+ crop_image = _decode_jpeg_data_uri(block["image_base64"])
crop_image.close()
for image in rendered_images:
with pytest.raises(ValueError, match="closed image"):
diff --git a/tests/unittest/test_title_level_postprocess.py b/tests/unittest/test_title_level_postprocess.py
index e4354c9b..bdcbd466 100644
--- a/tests/unittest/test_title_level_postprocess.py
+++ b/tests/unittest/test_title_level_postprocess.py
@@ -3,7 +3,7 @@ import json
import pytest
from mineru.parser.base import ParseResult
-from mineru.types import Block, ContentType, Line, PageInfo, Span
+from mineru.types import PageInfo
from mineru.utils import title_level_postprocess
@@ -63,44 +63,3 @@ def test_finalize_client_side_pages_uses_explicit_backend(monkeypatch) -> None:
with pytest.raises(ValueError, match="Unsupported client-side finalize backend 'pipeline'"):
title_level_postprocess.finalize_client_side_pages(pages, legacy_backend)
-
-
-def test_finalize_client_side_hybrid_pages_uses_round_tripped_merge_prev_then_cleans_it() -> None:
- """校验客户端 Hybrid finalize 会消费并清理 round-trip 后的 merge_prev 元数据。"""
- previous_block = Block(
- index=0,
- type="text",
- bbox=(0.0, 0.0, 100.0, 20.0),
- lines=[
- Line(
- bbox=(0.0, 0.0, 100.0, 10.0),
- spans=[Span(type=ContentType.TEXT, bbox=(0.0, 0.0, 100.0, 10.0), content="hello")],
- )
- ],
- )
- current_block = Block(
- index=1,
- type="text",
- bbox=(0.0, 15.0, 100.0, 30.0),
- merge_prev=True,
- lines=[
- Line(
- bbox=(0.0, 15.0, 100.0, 25.0),
- spans=[Span(type=ContentType.TEXT, bbox=(0.0, 15.0, 100.0, 25.0), content="world")],
- )
- ],
- )
- staged_payload = ParseResult(
- pages=[PageInfo(page_idx=0, preproc_blocks=[previous_block, current_block])]
- ).to_dict()
- round_tripped_pages = ParseResult.from_dict(staged_payload).pages
-
- title_level_postprocess.finalize_client_side_pages(round_tripped_pages, "hybrid", effort="high")
-
- para_blocks = round_tripped_pages[0].para_blocks
- merged_text = [span.content for line in para_blocks[0].lines for span in line.spans]
- finalized_payload = ParseResult(pages=round_tripped_pages).to_dict()
- assert merged_text == ["hello", "world"]
- assert para_blocks[1].lines == []
- assert "merge_prev" not in finalized_payload["pages"][0]["preproc_blocks"][1]
- assert "merge_prev" not in finalized_payload["pages"][0]["para_blocks"][1]
diff --git a/tests/unittest/test_visual_magic_model_utils.py b/tests/unittest/test_visual_magic_model_utils.py
index 62550cc6..7edc2ca3 100644
--- a/tests/unittest/test_visual_magic_model_utils.py
+++ b/tests/unittest/test_visual_magic_model_utils.py
@@ -10,7 +10,7 @@ from mineru.backend.utils.visual_magic_model_utils import (
is_block_outside_visual_gap,
regroup_visual_blocks,
)
-from mineru.types import Block, BlockType, Line
+from mineru.types import BlockType
def _line_metadata(count: int) -> list[dict[str, list[float]]]:
@@ -36,7 +36,7 @@ def test_normalized_dict_bbox_matches_scaled_caption_geometry_without_rewrite()
"type": BlockType.TEXT,
"bbox": [0.02, 0.125, 0.1, 0.145],
"content": "unrelated text",
- "_lines": _line_metadata(1),
+ "lines": _line_metadata(1),
}
normalized_blocks = [
{
@@ -44,7 +44,7 @@ def test_normalized_dict_bbox_matches_scaled_caption_geometry_without_rewrite()
"type": BlockType.CAPTION,
"bbox": [0.7, 0.1, 0.95, 0.12],
"content": "Table 1",
- "_lines": _line_metadata(1),
+ "lines": _line_metadata(1),
},
companion,
{
@@ -71,19 +71,15 @@ def test_normalized_dict_bbox_matches_scaled_caption_geometry_without_rewrite()
assert [block["bbox"] for block in normalized_blocks] == original_bboxes
-def test_normalized_block_bbox_matches_scaled_visual_parent_without_rewrite() -> None:
- """验证 Block 归一化框与千倍坐标选择同一视觉父块且保留原框。"""
- previous_table = Block(index=0, type=BlockType.TABLE_BODY, bbox=(0.1, 0.1, 0.4, 0.4))
- caption = Block(index=1, type=BlockType.CAPTION, bbox=(0.1, 0.42, 0.4, 0.44))
- following_table = Block(index=2, type=BlockType.TABLE_BODY, bbox=(0.1, 0.8, 0.4, 0.95))
+def test_normalized_dict_bbox_matches_scaled_visual_parent_without_rewrite() -> None:
+ """验证 raw dict 归一化框与千倍坐标选择同一视觉父块且保留原框。"""
+ previous_table = {"index": 0, "type": BlockType.TABLE_BODY, "bbox": [0.1, 0.1, 0.4, 0.4]}
+ caption = {"index": 1, "type": BlockType.CAPTION, "bbox": [0.1, 0.42, 0.4, 0.44]}
+ following_table = {"index": 2, "type": BlockType.TABLE_BODY, "bbox": [0.1, 0.8, 0.4, 0.95]}
normalized_blocks = [previous_table, caption, following_table]
- original_bboxes = [block.bbox for block in normalized_blocks]
+ original_bboxes = [list(block["bbox"]) for block in normalized_blocks]
scaled_blocks = [
- Block(
- index=block.index,
- type=block.type,
- bbox=tuple(value * 1000 for value in block.bbox),
- )
+ {**block, "bbox": [value * 1000 for value in block["bbox"]]}
for block in normalized_blocks
]
@@ -91,33 +87,29 @@ def test_normalized_block_bbox_matches_scaled_visual_parent_without_rewrite() ->
caption,
[previous_table, following_table],
normalized_blocks,
- {block.index: position for position, block in enumerate(normalized_blocks)},
+ {block["index"]: position for position, block in enumerate(normalized_blocks)},
)
scaled_parent = find_best_visual_parent(
scaled_blocks[1],
[scaled_blocks[0], scaled_blocks[2]],
scaled_blocks,
- {block.index: position for position, block in enumerate(scaled_blocks)},
+ {block["index"]: position for position, block in enumerate(scaled_blocks)},
)
assert normalized_parent is previous_table
assert scaled_parent is scaled_blocks[0]
- assert [block.bbox for block in normalized_blocks] == original_bboxes
+ assert [block["bbox"] for block in normalized_blocks] == original_bboxes
-def test_normalized_block_bbox_matches_scaled_visual_gap_geometry() -> None:
+def test_normalized_dict_bbox_matches_scaled_visual_gap_geometry() -> None:
"""验证归一化框在视觉间隔、相交和重叠判断中与千倍坐标一致。"""
- child = Block(index=0, type=BlockType.CAPTION, bbox=(0.1, 0.1, 0.4, 0.2))
- inside_gap = Block(index=1, type=BlockType.TEXT, bbox=(0.8, 0.3, 0.9, 0.4))
- outside_gap = Block(index=2, type=BlockType.TEXT, bbox=(0.8, 0.8, 0.9, 0.9))
- main = Block(index=3, type=BlockType.TABLE_BODY, bbox=(0.1, 0.6, 0.4, 0.7))
+ child = {"index": 0, "type": BlockType.CAPTION, "bbox": [0.1, 0.1, 0.4, 0.2]}
+ inside_gap = {"index": 1, "type": BlockType.TEXT, "bbox": [0.8, 0.3, 0.9, 0.4]}
+ outside_gap = {"index": 2, "type": BlockType.TEXT, "bbox": [0.8, 0.8, 0.9, 0.9]}
+ main = {"index": 3, "type": BlockType.TABLE_BODY, "bbox": [0.1, 0.6, 0.4, 0.7]}
normalized_blocks = [child, inside_gap, outside_gap, main]
scaled_blocks = [
- Block(
- index=block.index,
- type=block.type,
- bbox=tuple(value * 1000 for value in block.bbox),
- )
+ {**block, "bbox": [value * 1000 for value in block["bbox"]]}
for block in normalized_blocks
]
@@ -134,7 +126,7 @@ def test_dict_inline_caption_fragment_uses_common_fields() -> None:
"type": BlockType.TEXT,
"bbox": [40.0, 0.0, 80.0, 10.0],
"content": "continued caption",
- "_lines": _line_metadata(1),
+ "lines": _line_metadata(1),
}
blocks = [
{
@@ -142,7 +134,7 @@ def test_dict_inline_caption_fragment_uses_common_fields() -> None:
"type": BlockType.CAPTION,
"bbox": [0.0, 0.0, 40.0, 10.0],
"content": "Table 1",
- "_lines": _line_metadata(1),
+ "lines": _line_metadata(1),
},
companion,
{
@@ -156,17 +148,16 @@ def test_dict_inline_caption_fragment_uses_common_fields() -> None:
fallback_inline_caption_fragments(blocks, VISUAL_MAIN_TYPES)
assert companion["type"] == BlockType.CAPTION
- assert "merge_prev" not in companion
def test_dict_stacked_caption_fragment_uses_line_metadata() -> None:
- """验证堆叠标题片段根据 dict 的 _lines 区分单行和多行。"""
+ """验证堆叠标题片段根据 dict 的临时 lines 区分单行和多行。"""
single_line = {
"index": 1,
"type": BlockType.TEXT,
"bbox": [0.0, 12.0, 80.0, 22.0],
"content": "single line",
- "_lines": _line_metadata(1),
+ "lines": _line_metadata(1),
}
blocks = [
{
@@ -174,7 +165,7 @@ def test_dict_stacked_caption_fragment_uses_line_metadata() -> None:
"type": BlockType.CAPTION,
"bbox": [0.0, 0.0, 80.0, 10.0],
"content": "Table 1",
- "_lines": _line_metadata(1),
+ "lines": _line_metadata(1),
},
single_line,
{
@@ -189,7 +180,7 @@ def test_dict_stacked_caption_fragment_uses_line_metadata() -> None:
assert single_line["type"] == BlockType.CAPTION
single_line["type"] = BlockType.TEXT
- single_line["_lines"] = _line_metadata(2)
+ single_line["lines"] = _line_metadata(2)
fallback_inline_caption_fragments(blocks, VISUAL_MAIN_TYPES)
@@ -197,14 +188,13 @@ def test_dict_stacked_caption_fragment_uses_line_metadata() -> None:
def test_dict_leading_table_continuation_reads_top_level_content() -> None:
- """验证 dict 页首续表使用顶层 content 和 _lines 完成判断。"""
+ """验证 dict 页首续表使用顶层 content 和临时 lines 完成判断。"""
continuation = {
"index": 0,
"type": BlockType.TEXT,
"bbox": [0.0, 0.0, 80.0, 10.0],
"content": "Table 1 (continued)",
- "_lines": _line_metadata(1),
- "merge_prev": True,
+ "lines": _line_metadata(1),
}
blocks = [
continuation,
@@ -219,44 +209,6 @@ def test_dict_leading_table_continuation_reads_top_level_content() -> None:
fallback_leading_table_continuation_captions(blocks, VISUAL_MAIN_TYPES)
assert continuation["type"] == BlockType.CAPTION
- assert continuation["merge_prev"] is True
-
-
-def test_block_class_fallbacks_keep_attribute_access_compatibility() -> None:
- """验证两个 fallback 仍兼容使用属性和 Line 的 Block class。"""
- inline_companion = Block(
- index=1,
- type=BlockType.TEXT,
- bbox=(40.0, 0.0, 80.0, 10.0),
- lines=[Line(bbox=(40.0, 0.0, 80.0, 10.0))],
- content="continued caption",
- merge_prev=True,
- )
- inline_blocks = [
- Block(index=0, type=BlockType.CAPTION, bbox=(0.0, 0.0, 40.0, 10.0), content="Table 1"),
- inline_companion,
- Block(index=2, type=BlockType.TABLE_BODY, bbox=(0.0, 15.0, 80.0, 60.0)),
- ]
- fallback_inline_caption_fragments(inline_blocks, VISUAL_MAIN_TYPES)
-
- continuation = Block(
- index=0,
- type=BlockType.TEXT,
- bbox=(0.0, 0.0, 80.0, 10.0),
- lines=[Line(bbox=(0.0, 0.0, 80.0, 10.0))],
- content="Table 1 (continued)",
- merge_prev=True,
- )
- continuation_blocks = [
- continuation,
- Block(index=1, type=BlockType.TABLE_BODY, bbox=(0.0, 15.0, 80.0, 60.0)),
- ]
- fallback_leading_table_continuation_captions(continuation_blocks, VISUAL_MAIN_TYPES)
-
- assert inline_companion.type == BlockType.CAPTION
- assert inline_companion.merge_prev is True
- assert continuation.type == BlockType.CAPTION
- assert continuation.merge_prev is True
def test_regroup_visual_blocks_supports_bbox_dicts() -> None:
@@ -266,8 +218,7 @@ def test_regroup_visual_blocks_supports_bbox_dicts() -> None:
"type": BlockType.CAPTION,
"bbox": [0.0, 0.0, 80.0, 10.0],
"content": "Figure 1",
- "_lines": [{"bbox": [0.0, 0.0, 80.0, 10.0]}],
- "merge_prev": True,
+ "lines": [{"bbox": [0.0, 0.0, 80.0, 10.0]}],
}
body = {
"index": 1,
@@ -280,7 +231,7 @@ def test_regroup_visual_blocks_supports_bbox_dicts() -> None:
"type": BlockType.FOOTNOTE,
"bbox": [0.0, 65.0, 80.0, 75.0],
"content": "source",
- "_lines": [{"bbox": [0.0, 65.0, 80.0, 75.0]}],
+ "lines": [{"bbox": [0.0, 65.0, 80.0, 75.0]}],
}
grouped_blocks, unmatched_blocks = regroup_visual_blocks(
@@ -299,44 +250,14 @@ def test_regroup_visual_blocks_supports_bbox_dicts() -> None:
BlockType.IMAGE_FOOTNOTE,
]
image_caption, _, image_footnote = image_block["content"]
- assert "_lines" not in image_caption
- assert image_caption["merge_prev"] is True
- assert "_lines" not in image_footnote
- assert "_lines" in caption
- assert "_lines" in footnote
+ assert "lines" not in image_caption
+ assert "lines" not in image_footnote
+ assert "lines" in caption
+ assert "lines" in footnote
assert caption["type"] == BlockType.CAPTION
assert footnote["type"] == BlockType.FOOTNOTE
-def test_regroup_visual_blocks_keeps_block_output_compatibility() -> None:
- """验证 Block 输入仍生成 Block 两层结构。"""
- blocks = [
- Block(
- index=0,
- type=BlockType.CAPTION,
- bbox=(0.0, 0.0, 80.0, 10.0),
- ),
- Block(
- index=1,
- type=BlockType.IMAGE_BODY,
- bbox=(0.0, 15.0, 80.0, 60.0),
- sub_type="seal",
- ),
- ]
-
- grouped_blocks, unmatched_blocks = regroup_visual_blocks(blocks)
-
- assert unmatched_blocks == []
- image_block = grouped_blocks[BlockType.IMAGE][0]
- assert isinstance(image_block, Block)
- assert image_block.sub_type == "seal"
- assert [block.type for block in image_block.content] == [
- BlockType.IMAGE_CAPTION,
- BlockType.IMAGE_BODY,
- ]
- assert image_block.content[1].sub_type == ""
-
-
def test_regroup_visual_blocks_preserves_dict_visual_metadata() -> None:
"""验证 dict 根节点保留 code subtype、视觉 subtype 与表格合并信息。"""
blocks = [
@@ -358,7 +279,7 @@ def test_regroup_visual_blocks_preserves_dict_visual_metadata() -> None:
"content": "<table></table>",
"angle": 0,
"score": 0.0,
- "_cell_merge": [1, 0],
+ "cell_merge": [1, 0],
},
]
@@ -375,30 +296,27 @@ def test_regroup_visual_blocks_preserves_dict_visual_metadata() -> None:
assert "sub_type" not in table_block["content"][0]
assert table_block["content"][0]["angle"] == 0
assert table_block["content"][0]["score"] == 0.0
- assert "_cell_merge" not in table_block
- assert table_block["content"][0]["_cell_merge"] == [1, 0]
+ assert "cell_merge" not in table_block
+ assert table_block["content"][0]["cell_merge"] == [1, 0]
-def test_regroup_visual_blocks_keeps_cell_merge_on_block_body() -> None:
- """验证 Block 表格的 cell_merge 只保留在 table body。"""
- table_body = Block(
- index=0,
- type=BlockType.TABLE_BODY,
- bbox=(0.0, 0.0, 80.0, 60.0),
- content="<table></table>",
- )
- table_body._cell_merge = [1, 0]
+def test_regroup_visual_blocks_keeps_cell_merge_on_dict_body() -> None:
+ """验证 raw dict 表格的 cell_merge 只保留在 table body。"""
+ table_body = {
+ "index": 0,
+ "type": BlockType.TABLE_BODY,
+ "bbox": [0.0, 0.0, 80.0, 60.0],
+ "content": "<table></table>",
+ "cell_merge": [1, 0],
+ }
grouped_blocks, unmatched_blocks = regroup_visual_blocks([table_body])
assert unmatched_blocks == []
table_block = grouped_blocks[BlockType.TABLE][0]
- assert isinstance(table_block, Block)
- assert table_block._cell_merge == []
- assert len(table_block.content) == 1
- grouped_body = table_block.content[0]
- assert isinstance(grouped_body, Block)
- assert grouped_body._cell_merge == [1, 0]
+ assert "cell_merge" not in table_block
+ assert len(table_block["content"]) == 1
+ assert table_block["content"][0]["cell_merge"] == [1, 0]
def test_regroup_visual_blocks_without_bbox_prefers_previous_parent() -> None:
@@ -424,6 +342,32 @@ def test_regroup_visual_blocks_without_bbox_prefers_previous_parent() -> None:
] == [BlockType.TABLE_BODY]
+def test_regroup_visual_blocks_supports_code_footnote() -> None:
+ """验证具体 code_footnote 可直接归入 code,且不会残留为额外顶层块。"""
+ code_body = {
+ "index": 0,
+ "type": BlockType.CODE_BODY,
+ "content": "print('ok')",
+ "sub_type": "code",
+ }
+ code_footnote = {
+ "index": 1,
+ "type": BlockType.CODE_FOOTNOTE,
+ "content": "runtime note",
+ }
+
+ grouped_blocks, unmatched_blocks = regroup_visual_blocks(
+ [code_body, code_footnote],
+ use_bbox=False,
+ )
+
+ assert unmatched_blocks == []
+ assert [child["type"] for child in grouped_blocks[BlockType.CODE][0]["content"]] == [
+ BlockType.CODE_BODY,
+ BlockType.CODE_FOOTNOTE,
+ ]
+
+
def test_regroup_visual_blocks_without_bbox_keeps_text_as_barrier() -> None:
"""验证无 bbox 模式不会跨过普通文本关联 caption。"""
caption = {"index": 0, "type": BlockType.CAPTION, "content": "Table 1"}