Skip to content

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

feat: enhance content rendering for titles and equations, and improve image source handling

myhloli0aa0f608c5d3
diff --git a/docs/next/middle-json/rendering.md b/docs/next/middle-json/rendering.md
index 37a4ee2f..64882a7c 100644
--- a/docs/next/middle-json/rendering.md
+++ b/docs/next/middle-json/rendering.md
@@ -42,11 +42,16 @@ content_list = render_content_list(
`MarkdownRenderMode` 计划,因此不隐藏页面辅助块,也不合并 `continues_prev` 文本、
列表或跨页表格;`continues_prev` 和 `cell_merge` 等消费提示仍保留在对应 block。
-每个输出 block 的 `content` 都是完整块级 Markdown。`list/index` 的递归子树会收敛为
-一个字符串;`image/table/chart/code` 的唯一 body 会提升为父块 `content`,说明文本则
-按源 `index` 排序后分别输出为 `captions: list[str]` 和 `footnotes: list[str]`。视觉数组
-始终存在,空说明保留为空字符串。所有输出 block 都删除 `index/level/guess_lang`;其中
-`level` 和 `guess_lang` 仍会先参与标题与代码 Markdown 的生成。
+`content` 保存适合结构化消费的文本表示,而不是可直接拼接成整篇文档的完整视觉
+Markdown。`list/index` 的递归子树会收敛为一个字符串;`image/table/chart/code` 的唯一
+body 会提升为父块 `content`,但图片资源只放在 `image_source`,不在 `content` 重复
+输出图片语法或 details。说明文本按源 `index` 排序后分别输出为 `captions: list[str]`
+和 `footnotes: list[str]`,视觉数组始终存在,空说明保留为空字符串。
+
+`doc_title/paragraph_title.content` 只包含行内 Markdown,不含 heading 标记或 HTML
+anchor;原始 `level` 和可选 `anchor` 作为独立字段保留。`equation.content` 是不带行间
+定界符的裸 LaTeX,公式图片同样只通过 `image_source` 表达。所有输出 block 都删除
+`index/guess_lang/image_path/image_base64`,`guess_lang` 仍会先参与代码 Markdown 的生成。
```json
{
@@ -55,12 +60,15 @@ content_list = render_content_list(
"page_idx": 0,
"blocks": [
{
- "type": "code",
- "bbox": [0.1, 0.2, 0.9, 0.8],
- "sub_type": "code",
- "content": "```python\nprint('hello')\n```",
- "captions": ["**示例代码**"],
- "footnotes": []
+ "type": "paragraph_title",
+ "anchor": "section-a",
+ "level": 2,
+ "content": "**章节标题**"
+ },
+ {
+ "type": "equation",
+ "content": "x^2+y^2=z^2",
+ "image_source": "images/equation.png"
}
]
}
@@ -72,9 +80,12 @@ content_list = render_content_list(
}
```
-`image/table/chart` 的 body 有图片载荷时,还会输出最终选择的 `image_source`:
-`image_path` 优先,`image_base64` 兜底,并应用 `asset_base_url` 和 Markdown 地址转义。
-即使 table 的 `content` 选择 GFM/HTML 表示,图片来源也会保留。
+`image/table/chart/equation` 有图片载荷时,会输出最终选择的 `image_source`:`image_path`
+优先,`image_base64` 兜底,并应用 `asset_base_url` 和 Markdown 地址转义。即使 table
+选择 GFM/HTML、equation 已有 LaTeX,图片来源也会保留且只出现一次。
+
+如需完整可展示 Markdown,应调用 `render_markdown()`,不能简单拼接 content_list 中的
+`content`。
该接口目前只属于严格 `mineru.render` 公共面;本契约不迁移旧 parser、CLI、API、
doclib 或历史扁平 `content_list.json` 产物。
diff --git a/mineru/render/content_list.py b/mineru/render/content_list.py
index bbb9f64e..467eafa8 100644
--- a/mineru/render/content_list.py
+++ b/mineru/render/content_list.py
@@ -8,10 +8,12 @@ from typing import Any, TypeAlias
from mineru.config import LatexDelimitersConfig, config
from mineru.render.markdown import (
_render_single_block,
+ _render_title_inline_content,
_render_visual_annotation,
- _render_visual_body,
+ _render_visual_body_content,
)
from mineru.render.utils.assets import normalize_image_source, resolve_image_source
+from mineru.render.utils.markdown_utils import escape_standalone_marker_rule, escape_text_block_markdown_prefix
from mineru.types import (
BlockType,
ChartAnnotationBlock,
@@ -19,11 +21,15 @@ from mineru.types import (
ChartBodyBlock,
CodeAnnotationBlock,
CodeBlock,
+ DocTitleBlock,
+ EquationBlock,
ImageAnnotationBlock,
ImageBlock,
ImageBodyBlock,
+ ImagePayloadBlock,
MiddleJson,
PageBlock,
+ ParagraphTitleBlock,
TableAnnotationBlock,
TableBlock,
TableBodyBlock,
@@ -44,7 +50,7 @@ _FOOTNOTE_TYPES = {
BlockType.CHART_FOOTNOTE,
BlockType.CODE_FOOTNOTE,
}
-_REMOVED_BLOCK_FIELDS = {"content", "index", "level", "guess_lang"}
+_REMOVED_BLOCK_FIELDS = {"content", "index", "guess_lang", "image_path", "image_base64"}
def render_content_list(
@@ -91,6 +97,16 @@ def _render_content_block(
exclude=_REMOVED_BLOCK_FIELDS,
exclude_defaults=True,
)
+ if isinstance(block, (DocTitleBlock, ParagraphTitleBlock)):
+ content = _render_title_inline_content(block, delimiters)
+ payload["content"] = escape_standalone_marker_rule(escape_text_block_markdown_prefix(content))
+ return payload
+ if isinstance(block, EquationBlock):
+ payload["content"] = block.content.strip()
+ image_source = _resolve_content_image_source(block, asset_base_url)
+ if image_source is not None:
+ payload["image_source"] = image_source
+ return payload
if not isinstance(block, (ImageBlock, TableBlock, ChartBlock, CodeBlock)):
payload["content"] = _render_single_block(
block,
@@ -99,7 +115,7 @@ def _render_content_block(
)
return payload
- payload["content"] = _render_visual_body(
+ payload["content"] = _render_visual_body_content(
block,
delimiters=delimiters,
asset_base_url=asset_base_url,
@@ -145,9 +161,14 @@ def _resolve_visual_image_source(block: VisualBlock, asset_base_url: str) -> str
for child in block.content:
if not isinstance(child, (ImageBodyBlock, TableBodyBlock, ChartBodyBlock)):
continue
- source = resolve_image_source(child, asset_base_url)
- return normalize_image_source(source) if source else None
+ return _resolve_content_image_source(child, asset_base_url)
return None
+def _resolve_content_image_source(block: ImagePayloadBlock, asset_base_url: str) -> str | None:
+ """把图片载荷收敛为 content_list 中唯一且安全的 image_source。"""
+ source = resolve_image_source(block, asset_base_url)
+ return normalize_image_source(source) if source else None
+
+
__all__ = ["render_content_list"]
diff --git a/mineru/render/markdown.py b/mineru/render/markdown.py
index c4f99962..2e82e20b 100644
--- a/mineru/render/markdown.py
+++ b/mineru/render/markdown.py
@@ -170,13 +170,21 @@ def _render_title(
) -> str:
"""渲染带可选 HTML anchor 的 Markdown 标题。"""
level = min(max(block.level, 1), 6)
- title = f"{'#' * level} {render_inline_content(block.content, delimiters)}"
+ title = f"{'#' * level} {_render_title_inline_content(block, delimiters)}"
if not block.anchor:
return title
anchor = html.escape(block.anchor.strip(), quote=True)
return f'<a id="{anchor}"></a>\n{title}'
+def _render_title_inline_content(
+ block: DocTitleBlock | ParagraphTitleBlock,
+ delimiters: LatexDelimitersConfig,
+) -> str:
+ """只渲染标题的行内语义,不添加 heading 标记或 HTML anchor。"""
+ return render_inline_content(block.content, delimiters)
+
+
def _render_equation(
block: EquationBlock,
delimiters: LatexDelimitersConfig,
@@ -327,17 +335,22 @@ def _render_media_body(
) -> str:
"""渲染图片载荷,并将识别内容放入折叠详情。"""
source = resolve_image_source(block, asset_base_url)
- content = block.content.strip()
+ rendered_content = _render_media_content(block, delimiters, asset_base_url)
if source:
parts = [build_markdown_image(source)]
- if content:
- normalized = format_embedded_html(
- content,
- asset_base_url=asset_base_url,
- delimiters=delimiters,
- )
- parts.append(_render_details(normalized, summary))
+ if rendered_content:
+ parts.append(_render_details(rendered_content, summary))
return "\n\n".join(part for part in parts if part)
+ return rendered_content
+
+
+def _render_media_content(
+ block: ImageBodyBlock,
+ delimiters: LatexDelimitersConfig,
+ asset_base_url: str,
+) -> str:
+ """渲染图片识别内容,不添加图片语法或折叠详情包装。"""
+ content = block.content.strip()
if not content:
return ""
return format_embedded_html(content, asset_base_url=asset_base_url, delimiters=delimiters)
@@ -416,19 +429,31 @@ def _render_table_body(
asset_base_url: str,
) -> str:
"""按 HTML、空间投影文本、图片的优先级渲染表格主体。"""
- if block.content:
- html_table = render_html_table(
- block.content,
- asset_base_url=asset_base_url,
- delimiters=delimiters,
- )
- if html_table is not None:
- return html_table
- return _render_fenced_content(block.content)
+ rendered_content = _render_table_content(block, delimiters, asset_base_url)
+ if rendered_content:
+ return rendered_content
source = resolve_image_source(block, asset_base_url)
return build_markdown_image(source) if source else ""
+def _render_table_content(
+ block: TableBodyBlock,
+ delimiters: LatexDelimitersConfig,
+ asset_base_url: str,
+) -> str:
+ """渲染表格结构内容,不执行空内容时的图片回退。"""
+ if not block.content:
+ return ""
+ html_table = render_html_table(
+ block.content,
+ asset_base_url=asset_base_url,
+ delimiters=delimiters,
+ )
+ if html_table is not None:
+ return html_table
+ return _render_fenced_content(block.content)
+
+
def _render_code_block(block: CodeBlock, delimiters: LatexDelimitersConfig) -> str:
"""按父块 subtype 渲染普通代码或支持公式的算法。"""
parts: list[str] = []
@@ -449,21 +474,22 @@ def _render_code_block(block: CodeBlock, delimiters: LatexDelimitersConfig) -> s
return _join_visual_parts(parts)
-def _render_visual_body(
+def _render_visual_body_content(
block: ImageBlock | TableBlock | ChartBlock | CodeBlock,
*,
delimiters: LatexDelimitersConfig,
asset_base_url: str,
) -> str:
- """查找视觉父块唯一 body,并复用 Markdown body 规则渲染。"""
+ """查找视觉父块唯一 body,并只渲染可结构化消费的语义内容。"""
for child in block.content:
- if isinstance(child, (ImageBodyBlock, TableBodyBlock, ChartBodyBlock, CodeBodyBlock)):
- return _render_visual_body_child(
- block,
- child,
- delimiters=delimiters,
- asset_base_url=asset_base_url,
- )
+ if isinstance(block, ImageBlock) and isinstance(child, ImageBodyBlock):
+ return _render_media_content(child, delimiters, asset_base_url)
+ if isinstance(block, TableBlock) and isinstance(child, TableBodyBlock):
+ return _render_table_content(child, delimiters, asset_base_url)
+ if isinstance(block, ChartBlock) and isinstance(child, ChartBodyBlock):
+ return _render_chart_content(child.content, delimiters, asset_base_url)
+ if isinstance(block, CodeBlock) and isinstance(child, CodeBodyBlock):
+ return _render_code_body(block, child, delimiters)
raise ValueError(f"Missing visual body: {block.type}")
diff --git a/tests/unittest/test_content_list_render.py b/tests/unittest/test_content_list_render.py
index 08e0fbf1..930a81f6 100644
--- a/tests/unittest/test_content_list_render.py
+++ b/tests/unittest/test_content_list_render.py
@@ -6,11 +6,12 @@ from copy import deepcopy
import pytest
from mineru.config import Config
-from mineru.render import render_content_list
+from mineru.render import render_content_list, render_markdown
from mineru.types import (
ChartBlock,
ChartBodyBlock,
CodeBlock,
+ EquationBlock,
ImageBlock,
IndexBlock,
ListBlock,
@@ -41,17 +42,19 @@ def _page(page_idx: int, *blocks: PageBlock) -> PageInfo:
return PageInfo(page_idx=page_idx, blocks=list(blocks))
-def _assert_removed_fields_absent(value: object) -> None:
- """递归确认 content_list 没有暴露被移除的 block 字段。"""
+def _assert_output_field_contract(value: object) -> None:
+ """递归确认输出只在标题保留 level,且不暴露内部或重复图片字段。"""
if isinstance(value, list):
for item in value:
- _assert_removed_fields_absent(item)
+ _assert_output_field_contract(item)
return
if not isinstance(value, dict):
return
- assert not ({"index", "level", "guess_lang"} & value.keys())
+ assert not ({"index", "guess_lang", "image_path", "image_base64"} & value.keys())
+ if "level" in value:
+ assert value.get("type") in {"doc_title", "paragraph_title"}
for item in value.values():
- _assert_removed_fields_absent(item)
+ _assert_output_field_contract(item)
def test_content_list_preserves_document_tree_without_merging_or_mutation() -> None:
@@ -62,9 +65,9 @@ def test_content_list_preserves_document_tree_without_merging_or_mutation() -> N
ParagraphTitleBlock(
type="paragraph_title",
index=0,
- level=2,
+ level=8,
anchor="section-a",
- content="Section",
+ content='# <text style="bold">Section</text> <eq>x</eq>',
),
TextBlock(type="text", index=1, content="first-"),
PageAuxTextBlock(type="header", index=2, content="HEADER"),
@@ -90,13 +93,15 @@ def test_content_list_preserves_document_tree_without_merging_or_mutation() -> N
assert result["pages"][0]["blocks"][0] == {
"type": "paragraph_title",
"anchor": "section-a",
- "content": '<a id="section-a"></a>\n## Section',
+ "level": 8,
+ "content": r"\# **Section** $x$",
}
+ assert render_markdown(middle).startswith('<a id="section-a"></a>\n###### # **Section** $x$')
assert result["pages"][0]["blocks"][1]["content"] == "first-"
assert result["pages"][0]["blocks"][2]["content"] == "HEADER"
assert result["pages"][1]["blocks"][0]["content"] == "continued"
assert result["pages"][1]["blocks"][0]["continues_prev"] is True
- _assert_removed_fields_absent(result)
+ _assert_output_field_contract(result)
assert middle == original
@@ -146,7 +151,7 @@ def test_content_list_flattens_recursive_list_index_and_code_metadata() -> None:
assert blocks[2]["captions"] == ["**Example**"]
assert blocks[2]["footnotes"] == ["note $x$"]
assert "guess_lang" not in blocks[2]
- _assert_removed_fields_absent(blocks)
+ _assert_output_field_contract(blocks)
def test_content_list_sorts_visual_annotations_and_selects_image_source() -> None:
@@ -181,13 +186,14 @@ def test_content_list_sorts_visual_annotations_and_selects_image_source() -> Non
asset_base_url="https://cdn.example/doc",
)["pages"][0]["blocks"][0]
- assert result["content"].startswith("![](https://cdn.example/doc/images/a%20b.png)\n\n<details>")
- assert "description" in result["content"]
+ assert result["content"] == "description"
assert result["image_source"] == "https://cdn.example/doc/images/a%20b.png"
assert result["captions"] == ["**early**", "", "missing index"]
assert result["footnotes"] == ["after"]
- assert "data:image" not in result["content"]
- _assert_removed_fields_absent(result)
+ assert "![](" not in result["content"]
+ assert "<details>" not in result["content"]
+ assert "data:image" not in json.dumps(result)
+ _assert_output_field_contract(result)
def test_content_list_keeps_table_image_source_and_cross_page_metadata() -> None:
@@ -221,10 +227,23 @@ def test_content_list_keeps_table_image_source_and_cross_page_metadata() -> None
],
}
)
+ image_only = TableBlock(
+ type="table",
+ index=0,
+ content=[
+ TableBodyBlock(
+ type="table_body",
+ index=0,
+ content="",
+ image_path="images/image-only-table.png",
+ )
+ ],
+ )
- result = render_content_list(_middle(_page(0, first), _page(1, second)))
+ result = render_content_list(_middle(_page(0, first), _page(1, second), _page(2, image_only)))
first_output = result["pages"][0]["blocks"][0]
second_output = result["pages"][1]["blocks"][0]
+ image_only_output = result["pages"][2]["blocks"][0]
assert first_output["content"] == "| A |\n| --- |\n| 1 |"
assert first_output["image_source"] == "images/table.png"
@@ -235,10 +254,12 @@ def test_content_list_keeps_table_image_source_and_cross_page_metadata() -> None
assert second_output["cell_merge"] == [1]
assert second_output["captions"] == ["Table 2"]
assert second_output["footnotes"] == ["note"]
+ assert image_only_output["content"] == ""
+ assert image_only_output["image_source"] == "images/image-only-table.png"
-def test_content_list_uses_render_config_and_base64_fallback(monkeypatch: pytest.MonkeyPatch) -> None:
- """验证 content_list 复用公式配置,并在无路径时选择 base64 图片来源。"""
+def test_content_list_keeps_chart_content_separate_from_base64_source(monkeypatch: pytest.MonkeyPatch) -> None:
+ """验证 chart 只在 image_source 保存 base64,结构内容继续复用行内公式配置。"""
configured = Config(
render={
"latex_delimiters": {
@@ -264,8 +285,75 @@ def test_content_list_uses_render_config_and_base64_fallback(monkeypatch: pytest
output = render_content_list(_middle(_page(0, chart)))["pages"][0]["blocks"][0]
assert output["image_source"] == "data:image/png;base64,AAAA"
- assert output["content"].startswith("![](data:image/png;base64,AAAA)\n\n<details>")
- assert "| \\(x\\) |" in output["content"]
+ assert output["content"] == "| A |\n| --- |\n| \\(x\\) |"
+ assert json.dumps(output).count("data:image/png;base64,AAAA") == 1
+ assert "![](" not in output["content"]
+ assert "<details>" not in output["content"]
+
+
+def test_content_list_renders_equation_as_raw_latex_with_single_image_source(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """验证 equation 不加行间定界符,并把选中的图片载荷唯一提升为 image_source。"""
+ configured = Config(
+ render={
+ "latex_delimiters": {
+ "display": {"left": "\\[", "right": "\\]"},
+ "inline": {"left": "\\(", "right": "\\)"},
+ }
+ }
+ )
+ monkeypatch.setattr("mineru.render.content_list.config", configured)
+ middle = _middle(
+ _page(
+ 0,
+ EquationBlock(type="equation", index=0, content=" x=1 "),
+ EquationBlock(
+ type="equation",
+ index=1,
+ content="",
+ image_base64="data:image/png;base64,BBBB",
+ ),
+ EquationBlock(
+ type="equation",
+ index=2,
+ content="y=2",
+ image_base64="data:image/png;base64,CCCC",
+ ),
+ EquationBlock(
+ type="equation",
+ index=3,
+ content="z=3",
+ image_path="images/e q.png",
+ image_base64="data:image/png;base64,DDDD",
+ ),
+ )
+ )
+
+ blocks = render_content_list(middle, asset_base_url="https://cdn.example/doc")["pages"][0]["blocks"]
+
+ assert blocks[0] == {"type": "equation", "content": "x=1"}
+ assert blocks[1] == {
+ "type": "equation",
+ "content": "",
+ "image_source": "data:image/png;base64,BBBB",
+ }
+ assert blocks[2] == {
+ "type": "equation",
+ "content": "y=2",
+ "image_source": "data:image/png;base64,CCCC",
+ }
+ assert blocks[3] == {
+ "type": "equation",
+ "content": "z=3",
+ "image_source": "https://cdn.example/doc/images/e%20q.png",
+ }
+ serialized = json.dumps(blocks)
+ assert serialized.count("data:image/png;base64,BBBB") == 1
+ assert serialized.count("data:image/png;base64,CCCC") == 1
+ assert "data:image/png;base64,DDDD" not in serialized
+ assert "\\[" not in serialized and "\\]" not in serialized
+ _assert_output_field_contract(blocks)
def test_content_list_rejects_legacy_dict_input() -> None: