Skip to content

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

feat: implement render_content_list for structured Markdown output from MiddleJson

myhloli0103b60eaab9
diff --git a/docs/next/middle-json/rendering.md b/docs/next/middle-json/rendering.md
index 4a0c192d..37a4ee2f 100644
--- a/docs/next/middle-json/rendering.md
+++ b/docs/next/middle-json/rendering.md
@@ -23,6 +23,62 @@ backend 参数或旧 `Line/Span` renderer。渲染过程基于深拷贝,不修
图片优先使用 `image_path`,缺失时使用 `image_base64` data URI。
`asset_base_url` 只给相对 `image_path` 和 HTML 内相对 `img src` 添加前缀。
+## 树形 Markdown Content List
+
+严格 render 层还提供不合并、不丢块的树形内容输出:
+
+```python
+from mineru.render import render_content_list
+
+content_list = render_content_list(
+ middle_json,
+ asset_base_url="",
+)
+```
+
+`render_content_list()` 只接受 `MiddleJson`,返回可以直接交给 `json.dumps()` 的
+文档级 dict。顶层保留 `pages/file_suffix/effort/parse_mode/mineru_version`,每页保留
+`page_idx/blocks`,页面和顶层 block 的数量及顺序不变。它不使用下文的
+`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 的生成。
+
+```json
+{
+ "pages": [
+ {
+ "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": []
+ }
+ ]
+ }
+ ],
+ "file_suffix": "pdf",
+ "effort": "flash",
+ "parse_mode": "txt",
+ "mineru_version": "3.4.0"
+}
+```
+
+`image/table/chart` 的 body 有图片载荷时,还会输出最终选择的 `image_source`:
+`image_path` 优先,`image_base64` 兜底,并应用 `asset_base_url` 和 Markdown 地址转义。
+即使 table 的 `content` 选择 GFM/HTML 表示,图片来源也会保留。
+
+该接口目前只属于严格 `mineru.render` 公共面;本契约不迁移旧 parser、CLI、API、
+doclib 或历史扁平 `content_list.json` 产物。
+
## 展示模式
`MarkdownRenderMode.DEFAULT`:
diff --git a/mineru/render/__init__.py b/mineru/render/__init__.py
index c55a9d78..81e8695e 100644
--- a/mineru/render/__init__.py
+++ b/mineru/render/__init__.py
@@ -1,5 +1,6 @@
# Copyright (c) Opendatalab. All rights reserved.
+from .content_list import render_content_list
from .markdown import MarkdownRenderMode, render_markdown
-__all__ = ["MarkdownRenderMode", "render_markdown"]
+__all__ = ["MarkdownRenderMode", "render_content_list", "render_markdown"]
diff --git a/mineru/render/content_list.py b/mineru/render/content_list.py
new file mode 100644
index 00000000..bbb9f64e
--- /dev/null
+++ b/mineru/render/content_list.py
@@ -0,0 +1,153 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""严格 MiddleJson 到树形 Markdown content_list 的公共渲染实现。"""
+
+from __future__ import annotations
+
+from typing import Any, TypeAlias
+
+from mineru.config import LatexDelimitersConfig, config
+from mineru.render.markdown import (
+ _render_single_block,
+ _render_visual_annotation,
+ _render_visual_body,
+)
+from mineru.render.utils.assets import normalize_image_source, resolve_image_source
+from mineru.types import (
+ BlockType,
+ ChartAnnotationBlock,
+ ChartBlock,
+ ChartBodyBlock,
+ CodeAnnotationBlock,
+ CodeBlock,
+ ImageAnnotationBlock,
+ ImageBlock,
+ ImageBodyBlock,
+ MiddleJson,
+ PageBlock,
+ TableAnnotationBlock,
+ TableBlock,
+ TableBodyBlock,
+)
+
+VisualBlock: TypeAlias = ImageBlock | TableBlock | ChartBlock | CodeBlock
+VisualAnnotationBlock: TypeAlias = ImageAnnotationBlock | TableAnnotationBlock | ChartAnnotationBlock | CodeAnnotationBlock
+
+_CAPTION_TYPES = {
+ BlockType.IMAGE_CAPTION,
+ BlockType.TABLE_CAPTION,
+ BlockType.CHART_CAPTION,
+ BlockType.CODE_CAPTION,
+}
+_FOOTNOTE_TYPES = {
+ BlockType.IMAGE_FOOTNOTE,
+ BlockType.TABLE_FOOTNOTE,
+ BlockType.CHART_FOOTNOTE,
+ BlockType.CODE_FOOTNOTE,
+}
+_REMOVED_BLOCK_FIELDS = {"content", "index", "level", "guess_lang"}
+
+
+def render_content_list(
+ middle_json: MiddleJson,
+ *,
+ asset_base_url: str = "",
+) -> dict[str, Any]:
+ """把严格 MiddleJson 无副作用地渲染为树形 Markdown content_list。"""
+ if not isinstance(middle_json, MiddleJson):
+ raise TypeError("render_content_list expects a MiddleJson instance")
+
+ delimiters = config.render.latex_delimiters
+ document_fields = middle_json.model_dump(
+ mode="json",
+ exclude={"pages"},
+ exclude_defaults=True,
+ )
+ pages = [
+ {
+ "page_idx": page.page_idx,
+ "blocks": [
+ _render_content_block(
+ block,
+ delimiters=delimiters,
+ asset_base_url=asset_base_url,
+ )
+ for block in page.blocks
+ ],
+ }
+ for page in middle_json.pages
+ ]
+ return {"pages": pages, **document_fields}
+
+
+def _render_content_block(
+ block: PageBlock,
+ *,
+ delimiters: LatexDelimitersConfig,
+ asset_base_url: str,
+) -> dict[str, Any]:
+ """保留父块元数据,并把 block 内容收敛为 Markdown 字符串。"""
+ payload = block.model_dump(
+ mode="json",
+ exclude=_REMOVED_BLOCK_FIELDS,
+ exclude_defaults=True,
+ )
+ if not isinstance(block, (ImageBlock, TableBlock, ChartBlock, CodeBlock)):
+ payload["content"] = _render_single_block(
+ block,
+ delimiters=delimiters,
+ asset_base_url=asset_base_url,
+ )
+ return payload
+
+ payload["content"] = _render_visual_body(
+ block,
+ delimiters=delimiters,
+ asset_base_url=asset_base_url,
+ )
+ payload["captions"] = _render_annotation_group(block, _CAPTION_TYPES, delimiters)
+ payload["footnotes"] = _render_annotation_group(block, _FOOTNOTE_TYPES, delimiters)
+ image_source = _resolve_visual_image_source(block, asset_base_url)
+ if image_source is not None:
+ payload["image_source"] = image_source
+ return payload
+
+
+def _render_annotation_group(
+ block: VisualBlock,
+ accepted_types: set[str],
+ delimiters: LatexDelimitersConfig,
+) -> list[str]:
+ """按源 index 稳定排序一组视觉说明,并逐项渲染为 Markdown。"""
+ annotations: list[tuple[int, VisualAnnotationBlock]] = []
+ for position, child in enumerate(block.content):
+ if (
+ isinstance(
+ child,
+ (ImageAnnotationBlock, TableAnnotationBlock, ChartAnnotationBlock, CodeAnnotationBlock),
+ )
+ and child.type in accepted_types
+ ):
+ annotations.append((position, child))
+ annotations.sort(key=_annotation_sort_key)
+ return [_render_visual_annotation(child, delimiters) for _, child in annotations]
+
+
+def _annotation_sort_key(
+ item: tuple[int, VisualAnnotationBlock],
+) -> tuple[bool, int, int]:
+ """让有 index 的说明升序优先,缺失 index 的说明稳定排在末尾。"""
+ position, block = item
+ return block.index is None, block.index if block.index is not None else 0, position
+
+
+def _resolve_visual_image_source(block: VisualBlock, asset_base_url: str) -> str | None:
+ """解析视觉 body 实际选择的图片来源,并返回安全的 Markdown 地址。"""
+ 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 None
+
+
+__all__ = ["render_content_list"]
diff --git a/mineru/render/markdown.py b/mineru/render/markdown.py
index 95bd3162..c4f99962 100644
--- a/mineru/render/markdown.py
+++ b/mineru/render/markdown.py
@@ -36,6 +36,7 @@ from mineru.types import (
ListBlock,
MiddleJson,
PageAuxTextBlock,
+ PageBlock,
ParagraphTitleBlock,
RefTextBlock,
TableAnnotationBlock,
@@ -147,6 +148,22 @@ def _render_planned_block(
raise TypeError(f"Unsupported PageBlock type: {type(block).__name__}")
+def _render_single_block(
+ block: PageBlock,
+ *,
+ delimiters: LatexDelimitersConfig,
+ asset_base_url: str,
+) -> str:
+ """不执行续段合并或页面过滤,直接渲染一个顶层 block。"""
+ text_contents = [block.content] if isinstance(block, (TextBlock, RefTextBlock)) else []
+ planned = PlannedBlock(page_idx=0, block=block, text_contents=text_contents)
+ return _render_planned_block(
+ planned,
+ delimiters=delimiters,
+ asset_base_url=asset_base_url,
+ )
+
+
def _render_title(
block: DocTitleBlock | ParagraphTitleBlock,
delimiters: LatexDelimitersConfig,
@@ -262,14 +279,14 @@ def _render_image_block(
parts: list[str] = []
for child in block.content:
if isinstance(child, ImageBodyBlock):
- body = _render_media_body(
+ body = _render_visual_body_child(
+ block,
child,
- summary=block.sub_type or "image content",
delimiters=delimiters,
asset_base_url=asset_base_url,
)
elif isinstance(child, ImageAnnotationBlock):
- body = escape_standalone_marker_rule(render_inline_content(child.content, delimiters))
+ body = _render_visual_annotation(child, delimiters)
else:
raise TypeError(f"Unsupported image child: {type(child).__name__}")
if body:
@@ -286,14 +303,14 @@ def _render_chart_block(
parts: list[str] = []
for child in block.content:
if isinstance(child, ChartBodyBlock):
- body = _render_chart_body(
+ body = _render_visual_body_child(
+ block,
child,
- summary=block.sub_type or "chart content",
delimiters=delimiters,
asset_base_url=asset_base_url,
)
elif isinstance(child, ChartAnnotationBlock):
- body = escape_standalone_marker_rule(render_inline_content(child.content, delimiters))
+ body = _render_visual_annotation(child, delimiters)
else:
raise TypeError(f"Unsupported chart child: {type(child).__name__}")
if body:
@@ -378,9 +395,14 @@ def _render_table_block(
parts: list[str] = []
for child in block.content:
if isinstance(child, TableBodyBlock):
- body = _render_table_body(child, delimiters, asset_base_url)
+ body = _render_visual_body_child(
+ block,
+ child,
+ delimiters=delimiters,
+ asset_base_url=asset_base_url,
+ )
elif isinstance(child, TableAnnotationBlock):
- body = escape_standalone_marker_rule(render_inline_content(child.content, delimiters))
+ body = _render_visual_annotation(child, delimiters)
else:
raise TypeError(f"Unsupported table child: {type(child).__name__}")
if body:
@@ -412,14 +434,14 @@ def _render_code_block(block: CodeBlock, delimiters: LatexDelimitersConfig) -> s
parts: list[str] = []
for child in block.content:
if isinstance(child, CodeBodyBlock):
- if block.sub_type == BlockType.CODE:
- body = _render_fenced_content(child.content, _normalize_code_language(block.guess_lang))
- elif block.sub_type == RAW_ALGORITHM:
- body = _render_algorithm_html(child.content, delimiters)
- else:
- raise ValueError(f"Unsupported code subtype: {block.sub_type}")
+ body = _render_visual_body_child(
+ block,
+ child,
+ delimiters=delimiters,
+ asset_base_url="",
+ )
elif isinstance(child, CodeAnnotationBlock):
- body = escape_standalone_marker_rule(render_inline_content(child.content, delimiters))
+ body = _render_visual_annotation(child, delimiters)
else:
raise TypeError(f"Unsupported code child: {type(child).__name__}")
if body:
@@ -427,6 +449,74 @@ def _render_code_block(block: CodeBlock, delimiters: LatexDelimitersConfig) -> s
return _join_visual_parts(parts)
+def _render_visual_body(
+ block: ImageBlock | TableBlock | ChartBlock | CodeBlock,
+ *,
+ delimiters: LatexDelimitersConfig,
+ asset_base_url: str,
+) -> str:
+ """查找视觉父块唯一 body,并复用 Markdown 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,
+ )
+ raise ValueError(f"Missing visual body: {block.type}")
+
+
+def _render_visual_body_child(
+ block: ImageBlock | TableBlock | ChartBlock | CodeBlock,
+ child: ImageBodyBlock | TableBodyBlock | ChartBodyBlock | CodeBodyBlock,
+ *,
+ delimiters: LatexDelimitersConfig,
+ asset_base_url: str,
+) -> str:
+ """按视觉父子类型组合渲染一个 body 子块。"""
+ if isinstance(block, ImageBlock) and isinstance(child, ImageBodyBlock):
+ return _render_media_body(
+ child,
+ summary=block.sub_type or "image content",
+ delimiters=delimiters,
+ asset_base_url=asset_base_url,
+ )
+ if isinstance(block, TableBlock) and isinstance(child, TableBodyBlock):
+ return _render_table_body(child, delimiters, asset_base_url)
+ if isinstance(block, ChartBlock) and isinstance(child, ChartBodyBlock):
+ return _render_chart_body(
+ child,
+ summary=block.sub_type or "chart content",
+ delimiters=delimiters,
+ asset_base_url=asset_base_url,
+ )
+ if isinstance(block, CodeBlock) and isinstance(child, CodeBodyBlock):
+ return _render_code_body(block, child, delimiters)
+ raise TypeError(f"Unsupported visual body pair: {block.type}/{child.type}")
+
+
+def _render_visual_annotation(
+ block: ImageAnnotationBlock | TableAnnotationBlock | ChartAnnotationBlock | CodeAnnotationBlock,
+ delimiters: LatexDelimitersConfig,
+) -> str:
+ """把一个视觉说明子块渲染为独立 Markdown 字符串。"""
+ return escape_standalone_marker_rule(render_inline_content(block.content, delimiters))
+
+
+def _render_code_body(
+ block: CodeBlock,
+ child: CodeBodyBlock,
+ delimiters: LatexDelimitersConfig,
+) -> str:
+ """依据父块 subtype 渲染代码或算法 body。"""
+ if block.sub_type == BlockType.CODE:
+ return _render_fenced_content(child.content, _normalize_code_language(block.guess_lang))
+ if block.sub_type == RAW_ALGORITHM:
+ return _render_algorithm_html(child.content, delimiters)
+ raise ValueError(f"Unsupported code subtype: {block.sub_type}")
+
+
def _normalize_code_language(language: str | None) -> str:
"""校验 fenced code info string,非法值统一回退 txt。"""
normalized = (language or "").strip()
@@ -471,11 +561,7 @@ def _render_algorithm_html(content: str, delimiters: LatexDelimitersConfig) -> s
cursor = match.end()
parts.append(content[cursor:])
body = "".join(parts)
- return (
- '<div class="mineru-algorithm" style="white-space: pre-wrap; font-family:monospace;">\n'
- f"{body}\n"
- "</div>"
- )
+ return f'<div class="mineru-algorithm" style="white-space: pre-wrap; font-family:monospace;">\n{body}\n</div>'
def _join_visual_parts(parts: list[str]) -> str:
diff --git a/mineru/render/utils/assets.py b/mineru/render/utils/assets.py
index 7088214e..73a79cdf 100644
--- a/mineru/render/utils/assets.py
+++ b/mineru/render/utils/assets.py
@@ -35,13 +35,17 @@ def build_markdown_image(source: str, alt: str = "") -> str:
if not source:
return ""
safe_alt = alt.replace("[", r"\[").replace("]", r"\]")
- if source.startswith("data:"):
- destination = source
- else:
- destination = quote(source, safe="/:#?&=%@+~,;!$'*-._")
+ destination = normalize_image_source(source)
return f"![{safe_alt}]({destination})"
+def normalize_image_source(source: str) -> str:
+ """把图片来源规范化为 Markdown 与 content_list 共用的安全地址。"""
+ if source.startswith("data:"):
+ return source
+ return quote(source, safe="/:#?&=%@+~,;!$'*-._")
+
+
def prefix_html_image_sources(markup: str, asset_base_url: str = "") -> str:
"""给 HTML 中的相对图片地址添加资源根地址。"""
if not markup or not asset_base_url:
@@ -67,6 +71,7 @@ def _is_absolute_image_source(source: str) -> bool:
__all__ = [
"build_markdown_image",
"join_asset_base_url",
+ "normalize_image_source",
"prefix_html_image_sources",
"resolve_image_source",
]
diff --git a/tests/unittest/test_content_list_render.py b/tests/unittest/test_content_list_render.py
new file mode 100644
index 00000000..08e0fbf1
--- /dev/null
+++ b/tests/unittest/test_content_list_render.py
@@ -0,0 +1,276 @@
+from __future__ import annotations
+
+import json
+from copy import deepcopy
+
+import pytest
+
+from mineru.config import Config
+from mineru.render import render_content_list
+from mineru.types import (
+ ChartBlock,
+ ChartBodyBlock,
+ CodeBlock,
+ ImageBlock,
+ IndexBlock,
+ ListBlock,
+ MiddleJson,
+ PageAuxTextBlock,
+ PageBlock,
+ PageInfo,
+ ParagraphTitleBlock,
+ TableBlock,
+ TableBodyBlock,
+ TextBlock,
+)
+
+
+def _middle(*pages: PageInfo, file_suffix: str = "docx") -> MiddleJson:
+ """构造最小严格 MiddleJson 测试对象。"""
+ return MiddleJson(
+ pages=list(pages),
+ file_suffix=file_suffix,
+ effort="flash",
+ parse_mode="txt",
+ mineru_version="test",
+ )
+
+
+def _page(page_idx: int, *blocks: PageBlock) -> PageInfo:
+ """构造保持调用方 block 顺序的严格页面。"""
+ return PageInfo(page_idx=page_idx, blocks=list(blocks))
+
+
+def _assert_removed_fields_absent(value: object) -> None:
+ """递归确认 content_list 没有暴露被移除的 block 字段。"""
+ if isinstance(value, list):
+ for item in value:
+ _assert_removed_fields_absent(item)
+ return
+ if not isinstance(value, dict):
+ return
+ assert not ({"index", "level", "guess_lang"} & value.keys())
+ for item in value.values():
+ _assert_removed_fields_absent(item)
+
+
+def test_content_list_preserves_document_tree_without_merging_or_mutation() -> None:
+ """验证文档树、辅助块和续段字段原样保留,且输入对象不被修改。"""
+ middle = _middle(
+ _page(
+ 0,
+ ParagraphTitleBlock(
+ type="paragraph_title",
+ index=0,
+ level=2,
+ anchor="section-a",
+ content="Section",
+ ),
+ TextBlock(type="text", index=1, content="first-"),
+ PageAuxTextBlock(type="header", index=2, content="HEADER"),
+ ),
+ _page(
+ 1,
+ TextBlock(type="text", index=0, content="continued", continues_prev=True),
+ ),
+ )
+ original = deepcopy(middle)
+
+ result = render_content_list(middle)
+
+ assert json.loads(json.dumps(result, ensure_ascii=False)) == result
+ assert result["file_suffix"] == "docx"
+ assert result["effort"] == "flash"
+ assert [page["page_idx"] for page in result["pages"]] == [0, 1]
+ assert [block["type"] for block in result["pages"][0]["blocks"]] == [
+ "paragraph_title",
+ "text",
+ "header",
+ ]
+ assert result["pages"][0]["blocks"][0] == {
+ "type": "paragraph_title",
+ "anchor": "section-a",
+ "content": '<a id="section-a"></a>\n## Section',
+ }
+ 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 middle == original
+
+
+def test_content_list_flattens_recursive_list_index_and_code_metadata() -> None:
+ """验证递归容器和代码 body 上浮为 Markdown,渲染元数据不进入输出。"""
+ nested = ListBlock(
+ type="list",
+ content=[TextBlock(type="text", content="- inner")],
+ )
+ list_block = ListBlock(
+ type="list",
+ index=0,
+ sub_type="text",
+ content=[TextBlock(type="text", content="- outer"), nested],
+ )
+ index_block = IndexBlock(
+ type="index",
+ index=1,
+ content=[
+ ParagraphTitleBlock(
+ type="paragraph_title",
+ level=2,
+ anchor="section-b",
+ content="Section\t12",
+ )
+ ],
+ )
+ code = CodeBlock.model_validate(
+ {
+ "type": "code",
+ "index": 2,
+ "sub_type": "code",
+ "guess_lang": "python",
+ "content": [
+ {"type": "code_caption", "index": 4, "content": '<text style="bold">Example</text>'},
+ {"type": "code_body", "index": 2, "content": "print('x')\n```"},
+ {"type": "code_footnote", "index": 5, "content": "note <eq>x</eq>"},
+ ],
+ }
+ )
+
+ blocks = render_content_list(_middle(_page(0, list_block, index_block, code)))["pages"][0]["blocks"]
+
+ assert blocks[0]["content"] == "- outer\n - inner"
+ assert blocks[1]["content"] == "- [Section](#section-b)"
+ assert blocks[2]["content"] == "````python\nprint('x')\n```\n````"
+ assert blocks[2]["captions"] == ["**Example**"]
+ assert blocks[2]["footnotes"] == ["note $x$"]
+ assert "guess_lang" not in blocks[2]
+ _assert_removed_fields_absent(blocks)
+
+
+def test_content_list_sorts_visual_annotations_and_selects_image_source() -> None:
+ """验证视觉说明稳定排序、空项保留及图片 path 优先规则。"""
+ image = ImageBlock.model_validate(
+ {
+ "type": "image",
+ "index": 0,
+ "sub_type": "diagram",
+ "content": [
+ {"type": "image_caption", "content": "missing index"},
+ {
+ "type": "image_body",
+ "index": 0,
+ "content": "description",
+ "image_path": "images/a b.png",
+ "image_base64": "data:image/png;base64,AAAA",
+ },
+ {"type": "image_caption", "index": 5, "content": ""},
+ {
+ "type": "image_caption",
+ "index": 3,
+ "content": '<text style="bold">early</text>',
+ },
+ {"type": "image_footnote", "index": 4, "content": "after"},
+ ],
+ }
+ )
+
+ result = render_content_list(
+ _middle(_page(0, image)),
+ 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["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)
+
+
+def test_content_list_keeps_table_image_source_and_cross_page_metadata() -> None:
+ """验证表格 body 上浮后仍保留图片来源、续表字段且不执行跨页合并。"""
+ first = TableBlock(
+ type="table",
+ index=0,
+ content=[
+ TableBodyBlock(
+ type="table_body",
+ index=0,
+ content="<table><tr><th>A</th></tr><tr><td>1</td></tr></table>",
+ image_path="images/table.png",
+ )
+ ],
+ )
+ second = TableBlock.model_validate(
+ {
+ "type": "table",
+ "index": 0,
+ "continues_prev": True,
+ "cell_merge": [1],
+ "content": [
+ {
+ "type": "table_body",
+ "index": 0,
+ "content": "<table><tr><th>A</th></tr><tr><td>2</td></tr></table>",
+ },
+ {"type": "table_caption", "index": 2, "content": "Table 2"},
+ {"type": "table_footnote", "index": 3, "content": "note"},
+ ],
+ }
+ )
+
+ result = render_content_list(_middle(_page(0, first), _page(1, second)))
+ first_output = result["pages"][0]["blocks"][0]
+ second_output = result["pages"][1]["blocks"][0]
+
+ assert first_output["content"] == "| A |\n| --- |\n| 1 |"
+ assert first_output["image_source"] == "images/table.png"
+ assert first_output["captions"] == []
+ assert first_output["footnotes"] == []
+ assert second_output["content"] == "| A |\n| --- |\n| 2 |"
+ assert second_output["continues_prev"] is True
+ assert second_output["cell_merge"] == [1]
+ assert second_output["captions"] == ["Table 2"]
+ assert second_output["footnotes"] == ["note"]
+
+
+def test_content_list_uses_render_config_and_base64_fallback(monkeypatch: pytest.MonkeyPatch) -> None:
+ """验证 content_list 复用公式配置,并在无路径时选择 base64 图片来源。"""
+ configured = Config(
+ render={
+ "latex_delimiters": {
+ "display": {"left": "\\[", "right": "\\]"},
+ "inline": {"left": "\\(", "right": "\\)"},
+ }
+ }
+ )
+ monkeypatch.setattr("mineru.render.content_list.config", configured)
+ chart = ChartBlock(
+ type="chart",
+ index=0,
+ content=[
+ ChartBodyBlock(
+ type="chart_body",
+ index=0,
+ content="<table><tr><th>A</th></tr><tr><td><eq>x</eq></td></tr></table>",
+ image_base64="data:image/png;base64,AAAA",
+ )
+ ],
+ )
+
+ 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"]
+
+
+def test_content_list_rejects_legacy_dict_input() -> None:
+ """验证公共入口只接受严格 MiddleJson。"""
+ middle = _middle(_page(0))
+
+ with pytest.raises(TypeError, match="MiddleJson"):
+ render_content_list(middle.to_dict()) # type: ignore[arg-type]