Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.
Python ai4sciencedocument-analysisdocxextract-datalayout-analysisocrparserpdfpdf-converterpdf-extractor-llmpdf-extractor-pretrainpdf-extractor-ragpdf-parserpptxpythonxlsx
feat: implement rendering for Content List V1 and V2 with strict MiddleJson support
myhloliec5210e53395
diff --git a/docs/next/middle-json/rendering.md b/docs/next/middle-json/rendering.mdindex 0b09b54f..9c9e7de2 100644--- a/docs/next/middle-json/rendering.md+++ b/docs/next/middle-json/rendering.md@@ -1,8 +1,8 @@# Rendering Contract-状态: 统一入口 / Markdown / Structured Content / DOCX / HTML v1+状态: 统一入口 / Markdown / Content List V1/V2 / Structured Content / DOCX / HTML v1读者: render 开发者、backend 开发者、SDK 开发者-范围: 严格 MiddleJson 到 Markdown、Structured Content、DOCX 和 HTML 的统一消费契约+范围: 严格 MiddleJson 到 Markdown、Content List V1/V2、Structured Content、DOCX 和 HTML 的统一消费契约## 统一入口@@ -32,9 +32,11 @@ markdown = render(| `HTML` | `HtmlRenderOptions(mode, asset_base_url, standalone, document_title)` | `str` || `DOCX` | `DocxRenderOptions(mode, asset_resolver)` | `bytes` || `STRUCTURED_CONTENT` | `StructuredContentRenderOptions(asset_base_url)` | `dict[str, Any]` |+| `CONTENT_LIST` | `ContentListRenderOptions(asset_base_url)` | `list[dict[str, Any]]` |+| `CONTENT_LIST_V2` | `ContentListV2RenderOptions(asset_base_url)` | `list[list[dict[str, Any]]]` |`options` 省略时使用对应格式的默认 Options。入口只接受 `RenderFormat` 枚举,格式与 Options-类型不匹配时抛出 `TypeError`,不归一化字符串格式,也不在单次调用中批量渲染。四个专用+类型不匹配时抛出 `TypeError`,不归一化字符串格式,也不在单次调用中批量渲染。各专用`render_*()` 函数继续保留;统一入口只负责严格校验和分发,不改变底层渲染语义或异常类型。所有入口均不修改传入的 `MiddleJson`。renderer 不负责把结果或图片写到文件系统;DOCX@@ -42,7 +44,8 @@ markdown = render(### 内部依赖边界-`markdown.py`、`html.py`、`docx.py` 和 `structured_content.py` 是稳定公共门面;实现代码位于非公共+`markdown.py`、`html.py`、`docx.py`、`content_list.py`、`content_list_v2.py` 和+`structured_content.py` 是稳定公共门面;实现代码位于非公共`mineru.render._internal`。`common` 只保存跨格式 AST、解析、列表/目录语义和 render planner,不得依赖任一格式实现。`markdown`、`html`、`docx` 子包只能依赖 `common` 与自身模块,彼此不交叉导入。`_internal` 路径不属于 SDK 兼容承诺。@@ -229,6 +232,33 @@ Chart 的 pipe table 只实现 GFM 列结构与反斜杠/pipe 解码,cell 内v1 只增加严格 `mineru.render` 公共面,不迁移旧 parser、CLI、API 或 doclib,也不提供Markdown 字符串转 HTML、离线单文件、主题切换、侧边 TOC 或用户自定义 head/CSS/script。+## 3.4.5 兼容 Content List V1/V2++严格 render 层同时提供两个由当前 MiddleJson 派生的兼容结构:++```python+from mineru.render import render_content_list, render_content_list_v2++content_list = render_content_list(middle_json, asset_base_url="")+content_list_v2 = render_content_list_v2(middle_json, asset_base_url="")+```++`render_content_list()` 返回按页序扁平化的 `list[dict]`。每个 item 保留真实 `page_idx`,可用 bbox+转换为 0-1000 整数坐标;标题继续使用 `type: "text"` 和 `text_level`,视觉内容使用+`img_path`、caption、footnote 与 body 等 3.4.5 字段。++`render_content_list_v2()` 返回 `list[list[dict]]`,外层与输入页面一一对应,空页保留 `[]`;每个+item 使用 3.4.5 风格的 `type + content`,行内内容收敛为 `text`、`equation_inline`、+`code_inline` 和 `hyperlink` span。V2 不增加 envelope 或显式页号,因此抽页结果只能通过外层顺序消费。++两个 renderer 都只接受严格 `MiddleJson`,保持页面和 block 阅读顺序,不使用展示型 planner,也不合并+`continues_prev` 文本或跨页表格。同页连续 `ref_text` 会合并为 reference list;列表、目录按源顺序递归+展平,目录删除可信的末尾页码并保留 anchor。图片按 `image_path`、`image_base64`、`image_url` 的顺序+选择唯一来源,相对 sidecar 与 HTML 内相对图片使用 `asset_base_url`。++这是 render 层兼容 API;本阶段不新增 ParseResult 方法,不迁移 CLI/API 格式名,也不新增自动落盘产物。+现有 `render_structured_content()` 仍是独立的树形文档级 dict,不是 V2 的别名。+## 树形 Markdown Structured Content严格 render 层还提供不合并、不丢块的树形内容输出:diff --git a/mineru/render/__init__.py b/mineru/render/__init__.pyindex 4cdbb6a8..d1d8ddf1 100644--- a/mineru/render/__init__.py+++ b/mineru/render/__init__.py@@ -3,6 +3,8 @@from .api import renderfrom .contracts import (AssetResolver,+ ContentListRenderOptions,+ ContentListV2RenderOptions,DocxRenderOptions,HtmlRenderOptions,ImageRenderer,@@ -13,6 +15,8 @@ from .contracts import (RenderOutput,StructuredContentRenderOptions,)+from .content_list import render_content_list+from .content_list_v2 import render_content_list_v2from .docx import DocxRenderError, render_docxfrom .html import render_htmlfrom .markdown import render_markdown@@ -20,6 +24,8 @@ from .structured_content import render_structured_content__all__ = ["AssetResolver",+ "ContentListRenderOptions",+ "ContentListV2RenderOptions","DocxRenderError","DocxRenderOptions","HtmlRenderOptions",@@ -31,6 +37,8 @@ __all__ = ["RenderOutput","StructuredContentRenderOptions","render",+ "render_content_list",+ "render_content_list_v2","render_docx","render_html","render_markdown",diff --git a/mineru/render/_internal/content_list/__init__.py b/mineru/render/_internal/content_list/__init__.pynew file mode 100644index 00000000..d51738a4--- /dev/null+++ b/mineru/render/_internal/content_list/__init__.py@@ -0,0 +1,4 @@+# Copyright (c) Opendatalab. All rights reserved.+"""Content List V1/V2 私有渲染实现。"""++__all__: list[str] = []diff --git a/mineru/render/_internal/content_list/common.py b/mineru/render/_internal/content_list/common.pynew file mode 100644index 00000000..9eb45299--- /dev/null+++ b/mineru/render/_internal/content_list/common.py@@ -0,0 +1,298 @@+# Copyright (c) Opendatalab. All rights reserved.+"""Content List V1/V2 共用的严格 MiddleJson 投影能力。"""++from __future__ import annotations++import re+from collections.abc import Iterator+from dataclasses import dataclass+from typing import TypeAlias++from ....backend.postprocess.inline import inline_plain_text+from ....config import LatexDelimitersConfig+from ....types import (+ BBox,+ AlgorithmBodyBlock,+ ChartAnnotationBlock,+ ChartBlock,+ ChartBodyBlock,+ CodeAnnotationBlock,+ CodeBlock,+ CodeBodyBlock,+ CodeInlineSpan,+ DocTitleBlock,+ EquationInlineSpan,+ HyperlinkSpan,+ ImageAnnotationBlock,+ ImageBlock,+ ImageBodyBlock,+ ImagePayloadBlock,+ IndexBlock,+ InlineSpan,+ ListBlock,+ PageBlock,+ ParagraphTitleBlock,+ RefTextBlock,+ TableAnnotationBlock,+ TableBlock,+ TableBodyBlock,+ TextBlock,+ TextSpan,+)+from ..common.index import strip_index_page_tail+from ..common.list_items import parse_list_item_marker+from ..markdown.assets import normalize_image_source, resolve_image_source+from ..markdown.inline import render_inline_content+from ..markdown.table import format_embedded_html++VisualBlock: TypeAlias = ImageBlock | TableBlock | ChartBlock | CodeBlock+VisualBodyBlock: TypeAlias = ImageBodyBlock | TableBodyBlock | ChartBodyBlock | CodeBodyBlock | AlgorithmBodyBlock+VisualAnnotationBlock: TypeAlias = ImageAnnotationBlock | TableAnnotationBlock | ChartAnnotationBlock | CodeAnnotationBlock+ListLeafBlock: TypeAlias = TextBlock | RefTextBlock+IndexLeafBlock: TypeAlias = TextBlock | DocTitleBlock | ParagraphTitleBlock+++@dataclass(frozen=True, slots=True)+class ReferenceGroup:+ """保存同页连续参考文献块,供两个兼容 renderer 统一输出列表。"""++ blocks: tuple[RefTextBlock, ...]+++@dataclass(frozen=True, slots=True)+class ListLeaf:+ """保存递归列表叶子及其相对深度。"""++ block: ListLeafBlock+ depth: int+++@dataclass(frozen=True, slots=True)+class IndexLeaf:+ """保存递归目录叶子及其相对深度。"""++ block: IndexLeafBlock+ depth: int+++PageRenderUnit: TypeAlias = PageBlock | ReferenceGroup+++def iter_page_units(blocks: list[PageBlock]) -> Iterator[PageRenderUnit]:+ """保持阅读顺序遍历页面,并把连续 ref_text 合并为一个渲染单元。"""+ reference_blocks: list[RefTextBlock] = []++ def flush_references() -> Iterator[ReferenceGroup]:+ """输出并清空当前参考文献分组。"""+ nonlocal reference_blocks+ if not reference_blocks:+ return iter(())+ group = ReferenceGroup(tuple(reference_blocks))+ reference_blocks = []+ return iter((group,))++ for block in blocks:+ if isinstance(block, RefTextBlock):+ reference_blocks.append(block)+ continue+ yield from flush_references()+ yield block+ yield from flush_references()+++def unit_bbox(unit: PageRenderUnit) -> BBox | None:+ """返回普通块 bbox,或计算参考文献分组的最小包围盒。"""+ if not isinstance(unit, ReferenceGroup):+ return unit.bbox+ bboxes = [block.bbox for block in unit.blocks if block.bbox is not None]+ if not bboxes:+ return None+ return (+ min(bbox[0] for bbox in bboxes),+ min(bbox[1] for bbox in bboxes),+ max(bbox[2] for bbox in bboxes),+ max(bbox[3] for bbox in bboxes),+ )+++def normalize_bbox(bbox: BBox | None) -> list[int] | None:+ """把 MiddleJson 的 0-1 bbox 转换为 Content List 的 0-1000 整数框。"""+ if bbox is None:+ return None+ return [int(value * 1000) for value in bbox]+++def resolve_legacy_image_source(block: ImagePayloadBlock, asset_base_url: str) -> str:+ """按统一图片优先级解析并规范化旧 Content List 资源字段。"""+ source = resolve_image_source(block, asset_base_url)+ return normalize_image_source(source) if source else ""+++def visual_body(block: VisualBlock) -> VisualBodyBlock:+ """返回严格视觉父块中的唯一 body。"""+ for child in block.content:+ if isinstance(child, (ImageBodyBlock, TableBodyBlock, ChartBodyBlock, CodeBodyBlock, AlgorithmBodyBlock)):+ return child+ raise ValueError(f"Missing visual body: {block.type}")+++def sorted_annotations(block: VisualBlock, accepted_types: set[str]) -> list[VisualAnnotationBlock]:+ """按 index 优先、原位置兜底的顺序返回指定视觉说明。"""+ annotations: list[tuple[int, VisualAnnotationBlock]] = []+ for position, child in enumerate(block.content):+ if isinstance(child, (ImageAnnotationBlock, TableAnnotationBlock, ChartAnnotationBlock, CodeAnnotationBlock)):+ if str(child.type) in accepted_types:+ annotations.append((position, child))+ annotations.sort(+ key=lambda item: (+ item[1].index is None,+ item[1].index if item[1].index is not None else 0,+ item[0],+ )+ )+ return [child for _, child in annotations]+++def render_annotation_texts(+ block: VisualBlock,+ accepted_types: set[str],+ delimiters: LatexDelimitersConfig,+) -> list[str]:+ """把一组视觉说明渲染为 V1 使用的 Markdown 字符串数组。"""+ return [render_inline_content(child.content, delimiters) for child in sorted_annotations(block, accepted_types)]+++def render_annotation_spans(block: VisualBlock, accepted_types: set[str]) -> list[dict[str, object]]:+ """把一组视觉说明按顺序展平为 V2 span 数组。"""+ spans: list[dict[str, object]] = []+ for child in sorted_annotations(block, accepted_types):+ spans.extend(serialize_v2_spans(child.content))+ return spans+++def render_embedded_content(+ content: str,+ *,+ asset_base_url: str,+ delimiters: LatexDelimitersConfig,+) -> str:+ """保留视觉结构内容,只重写相对图片地址和安全行内公式标签。"""+ if not content:+ return ""+ return format_embedded_html(+ content,+ asset_base_url=asset_base_url,+ delimiters=delimiters,+ ).strip()+++def serialize_v2_spans(content: list[InlineSpan]) -> list[dict[str, object]]:+ """把严格 InlineSpan 转换为统一的 3.4.5 风格 V2 span。"""+ return [_serialize_v2_span(span) for span in content]+++def _serialize_v2_span(span: InlineSpan) -> dict[str, object]:+ """序列化单个 V2 span,并显式收敛链接 children 与样式字段。"""+ if isinstance(span, TextSpan):+ payload: dict[str, object] = {"type": "text", "content": span.content}+ if span.styles:+ payload["style"] = list(span.styles)+ return payload+ if isinstance(span, EquationInlineSpan):+ return {"type": "equation_inline", "content": span.content.strip()}+ if isinstance(span, CodeInlineSpan):+ return {"type": "code_inline", "content": span.content}+ if isinstance(span, HyperlinkSpan):+ children = [_serialize_v2_span(child) for child in span.content]+ payload = {+ "type": "hyperlink",+ "content": inline_plain_text(span.content),+ "url": span.url,+ }+ if len(children) == 1 and children[0]["type"] == "text":+ if style := children[0].get("style"):+ payload["style"] = style+ else:+ payload["children"] = children+ return payload+ raise TypeError(f"Unsupported InlineSpan type: {type(span).__name__}")+++def string_as_v2_spans(content: str) -> list[dict[str, object]]:+ """把代码字符串包装为 V2 文本 span,空字符串保持为空数组。"""+ if not content:+ return []+ return [{"type": "text", "content": content}]+++def flatten_list_leaves(block: ListBlock, depth: int = 0) -> list[ListLeaf]:+ """按源顺序递归展平列表叶子。"""+ leaves: list[ListLeaf] = []+ for child in block.content:+ if isinstance(child, ListBlock):+ leaves.extend(flatten_list_leaves(child, depth + 1))+ else:+ leaves.append(ListLeaf(block=child, depth=depth))+ return leaves+++def infer_list_attribute(block: ListBlock) -> str:+ """根据最浅层有效条目的 marker 推断 ordered/unordered。"""+ leaves = flatten_list_leaves(block)+ if not leaves:+ return "unordered"+ minimum_depth = min(leaf.depth for leaf in leaves)+ kinds = [+ parse_list_item_marker(leaf.block.content).kind+ for leaf in leaves+ if leaf.depth == minimum_depth and inline_plain_text(leaf.block.content).strip()+ ]+ return "ordered" if kinds and all(kind == "ordered" for kind in kinds) else "unordered"+++def flatten_index_leaves(block: IndexBlock, depth: int = 0) -> list[IndexLeaf]:+ """按源顺序递归展平目录叶子。"""+ leaves: list[IndexLeaf] = []+ for child in block.content:+ if isinstance(child, IndexBlock):+ leaves.extend(flatten_index_leaves(child, depth + 1))+ else:+ leaves.append(IndexLeaf(block=child, depth=depth))+ return leaves+++def normalized_index_content(block: IndexLeafBlock) -> list[InlineSpan]:+ """删除目录叶子可信页码尾缀,并保留其余行内语义。"""+ return strip_index_page_tail(block.content)+++def classify_table(content: str) -> tuple[str, int]:+ """按 rowspan、colspan 和嵌套 table 判断 V2 表格类型。"""+ table_count = len(re.findall(r"<table\b", content, flags=re.IGNORECASE))+ table_nest_level = 2 if table_count > 1 else 1+ complex_table = table_nest_level > 1 or re.search(r"\b(?:rowspan|colspan)\b", content, flags=re.IGNORECASE)+ return ("complex_table" if complex_table else "simple_table", table_nest_level)+++__all__ = [+ "IndexLeaf",+ "ListLeaf",+ "PageRenderUnit",+ "ReferenceGroup",+ "classify_table",+ "flatten_index_leaves",+ "flatten_list_leaves",+ "infer_list_attribute",+ "iter_page_units",+ "normalize_bbox",+ "normalized_index_content",+ "render_annotation_spans",+ "render_annotation_texts",+ "render_embedded_content",+ "resolve_legacy_image_source",+ "serialize_v2_spans",+ "sorted_annotations",+ "string_as_v2_spans",+ "unit_bbox",+ "visual_body",+]diff --git a/mineru/render/_internal/content_list/v1.py b/mineru/render/_internal/content_list/v1.pynew file mode 100644index 00000000..266d7ba8--- /dev/null+++ b/mineru/render/_internal/content_list/v1.py@@ -0,0 +1,253 @@+# Copyright (c) Opendatalab. All rights reserved.+"""严格 MiddleJson 到扁平 Content List V1 的渲染实现。"""++from __future__ import annotations++from typing import Any++from ....config import LatexDelimitersConfig, config+from ....types import (+ RAW_ALGORITHM,+ AlgorithmBodyBlock,+ BlockType,+ ChartBlock,+ CodeBlock,+ CodeBodyBlock,+ DocTitleBlock,+ EquationBlock,+ ImageBlock,+ IndexBlock,+ ListBlock,+ MiddleJson,+ PageAuxTextBlock,+ PageFootnoteBlock,+ ParagraphTitleBlock,+ TableBlock,+ TextBlock,+)+from ..markdown.inline import render_inline_content, render_internal_link+from .common import (+ PageRenderUnit,+ ReferenceGroup,+ flatten_index_leaves,+ flatten_list_leaves,+ iter_page_units,+ normalize_bbox,+ normalized_index_content,+ render_annotation_texts,+ render_embedded_content,+ resolve_legacy_image_source,+ unit_bbox,+ visual_body,+)++_IMAGE_CAPTION_TYPES = {str(BlockType.IMAGE_CAPTION)}+_IMAGE_FOOTNOTE_TYPES = {str(BlockType.IMAGE_FOOTNOTE)}+_TABLE_CAPTION_TYPES = {str(BlockType.TABLE_CAPTION)}+_TABLE_FOOTNOTE_TYPES = {str(BlockType.TABLE_FOOTNOTE)}+_CHART_CAPTION_TYPES = {str(BlockType.CHART_CAPTION)}+_CHART_FOOTNOTE_TYPES = {str(BlockType.CHART_FOOTNOTE)}+_CODE_CAPTION_TYPES = {str(BlockType.CODE_CAPTION)}+_CODE_FOOTNOTE_TYPES = {str(BlockType.CODE_FOOTNOTE)}+++def render_content_list(+ middle_json: MiddleJson,+ *,+ asset_base_url: str = "",+) -> list[dict[str, Any]]:+ """把严格 MiddleJson 无副作用地渲染为扁平 Content List V1。"""+ if not isinstance(middle_json, MiddleJson):+ raise TypeError("render_content_list expects a MiddleJson instance")+ if not isinstance(asset_base_url, str):+ raise TypeError("asset_base_url must be a string")++ delimiters = config.render.latex_delimiters+ output: list[dict[str, Any]] = []+ for page in middle_json.pages:+ for unit in iter_page_units(page.blocks):+ item = _render_unit(+ unit,+ page_idx=page.page_idx,+ asset_base_url=asset_base_url,+ delimiters=delimiters,+ )+ if item is not None:+ output.append(item)+ return output+++def _render_unit(+ unit: PageRenderUnit,+ *,+ page_idx: int,+ asset_base_url: str,+ delimiters: LatexDelimitersConfig,+) -> dict[str, Any] | None:+ """把一个页面渲染单元转换为 V1 item,并补齐 bbox 与 page_idx。"""+ item = _render_unit_content(unit, asset_base_url=asset_base_url, delimiters=delimiters)+ if item is None:+ return None+ if bbox := normalize_bbox(unit_bbox(unit)):+ item["bbox"] = bbox+ item["page_idx"] = page_idx+ return item+++def _render_unit_content(+ unit: PageRenderUnit,+ *,+ asset_base_url: str,+ delimiters: LatexDelimitersConfig,+) -> dict[str, Any] | None:+ """按严格 block 类型构造 V1 专有字段。"""+ if isinstance(unit, ReferenceGroup):+ return {+ "type": "list",+ "sub_type": "ref_text",+ "list_items": [render_inline_content(block.content, delimiters) for block in unit.blocks if block.content],+ }+ if isinstance(unit, TextBlock):+ return {"type": "text", "text": render_inline_content(unit.content, delimiters)}+ if isinstance(unit, (DocTitleBlock, ParagraphTitleBlock)):+ item: dict[str, Any] = {+ "type": "text",+ "text": render_inline_content(unit.content, delimiters),+ "text_level": unit.level,+ }+ _add_anchor(item, unit.anchor)+ return item+ if isinstance(unit, PageFootnoteBlock):+ item = {"type": "page_footnote", "text": render_inline_content(unit.content, delimiters)}+ _add_anchor(item, unit.anchor)+ return item+ if isinstance(unit, PageAuxTextBlock):+ return {"type": str(unit.type), "text": render_inline_content(unit.content, delimiters)}+ if isinstance(unit, EquationBlock):+ item = {+ "type": "equation",+ "img_path": resolve_legacy_image_source(unit, asset_base_url),+ }+ if latex := unit.content.strip():+ item["text"] = latex+ item["text_format"] = "latex"+ return item+ if isinstance(unit, ListBlock):+ return {+ "type": "list",+ "sub_type": str(unit.sub_type or BlockType.TEXT),+ "list_items": [+ render_inline_content(leaf.block.content, delimiters)+ for leaf in flatten_list_leaves(unit)+ if leaf.block.content+ ],+ }+ if isinstance(unit, IndexBlock):+ return {"type": "index", "list_items": _render_index_items(unit, delimiters)}+ if isinstance(unit, ImageBlock):+ return _render_image(unit, asset_base_url, delimiters)+ if isinstance(unit, TableBlock):+ return _render_table(unit, asset_base_url, delimiters)+ if isinstance(unit, ChartBlock):+ return _render_chart(unit, asset_base_url, delimiters)+ if isinstance(unit, CodeBlock):+ return _render_code(unit, delimiters)+ return None+++def _render_index_items(block: IndexBlock, delimiters: LatexDelimitersConfig) -> list[str]:+ """把递归目录叶子渲染为带缩进和可选内部链接的 V1 字符串。"""+ items: list[str] = []+ for leaf in flatten_index_leaves(block):+ content = normalized_index_content(leaf.block)+ label = render_inline_content(content, delimiters).strip()+ if not label:+ continue+ if isinstance(leaf.block, (DocTitleBlock, ParagraphTitleBlock)) and leaf.block.anchor:+ label = render_internal_link(label, leaf.block.anchor)+ items.append(f"{' ' * leaf.depth}- {label}")+ return items+++def _render_image(+ block: ImageBlock,+ asset_base_url: str,+ delimiters: LatexDelimitersConfig,+) -> dict[str, Any]:+ """构造 V1 图片 item。"""+ body = visual_body(block)+ item: dict[str, Any] = {+ "type": "image",+ "img_path": resolve_legacy_image_source(body, asset_base_url),+ "image_caption": render_annotation_texts(block, _IMAGE_CAPTION_TYPES, delimiters),+ "image_footnote": render_annotation_texts(block, _IMAGE_FOOTNOTE_TYPES, delimiters),+ }+ if content := render_embedded_content(body.content, asset_base_url=asset_base_url, delimiters=delimiters):+ item["content"] = content+ if block.sub_type:+ item["sub_type"] = block.sub_type+ return item+++def _render_table(+ block: TableBlock,+ asset_base_url: str,+ delimiters: LatexDelimitersConfig,+) -> dict[str, Any]:+ """构造 V1 表格 item。"""+ body = visual_body(block)+ item: dict[str, Any] = {+ "type": "table",+ "img_path": resolve_legacy_image_source(body, asset_base_url),+ "table_caption": render_annotation_texts(block, _TABLE_CAPTION_TYPES, delimiters),+ "table_footnote": render_annotation_texts(block, _TABLE_FOOTNOTE_TYPES, delimiters),+ }+ if content := render_embedded_content(body.content, asset_base_url=asset_base_url, delimiters=delimiters):+ item["table_body"] = content+ return item+++def _render_chart(+ block: ChartBlock,+ asset_base_url: str,+ delimiters: LatexDelimitersConfig,+) -> dict[str, Any]:+ """构造 V1 图表 item。"""+ body = visual_body(block)+ item: dict[str, Any] = {+ "type": "chart",+ "img_path": resolve_legacy_image_source(body, asset_base_url),+ "content": render_embedded_content(body.content, asset_base_url=asset_base_url, delimiters=delimiters),+ "chart_caption": render_annotation_texts(block, _CHART_CAPTION_TYPES, delimiters),+ "chart_footnote": render_annotation_texts(block, _CHART_FOOTNOTE_TYPES, delimiters),+ }+ if block.sub_type:+ item["sub_type"] = block.sub_type+ return item+++def _render_code(block: CodeBlock, delimiters: LatexDelimitersConfig) -> dict[str, Any]:+ """构造 V1 代码或算法 item。"""+ body = visual_body(block)+ if isinstance(body, CodeBodyBlock):+ body_content = body.content+ elif isinstance(body, AlgorithmBodyBlock):+ body_content = render_inline_content(body.content, delimiters)+ else:+ raise TypeError(f"Unsupported code body: {type(body).__name__}")+ return {+ "type": "code",+ "sub_type": "algorithm" if block.sub_type == RAW_ALGORITHM else "code",+ "code_body": body_content,+ "code_caption": render_annotation_texts(block, _CODE_CAPTION_TYPES, delimiters),+ "code_footnote": render_annotation_texts(block, _CODE_FOOTNOTE_TYPES, delimiters),+ }+++def _add_anchor(item: dict[str, Any], anchor: str | None) -> None:+ """把非空文档锚点写入兼容 item。"""+ if anchor and anchor.strip():+ item["anchor"] = anchor.strip()+++__all__ = ["render_content_list"]diff --git a/mineru/render/_internal/content_list/v2.py b/mineru/render/_internal/content_list/v2.pynew file mode 100644index 00000000..5a0aa760--- /dev/null+++ b/mineru/render/_internal/content_list/v2.py@@ -0,0 +1,317 @@+# Copyright (c) Opendatalab. All rights reserved.+"""严格 MiddleJson 到按页 Content List V2 的渲染实现。"""++from __future__ import annotations++from typing import Any++from ....config import LatexDelimitersConfig, config+from ....types import (+ RAW_ALGORITHM,+ AlgorithmBodyBlock,+ BlockType,+ ChartBlock,+ CodeBlock,+ CodeBodyBlock,+ DocTitleBlock,+ EquationBlock,+ ImageBlock,+ IndexBlock,+ ListBlock,+ MiddleJson,+ PageAuxTextBlock,+ PageFootnoteBlock,+ ParagraphTitleBlock,+ TableBlock,+ TextBlock,+)+from .common import (+ PageRenderUnit,+ ReferenceGroup,+ classify_table,+ flatten_index_leaves,+ flatten_list_leaves,+ infer_list_attribute,+ iter_page_units,+ normalize_bbox,+ normalized_index_content,+ render_annotation_spans,+ render_embedded_content,+ resolve_legacy_image_source,+ serialize_v2_spans,+ string_as_v2_spans,+ unit_bbox,+ visual_body,+)++_IMAGE_CAPTION_TYPES = {str(BlockType.IMAGE_CAPTION)}+_IMAGE_FOOTNOTE_TYPES = {str(BlockType.IMAGE_FOOTNOTE)}+_TABLE_CAPTION_TYPES = {str(BlockType.TABLE_CAPTION)}+_TABLE_FOOTNOTE_TYPES = {str(BlockType.TABLE_FOOTNOTE)}+_CHART_CAPTION_TYPES = {str(BlockType.CHART_CAPTION)}+_CHART_FOOTNOTE_TYPES = {str(BlockType.CHART_FOOTNOTE)}+_CODE_CAPTION_TYPES = {str(BlockType.CODE_CAPTION)}+_CODE_FOOTNOTE_TYPES = {str(BlockType.CODE_FOOTNOTE)}+++def render_content_list_v2(+ middle_json: MiddleJson,+ *,+ asset_base_url: str = "",+) -> list[list[dict[str, Any]]]:+ """把严格 MiddleJson 无副作用地渲染为按页 Content List V2。"""+ if not isinstance(middle_json, MiddleJson):+ raise TypeError("render_content_list_v2 expects a MiddleJson instance")+ if not isinstance(asset_base_url, str):+ raise TypeError("asset_base_url must be a string")++ delimiters = config.render.latex_delimiters+ output: list[list[dict[str, Any]]] = []+ for page in middle_json.pages:+ page_items: list[dict[str, Any]] = []+ for unit in iter_page_units(page.blocks):+ item = _render_unit(unit, asset_base_url=asset_base_url, delimiters=delimiters)+ if item is not None:+ page_items.append(item)+ output.append(page_items)+ return output+++def _render_unit(+ unit: PageRenderUnit,+ *,+ asset_base_url: str,+ delimiters: LatexDelimitersConfig,+) -> dict[str, Any] | None:+ """把一个页面渲染单元转换为 V2 item,并补齐归一化 bbox。"""+ item = _render_unit_content(unit, asset_base_url=asset_base_url, delimiters=delimiters)+ if item is None:+ return None+ if bbox := normalize_bbox(unit_bbox(unit)):+ item["bbox"] = bbox+ return item+++def _render_unit_content(+ unit: PageRenderUnit,+ *,+ asset_base_url: str,+ delimiters: LatexDelimitersConfig,+) -> dict[str, Any] | None:+ """按严格 block 类型构造 V2 的 type + content 字段。"""+ if isinstance(unit, ReferenceGroup):+ return _reference_list_item(unit)+ if isinstance(unit, TextBlock):+ return {"type": "paragraph", "content": {"paragraph_content": serialize_v2_spans(unit.content)}}+ if isinstance(unit, (DocTitleBlock, ParagraphTitleBlock)):+ item: dict[str, Any] = {+ "type": "title",+ "content": {+ "title_content": serialize_v2_spans(unit.content),+ "level": unit.level,+ },+ }+ _add_anchor(item, unit.anchor)+ return item+ if isinstance(unit, PageFootnoteBlock):+ item = {+ "type": "page_footnote",+ "content": {"page_footnote_content": serialize_v2_spans(unit.content)},+ }+ _add_anchor(item, unit.anchor)+ return item+ if isinstance(unit, PageAuxTextBlock):+ content_type = _page_content_type(str(unit.type))+ return {+ "type": content_type,+ "content": {f"{content_type}_content": serialize_v2_spans(unit.content)},+ }+ if isinstance(unit, EquationBlock):+ return {+ "type": "equation_interline",+ "content": {+ "math_content": unit.content.strip(),+ "math_type": "latex",+ "image_source": {"path": resolve_legacy_image_source(unit, asset_base_url)},+ },+ }+ if isinstance(unit, ListBlock):+ return _render_list(unit)+ if isinstance(unit, IndexBlock):+ return _render_index(unit)+ if isinstance(unit, ImageBlock):+ return _render_image(unit, asset_base_url, delimiters)+ if isinstance(unit, TableBlock):+ return _render_table(unit, asset_base_url, delimiters)+ if isinstance(unit, ChartBlock):+ return _render_chart(unit, asset_base_url, delimiters)+ if isinstance(unit, CodeBlock):+ return _render_code(unit)+ return None+++def _page_content_type(block_type: str) -> str:+ """把 MiddleJson 页面辅助块类型映射为 V2 类型。"""+ mapping = {+ str(BlockType.HEADER): "page_header",+ str(BlockType.FOOTER): "page_footer",+ str(BlockType.PAGE_NUMBER): "page_number",+ str(BlockType.ASIDE_TEXT): "page_aside_text",+ }+ return mapping[block_type]+++def _reference_list_item(group: ReferenceGroup) -> dict[str, Any]:+ """把连续参考文献块转换为一个 reference_list item。"""+ return {+ "type": "list",+ "content": {+ "list_type": "reference_list",+ "list_items": [+ {"item_type": "text", "item_content": serialize_v2_spans(block.content)}+ for block in group.blocks+ if block.content+ ],+ },+ }+++def _render_list(block: ListBlock) -> dict[str, Any]:+ """把递归列表展平为统一 V2 list item。"""+ list_type = "reference_list" if block.sub_type == BlockType.REF_TEXT else "text_list"+ content: dict[str, Any] = {+ "list_type": list_type,+ "list_items": [+ {"item_type": "text", "item_content": serialize_v2_spans(leaf.block.content)}+ for leaf in flatten_list_leaves(block)+ if leaf.block.content+ ],+ }+ if list_type == "text_list":+ content["attribute"] = infer_list_attribute(block)+ return {"type": "list", "content": content}+++def _render_index(block: IndexBlock) -> dict[str, Any]:+ """把递归目录展平为统一 V2 index item。"""+ list_items: list[dict[str, Any]] = []+ for leaf in flatten_index_leaves(block):+ content = normalized_index_content(leaf.block)+ if not content:+ continue+ item: dict[str, Any] = {+ "item_type": "text",+ "item_content": serialize_v2_spans(content),+ }+ if isinstance(leaf.block, (DocTitleBlock, ParagraphTitleBlock)):+ _add_anchor(item, leaf.block.anchor)+ list_items.append(item)+ return {+ "type": "index",+ "content": {+ "list_type": "text_list",+ "list_items": list_items,+ },+ }+++def _render_image(+ block: ImageBlock,+ asset_base_url: str,+ delimiters: LatexDelimitersConfig,+) -> dict[str, Any]:+ """构造 V2 图片 item。"""+ body = visual_body(block)+ body_content = render_embedded_content(body.content, asset_base_url=asset_base_url, delimiters=delimiters)+ content: dict[str, Any] = {+ "image_source": {"path": resolve_legacy_image_source(body, asset_base_url)},+ "image_caption": render_annotation_spans(block, _IMAGE_CAPTION_TYPES),+ "image_footnote": render_annotation_spans(block, _IMAGE_FOOTNOTE_TYPES),+ }+ if body_content or block.sub_type:+ content["content"] = body_content+ item: dict[str, Any] = {"type": "image", "content": content}+ if block.sub_type:+ item["sub_type"] = block.sub_type+ return item+++def _render_table(+ block: TableBlock,+ asset_base_url: str,+ delimiters: LatexDelimitersConfig,+) -> dict[str, Any]:+ """构造 V2 表格 item并计算复杂度。"""+ body = visual_body(block)+ html = render_embedded_content(body.content, asset_base_url=asset_base_url, delimiters=delimiters)+ table_type, table_nest_level = classify_table(html)+ return {+ "type": "table",+ "content": {+ "image_source": {"path": resolve_legacy_image_source(body, asset_base_url)},+ "table_caption": render_annotation_spans(block, _TABLE_CAPTION_TYPES),+ "table_footnote": render_annotation_spans(block, _TABLE_FOOTNOTE_TYPES),+ "html": html,+ "table_type": table_type,+ "table_nest_level": table_nest_level,+ },+ }+++def _render_chart(+ block: ChartBlock,+ asset_base_url: str,+ delimiters: LatexDelimitersConfig,+) -> dict[str, Any]:+ """构造 V2 图表 item。"""+ body = visual_body(block)+ item: dict[str, Any] = {+ "type": "chart",+ "content": {+ "image_source": {"path": resolve_legacy_image_source(body, asset_base_url)},+ "content": render_embedded_content(body.content, asset_base_url=asset_base_url, delimiters=delimiters),+ "chart_caption": render_annotation_spans(block, _CHART_CAPTION_TYPES),+ "chart_footnote": render_annotation_spans(block, _CHART_FOOTNOTE_TYPES),+ },+ }+ if block.sub_type:+ item["sub_type"] = block.sub_type+ return item+++def _render_code(block: CodeBlock) -> dict[str, Any]:+ """构造 V2 代码或算法 item。"""+ body = visual_body(block)+ captions = render_annotation_spans(block, _CODE_CAPTION_TYPES)+ footnotes = render_annotation_spans(block, _CODE_FOOTNOTE_TYPES)+ if block.sub_type == RAW_ALGORITHM:+ if not isinstance(body, AlgorithmBodyBlock):+ raise TypeError("algorithm subtype requires AlgorithmBodyBlock")+ return {+ "type": "algorithm",+ "content": {+ "algorithm_caption": captions,+ "algorithm_content": serialize_v2_spans(body.content),+ "algorithm_footnote": footnotes,+ },+ }+ if not isinstance(body, CodeBodyBlock):+ raise TypeError("code subtype requires CodeBodyBlock")+ return {+ "type": "code",+ "content": {+ "code_caption": captions,+ "code_content": string_as_v2_spans(body.content),+ "code_footnote": footnotes,+ "code_language": block.guess_lang or "txt",+ },+ }+++def _add_anchor(item: dict[str, Any], anchor: str | None) -> None:+ """把非空文档锚点写入 V2 item 或目录叶子。"""+ if anchor and anchor.strip():+ item["anchor"] = anchor.strip()+++__all__ = ["render_content_list_v2"]diff --git a/mineru/render/api.py b/mineru/render/api.pyindex 9a6bab77..550e5f96 100644--- a/mineru/render/api.py+++ b/mineru/render/api.py@@ -8,6 +8,8 @@ from typing import Any, Literal, overloadfrom ..types import MiddleJsonfrom .contracts import (+ ContentListRenderOptions,+ ContentListV2RenderOptions,DocxRenderOptions,HtmlRenderOptions,MarkdownRenderOptions,@@ -16,6 +18,8 @@ from .contracts import (RenderOutput,StructuredContentRenderOptions,)+from .content_list import render_content_list+from .content_list_v2 import render_content_list_v2from .docx import render_docxfrom .html import render_htmlfrom .markdown import render_markdown@@ -66,6 +70,28 @@ def render(...+@overload+def render(+ middle_json: MiddleJson,+ output_format: Literal[RenderFormat.CONTENT_LIST],+ *,+ options: ContentListRenderOptions | None = None,+) -> list[dict[str, Any]]:+ """声明 Content List V1 目标对应的扁平列表返回类型。"""+ ...+++@overload+def render(+ middle_json: MiddleJson,+ output_format: Literal[RenderFormat.CONTENT_LIST_V2],+ *,+ options: ContentListV2RenderOptions | None = None,+) -> list[list[dict[str, Any]]]:+ """声明 Content List V2 目标对应的按页列表返回类型。"""+ ...++def render(middle_json: MiddleJson,output_format: RenderFormat,@@ -120,6 +146,24 @@ def render(asset_base_url=resolved_options.asset_base_url,)+ if output_format is RenderFormat.CONTENT_LIST:+ resolved_options = options if options is not None else ContentListRenderOptions()+ if not isinstance(resolved_options, ContentListRenderOptions):+ raise TypeError("CONTENT_LIST output requires ContentListRenderOptions")+ return render_content_list(+ middle_json,+ asset_base_url=resolved_options.asset_base_url,+ )++ if output_format is RenderFormat.CONTENT_LIST_V2:+ resolved_options = options if options is not None else ContentListV2RenderOptions()+ if not isinstance(resolved_options, ContentListV2RenderOptions):+ raise TypeError("CONTENT_LIST_V2 output requires ContentListV2RenderOptions")+ return render_content_list_v2(+ middle_json,+ asset_base_url=resolved_options.asset_base_url,+ )+raise ValueError(f"Unsupported RenderFormat: {output_format}")diff --git a/mineru/render/content_list.py b/mineru/render/content_list.pynew file mode 100644index 00000000..76837757--- /dev/null+++ b/mineru/render/content_list.py@@ -0,0 +1,22 @@+# Copyright (c) Opendatalab. All rights reserved.+"""严格 MiddleJson 到 Content List V1 的轻量公共门面。"""++from __future__ import annotations++from typing import Any++from ..types import MiddleJson+++def render_content_list(+ middle_json: MiddleJson,+ *,+ asset_base_url: str = "",+) -> list[dict[str, Any]]:+ """惰性加载 Content List V1 实现并渲染严格 MiddleJson。"""+ from ._internal.content_list.v1 import render_content_list as _render_content_list++ return _render_content_list(middle_json, asset_base_url=asset_base_url)+++__all__ = ["render_content_list"]diff --git a/mineru/render/content_list_v2.py b/mineru/render/content_list_v2.pynew file mode 100644index 00000000..317658c7--- /dev/null+++ b/mineru/render/content_list_v2.py@@ -0,0 +1,22 @@+# Copyright (c) Opendatalab. All rights reserved.+"""严格 MiddleJson 到 Content List V2 的轻量公共门面。"""++from __future__ import annotations++from typing import Any++from ..types import MiddleJson+++def render_content_list_v2(+ middle_json: MiddleJson,+ *,+ asset_base_url: str = "",+) -> list[list[dict[str, Any]]]:+ """惰性加载 Content List V2 实现并渲染严格 MiddleJson。"""+ from ._internal.content_list.v2 import render_content_list_v2 as _render_content_list_v2++ return _render_content_list_v2(middle_json, asset_base_url=asset_base_url)+++__all__ = ["render_content_list_v2"]diff --git a/mineru/render/contracts.py b/mineru/render/contracts.pyindex 797a15b8..6c7106b3 100644--- a/mineru/render/contracts.py+++ b/mineru/render/contracts.py@@ -17,6 +17,8 @@ class RenderFormat(str, Enum):HTML = "html"DOCX = "docx"STRUCTURED_CONTENT = "structured_content"+ CONTENT_LIST = "content_list"+ CONTENT_LIST_V2 = "content_list_v2"class RenderMode(str, Enum):@@ -102,12 +104,43 @@ class StructuredContentRenderOptions:_validate_asset_base_url(self.asset_base_url)-RenderOptions: TypeAlias = MarkdownRenderOptions | HtmlRenderOptions | DocxRenderOptions | StructuredContentRenderOptions-RenderOutput: TypeAlias = str | bytes | dict[str, Any]+@dataclass(frozen=True, slots=True)+class ContentListRenderOptions:+ """扁平 Content List V1 renderer 的统一入口选项。"""++ asset_base_url: str = ""++ def __post_init__(self) -> None:+ """在构造时校验图片资源根地址。"""+ _validate_asset_base_url(self.asset_base_url)+++@dataclass(frozen=True, slots=True)+class ContentListV2RenderOptions:+ """按页 Content List V2 renderer 的统一入口选项。"""++ asset_base_url: str = ""++ def __post_init__(self) -> None:+ """在构造时校验图片资源根地址。"""+ _validate_asset_base_url(self.asset_base_url)+++RenderOptions: TypeAlias = (+ MarkdownRenderOptions+ | HtmlRenderOptions+ | DocxRenderOptions+ | StructuredContentRenderOptions+ | ContentListRenderOptions+ | ContentListV2RenderOptions+)+RenderOutput: TypeAlias = str | bytes | dict[str, Any] | list[dict[str, Any]] | list[list[dict[str, Any]]]__all__ = ["AssetResolver",+ "ContentListRenderOptions",+ "ContentListV2RenderOptions","DocxRenderOptions","HtmlRenderOptions","ImageRenderer",diff --git a/tests/unittest/test_content_list_render.py b/tests/unittest/test_content_list_render.pynew file mode 100644index 00000000..bc584078--- /dev/null+++ b/tests/unittest/test_content_list_render.py@@ -0,0 +1,273 @@+from __future__ import annotations++from copy import deepcopy++import pytest++from _span_test_utils import inline as _inline+from mineru.render import render_content_list+from mineru.types import (+ AlgorithmBodyBlock,+ ChartAnnotationBlock,+ ChartBlock,+ ChartBodyBlock,+ CodeBlock,+ CodeBodyBlock,+ DocTitleBlock,+ EquationBlock,+ ImageBlock,+ IndexBlock,+ ListBlock,+ MiddleJson,+ PageAuxTextBlock,+ PageInfo,+ ParagraphTitleBlock,+ RefTextBlock,+ TableBlock,+ TextBlock,+)+++def _middle(*pages: PageInfo) -> MiddleJson:+ """构造允许可选 bbox 的最小严格 MiddleJson。"""+ return MiddleJson(+ pages=list(pages),+ is_full_document=True,+ file_suffix="docx",+ effort="flash",+ parse_mode="txt",+ mineru_version="test",+ )+++def _page(page_idx: int, *blocks: object) -> PageInfo:+ """按调用方顺序构造测试页面。"""+ return PageInfo(page_idx=page_idx, blocks=list(blocks)) # type: ignore[arg-type]+++def _assert_no_internal_fields(value: object) -> None:+ """递归确认兼容输出不泄漏 MiddleJson 内部消费提示。"""+ if isinstance(value, list):+ for item in value:+ _assert_no_internal_fields(item)+ return+ if not isinstance(value, dict):+ return+ assert not ({"index", "continues_prev", "cell_merge", "guess_lang", "image_base64"} & value.keys())+ for item in value.values():+ _assert_no_internal_fields(item)+++def test_content_list_v1_flattens_pages_titles_lists_references_and_indices() -> None:+ """验证 V1 页序扁平化、标题层级、参考文献分组和目录链接。"""+ nested_list = ListBlock(+ type="list",+ content=[TextBlock(type="text", content=_inline(" - nested"))],+ )+ list_block = ListBlock(+ type="list",+ index=5,+ bbox=(0.1, 0.6, 0.9, 0.8),+ sub_type="text",+ content=[TextBlock(type="text", content=_inline("1. first")), nested_list],+ )+ index_block = IndexBlock(+ type="index",+ index=6,+ content=[+ ParagraphTitleBlock(+ type="paragraph_title",+ level=2,+ anchor="section-a",+ content=_inline("Section A\t12"),+ )+ ],+ )+ middle = _middle(+ _page(+ 2,+ DocTitleBlock(+ type="doc_title",+ index=0,+ bbox=(0.1, 0.1, 0.9, 0.2),+ level=1,+ anchor="document-title",+ content=_inline("Document"),+ ),+ TextBlock(+ type="text",+ index=1,+ content=[+ {"type": "text", "content": "A "},+ {"type": "text", "content": "B", "styles": ["bold"]},+ {"type": "text", "content": " "},+ {"type": "hyperlink", "url": "https://example.com/a b", "content": _inline("link")},+ {"type": "text", "content": " "},+ {"type": "equation_inline", "content": "x"},+ ],+ ),+ RefTextBlock(type="ref_text", index=2, bbox=(0.1, 0.2, 0.4, 0.3), content=_inline("[1] first")),+ RefTextBlock(type="ref_text", index=3, bbox=(0.05, 0.4, 0.5, 0.6), content=_inline("[2] second")),+ PageAuxTextBlock(type="header", index=4, content=_inline("HEADER")),+ list_block,+ index_block,+ ),+ _page(9),+ )+ original = deepcopy(middle)++ output = render_content_list(middle)++ assert [item["type"] for item in output] == ["text", "text", "list", "header", "list", "index"]+ assert output[0] == {+ "type": "text",+ "text": "Document",+ "text_level": 1,+ "anchor": "document-title",+ "bbox": [100, 100, 900, 200],+ "page_idx": 2,+ }+ assert output[1]["text"] == "A **B** [link](https://example.com/a%20b) $x$"+ assert output[2] == {+ "type": "list",+ "sub_type": "ref_text",+ "list_items": ["[1] first", "[2] second"],+ "bbox": [50, 200, 500, 600],+ "page_idx": 2,+ }+ assert output[4]["list_items"] == ["1. first", " - nested"]+ assert output[5]["list_items"] == ["- [Section A](#section-a)"]+ assert all(item["page_idx"] == 2 for item in output)+ assert middle == original+ _assert_no_internal_fields(output)+++def test_content_list_v1_renders_equation_visuals_code_and_resource_priority() -> None:+ """验证 V1 视觉字段、说明排序、代码算法和图片来源优先级。"""+ image = ImageBlock.model_validate(+ {+ "type": "image",+ "index": 1,+ "bbox": [0.1, 0.2, 0.8, 0.6],+ "sub_type": "diagram",+ "content": [+ {"type": "image_caption", "index": 8, "content": _inline("late")},+ {+ "type": "image_body",+ "index": 1,+ "content": "<p>description</p>",+ "image_path": "images/a b.png",+ "image_base64": "data:image/png;base64,AAAA",+ },+ {"type": "image_caption", "index": 6, "content": _inline("early", styles=["bold"])},+ {"type": "image_footnote", "index": 7, "content": _inline("source")},+ ],+ }+ )+ table = TableBlock.model_validate(+ {+ "type": "table",+ "index": 2,+ "content": [+ {+ "type": "table_body",+ "index": 2,+ "content": '<table><tr><td><img src="cell.png"><eq>x</eq></td></tr></table>',+ "image_path": "images/table.png",+ },+ {"type": "table_caption", "content": _inline("Table 1")},+ {"type": "table_footnote", "content": _inline("note")},+ ],+ }+ )+ chart = ChartBlock(+ type="chart",+ index=3,+ sub_type="bar",+ content=[+ ChartBodyBlock(+ type="chart_body",+ index=3,+ content="<div>chart</div>",+ image_url="https://example.com/chart.png",+ ),+ ChartAnnotationBlock(type="chart_caption", content=_inline("Chart 1")),+ ChartAnnotationBlock(type="chart_footnote", content=_inline("chart note")),+ ],+ )+ code = CodeBlock(+ type="code",+ index=4,+ sub_type="code",+ guess_lang="python",+ content=[+ CodeBodyBlock(type="code_body", index=4, content="print('x')"),+ {"type": "code_caption", "content": _inline("Example")},+ {"type": "code_footnote", "content": _inline("code note")},+ ],+ )+ algorithm = CodeBlock(+ type="code",+ index=5,+ sub_type="algorithm",+ content=[+ AlgorithmBodyBlock(+ type="algorithm_body",+ index=5,+ content=[{"type": "text", "content": "for "}, {"type": "equation_inline", "content": "n"}],+ )+ ],+ )+ middle = _middle(+ _page(+ 0,+ EquationBlock(+ type="equation",+ index=0,+ content=" x=1 ",+ image_path="images/e q.png",+ image_base64="data:image/png;base64,BBBB",+ ),+ image,+ table,+ chart,+ code,+ algorithm,+ )+ )++ output = render_content_list(middle, asset_base_url="https://cdn.example/doc")++ assert output[0] == {+ "type": "equation",+ "img_path": "https://cdn.example/doc/images/e%20q.png",+ "text": "x=1",+ "text_format": "latex",+ "page_idx": 0,+ }+ assert output[1]["img_path"] == "https://cdn.example/doc/images/a%20b.png"+ assert output[1]["content"] == "<p>description</p>"+ assert output[1]["image_caption"] == ["**early**", "late"]+ assert output[1]["image_footnote"] == ["source"]+ assert output[1]["sub_type"] == "diagram"+ assert 'src="https://cdn.example/doc/cell.png"' in output[2]["table_body"]+ assert "$x$" in output[2]["table_body"]+ assert output[2]["img_path"] == "https://cdn.example/doc/images/table.png"+ assert output[3]["img_path"] == "https://example.com/chart.png"+ assert output[3]["sub_type"] == "bar"+ assert output[4]["code_body"] == "print('x')"+ assert output[4]["code_caption"] == ["Example"]+ assert output[5]["sub_type"] == "algorithm"+ assert output[5]["code_body"] == "for $n$"+ _assert_no_internal_fields(output)+++def test_content_list_v1_handles_empty_input_and_rejects_legacy_arguments() -> None:+ """验证空文档、严格 MiddleJson 输入和资源参数类型。"""+ middle = _middle()++ assert render_content_list(middle) == []+ with pytest.raises(TypeError, match="MiddleJson"):+ render_content_list(middle.to_dict()) # type: ignore[arg-type]+ with pytest.raises(TypeError, match="asset_base_url"):+ render_content_list(middle, asset_base_url=1) # type: ignore[arg-type]diff --git a/tests/unittest/test_content_list_v2_render.py b/tests/unittest/test_content_list_v2_render.pynew file mode 100644index 00000000..d45a6770--- /dev/null+++ b/tests/unittest/test_content_list_v2_render.py@@ -0,0 +1,327 @@+from __future__ import annotations++from copy import deepcopy++import pytest++from _span_test_utils import inline as _inline+from mineru.render import render_content_list_v2+from mineru.types import (+ AlgorithmBodyBlock,+ ChartAnnotationBlock,+ ChartBlock,+ ChartBodyBlock,+ CodeBlock,+ CodeBodyBlock,+ EquationBlock,+ ImageBlock,+ IndexBlock,+ ListBlock,+ MiddleJson,+ PageAuxTextBlock,+ PageFootnoteBlock,+ PageInfo,+ ParagraphTitleBlock,+ RefTextBlock,+ TableBlock,+ TextBlock,+)+++def _middle(*pages: PageInfo) -> MiddleJson:+ """构造允许可选 bbox 的最小严格 MiddleJson。"""+ return MiddleJson(+ pages=list(pages),+ is_full_document=True,+ file_suffix="docx",+ effort="flash",+ parse_mode="txt",+ mineru_version="test",+ )+++def _page(page_idx: int, *blocks: object) -> PageInfo:+ """按调用方顺序构造测试页面。"""+ return PageInfo(page_idx=page_idx, blocks=list(blocks)) # type: ignore[arg-type]+++def test_content_list_v2_preserves_pages_bbox_titles_aux_and_rich_spans() -> None:+ """验证 V2 按页结构、空页、标题、辅助块和规范 span。"""+ title = ParagraphTitleBlock(+ type="paragraph_title",+ index=0,+ bbox=(0.1, 0.1, 0.9, 0.2),+ level=6,+ anchor="section-a",+ content=[+ {"type": "text", "content": "Styled", "styles": ["bold"]},+ {"type": "text", "content": " "},+ {+ "type": "hyperlink",+ "url": "https://example.com/a",+ "content": _inline("single", styles=["underline"]),+ },+ {"type": "text", "content": " "},+ {+ "type": "hyperlink",+ "url": "#target",+ "content": [+ {"type": "text", "content": "mix", "styles": ["italic"]},+ {"type": "equation_inline", "content": "x"},+ {"type": "code_inline", "content": "code"},+ ],+ },+ ],+ )+ middle = _middle(+ _page(+ 3,+ title,+ PageAuxTextBlock(type="header", index=1, content=_inline("HEADER")),+ PageAuxTextBlock(type="footer", index=2, content=_inline("FOOTER")),+ PageAuxTextBlock(type="page_number", index=3, content=_inline("3")),+ PageAuxTextBlock(type="aside_text", index=4, content=_inline("ASIDE")),+ PageFootnoteBlock(type="page_footnote", index=5, anchor="note-one", content=_inline("note")),+ ),+ _page(8),+ )+ original = deepcopy(middle)++ output = render_content_list_v2(middle)++ assert len(output) == 2 and output[1] == []+ assert output[0][0]["type"] == "title"+ assert output[0][0]["content"]["level"] == 6+ assert output[0][0]["anchor"] == "section-a"+ assert output[0][0]["bbox"] == [100, 100, 900, 200]+ spans = output[0][0]["content"]["title_content"]+ assert spans[0] == {"type": "text", "content": "Styled", "style": ["bold"]}+ assert spans[2] == {+ "type": "hyperlink",+ "content": "single",+ "url": "https://example.com/a",+ "style": ["underline"],+ }+ assert spans[4] == {+ "type": "hyperlink",+ "content": "mixxcode",+ "url": "#target",+ "children": [+ {"type": "text", "content": "mix", "style": ["italic"]},+ {"type": "equation_inline", "content": "x"},+ {"type": "code_inline", "content": "code"},+ ],+ }+ assert [item["type"] for item in output[0][1:]] == [+ "page_header",+ "page_footer",+ "page_number",+ "page_aside_text",+ "page_footnote",+ ]+ assert output[0][-1]["anchor"] == "note-one"+ assert middle == original+++def test_content_list_v2_normalizes_references_lists_and_indices() -> None:+ """验证连续参考文献、列表属性推断和目录 anchor。"""+ ordered_list = ListBlock(+ type="list",+ index=2,+ sub_type="text",+ content=[+ TextBlock(type="text", content=_inline("1. first")),+ TextBlock(type="text", content=_inline("2. second")),+ ListBlock(type="list", content=[TextBlock(type="text", content=_inline(" - nested"))]),+ ],+ )+ index = IndexBlock(+ type="index",+ index=3,+ content=[+ ParagraphTitleBlock(+ type="paragraph_title",+ level=2,+ anchor="section-b",+ content=_inline("Section B\tIV", styles=["bold"]),+ )+ ],+ )+ middle = _middle(+ _page(+ 0,+ RefTextBlock(type="ref_text", index=0, bbox=(0.1, 0.2, 0.4, 0.3), content=_inline("[1] first")),+ RefTextBlock(type="ref_text", index=1, bbox=(0.05, 0.4, 0.5, 0.6), content=_inline("[2] second")),+ ordered_list,+ index,+ )+ )++ page = render_content_list_v2(middle)[0]++ assert page[0] == {+ "type": "list",+ "content": {+ "list_type": "reference_list",+ "list_items": [+ {"item_type": "text", "item_content": [{"type": "text", "content": "[1] first"}]},+ {"item_type": "text", "item_content": [{"type": "text", "content": "[2] second"}]},+ ],+ },+ "bbox": [50, 200, 500, 600],+ }+ assert page[1]["content"]["list_type"] == "text_list"+ assert page[1]["content"]["attribute"] == "ordered"+ assert [item["item_content"][0]["content"] for item in page[1]["content"]["list_items"]] == [+ "1. first",+ "2. second",+ " - nested",+ ]+ assert page[2] == {+ "type": "index",+ "content": {+ "list_type": "text_list",+ "list_items": [+ {+ "item_type": "text",+ "item_content": [{"type": "text", "content": "Section B", "style": ["bold"]}],+ "anchor": "section-b",+ }+ ],+ },+ }+++def test_content_list_v2_renders_equation_visuals_tables_code_and_algorithm() -> None:+ """验证 V2 视觉资源、表格分类、说明 span 以及代码算法结构。"""+ image = ImageBlock.model_validate(+ {+ "type": "image",+ "index": 1,+ "sub_type": "diagram",+ "content": [+ {"type": "image_caption", "index": 8, "content": _inline("late")},+ {+ "type": "image_body",+ "index": 1,+ "content": "<p>description</p>",+ "image_path": "images/a b.png",+ "image_base64": "data:image/png;base64,AAAA",+ },+ {"type": "image_caption", "index": 6, "content": _inline("early", styles=["bold"])},+ {"type": "image_footnote", "index": 7, "content": _inline("source")},+ ],+ }+ )+ table = TableBlock.model_validate(+ {+ "type": "table",+ "index": 2,+ "content": [+ {+ "type": "table_body",+ "index": 2,+ "content": (+ '<table><tr><td rowspan="2"><img src="cell.png"><eq>x</eq>'+ "<table><tr><td>nested</td></tr></table></td></tr></table>"+ ),+ "image_path": "images/table.png",+ },+ {"type": "table_caption", "content": _inline("Table 1")},+ {"type": "table_footnote", "content": _inline("note")},+ ],+ }+ )+ chart = ChartBlock(+ type="chart",+ index=3,+ sub_type="bar",+ content=[+ ChartBodyBlock(+ type="chart_body",+ index=3,+ content="<div>chart</div>",+ image_base64="data:image/png;base64,BBBB",+ ),+ ChartAnnotationBlock(type="chart_caption", content=_inline("Chart 1")),+ ChartAnnotationBlock(type="chart_footnote", content=_inline("chart note")),+ ],+ )+ code = CodeBlock(+ type="code",+ index=4,+ sub_type="code",+ guess_lang="python",+ content=[+ CodeBodyBlock(type="code_body", index=4, content="print('x')"),+ {"type": "code_caption", "content": _inline("Example")},+ {"type": "code_footnote", "content": _inline("code note")},+ ],+ )+ algorithm = CodeBlock(+ type="code",+ index=5,+ sub_type="algorithm",+ content=[+ AlgorithmBodyBlock(+ type="algorithm_body",+ index=5,+ content=[{"type": "text", "content": "for "}, {"type": "equation_inline", "content": "n"}],+ )+ ],+ )+ middle = _middle(+ _page(+ 0,+ EquationBlock(type="equation", index=0, content=" x=1 "),+ image,+ table,+ chart,+ code,+ algorithm,+ )+ )++ page = render_content_list_v2(middle, asset_base_url="https://cdn.example/doc")[0]++ assert page[0]["content"] == {+ "math_content": "x=1",+ "math_type": "latex",+ "image_source": {"path": ""},+ }+ assert page[1]["sub_type"] == "diagram"+ assert page[1]["content"]["image_source"] == {"path": "https://cdn.example/doc/images/a%20b.png"}+ assert page[1]["content"]["image_caption"] == [+ {"type": "text", "content": "early", "style": ["bold"]},+ {"type": "text", "content": "late"},+ ]+ assert page[1]["content"]["image_footnote"] == [{"type": "text", "content": "source"}]+ assert page[2]["content"]["table_type"] == "complex_table"+ assert page[2]["content"]["table_nest_level"] == 2+ assert 'src="https://cdn.example/doc/cell.png"' in page[2]["content"]["html"]+ assert "$x$" in page[2]["content"]["html"]+ assert page[3]["content"]["image_source"] == {"path": "data:image/png;base64,BBBB"}+ assert page[4]["content"]["code_content"] == [{"type": "text", "content": "print('x')"}]+ assert page[4]["content"]["code_language"] == "python"+ assert page[5] == {+ "type": "algorithm",+ "content": {+ "algorithm_caption": [],+ "algorithm_content": [+ {"type": "text", "content": "for "},+ {"type": "equation_inline", "content": "n"},+ ],+ "algorithm_footnote": [],+ },+ }+++def test_content_list_v2_handles_empty_input_and_rejects_legacy_arguments() -> None:+ """验证空文档、严格 MiddleJson 输入和资源参数类型。"""+ middle = _middle()++ assert render_content_list_v2(middle) == []+ with pytest.raises(TypeError, match="MiddleJson"):+ render_content_list_v2(middle.to_dict()) # type: ignore[arg-type]+ with pytest.raises(TypeError, match="asset_base_url"):+ render_content_list_v2(middle, asset_base_url=1) # type: ignore[arg-type]diff --git a/tests/unittest/test_render_api.py b/tests/unittest/test_render_api.pyindex 2a27cc8d..221352d0 100644--- a/tests/unittest/test_render_api.py+++ b/tests/unittest/test_render_api.py@@ -10,6 +10,8 @@ import pytestimport mineru.render as render_modulefrom mineru.render import (+ ContentListRenderOptions,+ ContentListV2RenderOptions,DocxRenderError,DocxRenderOptions,HtmlRenderOptions,@@ -55,12 +57,18 @@ def test_unified_render_dispatches_all_native_output_types_without_mutation() ->html = render(middle, RenderFormat.HTML)docx = render(middle, RenderFormat.DOCX)structured_content = render(middle, RenderFormat.STRUCTURED_CONTENT)+ content_list = render(middle, RenderFormat.CONTENT_LIST)+ content_list_v2 = render(middle, RenderFormat.CONTENT_LIST_V2)assert markdown == "hello"assert isinstance(html, str) and "<html" in html and "hello" in htmlassert isinstance(docx, bytes) and docx.startswith(b"PK\x03\x04")assert Document(BytesIO(docx)).paragraphs[0].text == "hello"assert structured_content["pages"][0]["blocks"][0]["content"] == "hello"+ assert content_list == [{"type": "text", "text": "hello", "page_idx": 0}]+ assert content_list_v2 == [+ [{"type": "paragraph", "content": {"paragraph_content": [{"type": "text", "content": "hello"}]}}]+ ]assert middle == original@@ -103,6 +111,16 @@ def test_unified_render_forwards_format_specific_options() -> None:RenderFormat.STRUCTURED_CONTENT,options=StructuredContentRenderOptions(asset_base_url="https://cdn.example/doc"),)+ content_list = render(+ image_middle,+ RenderFormat.CONTENT_LIST,+ options=ContentListRenderOptions(asset_base_url="https://cdn.example/doc"),+ )+ content_list_v2 = render(+ image_middle,+ RenderFormat.CONTENT_LIST_V2,+ options=ContentListV2RenderOptions(asset_base_url="https://cdn.example/doc"),+ )image_markdown = render(image_middle,RenderFormat.MARKDOWN,@@ -123,6 +141,8 @@ def test_unified_render_forwards_format_specific_options() -> None:assert 'data-mineru-html-version="1" data-render-mode="full"' in htmlassert "<!doctype html>" not in htmlassert structured_content["pages"][0]["blocks"][0]["image_source"] == ("https://cdn.example/doc/images/a%20b.png")+ assert content_list[0]["img_path"] == "https://cdn.example/doc/images/a%20b.png"+ assert content_list_v2[0][0]["content"]["image_source"] == {"path": "https://cdn.example/doc/images/a%20b.png"}assert "https://cdn.example/doc/images/a%20b.png" in image_markdownassert "<title>Unified Render</title>" in html_documentassert 'src="https://cdn.example/doc/images/a%20b.png"' in html_document@@ -182,16 +202,31 @@ def test_unified_render_rejects_legacy_format_and_mismatched_options() -> None:render(middle, RenderFormat.MARKDOWN, options=HtmlRenderOptions()) # type: ignore[arg-type]with pytest.raises(TypeError, match="StructuredContentRenderOptions"):render(middle, RenderFormat.STRUCTURED_CONTENT, options=DocxRenderOptions()) # type: ignore[arg-type]+ with pytest.raises(TypeError, match="ContentListRenderOptions"):+ render(middle, RenderFormat.CONTENT_LIST, options=DocxRenderOptions()) # type: ignore[arg-type]+ with pytest.raises(TypeError, match="ContentListV2RenderOptions"):+ render(middle, RenderFormat.CONTENT_LIST_V2, options=ContentListRenderOptions()) # type: ignore[arg-type]def test_public_options_validate_fields() -> None:"""验证 Options 构造期的严格字段类型检查。"""- assert [item.value for item in RenderFormat] == ["markdown", "html", "docx", "structured_content"]+ assert [item.value for item in RenderFormat] == [+ "markdown",+ "html",+ "docx",+ "structured_content",+ "content_list",+ "content_list_v2",+ ]with pytest.raises(TypeError, match="RenderMode"):MarkdownRenderOptions(mode="default") # type: ignore[arg-type]with pytest.raises(TypeError, match="asset_base_url"):StructuredContentRenderOptions(asset_base_url=1) # type: ignore[arg-type]+ with pytest.raises(TypeError, match="asset_base_url"):+ ContentListRenderOptions(asset_base_url=1) # type: ignore[arg-type]+ with pytest.raises(TypeError, match="asset_base_url"):+ ContentListV2RenderOptions(asset_base_url=1) # type: ignore[arg-type]with pytest.raises(TypeError, match="standalone"):HtmlRenderOptions(standalone=1) # type: ignore[arg-type]with pytest.raises(TypeError, match="document_title"):@@ -200,10 +235,13 @@ def test_public_options_validate_fields() -> None:DocxRenderOptions(asset_resolver="images") # type: ignore[arg-type]-def test_public_render_exposes_only_structured_content_names() -> None:- """验证严格 render 公共面只暴露 Structured Content 新名称。"""+def test_public_render_exposes_all_three_structured_output_names() -> None:+ """验证严格 render 公共面同时暴露树形输出和两个兼容 Content List。"""assert callable(render_module.render_structured_content)+ assert callable(render_module.render_content_list)+ assert callable(render_module.render_content_list_v2)assert not hasattr(render_module, "MarkdownRenderMode")- assert not hasattr(render_module, "render_content_list")- assert not hasattr(render_module, "ContentListRenderOptions")- assert "CONTENT_LIST" not in RenderFormat.__members__+ assert ContentListRenderOptions is render_module.ContentListRenderOptions+ assert ContentListV2RenderOptions is render_module.ContentListV2RenderOptions+ assert "CONTENT_LIST" in RenderFormat.__members__+ assert "CONTENT_LIST_V2" in RenderFormat.__members__