Skip to content

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

feat: unify equation block type by replacing 'interline_equation' with 'equation' across the codebase

myhloli3e968b1bad3b
diff --git a/docs/next/middle-json/current-medium.md b/docs/next/middle-json/current-medium.md
index 27c930c8..bd403ecf 100644
--- a/docs/next/middle-json/current-medium.md
+++ b/docs/next/middle-json/current-medium.md
@@ -67,15 +67,18 @@ 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
+equation, index, list
page_footnote, page_number, ref_text
table, table_body, table_caption, table_footnote
text
```
-仅 raw 阶段允许的 `algorithm/caption/equation/footnote/title/phonetic` 不属于
+仅 raw 阶段允许的 `algorithm/caption/footnote/title/phonetic` 不属于
公开 union。其它旧 `BlockType` 常量也不会被严格反序列化接受。
+块级行间公式唯一使用 `equation`。Legacy Span 链中的
+`ContentType.INTERLINE_EQUATION` 暂未迁移,不属于公开 Block discriminator。
+
## 主要具体模型
| 模型 | `content` | 专属字段 |
@@ -138,7 +141,7 @@ index 时 body 必须使用相同 index;父子同时有 bbox 时必须相等
- `image_body`
- `table_body`
- `chart_body`
-- `interline_equation`
+- `equation`
普通 `to_dict()` / `to_json()` 不执行文件 I/O;可通过
`exclude_block_fields={"image_base64"}` 递归排除图片字段。完整序列化保留
diff --git a/docs/next/middle-json/rendering.md b/docs/next/middle-json/rendering.md
index 4d1c4f8d..70aa6374 100644
--- a/docs/next/middle-json/rendering.md
+++ b/docs/next/middle-json/rendering.md
@@ -64,7 +64,7 @@ render 不应直接依赖:
| `title` | heading,使用 `level`。 | text item with level。 |
| `list` | 列表。 | list item。 |
| `index` | 目录。 | index/list item。 |
-| `interline_equation` | display math。 | equation item。 |
+| `equation` | display math。 | equation item。 |
| `image` | image markdown,包含 caption/footnote。 | image item。 |
| `table` | HTML 或 table image。 | table item。 |
| `chart` | chart image/content。 | chart item。 |
diff --git a/docs/next/open-questions.md b/docs/next/open-questions.md
index 565854d5..0abf80a7 100644
--- a/docs/next/open-questions.md
+++ b/docs/next/open-questions.md
@@ -33,6 +33,7 @@
| SDK tier 参数 | 普通 parser 入口应支持 `tier` 语义;`backend` 只作为专家层或过渡参数暴露。 |
| 错误映射 | `quality_tier_unavailable` 应进入稳定错误体系。 |
| JSON 输出格式 | 不把 `json` 作为正式产物名;正式格式为 `middle_json`、`content_list`、`structured_content`,详见 [ADR-0001](decisions/0001-json-output-formats.md)。 |
+| Middle JSON 行间公式 | Block discriminator 统一为 `equation`;Legacy Span 的 `ContentType.INTERLINE_EQUATION` 暂时保留。 |
| Force 与 invalidate | `--force` 跳过 done cache,可复用 active parse,只为未覆盖页创建新 parse;invalidate 才改变旧缓存可用性,详见 [ADR-0002](decisions/0002-force-vs-invalidate.md)。 |
| doclib HTTP API | 本地 doclib HTTP API 使用 `/docs`、`/parses`、`/search` 和 `POST /invalidate`,详见 [ADR-0004](decisions/0004-doclib-http-api-resources.md)。 |
| 本地 `high` | `high` 本地运行是正式支持能力,不是实验能力;当前代码基本 ready。 |
@@ -120,7 +121,6 @@
| OQ-M-002 | `filename` 是否默认写入 Middle JSON envelope。 | Middle JSON envelope |
| OQ-M-003 | `parsed_at` 是否默认写入;写入会降低跨机器 diff 稳定性。 | Middle JSON envelope |
| OQ-M-005 | backend-specific block type 的公开枚举、兼容策略和降级策略如何定稿。 | Middle JSON schema |
-| 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-010 | `_meta.models` 字段粒度如何定义,是按 layout/OCR/formula/table/VLM 细分,还是仅保留 backend/model 汇总。 | Middle JSON envelope |
diff --git a/mineru/backend/analyze.py b/mineru/backend/analyze.py
index ac728365..b656c323 100644
--- a/mineru/backend/analyze.py
+++ b/mineru/backend/analyze.py
@@ -37,7 +37,6 @@ 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,
@@ -125,7 +124,7 @@ MODEL_JSON_VISUAL_BLOCK_TYPES = {
BlockType.IMAGE,
BlockType.CHART,
BlockType.TABLE,
- RAW_EQUATION,
+ BlockType.EQUATION,
}
LOCAL_LAYOUT_IMAGE_BLOCK_BODY_TYPES = {
BlockType.IMAGE,
@@ -146,7 +145,7 @@ VLM_LAYOUT_LABEL_MAP = {
"aside_text": BlockType.ASIDE_TEXT,
"chart": BlockType.CHART,
"content": BlockType.INDEX,
- "display_formula": RAW_EQUATION,
+ "display_formula": BlockType.EQUATION,
"doc_title": BlockType.DOC_TITLE,
"figure_title": RAW_CAPTION,
"footer": BlockType.FOOTER,
@@ -495,7 +494,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") != RAW_EQUATION:
+ if block.get("type") != BlockType.EQUATION:
continue
block_bbox = block.get("bbox")
if block_bbox is None or len(block_bbox) != 4:
@@ -2086,7 +2085,7 @@ def _remove_low_table_inner_blocks(
"""按表格中心点归属规则移除 low 表内图片、公式和公式编号块。"""
inner_block_types = {
BlockType.IMAGE,
- RAW_EQUATION,
+ BlockType.EQUATION,
BlockType.FORMULA_NUMBER,
}
for image_dict, page_model_list in zip(images_list, model_list):
@@ -2491,8 +2490,7 @@ def _normalize_pdf_model_list(model_list: list[list[dict[str, Any]]]) -> None:
raw_type = block.get("type")
if raw_type == RAW_PHONETIC:
block["type"] = BlockType.TEXT
- elif raw_type == RAW_EQUATION:
- block["type"] = BlockType.INTERLINE_EQUATION
+ elif raw_type == BlockType.EQUATION:
equation_content = block.get("content")
if isinstance(equation_content, str):
if equation_content.startswith("\\["):
diff --git a/mineru/backend/magic_model.py b/mineru/backend/magic_model.py
index 6a665c5f..0d1adb09 100644
--- a/mineru/backend/magic_model.py
+++ b/mineru/backend/magic_model.py
@@ -6,7 +6,6 @@ from mineru.backend.utils.boxbase import calculate_overlap_area_in_bbox1_area_ra
from mineru.backend.utils.raw_block_types import (
RAW_ALGORITHM,
RAW_CAPTION,
- RAW_EQUATION,
RAW_FOOTNOTE,
RAW_TITLE,
)
@@ -59,8 +58,7 @@ class MagicModel:
code_block_sub_type = block_type
block_content = code_content_clean(block_content)
block_type = BlockType.CODE_BODY
- elif block_type == RAW_EQUATION:
- block_type = BlockType.INTERLINE_EQUATION
+ elif block_type == BlockType.EQUATION:
block_content = isolated_formula_clean(block_content)
if block_type not in [BlockType.IMAGE_BODY, BlockType.TABLE_BODY, BlockType.CHART_BODY]:
diff --git a/mineru/backend/utils/formula_number.py b/mineru/backend/utils/formula_number.py
index 82b23234..41006616 100644
--- a/mineru/backend/utils/formula_number.py
+++ b/mineru/backend/utils/formula_number.py
@@ -34,7 +34,10 @@ def build_tagged_formula_content(formula_content: str, tag_content: str) -> str
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}
+ return str(block.get("type") or "").lower() in {
+ BlockType.EQUATION,
+ "display_formula",
+ }
def _is_hybrid_formula_number_block(block: dict[str, Any]) -> bool:
diff --git a/mineru/backend/utils/para_block_utils.py b/mineru/backend/utils/para_block_utils.py
index 90746c67..5c8800f1 100644
--- a/mineru/backend/utils/para_block_utils.py
+++ b/mineru/backend/utils/para_block_utils.py
@@ -10,7 +10,7 @@ SECTION_MERGE_BARRIER_TYPES = {
BlockType.TITLE,
BlockType.DOC_TITLE,
BlockType.PARAGRAPH_TITLE,
- BlockType.INTERLINE_EQUATION,
+ BlockType.EQUATION,
}
TEXT_MERGE_BARRIER_TYPES = {
*SECTION_MERGE_BARRIER_TYPES,
diff --git a/mineru/backend/utils/raw_block_types.py b/mineru/backend/utils/raw_block_types.py
index bfba7633..fc286167 100644
--- a/mineru/backend/utils/raw_block_types.py
+++ b/mineru/backend/utils/raw_block_types.py
@@ -5,7 +5,6 @@ from typing import Literal, TypeAlias
RawBlockType: TypeAlias = Literal[
"algorithm",
"caption",
- "equation",
"footnote",
"title",
"phonetic",
@@ -13,11 +12,10 @@ RawBlockType: TypeAlias = Literal[
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}
+ {RAW_ALGORITHM, RAW_CAPTION, RAW_FOOTNOTE, RAW_TITLE, RAW_PHONETIC}
)
diff --git a/mineru/backend/utils/span_pre_proc.py b/mineru/backend/utils/span_pre_proc.py
index a4d5463f..e1b43aa4 100644
--- a/mineru/backend/utils/span_pre_proc.py
+++ b/mineru/backend/utils/span_pre_proc.py
@@ -89,7 +89,7 @@ def txt_spans_extract(
for span in spans:
if span.type in [ContentType.TEXT]:
for block in all_bboxes + all_discarded_blocks:
- if block[7] in [BlockType.IMAGE_BODY, BlockType.TABLE_BODY, BlockType.INTERLINE_EQUATION]:
+ if block[7] in [BlockType.IMAGE_BODY, BlockType.TABLE_BODY, BlockType.EQUATION]:
continue
if calculate_overlap_area_in_bbox1_area_ratio(span.bbox, block[0:4]) > 0.5:
if (
diff --git a/mineru/model/vlm/runtime.py b/mineru/model/vlm/runtime.py
index f0694c17..46cf4945 100644
--- a/mineru/model/vlm/runtime.py
+++ b/mineru/model/vlm/runtime.py
@@ -243,7 +243,7 @@ class ModelSingleton:
retry_backoff_factor=retry_backoff_factor,
enable_table_formula_eq_wrap=True,
image_analysis=True,
- enable_cross_page_table_merge=True,
+ enable_cross_page_table_merge=False,
)
predictor._mineru_runtime_handles = {
"backend": backend,
diff --git a/mineru/render/content_list.py b/mineru/render/content_list.py
index dc5245a8..bfd0f40d 100644
--- a/mineru/render/content_list.py
+++ b/mineru/render/content_list.py
@@ -62,7 +62,7 @@ def block_to_content_list(
text=merge_para_text(para_block),
text_level=title_level if title_level != 0 else None,
)
- elif para_type == BlockType.INTERLINE_EQUATION:
+ elif para_type == BlockType.EQUATION:
item = ContentItem(
type=ContentType.EQUATION,
img_path=_body_data(para_block, img_bucket_path)[0],
@@ -134,7 +134,7 @@ def _body_data(para_block: Block, img_bucket_path: str) -> tuple[str, str]:
BlockType.IMAGE_BODY,
BlockType.TABLE_BODY,
BlockType.CHART_BODY,
- BlockType.INTERLINE_EQUATION,
+ BlockType.EQUATION,
]
for line in block.lines
for span in line.spans
diff --git a/mineru/render/markdown.py b/mineru/render/markdown.py
index 9c8a9b69..b9112c34 100644
--- a/mineru/render/markdown.py
+++ b/mineru/render/markdown.py
@@ -54,7 +54,7 @@ def _block_to_markdown(
if para_type == BlockType.CODE:
return merge_visual_para_text(para_block)
- if para_type == BlockType.INTERLINE_EQUATION:
+ if para_type == BlockType.EQUATION:
if not formula_as_image:
if (para_text := merge_para_text(para_block)).strip():
return para_text
diff --git a/mineru/render/office/output.py b/mineru/render/office/output.py
index 929615cd..df731577 100644
--- a/mineru/render/office/output.py
+++ b/mineru/render/office/output.py
@@ -366,7 +366,7 @@ def blocks_to_markdown(
for para_block in para_blocks:
para_text = ""
para_type = para_block.type
- if para_type in [BlockType.TEXT, BlockType.INTERLINE_EQUATION]:
+ if para_type in [BlockType.TEXT, BlockType.EQUATION]:
para_text = merge_para_with_text(para_block)
if para_type == BlockType.TEXT:
bookmark_anchor = para_block.anchor
@@ -454,7 +454,7 @@ def make_blocks_to_content_list(para_block: Block, img_bucket_path: str, page_id
}
if title_level != 0:
para_content["text_level"] = title_level
- elif para_type == BlockType.INTERLINE_EQUATION:
+ elif para_type == BlockType.EQUATION:
para_content = {
"type": ContentType.EQUATION,
"text": merge_para_with_text(para_block),
@@ -547,7 +547,7 @@ def block_to_structured_content(para_block: Block, img_bucket_path: str) -> dict
"paragraph_content": merge_para_with_structured_spans(para_block),
},
}
- elif para_type == BlockType.INTERLINE_EQUATION:
+ elif para_type == BlockType.EQUATION:
_, math_content = get_body_data(para_block)
para_content = {
"type": ContentTypeV2.EQUATION_INTERLINE,
@@ -640,7 +640,7 @@ def get_body_data(para_block: Block) -> tuple[str, str]:
"""
Extract image_path and body content from para_block
Returns:
- - For IMAGE/INTERLINE_EQUATION: (image_path, '')
+ - For IMAGE/EQUATION: (image_path, '')
- For TABLE: (image_path, html)
- For CHART: (image_path, content)
- Default: ('', '')
diff --git a/mineru/render/structured_content.py b/mineru/render/structured_content.py
index acb1efce..ef0e822d 100644
--- a/mineru/render/structured_content.py
+++ b/mineru/render/structured_content.py
@@ -87,7 +87,7 @@ def block_to_structured_content(
para_content = _paragraph_content(para_block)
elif para_type in [BlockType.TEXT, BlockType.ABSTRACT, BlockType.PHONETIC]:
para_content = _paragraph_content(para_block)
- elif para_type == BlockType.INTERLINE_EQUATION:
+ elif para_type == BlockType.EQUATION:
image_path, math_content = _get_body_data(para_block)
para_content = {
"type": ContentTypeV2.EQUATION_INTERLINE,
diff --git a/mineru/types.py b/mineru/types.py
index 4e344a5b..07964f97 100644
--- a/mineru/types.py
+++ b/mineru/types.py
@@ -68,8 +68,7 @@ class BlockType:
FOOTNOTE = "footnote" # pp_layout中的vision_footnote
TEXT = "text"
TITLE = "title"
- INTERLINE_EQUATION = "interline_equation"
- EQUATION = "equation" # 公式(独立公式)
+ EQUATION = "equation" # 行间公式(独立公式)
LIST = "list"
INDEX = "index"
DISCARDED = "discarded"
@@ -146,7 +145,7 @@ BlockTypes = Literal[
BlockType.TABLE_FOOTNOTE,
BlockType.CHART_FOOTNOTE,
BlockType.TEXT,
- BlockType.INTERLINE_EQUATION,
+ BlockType.EQUATION,
BlockType.LIST,
BlockType.INDEX,
BlockType.CODE,
@@ -178,7 +177,7 @@ BLOCK_TYPES = {
BlockType.TABLE_FOOTNOTE,
BlockType.CHART_FOOTNOTE,
BlockType.TEXT,
- BlockType.INTERLINE_EQUATION,
+ BlockType.EQUATION,
BlockType.LIST,
BlockType.INDEX,
BlockType.CODE,
@@ -228,7 +227,7 @@ TEXT_LIKE_BLOCK_TYPES_FOR_BBOX = {
# layout.pdf 中这些 block 直接使用自身 bbox,复合 block 则使用子 block bbox。
DIRECT_LAYOUT_BBOX_BLOCK_TYPES = TEXT_LIKE_BLOCK_TYPES_FOR_BBOX | {
BlockType.TITLE,
- BlockType.INTERLINE_EQUATION,
+ BlockType.EQUATION,
BlockType.LIST,
BlockType.INDEX,
}
@@ -442,8 +441,8 @@ class ImagePayloadBlock(BlockBase):
return validate_image_sidecar_path(value)
-class InterlineEquationBlock(ImagePayloadBlock):
- type: Literal[BlockType.INTERLINE_EQUATION]
+class EquationBlock(ImagePayloadBlock):
+ type: Literal[BlockType.EQUATION]
content: str
@@ -643,7 +642,7 @@ Block: TypeAlias = Annotated[
PageNumberBlock,
PageFootnoteBlock,
FormulaNumberBlock,
- InterlineEquationBlock,
+ EquationBlock,
ListBlock,
IndexBlock,
ImageBodyBlock,
diff --git a/mineru/utils/draw_bbox.py b/mineru/utils/draw_bbox.py
index 9596b889..704a4ebe 100644
--- a/mineru/utils/draw_bbox.py
+++ b/mineru/utils/draw_bbox.py
@@ -22,7 +22,7 @@ TEXT_LIKE_BLOCK_TYPES_FOR_BBOX = {
# layout.pdf 中这些 block 直接使用自身 bbox,复合 block 则使用子 block bbox。
DIRECT_LAYOUT_BBOX_BLOCK_TYPES = TEXT_LIKE_BLOCK_TYPES_FOR_BBOX | {
BlockType.TITLE,
- BlockType.INTERLINE_EQUATION,
+ BlockType.EQUATION,
BlockType.LIST,
BlockType.INDEX,
}
@@ -172,7 +172,7 @@ def draw_layout_bbox(
codes_body_list, codes_caption_list, codes_footnote_list = [], [], []
titles_list = []
texts_list = []
- interline_equations_list = []
+ equations_list = []
lists_list = []
list_items_list = []
indexs_list = []
@@ -184,7 +184,7 @@ def draw_layout_bbox(
codes_body, codes_caption, codes_footnote = [], [], []
titles = []
texts = []
- interline_equations = []
+ equations = []
lists = []
list_items = []
indices = []
@@ -240,8 +240,8 @@ def draw_layout_bbox(
titles.append(bbox)
elif block.type in TEXT_LIKE_BLOCK_TYPES_FOR_BBOX:
texts.append(bbox)
- elif block.type == BlockType.INTERLINE_EQUATION:
- interline_equations.append(bbox)
+ elif block.type == BlockType.EQUATION:
+ equations.append(bbox)
elif block.type == BlockType.LIST:
lists.append(bbox)
if block.blocks:
@@ -258,7 +258,7 @@ def draw_layout_bbox(
imgs_footnote_list.append(imgs_footnote)
titles_list.append(titles)
texts_list.append(texts)
- interline_equations_list.append(interline_equations)
+ equations_list.append(equations)
lists_list.append(lists)
list_items_list.append(list_items)
indexs_list.append(indices)
@@ -308,7 +308,7 @@ def draw_layout_bbox(
c = draw_bbox_without_number(i, imgs_footnote_list, page, c, [255, 178, 102], True)
c = draw_bbox_without_number(i, titles_list, page, c, [102, 102, 255], True)
c = draw_bbox_without_number(i, texts_list, page, c, [153, 0, 76], True)
- c = draw_bbox_without_number(i, interline_equations_list, page, c, [0, 255, 0], True)
+ c = draw_bbox_without_number(i, equations_list, page, c, [0, 255, 0], True)
c = draw_bbox_without_number(i, lists_list, page, c, [40, 169, 92], True)
c = draw_bbox_without_number(i, list_items_list, page, c, [40, 169, 92], False)
c = draw_bbox_without_number(i, indexs_list, page, c, [40, 169, 92], True)
diff --git a/tests/unittest/test_magic_model.py b/tests/unittest/test_magic_model.py
index 2d62af7c..98890f03 100644
--- a/tests/unittest/test_magic_model.py
+++ b/tests/unittest/test_magic_model.py
@@ -4,6 +4,24 @@ from mineru.backend.magic_model import MagicModel, fix_pdf_list_blocks
from mineru.types import BlockType
+def test_magic_model_keeps_canonical_equation_type_and_cleans_content() -> None:
+ """验证 MagicModel 清理行间公式内容时不再改写 equation 类型。"""
+ equation = {
+ "type": BlockType.EQUATION,
+ "content": r"\[x+1\]",
+ }
+
+ magic_model = MagicModel([equation], use_bbox=False)
+
+ assert magic_model.blocks == [
+ {
+ "type": BlockType.EQUATION,
+ "content": "x+1",
+ "index": 0,
+ }
+ ]
+
+
def test_fix_pdf_list_blocks_supports_unit_bbox_without_rewrite() -> None:
"""验证归一化列表框可与像素文本框计算包含关系且不回写 bbox。"""
list_bbox = [0.0, 0.0, 1.0, 1.0]
diff --git a/tests/unittest/test_middle_json_block_models.py b/tests/unittest/test_middle_json_block_models.py
index 6f831827..ec8edad6 100644
--- a/tests/unittest/test_middle_json_block_models.py
+++ b/tests/unittest/test_middle_json_block_models.py
@@ -6,9 +6,12 @@ import pytest
from pydantic import ValidationError
import mineru.types as types_module
+from mineru.backend.utils.raw_block_types import RAW_ONLY_BLOCK_TYPES
from mineru.types import (
+ BLOCK_ADAPTER,
BLOCK_TYPES,
CodeBlock,
+ EquationBlock,
ListBlock,
MiddleJson,
PageInfo,
@@ -27,7 +30,7 @@ def _public_block_payloads() -> dict[str, dict[str, object]]:
"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"},
+ "equation": {"type": "equation", "content": "x=1"},
"list": {"type": "list", "content": [text_leaf]},
"page_footnote": {"type": "page_footnote", "content": "note"},
"page_number": {"type": "page_number", "content": "1"},
@@ -69,16 +72,37 @@ def test_all_29_public_discriminators_parse_to_concrete_models() -> None:
assert set(payloads) == BLOCK_TYPES
assert len(payloads) == 29
+ assert "equation" not in RAW_ONLY_BLOCK_TYPES
assert all(parse_block(payload).type == block_type for block_type, payload in payloads.items())
+ assert isinstance(parse_block(payloads["equation"]), EquationBlock)
[email protected]("raw_type", ["algorithm", "caption", "equation", "footnote", "title", "phonetic"])
[email protected]("raw_type", ["algorithm", "caption", "footnote", "title", "phonetic"])
def test_raw_only_types_are_rejected(raw_type: str) -> None:
"""验证 Analyze 私有 raw type 不能越过公开对象边界。"""
+ assert raw_type in RAW_ONLY_BLOCK_TYPES
with pytest.raises(ValidationError):
parse_block({"type": raw_type, "content": "raw"})
+def test_legacy_interline_equation_discriminator_is_rejected() -> None:
+ """验证旧 interline_equation 不提供兼容入口,严格对象只接受 equation。"""
+ with pytest.raises(ValidationError):
+ parse_block({"type": "interline_equation", "content": "x=1"})
+
+
+def test_equation_schema_uses_only_canonical_discriminator() -> None:
+ """验证生成的 JSON Schema 只公开 equation 与 EquationBlock。"""
+ schema = BLOCK_ADAPTER.json_schema()
+ mapping = schema["discriminator"]["mapping"]
+ legacy_model_name = "Interline" + "EquationBlock"
+
+ assert mapping["equation"] == "#/$defs/EquationBlock"
+ assert "interline_equation" not in mapping
+ assert "EquationBlock" in schema["$defs"]
+ assert legacy_model_name not in schema["$defs"]
+
+
def test_cross_type_fields_and_unknown_fields_are_rejected() -> None:
"""验证 Text/RefText 的专属字段边界与 extra forbid。"""
with pytest.raises(ValidationError):
@@ -100,10 +124,12 @@ def test_every_public_block_rejects_removed_merge_field() -> None:
def test_removed_block_classes_are_not_exposed() -> None:
"""验证未采用的旧 block 类没有重新进入公开对象体系。"""
+ legacy_equation_model_name = "Interline" + "EquationBlock"
removed_names = (
"TitleBlock",
"HeaderImageBlock",
"FooterImageBlock",
+ legacy_equation_model_name,
"_DocElement",
"Span",
"Line",
@@ -115,6 +141,7 @@ def test_removed_block_classes_are_not_exposed() -> None:
)
for removed_name in removed_names:
assert not hasattr(types_module, removed_name)
+ assert not hasattr(types_module.BlockType, "INTERLINE_" + "EQUATION")
@pytest.mark.parametrize(
diff --git a/tests/unittest/test_middle_json_export.py b/tests/unittest/test_middle_json_export.py
index d275283c..722bf94c 100644
--- a/tests/unittest/test_middle_json_export.py
+++ b/tests/unittest/test_middle_json_export.py
@@ -7,7 +7,7 @@ from pathlib import Path
import pytest
-from mineru.types import MiddleJson, PageInfo, TableBlock, TableBodyBlock
+from mineru.types import EquationBlock, MiddleJson, PageInfo, TableBlock, TableBodyBlock
def _data_uri(mime_subtype: str, payload: bytes) -> str:
@@ -42,6 +42,33 @@ def test_full_serialization_round_trip_and_recursive_field_exclusion() -> None:
assert "image_base64" not in excluded["pages"][0]["blocks"][0]["content"][0]
+def test_equation_export_uses_canonical_sidecar_name(tmp_path: Path) -> None:
+ """验证行间公式图片使用 equation discriminator 生成确定性 sidecar 名称。"""
+ jpeg_payload = b"\xff\xd8\xffequation\xff\xd9"
+ equation = EquationBlock(
+ type="equation",
+ index=6,
+ content="x+1",
+ image_base64=_data_uri("jpeg", jpeg_payload),
+ )
+ middle_json = MiddleJson(
+ pages=[PageInfo(page_idx=3, blocks=[equation])],
+ file_suffix="docx",
+ effort="flash",
+ parse_mode="txt",
+ mineru_version="test",
+ )
+
+ result = middle_json.export(tmp_path)
+ exported_equation = result.middle_json.pages[0].blocks[0]
+
+ assert [path.name for path in result.image_paths] == ["page_3_equation_6.jpg"]
+ assert (tmp_path / "images/page_3_equation_6.jpg").read_bytes() == jpeg_payload
+ assert exported_equation.image_path == "images/page_3_equation_6.jpg"
+ assert exported_equation.image_base64 is None
+ assert equation.image_base64 is not None
+
+
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"
diff --git a/tests/unittest/test_model_list_to_midlle_json.py b/tests/unittest/test_model_list_to_midlle_json.py
index 17bff98c..e00fdfae 100644
--- a/tests/unittest/test_model_list_to_midlle_json.py
+++ b/tests/unittest/test_model_list_to_midlle_json.py
@@ -3,7 +3,36 @@ from copy import deepcopy
import pytest
from mineru.backend.model_list_to_midlle_json import model_list_to_pages
-from mineru.types import ImageBlock, ListBlock, PageInfo, ParagraphTitleBlock, TableBlock, TextBlock
+from mineru.types import (
+ EquationBlock,
+ ImageBlock,
+ ListBlock,
+ PageInfo,
+ ParagraphTitleBlock,
+ TableBlock,
+ TextBlock,
+)
+
+
+def test_model_list_to_pages_keeps_equation_type_without_mutating_input() -> None:
+ """验证 equation 经 MagicModel 和严格对象化后保持类型、内容与图片载荷。"""
+ model_list = [[
+ {
+ "type": "equation",
+ "bbox": [0.1, 0.2, 0.9, 0.4],
+ "content": r"\[x+1\]",
+ "image_base64": "data:image/jpeg;base64,/9j/2Q==",
+ }
+ ]]
+ original = deepcopy(model_list)
+
+ page = model_list_to_pages(model_list)[0]
+
+ assert model_list == original
+ assert isinstance(page.blocks[0], EquationBlock)
+ assert page.blocks[0].type == "equation"
+ assert page.blocks[0].content == "x+1"
+ assert page.blocks[0].image_base64 == "data:image/jpeg;base64,/9j/2Q=="
def test_model_list_to_pages_returns_typed_pdf_tree_without_mutating_input() -> None:
diff --git a/tests/unittest/test_pdf_analyze_visual_blocks.py b/tests/unittest/test_pdf_analyze_visual_blocks.py
index 9ac1d9ed..77471d83 100644
--- a/tests/unittest/test_pdf_analyze_visual_blocks.py
+++ b/tests/unittest/test_pdf_analyze_visual_blocks.py
@@ -596,8 +596,8 @@ 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 校验前转成公开类型。"""
+def test_normalize_pdf_model_list_converts_phonetic_and_cleans_equation() -> None:
+ """验证 phonetic 转公开类型,同时 equation 保持类型并清理展示分隔符。"""
model_list = [[
{
"type": BlockType.PHONETIC,
@@ -616,12 +616,47 @@ def test_normalize_pdf_model_list_converts_phonetic_and_equation_raw_types() ->
assert model_list[0][0]["type"] == BlockType.TEXT
assert model_list[0][1] == {
- "type": BlockType.INTERLINE_EQUATION,
+ "type": BlockType.EQUATION,
"bbox": [0.1, 0.3, 0.9, 0.4],
"content": "x+1",
}
[email protected]("equation_type", [BlockType.EQUATION, "display_formula"])
+def test_formula_number_optimizer_recognizes_canonical_and_upstream_equation_types(
+ equation_type: str,
+) -> None:
+ """验证公式编号只需兼容 canonical equation 与上游 display_formula 标签。"""
+ optimized = analyze.optimize_hybrid_formula_number_blocks(
+ [
+ {"type": equation_type, "content": r"\[x+1\]"},
+ {"type": BlockType.FORMULA_NUMBER, "content": "(2)"},
+ ]
+ )
+
+ assert optimized == [
+ {
+ "type": equation_type,
+ "content": r"x+1\tag{2}",
+ }
+ ]
+
+
+def test_formula_number_optimizer_does_not_accept_legacy_interline_equation() -> None:
+ """验证旧 interline_equation 不再被公式编号合并逻辑视为合法公式块。"""
+ optimized = analyze.optimize_hybrid_formula_number_blocks(
+ [
+ {"type": "interline_equation", "content": "x+1"},
+ {"type": BlockType.FORMULA_NUMBER, "content": "(2)"},
+ ]
+ )
+
+ assert optimized == [
+ {"type": "interline_equation", "content": "x+1"},
+ {"type": BlockType.TEXT, "content": "(2)"},
+ ]
+
+
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"):
@@ -960,6 +995,22 @@ def test_doc_analyze_office_real_samples(file_suffix: str, 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)
+ if file_suffix == "docx":
+ model_equations = [
+ block
+ for page_model_list in model_list
+ for block in page_model_list
+ if block.get("type") == BlockType.EQUATION
+ ]
+ middle_equations = [
+ block
+ for page in middle_json.pages
+ for block in page.blocks
+ if block.type == BlockType.EQUATION
+ ]
+ assert model_equations
+ assert len(middle_equations) == len(model_equations)
+ assert "interline_equation" not in middle_json.to_json()
def test_doc_analyze_flash_real_pdf_returns_typed_middle_json() -> None:
@@ -980,6 +1031,35 @@ def test_doc_analyze_flash_real_pdf_returns_typed_middle_json() -> None:
assert MiddleJson.model_validate_json(middle_json.to_json()) == middle_json
+def test_doc_analyze_flash_demo1_uses_canonical_equation_type() -> None:
+ """验证真实 demo1.pdf 的 model list 与 MiddleJson 统一输出 equation。"""
+ sample_path = _PROJECT_ROOT / "demo" / "pdfs" / "demo1.pdf"
+
+ middle_json, model_list = analyze.doc_analyze(
+ sample_path.read_bytes(),
+ effort="flash",
+ parse_mode="txt",
+ file_suffix="pdf",
+ )
+
+ model_equations = [
+ block
+ for page_model_list in model_list
+ for block in page_model_list
+ if block.get("type") == BlockType.EQUATION
+ ]
+ middle_equations = [
+ block
+ for page in middle_json.pages
+ for block in page.blocks
+ if block.type == BlockType.EQUATION
+ ]
+
+ assert model_equations
+ assert len(middle_equations) == len(model_equations)
+ assert "interline_equation" not in middle_json.to_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
@@ -1092,6 +1172,9 @@ def test_doc_analyze_flash_returns_complete_model_list_and_typed_middle_json(mon
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 model_list[2][0]["type"] == BlockType.EQUATION
+ assert middle_json.pages[2].blocks[0].type == BlockType.EQUATION
+ assert "interline_equation" not in middle_json.to_json()
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"])