Skip to content

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

feat: implement shared rendering semantics and internal structures for multiple output formats

myhloli29a0b2768859
diff --git a/docs/next/middle-json/rendering.md b/docs/next/middle-json/rendering.md
index f0f84f09..9f9810f5 100644
--- a/docs/next/middle-json/rendering.md
+++ b/docs/next/middle-json/rendering.md
@@ -1,10 +1,53 @@
# Rendering Contract
-状态: Markdown / Content List / DOCX / HTML v1
+状态: 统一入口 / Markdown / Content List / DOCX / HTML v1
读者: render 开发者、backend 开发者、SDK 开发者
-范围: 严格 MiddleJson 到 Markdown、Content List、DOCX 和 HTML 的消费契约
+范围: 严格 MiddleJson 到 Markdown、Content List、DOCX 和 HTML 的统一消费契约
-## 公共入口
+## 统一入口
+
+```python
+from mineru.render import (
+ MarkdownRenderOptions,
+ RenderFormat,
+ RenderMode,
+ render,
+)
+
+markdown = render(
+ middle_json,
+ RenderFormat.MARKDOWN,
+ options=MarkdownRenderOptions(
+ mode=RenderMode.DEFAULT,
+ asset_base_url="",
+ ),
+)
+```
+
+`render()` 每次接收一个严格 `MiddleJson` 和一个 `RenderFormat`,返回目标格式的原生结果:
+
+| `RenderFormat` | Options | 返回类型 |
+| --- | --- | --- |
+| `MARKDOWN` | `MarkdownRenderOptions(mode, asset_base_url)` | `str` |
+| `HTML` | `HtmlRenderOptions(mode, asset_base_url, standalone, document_title)` | `str` |
+| `DOCX` | `DocxRenderOptions(mode, asset_resolver)` | `bytes` |
+| `CONTENT_LIST` | `ContentListRenderOptions(asset_base_url)` | `dict[str, Any]` |
+
+`options` 省略时使用对应格式的默认 Options。入口只接受 `RenderFormat` 枚举,格式与 Options
+类型不匹配时抛出 `TypeError`,不归一化字符串格式,也不在单次调用中批量渲染。四个专用
+`render_*()` 函数继续保留;统一入口只负责严格校验和分发,不改变底层渲染语义或异常类型。
+
+所有入口均不修改传入的 `MiddleJson`。renderer 不负责把结果或图片写到文件系统;DOCX
+需要读取相对图片 sidecar 时,只能通过显式 `asset_resolver` 获取字节。
+
+### 内部依赖边界
+
+`markdown.py`、`html.py`、`docx.py` 和 `content_list.py` 是稳定公共门面;实现代码位于非公共
+`mineru.render._internal`。`common` 只保存跨格式 AST、解析、列表/目录语义和 render planner,
+不得依赖任一格式实现。`markdown`、`html`、`docx` 子包只能依赖 `common` 与自身模块,彼此
+不交叉导入。`_internal` 路径不属于 SDK 兼容承诺。
+
+## Markdown
```python
from mineru.render import MarkdownRenderMode, render_markdown
diff --git a/mineru/render/__init__.py b/mineru/render/__init__.py
index 6a88641f..1543d683 100644
--- a/mineru/render/__init__.py
+++ b/mineru/render/__init__.py
@@ -1,15 +1,36 @@
# Copyright (c) Opendatalab. All rights reserved.
+from .contracts import (
+ AssetResolver,
+ ContentListRenderOptions,
+ DocxRenderOptions,
+ HtmlRenderOptions,
+ MarkdownRenderMode,
+ MarkdownRenderOptions,
+ RenderFormat,
+ RenderMode,
+ RenderOptions,
+ RenderOutput,
+)
from .content_list import render_content_list
from .docx import DocxRenderError, render_docx
from .html import render_html
-from .markdown import MarkdownRenderMode, render_markdown
-from .utils.logical_blocks import RenderMode
+from .markdown import render_markdown
+from .api import render
__all__ = [
+ "AssetResolver",
+ "ContentListRenderOptions",
"DocxRenderError",
+ "DocxRenderOptions",
+ "HtmlRenderOptions",
"MarkdownRenderMode",
+ "MarkdownRenderOptions",
+ "RenderFormat",
"RenderMode",
+ "RenderOptions",
+ "RenderOutput",
+ "render",
"render_content_list",
"render_docx",
"render_html",
diff --git a/mineru/render/_internal/__init__.py b/mineru/render/_internal/__init__.py
new file mode 100644
index 00000000..070d526c
--- /dev/null
+++ b/mineru/render/_internal/__init__.py
@@ -0,0 +1 @@
+"""MinerU renderer 的非公共实现模块。"""
diff --git a/mineru/render/_internal/common/__init__.py b/mineru/render/_internal/common/__init__.py
new file mode 100644
index 00000000..4bcee000
--- /dev/null
+++ b/mineru/render/_internal/common/__init__.py
@@ -0,0 +1 @@
+"""各输出格式共用的渲染语义与规划实现。"""
diff --git a/mineru/render/utils/index.py b/mineru/render/_internal/common/index.py
similarity index 86%
rename from mineru/render/utils/index.py
rename to mineru/render/_internal/common/index.py
index 07992463..21142821 100644
--- a/mineru/render/utils/index.py
+++ b/mineru/render/_internal/common/index.py
@@ -1,11 +1,11 @@
# Copyright (c) Opendatalab. All rights reserved.
-"""目录页码尾清理的共享工具。"""
+"""各格式共用的目录页码尾部识别与清理。"""
from __future__ import annotations
import re
-from mineru.render.utils.inline import inline_plain_text, parse_inline_content
+from mineru.render._internal.common.inline import inline_plain_text, parse_inline_content
_INDEX_ROMAN_RE = re.compile(r"[ivxlcdm]+", re.IGNORECASE)
diff --git a/mineru/render/utils/inline.py b/mineru/render/_internal/common/inline.py
similarity index 51%
rename from mineru/render/utils/inline.py
rename to mineru/render/_internal/common/inline.py
index bacb1875..fb5615f4 100644
--- a/mineru/render/utils/inline.py
+++ b/mineru/render/_internal/common/inline.py
@@ -1,5 +1,5 @@
# Copyright (c) Opendatalab. All rights reserved.
-"""MiddleJson 行内语义解析与 Markdown 序列化。"""
+"""各格式共用的 MiddleJson 行内 AST、解析与段落边界合并。"""
from __future__ import annotations
@@ -8,8 +8,6 @@ import re
from dataclasses import dataclass
from typing import TypeAlias, Union
-from mineru.config import LatexDelimitersConfig
-from mineru.render.utils.markdown_utils import escape_conservative_markdown_text
from mineru.utils.language import detect_lang
from mineru.utils.text_utils import CJK_LANGS, resolve_text_line_boundary
@@ -20,14 +18,6 @@ _INLINE_START_RE = re.compile(
_STYLE_ATTR_RE = re.compile(r"\bstyle\s*=\s*([\"'])(?P<style>.*?)\1", re.IGNORECASE | re.DOTALL)
_URL_RE = re.compile(r"<url>(?P<url>.*?)</url>", re.IGNORECASE | re.DOTALL)
_CJK_RE = re.compile(r"[\u3040-\u30ff\u3400-\u9fff\uac00-\ud7af]")
-_ANGLE_TEXT_RE = re.compile(r"<[^<>\n]*>")
-
-_SIMPLE_STYLE_WRAPPERS = {
- frozenset({"bold"}): "**",
- frozenset({"italic"}): "*",
- frozenset({"strikethrough"}): "~~",
- frozenset({"bold", "italic"}): "***",
-}
_KNOWN_STYLES = {
"bold",
"italic",
@@ -183,16 +173,6 @@ def _append_text(nodes: list[InlineNode], content: str) -> None:
nodes.append(InlineText(content))
-def render_inline_content(content: str, delimiters: LatexDelimitersConfig) -> str:
- """把一段 MiddleJson 行内内容渲染为 Markdown。"""
- return render_inline_nodes(parse_inline_content(content), delimiters)
-
-
-def render_joined_inline_contents(contents: list[str], delimiters: LatexDelimitersConfig) -> str:
- """按物理段落边界规则合并多段 content 后渲染 Markdown。"""
- return render_inline_nodes(join_inline_contents(contents), delimiters)
-
-
def join_inline_contents(contents: list[str]) -> list[InlineNode]:
"""按物理段落边界规则合并多段 content,并保留中性的行内节点。"""
merged: list[InlineNode] = []
@@ -270,178 +250,6 @@ def _last_text_node(nodes: list[InlineNode]) -> InlineText | None:
return None
-def render_inline_nodes(nodes: list[InlineNode], delimiters: LatexDelimitersConfig) -> str:
- """把已解析的行内节点序列化为 Markdown 与安全 HTML。"""
- return "".join(_render_inline_node(node, delimiters) for node in nodes)
-
-
-def _render_inline_node(node: InlineNode, delimiters: LatexDelimitersConfig) -> str:
- """渲染单个行内节点。"""
- if isinstance(node, InlineText):
- return _escape_plain_markdown_text(node.content)
- if isinstance(node, InlineEquation):
- return f"{delimiters.inline.left}{node.latex}{delimiters.inline.right}"
- if isinstance(node, InlineStyled):
- content = render_inline_nodes(node.children, delimiters)
- return _apply_styles(content, inline_plain_text(node.children), node.styles)
- if isinstance(node, InlineLink):
- label = render_inline_nodes(node.children, delimiters)
- return _render_link(label, node.url, _requires_html_link(node.children))
- raise TypeError(f"Unsupported inline node: {type(node).__name__}")
-
-
-def _escape_plain_markdown_text(content: str) -> str:
- """转义普通 Markdown 符号,同时原样保留正文中的尖括号片段。"""
- parts: list[str] = []
- cursor = 0
- for match in _ANGLE_TEXT_RE.finditer(content):
- parts.append(escape_conservative_markdown_text(content[cursor : match.start()]))
- parts.append(match.group(0))
- cursor = match.end()
- parts.append(escape_conservative_markdown_text(content[cursor:]))
- return "".join(parts)
-
-
-def _apply_styles(content: str, plain_text: str, styles: tuple[str, ...]) -> str:
- """按样式复杂度选择 Markdown wrapper 或安全 HTML 标签。"""
- if not content or not styles:
- return content
- marker = _get_visible_space_marker(styles)
- if marker is not None:
- rendered_markers = _render_visible_space_marker_text(content, plain_text, styles, marker)
- if rendered_markers is not None:
- return rendered_markers
- if plain_text and not plain_text.strip() and any(style in styles for style in ("underline", "strikethrough", "emphasis")):
- return _render_visible_whitespace(plain_text, styles)
-
- return _apply_style_wrappers(content, styles)
-
-
-def _get_visible_space_marker(styles: tuple[str, ...]) -> str | None:
- """按 dev 规则选择可见空格 marker,下划线优先于删除线。"""
- if "underline" in styles:
- return "_"
- if "strikethrough" in styles:
- return "-"
- return None
-
-
-def _render_visible_space_marker_text(
- content: str,
- plain_text: str,
- styles: tuple[str, ...],
- marker: str,
-) -> str | None:
- """把纯 ASCII 空格或非空文本首尾空格转换为可见 marker。"""
- if not plain_text:
- return None
- style_key = frozenset(styles)
- force_html = style_key not in _SIMPLE_STYLE_WRAPPERS
- if all(char == " " for char in plain_text):
- ignored_style = "underline" if marker == "_" else "strikethrough"
- remaining_styles = tuple(style for style in styles if style != ignored_style)
- return _apply_style_wrappers(
- marker * len(plain_text),
- remaining_styles,
- force_html=force_html,
- )
-
- leading_count = len(plain_text) - len(plain_text.lstrip(" "))
- trailing_count = len(plain_text) - len(plain_text.rstrip(" "))
- if leading_count == 0 and trailing_count == 0:
- return None
- if not content.startswith(" " * leading_count) or not content.endswith(" " * trailing_count):
- return None
- content_end = len(content) - trailing_count if trailing_count else len(content)
- core = content[leading_count:content_end]
- rendered = f"{marker * leading_count}{core}{marker * trailing_count}"
- return _apply_style_wrappers(rendered, styles, force_html=force_html)
-
-
-def _apply_style_wrappers(
- content: str,
- styles: tuple[str, ...],
- *,
- force_html: bool = False,
-) -> str:
- """给已处理空格的内容添加 Markdown 或 HTML 样式 wrapper。"""
- if not content or not styles:
- return content
-
- leading = content[: len(content) - len(content.lstrip(" \t"))]
- trailing = content[len(content.rstrip(" \t")) :]
- core = content.strip(" \t")
- if not core:
- return content
-
- style_key = frozenset(styles)
- wrapper = _SIMPLE_STYLE_WRAPPERS.get(style_key)
- if wrapper is not None and not force_html:
- return f"{leading}{wrapper}{core}{wrapper}{trailing}"
- return f"{leading}{_apply_html_styles(core, styles)}{trailing}"
-
-
-def _render_visible_whitespace(content: str, styles: tuple[str, ...]) -> str:
- """使用原 HTML 规则保留非 ASCII marker 场景的可见空白。"""
- visible = "".join("<br>" if char == "\n" else "&nbsp;" for char in content.expandtabs(4))
- return _apply_html_styles(visible, styles)
-
-
-def _apply_html_styles(content: str, styles: tuple[str, ...]) -> str:
- """按稳定顺序给复杂样式添加 HTML wrapper。"""
- if "superscript" in styles:
- content = f"<sup>{content}</sup>"
- elif "subscript" in styles:
- content = f"<sub>{content}</sub>"
- if "underline" in styles:
- content = f"<u>{content}</u>"
- if "bold" in styles:
- content = f"<strong>{content}</strong>"
- if "italic" in styles:
- content = f"<em>{content}</em>"
- if "strikethrough" in styles:
- content = f"<s>{content}</s>"
- if "emphasis" in styles:
- content = f'<span style="text-emphasis: dot; text-emphasis-position: under;">{content}</span>'
- return content
-
-
-def _requires_html_link(nodes: list[InlineNode]) -> bool:
- """判断链接标签是否含不适合嵌入 Markdown link 的复杂样式。"""
- for node in nodes:
- if isinstance(node, InlineLink):
- return True
- if isinstance(node, InlineStyled):
- if frozenset(node.styles) not in _SIMPLE_STYLE_WRAPPERS:
- return True
- if _requires_html_link(node.children):
- return True
- return False
-
-
-def _render_link(label: str, url: str, use_html: bool) -> str:
- """按标签复杂度输出 Markdown 或 HTML 超链接。"""
- if not label:
- return ""
- if not url or url == ".":
- return label
- if use_html:
- return f'<a href="{html.escape(url, quote=True)}">{label}</a>'
- safe_url = url.replace("\\", "%5C").replace(" ", "%20").replace("(", "%28").replace(")", "%29")
- return f"[{_escape_markdown_link_label(label)}]({safe_url})"
-
-
-def render_internal_link(label: str, anchor: str) -> str:
- """把已渲染目录标签包装为当前文档内锚点链接。"""
- safe_anchor = anchor.replace(" ", "%20").replace("(", "%28").replace(")", "%29")
- return f"[{_escape_markdown_link_label(label)}](#{safe_anchor})"
-
-
-def _escape_markdown_link_label(label: str) -> str:
- """转义 Markdown link 标签中的方括号并保留既有反斜杠。"""
- return re.sub(r"(?<!\\)([\[\]])", r"\\\1", label)
-
-
def inline_plain_text(nodes: list[InlineNode]) -> str:
"""提取行内节点的可见文本,供边界和目录页码判断使用。"""
parts: list[str] = []
@@ -456,12 +264,12 @@ def inline_plain_text(nodes: list[InlineNode]) -> str:
__all__ = [
+ "InlineEquation",
+ "InlineLink",
"InlineNode",
+ "InlineStyled",
+ "InlineText",
"inline_plain_text",
"join_inline_contents",
"parse_inline_content",
- "render_inline_content",
- "render_inline_nodes",
- "render_internal_link",
- "render_joined_inline_contents",
]
diff --git a/mineru/render/utils/list_items.py b/mineru/render/_internal/common/list_items.py
similarity index 97%
rename from mineru/render/utils/list_items.py
rename to mineru/render/_internal/common/list_items.py
index ac16d09e..018bceb2 100644
--- a/mineru/render/utils/list_items.py
+++ b/mineru/render/_internal/common/list_items.py
@@ -1,5 +1,5 @@
# Copyright (c) Opendatalab. All rights reserved.
-"""列表条目标记与参考文献列表判定的共享工具。"""
+"""各格式共用的列表 marker 解析与参考文献判定。"""
from __future__ import annotations
@@ -7,7 +7,7 @@ from dataclasses import dataclass
import re
from typing import Literal, TypeAlias
-from mineru.render.utils.inline import inline_plain_text, parse_inline_content
+from mineru.render._internal.common.inline import inline_plain_text, parse_inline_content
from mineru.types import BlockType, ListBlock
ListItemKind: TypeAlias = Literal["unordered", "ordered", "explicit", "none"]
diff --git a/mineru/render/utils/logical_blocks.py b/mineru/render/_internal/common/planner.py
similarity index 94%
rename from mineru/render/utils/logical_blocks.py
rename to mineru/render/_internal/common/planner.py
index 3560e21a..1ce7da14 100644
--- a/mineru/render/utils/logical_blocks.py
+++ b/mineru/render/_internal/common/planner.py
@@ -1,12 +1,12 @@
# Copyright (c) Opendatalab. All rights reserved.
-"""MiddleJson 渲染前的逻辑块复制、延续合并与页面规划。"""
+"""各格式共用的逻辑块复制、延续合并与页面规划。"""
from __future__ import annotations
from dataclasses import dataclass, field
-from enum import Enum
from mineru.backend.postprocess.table_merge import merge_table_content
+from mineru.render.contracts import MarkdownRenderMode, RenderMode
from mineru.types import (
PAGE_AUXILIARY_BLOCK_TYPES,
BlockType,
@@ -20,17 +20,6 @@ from mineru.types import (
)
-class RenderMode(str, Enum):
- """MiddleJson renderer 共用的默认合并视图与完整分页视图。"""
-
- DEFAULT = "default"
- FULL = "full"
-
-
-# 保留既有 Markdown 公共名称,同时让新增 renderer 共用同一枚举类型。
-MarkdownRenderMode = RenderMode
-
-
@dataclass(slots=True)
class PlannedBlock:
"""保存一个待渲染块及其来源页和文本延续片段。"""
diff --git a/mineru/render/_internal/docx/__init__.py b/mineru/render/_internal/docx/__init__.py
new file mode 100644
index 00000000..80c63481
--- /dev/null
+++ b/mineru/render/_internal/docx/__init__.py
@@ -0,0 +1 @@
+"""DOCX renderer 的内部实现。"""
diff --git a/mineru/render/utils/docx_assets.py b/mineru/render/_internal/docx/assets.py
similarity index 97%
rename from mineru/render/utils/docx_assets.py
rename to mineru/render/_internal/docx/assets.py
index baae2b84..e4b87d4e 100644
--- a/mineru/render/utils/docx_assets.py
+++ b/mineru/render/_internal/docx/assets.py
@@ -1,5 +1,5 @@
# Copyright (c) Opendatalab. All rights reserved.
-"""DOCX renderer 使用的安全图片素材解析与格式准备。"""
+"""DOCX renderer 的安全图片素材解析与格式准备。"""
from __future__ import annotations
@@ -7,16 +7,14 @@ from dataclasses import dataclass
from io import BytesIO
from pathlib import PurePosixPath
import re
-from typing import Callable, TypeAlias
from urllib.parse import urlsplit
from PIL import Image, UnidentifiedImageError
+from mineru.render.contracts import AssetResolver
from mineru.types import ImagePayloadBlock
from mineru.utils.image_payload import parse_image_data_uri_strict, validate_image_sidecar_path
-AssetResolver: TypeAlias = Callable[[str], bytes]
-
_PIL_FORMAT_EXTENSIONS = {
"BMP": "bmp",
"GIF": "gif",
diff --git a/mineru/render/utils/docx_inline.py b/mineru/render/_internal/docx/inline.py
similarity index 98%
rename from mineru/render/utils/docx_inline.py
rename to mineru/render/_internal/docx/inline.py
index 851e1c58..2dd50b2b 100644
--- a/mineru/render/utils/docx_inline.py
+++ b/mineru/render/_internal/docx/inline.py
@@ -1,5 +1,5 @@
# Copyright (c) Opendatalab. All rights reserved.
-"""MiddleJson 行内节点到 Word run、超链接、书签和 OMML 的写入工具。"""
+"""MiddleJson 行内节点到 Word run、超链接、书签和 OMML 的 DOCX 写入。"""
from __future__ import annotations
@@ -17,8 +17,7 @@ from docx.shared import Pt, RGBColor
from lxml import etree
from loguru import logger
-from mineru.render.utils.docx_math import DocxFormulaError, latex_to_omml
-from mineru.render.utils.inline import (
+from mineru.render._internal.common.inline import (
InlineEquation,
InlineLink,
InlineNode,
@@ -28,6 +27,7 @@ from mineru.render.utils.inline import (
join_inline_contents,
parse_inline_content,
)
+from mineru.render._internal.docx.math import DocxFormulaError, latex_to_omml
_BOOKMARK_SAFE_RE = re.compile(r"[^A-Za-z0-9_]+")
_BOOKMARK_MAX_LENGTH = 40
diff --git a/mineru/render/utils/docx_math.py b/mineru/render/_internal/docx/math.py
similarity index 99%
rename from mineru/render/utils/docx_math.py
rename to mineru/render/_internal/docx/math.py
index 72a34a71..d675cb62 100644
--- a/mineru/render/utils/docx_math.py
+++ b/mineru/render/_internal/docx/math.py
@@ -1,5 +1,5 @@
# Copyright (c) Opendatalab. All rights reserved.
-"""DOCX 渲染使用的 LaTeX 与 OMML 转换工具。"""
+"""DOCX renderer 使用的 LaTeX 与 OMML 转换。"""
from __future__ import annotations
diff --git a/mineru/render/utils/docx_styles.py b/mineru/render/_internal/docx/styles.py
similarity index 98%
rename from mineru/render/utils/docx_styles.py
rename to mineru/render/_internal/docx/styles.py
index 8d9e6f74..357c6a17 100644
--- a/mineru/render/utils/docx_styles.py
+++ b/mineru/render/_internal/docx/styles.py
@@ -1,5 +1,5 @@
# Copyright (c) Opendatalab. All rights reserved.
-"""DOCX renderer 的页面几何与显式 Word 样式定义。"""
+"""DOCX renderer 的页面几何与 Word 样式定义。"""
from __future__ import annotations
diff --git a/mineru/render/utils/docx_table.py b/mineru/render/_internal/docx/table.py
similarity index 99%
rename from mineru/render/utils/docx_table.py
rename to mineru/render/_internal/docx/table.py
index 7d2c2600..8df167ea 100644
--- a/mineru/render/utils/docx_table.py
+++ b/mineru/render/_internal/docx/table.py
@@ -1,5 +1,5 @@
# Copyright (c) Opendatalab. All rights reserved.
-"""HTML 表格占位网格解析与 python-docx 表格物化。"""
+"""DOCX renderer 的 HTML 表格占位网格解析与原生表格物化。"""
from __future__ import annotations
diff --git a/mineru/render/_internal/html/__init__.py b/mineru/render/_internal/html/__init__.py
new file mode 100644
index 00000000..756f3dc3
--- /dev/null
+++ b/mineru/render/_internal/html/__init__.py
@@ -0,0 +1 @@
+"""HTML renderer 的内部实现。"""
diff --git a/mineru/render/utils/html_inline.py b/mineru/render/_internal/html/inline.py
similarity index 96%
rename from mineru/render/utils/html_inline.py
rename to mineru/render/_internal/html/inline.py
index ddf6c0e6..a262426a 100644
--- a/mineru/render/utils/html_inline.py
+++ b/mineru/render/_internal/html/inline.py
@@ -1,5 +1,5 @@
# Copyright (c) Opendatalab. All rights reserved.
-"""MiddleJson 共享行内语义到安全 HTML 的序列化工具。"""
+"""MiddleJson 共享行内语义到安全 HTML 的序列化。"""
from __future__ import annotations
@@ -7,8 +7,7 @@ import html
import re
from dataclasses import dataclass
-from mineru.render.utils.html_sanitizer import sanitize_link_url
-from mineru.render.utils.inline import (
+from mineru.render._internal.common.inline import (
InlineEquation,
InlineLink,
InlineNode,
@@ -18,6 +17,7 @@ from mineru.render.utils.inline import (
join_inline_contents,
parse_inline_content,
)
+from mineru.render._internal.html.sanitizer import sanitize_link_url
@dataclass(frozen=True, slots=True)
diff --git a/mineru/render/utils/html_sanitizer.py b/mineru/render/_internal/html/sanitizer.py
similarity index 99%
rename from mineru/render/utils/html_sanitizer.py
rename to mineru/render/_internal/html/sanitizer.py
index 4b898c09..97fae212 100644
--- a/mineru/render/utils/html_sanitizer.py
+++ b/mineru/render/_internal/html/sanitizer.py
@@ -1,5 +1,5 @@
# Copyright (c) Opendatalab. All rights reserved.
-"""HTML renderer 使用的嵌入片段安全处理。"""
+"""HTML renderer 使用的嵌入片段与 URL 安全处理。"""
from __future__ import annotations
diff --git a/mineru/render/utils/html_table.py b/mineru/render/_internal/html/table.py
similarity index 96%
rename from mineru/render/utils/html_table.py
rename to mineru/render/_internal/html/table.py
index 89f6fe86..715afedc 100644
--- a/mineru/render/utils/html_table.py
+++ b/mineru/render/_internal/html/table.py
@@ -1,11 +1,11 @@
# Copyright (c) Opendatalab. All rights reserved.
-"""HTML renderer 使用的严格 GFM pipe table 转换工具。"""
+"""HTML renderer 使用的严格 GFM pipe table 转换。"""
from __future__ import annotations
import re
-from mineru.render.utils.html_inline import HtmlInlineResult, render_inline_content_html
+from mineru.render._internal.html.inline import HtmlInlineResult, render_inline_content_html
_SEPARATOR_CELL_RE = re.compile(r"^:?-{3,}:?$")
diff --git a/mineru/render/_internal/markdown/__init__.py b/mineru/render/_internal/markdown/__init__.py
new file mode 100644
index 00000000..fd246652
--- /dev/null
+++ b/mineru/render/_internal/markdown/__init__.py
@@ -0,0 +1 @@
+"""Markdown 与 Content List 共用的内部实现。"""
diff --git a/mineru/render/utils/assets.py b/mineru/render/_internal/markdown/assets.py
similarity index 97%
rename from mineru/render/utils/assets.py
rename to mineru/render/_internal/markdown/assets.py
index 73a79cdf..57c5bd44 100644
--- a/mineru/render/utils/assets.py
+++ b/mineru/render/_internal/markdown/assets.py
@@ -1,5 +1,5 @@
# Copyright (c) Opendatalab. All rights reserved.
-"""Markdown 与嵌入 HTML 共用的图片资源解析。"""
+"""Markdown 与 Content List 共用的图片资源解析。"""
from __future__ import annotations
diff --git a/mineru/render/_internal/markdown/blocks.py b/mineru/render/_internal/markdown/blocks.py
new file mode 100644
index 00000000..6b75b030
--- /dev/null
+++ b/mineru/render/_internal/markdown/blocks.py
@@ -0,0 +1,504 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""Markdown 与 Content List 共用的 block 级序列化。"""
+
+from __future__ import annotations
+
+import html
+import re
+
+from mineru.config import LatexDelimitersConfig
+from mineru.render._internal.common.index import strip_index_page_tail
+from mineru.render._internal.common.list_items import has_markdown_unordered_marker, reference_list_needs_bullets
+from mineru.render._internal.common.planner import PlannedBlock
+from mineru.render._internal.markdown.assets import build_markdown_image, resolve_image_source
+from mineru.render._internal.markdown.escaping import escape_standalone_marker_rule, escape_text_block_markdown_prefix
+from mineru.render._internal.markdown.inline import (
+ render_inline_content,
+ render_internal_link,
+ render_joined_inline_contents,
+)
+from mineru.render._internal.markdown.table import format_embedded_html, render_html_table
+from mineru.types import (
+ RAW_ALGORITHM,
+ BlockType,
+ ChartAnnotationBlock,
+ ChartBlock,
+ ChartBodyBlock,
+ CodeAnnotationBlock,
+ CodeBlock,
+ CodeBodyBlock,
+ DocTitleBlock,
+ EquationBlock,
+ ImageAnnotationBlock,
+ ImageBlock,
+ ImageBodyBlock,
+ IndexBlock,
+ ListBlock,
+ PageAuxTextBlock,
+ PageBlock,
+ ParagraphTitleBlock,
+ RefTextBlock,
+ TableAnnotationBlock,
+ TableBlock,
+ TableBodyBlock,
+ TextBlock,
+)
+
+_ALGORITHM_TOKEN_RE = re.compile(
+ r"<eq>(?P<latex>.*?)</eq>|(?P<script_tag></?(?:sub|sup)>)",
+ re.IGNORECASE | re.DOTALL,
+)
+_VALID_CODE_LANGUAGE_RE = re.compile(r"[A-Za-z0-9_.+#-]+")
+
+
+def render_planned_block(
+ planned: PlannedBlock,
+ *,
+ delimiters: LatexDelimitersConfig,
+ asset_base_url: str,
+) -> str:
+ """按具体 Pydantic block 类型分发 Markdown 渲染。"""
+ block = planned.block
+ if isinstance(block, TextBlock):
+ content = render_joined_inline_contents(planned.text_contents or [block.content], delimiters)
+ return escape_standalone_marker_rule(escape_text_block_markdown_prefix(content))
+ if isinstance(block, RefTextBlock):
+ content = render_joined_inline_contents(planned.text_contents or [block.content], delimiters)
+ return escape_standalone_marker_rule(content)
+ if isinstance(block, (DocTitleBlock, ParagraphTitleBlock)):
+ return _render_title(block, delimiters)
+ if isinstance(block, PageAuxTextBlock):
+ content = escape_text_block_markdown_prefix(render_inline_content(block.content, delimiters))
+ return escape_standalone_marker_rule(content)
+ if isinstance(block, EquationBlock):
+ return _render_equation(block, delimiters, asset_base_url)
+ if isinstance(block, ListBlock):
+ return _render_list(block, delimiters)
+ if isinstance(block, IndexBlock):
+ return _render_index(block, delimiters)
+ if isinstance(block, ImageBlock):
+ return _render_image_block(block, delimiters, asset_base_url)
+ if isinstance(block, TableBlock):
+ return _render_table_block(block, delimiters, asset_base_url)
+ if isinstance(block, ChartBlock):
+ return _render_chart_block(block, delimiters, asset_base_url)
+ if isinstance(block, CodeBlock):
+ return _render_code_block(block, delimiters)
+ 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,
+) -> str:
+ """渲染带可选 HTML anchor 的 Markdown 标题。"""
+ level = min(max(block.level, 1), 6)
+ 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,
+ asset_base_url: str,
+) -> str:
+ """优先渲染行间 LaTeX,空公式内容回退到公式图片。"""
+ latex = block.content.strip()
+ if latex:
+ return f"{delimiters.display.left}\n{latex}\n{delimiters.display.right}"
+ source = resolve_image_source(block, asset_base_url)
+ return build_markdown_image(source) if source else ""
+
+
+def _render_list(block: ListBlock, delimiters: LatexDelimitersConfig, depth: int = 0) -> str:
+ """递归渲染列表,并给多数条目无数字前缀的参考文献补无序标记。"""
+ add_ref_bullets = reference_list_needs_bullets(block)
+ lines: list[str] = []
+ for child in block.content:
+ if isinstance(child, ListBlock):
+ nested = _render_list(child, delimiters, depth + 1)
+ if nested:
+ lines.extend(nested.splitlines())
+ continue
+ item = render_inline_content(child.content, delimiters)
+ if not item:
+ continue
+ item = escape_standalone_marker_rule(item)
+ indent = " " * depth
+ item_lines = item.splitlines() or [item]
+ if add_ref_bullets and not has_markdown_unordered_marker(item):
+ lines.append(f"{indent}- {item_lines[0]}")
+ lines.extend(f"{indent} {line}" for line in item_lines[1:])
+ else:
+ lines.extend(f"{indent}{line}" for line in item_lines)
+ return "\n".join(lines)
+
+def _render_index(block: IndexBlock, delimiters: LatexDelimitersConfig, depth: int = 0) -> str:
+ """递归渲染目录列表,并给标题叶子添加内部 anchor 链接。"""
+ lines: list[str] = []
+ for child in block.content:
+ if isinstance(child, IndexBlock):
+ nested = _render_index(child, delimiters, depth + 1)
+ if nested:
+ lines.extend(nested.splitlines())
+ continue
+ content = strip_index_page_tail(child.content)
+ label = render_inline_content(content, delimiters).strip()
+ if not label:
+ continue
+ if isinstance(child, (DocTitleBlock, ParagraphTitleBlock)) and child.anchor:
+ label = render_internal_link(label, child.anchor)
+ lines.append(f"{' ' * depth}- {label}")
+ return "\n".join(lines)
+
+def _render_image_block(
+ block: ImageBlock,
+ delimiters: LatexDelimitersConfig,
+ asset_base_url: str,
+) -> str:
+ """按原始子块顺序渲染图片主体及说明文本。"""
+ parts: list[str] = []
+ for child in block.content:
+ if isinstance(child, ImageBodyBlock):
+ body = _render_visual_body_child(
+ block,
+ child,
+ delimiters=delimiters,
+ asset_base_url=asset_base_url,
+ )
+ elif isinstance(child, ImageAnnotationBlock):
+ body = render_visual_annotation(child, delimiters)
+ else:
+ raise TypeError(f"Unsupported image child: {type(child).__name__}")
+ if body:
+ parts.append(body)
+ return _join_visual_parts(parts)
+
+
+def _render_chart_block(
+ block: ChartBlock,
+ delimiters: LatexDelimitersConfig,
+ asset_base_url: str,
+) -> str:
+ """按原始子块顺序渲染图表图片、结构内容和说明文本。"""
+ parts: list[str] = []
+ for child in block.content:
+ if isinstance(child, ChartBodyBlock):
+ body = _render_visual_body_child(
+ block,
+ child,
+ delimiters=delimiters,
+ asset_base_url=asset_base_url,
+ )
+ elif isinstance(child, ChartAnnotationBlock):
+ body = render_visual_annotation(child, delimiters)
+ else:
+ raise TypeError(f"Unsupported chart child: {type(child).__name__}")
+ if body:
+ parts.append(body)
+ return _join_visual_parts(parts)
+
+
+def _render_media_body(
+ block: ImageBodyBlock,
+ *,
+ summary: str,
+ delimiters: LatexDelimitersConfig,
+ asset_base_url: str,
+) -> str:
+ """渲染图片载荷,并将识别内容放入折叠详情。"""
+ source = resolve_image_source(block, asset_base_url)
+ rendered_content = _render_media_content(block, delimiters, asset_base_url)
+ if source:
+ parts = [build_markdown_image(source)]
+ 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)
+
+
+def _render_chart_body(
+ block: ChartBodyBlock,
+ *,
+ summary: str,
+ delimiters: LatexDelimitersConfig,
+ asset_base_url: str,
+) -> str:
+ """渲染 chart 图片,并统一转换其 HTML 表格内容。"""
+ source = resolve_image_source(block, asset_base_url)
+ rendered_content = _render_chart_content(block.content, delimiters, asset_base_url)
+ if source:
+ parts = [build_markdown_image(source)]
+ 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_chart_content(
+ content: str,
+ delimiters: LatexDelimitersConfig,
+ asset_base_url: str,
+) -> str:
+ """把 chart 内容中的简单 HTML 表格转为 GFM,其他内容保持原表示。"""
+ normalized = content.strip()
+ if not normalized:
+ return ""
+ html_table = render_html_table(
+ normalized,
+ asset_base_url=asset_base_url,
+ delimiters=delimiters,
+ )
+ if html_table is not None:
+ return html_table
+ return format_embedded_html(normalized, asset_base_url=asset_base_url, delimiters=delimiters)
+
+
+def _render_details(content: str, summary: str) -> str:
+ """构造保留已渲染视觉内容的折叠 HTML 详情块。"""
+ safe_summary = html.escape(summary, quote=False)
+ return f"<details>\n<summary>{safe_summary}</summary>\n\n{content.strip()}\n</details>"
+
+
+def _render_table_block(
+ block: TableBlock,
+ delimiters: LatexDelimitersConfig,
+ asset_base_url: str,
+) -> str:
+ """按原始子块顺序渲染表格主体及说明文本。"""
+ parts: list[str] = []
+ for child in block.content:
+ if isinstance(child, TableBodyBlock):
+ body = _render_visual_body_child(
+ block,
+ child,
+ delimiters=delimiters,
+ asset_base_url=asset_base_url,
+ )
+ elif isinstance(child, TableAnnotationBlock):
+ body = render_visual_annotation(child, delimiters)
+ else:
+ raise TypeError(f"Unsupported table child: {type(child).__name__}")
+ if body:
+ parts.append(body)
+ return _join_visual_parts(parts)
+
+
+def _render_table_body(
+ block: TableBodyBlock,
+ delimiters: LatexDelimitersConfig,
+ asset_base_url: str,
+) -> str:
+ """按 HTML、空间投影文本、图片的优先级渲染表格主体。"""
+ 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] = []
+ for child in block.content:
+ if isinstance(child, CodeBodyBlock):
+ body = _render_visual_body_child(
+ block,
+ child,
+ delimiters=delimiters,
+ asset_base_url="",
+ )
+ elif isinstance(child, CodeAnnotationBlock):
+ body = render_visual_annotation(child, delimiters)
+ else:
+ raise TypeError(f"Unsupported code child: {type(child).__name__}")
+ if body:
+ parts.append(body)
+ return _join_visual_parts(parts)
+
+
+def render_visual_body_content(
+ block: ImageBlock | TableBlock | ChartBlock | CodeBlock,
+ *,
+ delimiters: LatexDelimitersConfig,
+ asset_base_url: str,
+) -> str:
+ """查找视觉父块唯一 body,并只渲染可结构化消费的语义内容。"""
+ for child in block.content:
+ 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}")
+
+
+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()
+ if not normalized or _VALID_CODE_LANGUAGE_RE.fullmatch(normalized) is None:
+ return "txt"
+ return normalized
+
+
+def _render_fenced_content(content: str, language: str | None = None) -> str:
+ """使用长于正文反引号游程的围栏包裹原始内容。"""
+ longest = max((len(match.group(0)) for match in re.finditer(r"`+", content)), default=0)
+ fence = "`" * max(3, longest + 1)
+ opening = f"{fence}{language or ''}"
+ closing_prefix = "" if content.endswith("\n") else "\n"
+ return f"{opening}\n{content}{closing_prefix}{fence}"
+
+
+def _render_algorithm_html(content: str, delimiters: LatexDelimitersConfig) -> str:
+ """参考 dev 实现渲染保留空白、上下标和行内公式的算法 HTML。"""
+ if not content.strip():
+ return ""
+ parts: list[str] = []
+ cursor = 0
+ previous_was_equation = False
+ for match in _ALGORITHM_TOKEN_RE.finditer(content):
+ plain = content[cursor : match.start()]
+ if plain:
+ parts.append(plain)
+ previous_was_equation = False
+ script_tag = match.group("script_tag")
+ if script_tag is not None:
+ parts.append(script_tag.lower())
+ previous_was_equation = False
+ cursor = match.end()
+ continue
+ latex = html.unescape(match.group("latex")).strip()
+ if latex:
+ if previous_was_equation and parts and not parts[-1].endswith((" ", "\n", "\t")):
+ parts.append(" ")
+ parts.append(f"{delimiters.inline.left}{latex}{delimiters.inline.right}")
+ previous_was_equation = True
+ cursor = match.end()
+ parts.append(content[cursor:])
+ body = "".join(parts)
+ 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:
+ """使用安全空行连接同一视觉父块中的有序子块。"""
+ return "\n\n".join(part.strip("\n") for part in parts if part and part.strip())
+
+
+__all__ = [
+ "render_planned_block",
+ "render_single_block",
+ "render_title_inline_content",
+ "render_visual_annotation",
+ "render_visual_body_content",
+]
diff --git a/mineru/render/utils/markdown_utils.py b/mineru/render/_internal/markdown/escaping.py
similarity index 96%
rename from mineru/render/utils/markdown_utils.py
rename to mineru/render/_internal/markdown/escaping.py
index bc95f625..49ac191a 100644
--- a/mineru/render/utils/markdown_utils.py
+++ b/mineru/render/_internal/markdown/escaping.py
@@ -1,5 +1,7 @@
# Copyright (c) Opendatalab. All rights reserved.
+"""Markdown 文本转义与 block 前缀保护。"""
+
import re
CONSERVATIVE_MARKDOWN_SPECIAL_CHARS = ("*", "_", "`", "~", "$")
diff --git a/mineru/render/_internal/markdown/inline.py b/mineru/render/_internal/markdown/inline.py
new file mode 100644
index 00000000..7d58698f
--- /dev/null
+++ b/mineru/render/_internal/markdown/inline.py
@@ -0,0 +1,218 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""共享 inline AST 到 Markdown 与安全 HTML 的序列化。"""
+
+from __future__ import annotations
+
+import html
+import re
+
+from mineru.config import LatexDelimitersConfig
+from mineru.render._internal.common.inline import (
+ InlineEquation,
+ InlineLink,
+ InlineNode,
+ InlineStyled,
+ InlineText,
+ inline_plain_text,
+ join_inline_contents,
+ parse_inline_content,
+)
+from mineru.render._internal.markdown.escaping import escape_conservative_markdown_text
+
+_ANGLE_TEXT_RE = re.compile(r"<[^<>\n]*>")
+_SIMPLE_STYLE_WRAPPERS = {
+ frozenset({"bold"}): "**",
+ frozenset({"italic"}): "*",
+ frozenset({"strikethrough"}): "~~",
+ frozenset({"bold", "italic"}): "***",
+}
+
+
+def render_inline_content(content: str, delimiters: LatexDelimitersConfig) -> str:
+ """把一段 MiddleJson 行内内容渲染为 Markdown。"""
+ return render_inline_nodes(parse_inline_content(content), delimiters)
+
+
+def render_joined_inline_contents(contents: list[str], delimiters: LatexDelimitersConfig) -> str:
+ """按物理段落边界规则合并多段 content 后渲染 Markdown。"""
+ return render_inline_nodes(join_inline_contents(contents), delimiters)
+
+
+def render_inline_nodes(nodes: list[InlineNode], delimiters: LatexDelimitersConfig) -> str:
+ """把已解析的行内节点序列化为 Markdown 与安全 HTML。"""
+ return "".join(_render_inline_node(node, delimiters) for node in nodes)
+
+
+def _render_inline_node(node: InlineNode, delimiters: LatexDelimitersConfig) -> str:
+ """渲染单个行内节点。"""
+ if isinstance(node, InlineText):
+ return _escape_plain_markdown_text(node.content)
+ if isinstance(node, InlineEquation):
+ return f"{delimiters.inline.left}{node.latex}{delimiters.inline.right}"
+ if isinstance(node, InlineStyled):
+ content = render_inline_nodes(node.children, delimiters)
+ return _apply_styles(content, inline_plain_text(node.children), node.styles)
+ if isinstance(node, InlineLink):
+ label = render_inline_nodes(node.children, delimiters)
+ return _render_link(label, node.url, _requires_html_link(node.children))
+ raise TypeError(f"Unsupported inline node: {type(node).__name__}")
+
+
+def _escape_plain_markdown_text(content: str) -> str:
+ """转义普通 Markdown 符号,同时原样保留正文中的尖括号片段。"""
+ parts: list[str] = []
+ cursor = 0
+ for match in _ANGLE_TEXT_RE.finditer(content):
+ parts.append(escape_conservative_markdown_text(content[cursor : match.start()]))
+ parts.append(match.group(0))
+ cursor = match.end()
+ parts.append(escape_conservative_markdown_text(content[cursor:]))
+ return "".join(parts)
+
+
+def _apply_styles(content: str, plain_text: str, styles: tuple[str, ...]) -> str:
+ """按样式复杂度选择 Markdown wrapper 或安全 HTML 标签。"""
+ if not content or not styles:
+ return content
+ marker = _get_visible_space_marker(styles)
+ if marker is not None:
+ rendered_markers = _render_visible_space_marker_text(content, plain_text, styles, marker)
+ if rendered_markers is not None:
+ return rendered_markers
+ if plain_text and not plain_text.strip() and any(style in styles for style in ("underline", "strikethrough", "emphasis")):
+ return _render_visible_whitespace(plain_text, styles)
+
+ return _apply_style_wrappers(content, styles)
+
+
+def _get_visible_space_marker(styles: tuple[str, ...]) -> str | None:
+ """按 dev 规则选择可见空格 marker,下划线优先于删除线。"""
+ if "underline" in styles:
+ return "_"
+ if "strikethrough" in styles:
+ return "-"
+ return None
+
+
+def _render_visible_space_marker_text(
+ content: str,
+ plain_text: str,
+ styles: tuple[str, ...],
+ marker: str,
+) -> str | None:
+ """把纯 ASCII 空格或非空文本首尾空格转换为可见 marker。"""
+ if not plain_text:
+ return None
+ style_key = frozenset(styles)
+ force_html = style_key not in _SIMPLE_STYLE_WRAPPERS
+ if all(char == " " for char in plain_text):
+ ignored_style = "underline" if marker == "_" else "strikethrough"
+ remaining_styles = tuple(style for style in styles if style != ignored_style)
+ return _apply_style_wrappers(
+ marker * len(plain_text),
+ remaining_styles,
+ force_html=force_html,
+ )
+
+ leading_count = len(plain_text) - len(plain_text.lstrip(" "))
+ trailing_count = len(plain_text) - len(plain_text.rstrip(" "))
+ if leading_count == 0 and trailing_count == 0:
+ return None
+ if not content.startswith(" " * leading_count) or not content.endswith(" " * trailing_count):
+ return None
+ content_end = len(content) - trailing_count if trailing_count else len(content)
+ core = content[leading_count:content_end]
+ rendered = f"{marker * leading_count}{core}{marker * trailing_count}"
+ return _apply_style_wrappers(rendered, styles, force_html=force_html)
+
+
+def _apply_style_wrappers(
+ content: str,
+ styles: tuple[str, ...],
+ *,
+ force_html: bool = False,
+) -> str:
+ """给已处理空格的内容添加 Markdown 或 HTML 样式 wrapper。"""
+ if not content or not styles:
+ return content
+
+ leading = content[: len(content) - len(content.lstrip(" \t"))]
+ trailing = content[len(content.rstrip(" \t")) :]
+ core = content.strip(" \t")
+ if not core:
+ return content
+
+ style_key = frozenset(styles)
+ wrapper = _SIMPLE_STYLE_WRAPPERS.get(style_key)
+ if wrapper is not None and not force_html:
+ return f"{leading}{wrapper}{core}{wrapper}{trailing}"
+ return f"{leading}{_apply_html_styles(core, styles)}{trailing}"
+
+
+def _render_visible_whitespace(content: str, styles: tuple[str, ...]) -> str:
+ """使用原 HTML 规则保留非 ASCII marker 场景的可见空白。"""
+ visible = "".join("<br>" if char == "\n" else "&nbsp;" for char in content.expandtabs(4))
+ return _apply_html_styles(visible, styles)
+
+
+def _apply_html_styles(content: str, styles: tuple[str, ...]) -> str:
+ """按稳定顺序给复杂样式添加 HTML wrapper。"""
+ if "superscript" in styles:
+ content = f"<sup>{content}</sup>"
+ elif "subscript" in styles:
+ content = f"<sub>{content}</sub>"
+ if "underline" in styles:
+ content = f"<u>{content}</u>"
+ if "bold" in styles:
+ content = f"<strong>{content}</strong>"
+ if "italic" in styles:
+ content = f"<em>{content}</em>"
+ if "strikethrough" in styles:
+ content = f"<s>{content}</s>"
+ if "emphasis" in styles:
+ content = f'<span style="text-emphasis: dot; text-emphasis-position: under;">{content}</span>'
+ return content
+
+
+def _requires_html_link(nodes: list[InlineNode]) -> bool:
+ """判断链接标签是否含不适合嵌入 Markdown link 的复杂样式。"""
+ for node in nodes:
+ if isinstance(node, InlineLink):
+ return True
+ if isinstance(node, InlineStyled):
+ if frozenset(node.styles) not in _SIMPLE_STYLE_WRAPPERS:
+ return True
+ if _requires_html_link(node.children):
+ return True
+ return False
+
+
+def _render_link(label: str, url: str, use_html: bool) -> str:
+ """按标签复杂度输出 Markdown 或 HTML 超链接。"""
+ if not label:
+ return ""
+ if not url or url == ".":
+ return label
+ if use_html:
+ return f'<a href="{html.escape(url, quote=True)}">{label}</a>'
+ safe_url = url.replace("\\", "%5C").replace(" ", "%20").replace("(", "%28").replace(")", "%29")
+ return f"[{_escape_markdown_link_label(label)}]({safe_url})"
+
+
+def render_internal_link(label: str, anchor: str) -> str:
+ """把已渲染目录标签包装为当前文档内锚点链接。"""
+ safe_anchor = anchor.replace(" ", "%20").replace("(", "%28").replace(")", "%29")
+ return f"[{_escape_markdown_link_label(label)}](#{safe_anchor})"
+
+
+def _escape_markdown_link_label(label: str) -> str:
+ """转义 Markdown link 标签中的方括号并保留既有反斜杠。"""
+ return re.sub(r"(?<!\\)([\[\]])", r"\\\1", label)
+
+
+__all__ = [
+ "render_inline_content",
+ "render_inline_nodes",
+ "render_internal_link",
+ "render_joined_inline_contents",
+]
diff --git a/mineru/render/utils/markdown_table.py b/mineru/render/_internal/markdown/table.py
similarity index 98%
rename from mineru/render/utils/markdown_table.py
rename to mineru/render/_internal/markdown/table.py
index b5577144..31e016e4 100644
--- a/mineru/render/utils/markdown_table.py
+++ b/mineru/render/_internal/markdown/table.py
@@ -1,5 +1,5 @@
# Copyright (c) Opendatalab. All rights reserved.
-"""HTML 表格判型、内嵌资源处理与无损 GFM 转换。"""
+"""Markdown renderer 的 HTML 表格判型与无损 GFM 转换。"""
from __future__ import annotations
@@ -10,7 +10,7 @@ from bs4 import BeautifulSoup
from bs4.element import NavigableString, Tag
from mineru.config import LatexDelimitersConfig
-from mineru.render.utils.assets import prefix_html_image_sources
+from mineru.render._internal.markdown.assets import prefix_html_image_sources
_INLINE_EQ_RE = re.compile(r"<eq>(?P<latex>.*?)</eq>", re.IGNORECASE | re.DOTALL)
_GFM_FORMULA_PIPE_RE = re.compile(r"(?P<slashes>\\*)\|")
diff --git a/mineru/render/api.py b/mineru/render/api.py
new file mode 100644
index 00000000..8b0f0c1c
--- /dev/null
+++ b/mineru/render/api.py
@@ -0,0 +1,125 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""严格 MiddleJson 多格式渲染的统一公共入口。"""
+
+from __future__ import annotations
+
+from typing import Any, Literal, overload
+
+from mineru.types import MiddleJson
+
+from .content_list import render_content_list
+from .contracts import (
+ ContentListRenderOptions,
+ DocxRenderOptions,
+ HtmlRenderOptions,
+ MarkdownRenderOptions,
+ RenderFormat,
+ RenderOptions,
+ RenderOutput,
+)
+from .docx import render_docx
+from .html import render_html
+from .markdown import render_markdown
+
+
+@overload
+def render(
+ middle_json: MiddleJson,
+ output_format: Literal[RenderFormat.MARKDOWN],
+ *,
+ options: MarkdownRenderOptions | None = None,
+) -> str:
+ """声明 Markdown 目标对应的字符串返回类型。"""
+ ...
+
+
+@overload
+def render(
+ middle_json: MiddleJson,
+ output_format: Literal[RenderFormat.HTML],
+ *,
+ options: HtmlRenderOptions | None = None,
+) -> str:
+ """声明 HTML 目标对应的字符串返回类型。"""
+ ...
+
+
+@overload
+def render(
+ middle_json: MiddleJson,
+ output_format: Literal[RenderFormat.DOCX],
+ *,
+ options: DocxRenderOptions | None = None,
+) -> bytes:
+ """声明 DOCX 目标对应的字节返回类型。"""
+ ...
+
+
+@overload
+def render(
+ middle_json: MiddleJson,
+ output_format: Literal[RenderFormat.CONTENT_LIST],
+ *,
+ options: ContentListRenderOptions | None = None,
+) -> dict[str, Any]:
+ """声明 Content List 目标对应的字典返回类型。"""
+ ...
+
+
+def render(
+ middle_json: MiddleJson,
+ output_format: RenderFormat,
+ *,
+ options: RenderOptions | None = None,
+) -> RenderOutput:
+ """按严格目标格式和对应选项把 MiddleJson 渲染为原生结果。"""
+ if not isinstance(middle_json, MiddleJson):
+ raise TypeError("render expects a MiddleJson instance")
+ if not isinstance(output_format, RenderFormat):
+ raise TypeError("output_format must be a RenderFormat value")
+
+ if output_format is RenderFormat.MARKDOWN:
+ resolved_options = options if options is not None else MarkdownRenderOptions()
+ if not isinstance(resolved_options, MarkdownRenderOptions):
+ raise TypeError("MARKDOWN output requires MarkdownRenderOptions")
+ return render_markdown(
+ middle_json,
+ mode=resolved_options.mode,
+ asset_base_url=resolved_options.asset_base_url,
+ )
+
+ if output_format is RenderFormat.HTML:
+ resolved_options = options if options is not None else HtmlRenderOptions()
+ if not isinstance(resolved_options, HtmlRenderOptions):
+ raise TypeError("HTML output requires HtmlRenderOptions")
+ return render_html(
+ middle_json,
+ mode=resolved_options.mode,
+ asset_base_url=resolved_options.asset_base_url,
+ standalone=resolved_options.standalone,
+ document_title=resolved_options.document_title,
+ )
+
+ if output_format is RenderFormat.DOCX:
+ resolved_options = options if options is not None else DocxRenderOptions()
+ if not isinstance(resolved_options, DocxRenderOptions):
+ raise TypeError("DOCX output requires DocxRenderOptions")
+ return render_docx(
+ middle_json,
+ mode=resolved_options.mode,
+ asset_resolver=resolved_options.asset_resolver,
+ )
+
+ 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,
+ )
+
+ raise ValueError(f"Unsupported RenderFormat: {output_format}")
+
+
+__all__ = ["render"]
diff --git a/mineru/render/content_list.py b/mineru/render/content_list.py
index 467eafa8..d505a52f 100644
--- a/mineru/render/content_list.py
+++ b/mineru/render/content_list.py
@@ -6,14 +6,14 @@ from __future__ import annotations
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_content,
+from mineru.render._internal.markdown.blocks import (
+ render_single_block,
+ render_title_inline_content,
+ render_visual_annotation,
+ 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.render._internal.markdown.assets import normalize_image_source, resolve_image_source
+from mineru.render._internal.markdown.escaping import escape_standalone_marker_rule, escape_text_block_markdown_prefix
from mineru.types import (
BlockType,
ChartAnnotationBlock,
@@ -98,7 +98,7 @@ def _render_content_block(
exclude_defaults=True,
)
if isinstance(block, (DocTitleBlock, ParagraphTitleBlock)):
- content = _render_title_inline_content(block, delimiters)
+ 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):
@@ -108,14 +108,14 @@ def _render_content_block(
payload["image_source"] = image_source
return payload
if not isinstance(block, (ImageBlock, TableBlock, ChartBlock, CodeBlock)):
- payload["content"] = _render_single_block(
+ payload["content"] = render_single_block(
block,
delimiters=delimiters,
asset_base_url=asset_base_url,
)
return payload
- payload["content"] = _render_visual_body_content(
+ payload["content"] = render_visual_body_content(
block,
delimiters=delimiters,
asset_base_url=asset_base_url,
@@ -145,7 +145,7 @@ def _render_annotation_group(
):
annotations.append((position, child))
annotations.sort(key=_annotation_sort_key)
- return [_render_visual_annotation(child, delimiters) for _, child in annotations]
+ return [render_visual_annotation(child, delimiters) for _, child in annotations]
def _annotation_sort_key(
diff --git a/mineru/render/contracts.py b/mineru/render/contracts.py
new file mode 100644
index 00000000..d873aaf2
--- /dev/null
+++ b/mineru/render/contracts.py
@@ -0,0 +1,119 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""MiddleJson 多格式 renderer 共用的公共类型与调用选项。"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from enum import Enum
+from typing import Any, Callable, TypeAlias
+
+
+class RenderFormat(str, Enum):
+ """统一渲染入口支持的目标格式。"""
+
+ MARKDOWN = "markdown"
+ HTML = "html"
+ DOCX = "docx"
+ CONTENT_LIST = "content_list"
+
+
+class RenderMode(str, Enum):
+ """MiddleJson renderer 共用的默认合并视图与完整分页视图。"""
+
+ DEFAULT = "default"
+ FULL = "full"
+
+
+# 保留既有 Markdown 公共名称,同时让全部展示型 renderer 共用同一枚举类型。
+MarkdownRenderMode = RenderMode
+
+AssetResolver: TypeAlias = Callable[[str], bytes]
+
+
+def _validate_mode(mode: object) -> None:
+ """校验展示型 renderer 的公共模式参数。"""
+ if not isinstance(mode, RenderMode):
+ raise TypeError("mode must be a RenderMode value")
+
+
+def _validate_asset_base_url(asset_base_url: object) -> None:
+ """校验用于拼接相对图片路径的资源根地址。"""
+ if not isinstance(asset_base_url, str):
+ raise TypeError("asset_base_url must be a string")
+
+
+@dataclass(frozen=True, slots=True)
+class MarkdownRenderOptions:
+ """Markdown renderer 的统一入口选项。"""
+
+ mode: RenderMode = RenderMode.DEFAULT
+ asset_base_url: str = ""
+
+ def __post_init__(self) -> None:
+ """在构造时拒绝不符合严格公共契约的选项值。"""
+ _validate_mode(self.mode)
+ _validate_asset_base_url(self.asset_base_url)
+
+
+@dataclass(frozen=True, slots=True)
+class HtmlRenderOptions:
+ """HTML renderer 的统一入口选项。"""
+
+ mode: RenderMode = RenderMode.DEFAULT
+ asset_base_url: str = ""
+ standalone: bool = True
+ document_title: str | None = None
+
+ def __post_init__(self) -> None:
+ """在构造时校验 HTML 文档形态与标题选项。"""
+ _validate_mode(self.mode)
+ _validate_asset_base_url(self.asset_base_url)
+ if not isinstance(self.standalone, bool):
+ raise TypeError("standalone must be a bool")
+ if self.document_title is not None and not isinstance(self.document_title, str):
+ raise TypeError("document_title must be a string or None")
+
+
+@dataclass(frozen=True, slots=True)
+class DocxRenderOptions:
+ """DOCX renderer 的统一入口选项。"""
+
+ mode: RenderMode = RenderMode.DEFAULT
+ asset_resolver: AssetResolver | None = None
+
+ def __post_init__(self) -> None:
+ """在构造时校验分页模式与可选素材解析器。"""
+ _validate_mode(self.mode)
+ if self.asset_resolver is not None and not callable(self.asset_resolver):
+ raise TypeError("asset_resolver must be callable or None")
+
+
+@dataclass(frozen=True, slots=True)
+class ContentListRenderOptions:
+ """树形 Markdown Content List renderer 的统一入口选项。"""
+
+ asset_base_url: str = ""
+
+ def __post_init__(self) -> None:
+ """在构造时校验图片资源根地址。"""
+ _validate_asset_base_url(self.asset_base_url)
+
+
+RenderOptions: TypeAlias = (
+ MarkdownRenderOptions | HtmlRenderOptions | DocxRenderOptions | ContentListRenderOptions
+)
+RenderOutput: TypeAlias = str | bytes | dict[str, Any]
+
+
+__all__ = [
+ "AssetResolver",
+ "ContentListRenderOptions",
+ "DocxRenderOptions",
+ "HtmlRenderOptions",
+ "MarkdownRenderMode",
+ "MarkdownRenderOptions",
+ "RenderFormat",
+ "RenderMode",
+ "RenderOptions",
+ "RenderOutput",
+]
diff --git a/mineru/render/docx.py b/mineru/render/docx.py
index 06b93ee1..05ea4e01 100644
--- a/mineru/render/docx.py
+++ b/mineru/render/docx.py
@@ -20,14 +20,24 @@ from docx.text.paragraph import Paragraph
from lxml import etree
from loguru import logger
-from mineru.render.utils.docx_assets import (
- AssetResolver,
+from mineru.render._internal.common.index import strip_index_page_tail
+from mineru.render._internal.common.inline import (
+ InlineEquation,
+ InlineLink,
+ InlineNode,
+ InlineStyled,
+ InlineText,
+ parse_inline_content,
+)
+from mineru.render._internal.common.list_items import parse_list_item_marker
+from mineru.render._internal.common.planner import PlannedBlock, build_render_plan
+from mineru.render._internal.docx.assets import (
DocxAssetError,
PreparedImage,
prepare_block_image,
prepare_html_image,
)
-from mineru.render.utils.docx_inline import (
+from mineru.render._internal.docx.inline import (
BookmarkRegistry,
InlineRenderContext,
append_inline_content,
@@ -36,8 +46,8 @@ from mineru.render.utils.docx_inline import (
append_joined_inline_contents,
sanitize_xml_text,
)
-from mineru.render.utils.docx_math import DocxFormulaError, latex_to_omml, split_formula_tag
-from mineru.render.utils.docx_styles import (
+from mineru.render._internal.docx.math import DocxFormulaError, latex_to_omml, split_formula_tag
+from mineru.render._internal.docx.styles import (
AUXILIARY_STYLE,
BODY_STYLE,
CAPTION_STYLE,
@@ -48,11 +58,8 @@ from mineru.render.utils.docx_styles import (
usable_width_emu,
usable_width_twips,
)
-from mineru.render.utils.docx_table import DocxTableError, NestedTableWriter, materialize_docx_tables
-from mineru.render.utils.inline import InlineEquation, InlineLink, InlineNode, InlineStyled, InlineText, parse_inline_content
-from mineru.render.utils.index import strip_index_page_tail
-from mineru.render.utils.list_items import parse_list_item_marker
-from mineru.render.utils.logical_blocks import PlannedBlock, RenderMode, build_render_plan
+from mineru.render._internal.docx.table import DocxTableError, NestedTableWriter, materialize_docx_tables
+from mineru.render.contracts import AssetResolver, RenderMode
from mineru.types import (
PAGE_AUXILIARY_BLOCK_TYPES,
RAW_ALGORITHM,
diff --git a/mineru/render/html.py b/mineru/render/html.py
index 3fa3b260..129d327d 100644
--- a/mineru/render/html.py
+++ b/mineru/render/html.py
@@ -12,23 +12,24 @@ from urllib.parse import quote
from bs4 import BeautifulSoup
from loguru import logger
-from mineru.render.utils.html_inline import (
+from mineru.render._internal.common.index import strip_index_page_tail
+from mineru.render._internal.common.inline import inline_plain_text, parse_inline_content
+from mineru.render._internal.common.list_items import ListItem, parse_list_item_marker, reference_list_needs_bullets
+from mineru.render._internal.common.planner import PlannedBlock, build_render_plan
+from mineru.render._internal.html.inline import (
HtmlInlineResult,
render_inline_content_html,
render_inline_nodes_html,
render_joined_inline_contents_html,
render_math_html,
)
-from mineru.render.utils.html_sanitizer import (
+from mineru.render._internal.html.sanitizer import (
is_supported_html_markup,
sanitize_html_fragment,
sanitize_image_source,
)
-from mineru.render.utils.html_table import looks_like_gfm_table, render_gfm_table_html
-from mineru.render.utils.index import strip_index_page_tail
-from mineru.render.utils.inline import inline_plain_text, parse_inline_content
-from mineru.render.utils.list_items import ListItem, parse_list_item_marker, reference_list_needs_bullets
-from mineru.render.utils.logical_blocks import PlannedBlock, RenderMode, build_render_plan
+from mineru.render._internal.html.table import looks_like_gfm_table, render_gfm_table_html
+from mineru.render.contracts import RenderMode
from mineru.types import (
PAGE_AUXILIARY_BLOCK_TYPES,
RAW_ALGORITHM,
diff --git a/mineru/render/markdown.py b/mineru/render/markdown.py
index bb140e5d..0ddf7c96 100644
--- a/mineru/render/markdown.py
+++ b/mineru/render/markdown.py
@@ -3,61 +3,13 @@
from __future__ import annotations
-import html
-import re
-
from mineru.config import LatexDelimitersConfig, config
-from mineru.render.utils.assets import build_markdown_image, resolve_image_source
-from mineru.render.utils.inline import (
- render_inline_content,
- render_internal_link,
- render_joined_inline_contents,
-)
-from mineru.render.utils.index import strip_index_page_tail
-from mineru.render.utils.list_items import has_markdown_unordered_marker, reference_list_needs_bullets
-from mineru.render.utils.logical_blocks import MarkdownRenderMode, PlannedBlock, build_render_plan
-from mineru.render.utils.markdown_table import format_embedded_html, render_html_table
-from mineru.render.utils.markdown_utils import escape_standalone_marker_rule, escape_text_block_markdown_prefix
-from mineru.types import (
- RAW_ALGORITHM,
- BlockType,
- ChartAnnotationBlock,
- ChartBlock,
- ChartBodyBlock,
- CodeAnnotationBlock,
- CodeBlock,
- CodeBodyBlock,
- DocTitleBlock,
- EquationBlock,
- ImageAnnotationBlock,
- ImageBlock,
- ImageBodyBlock,
- IndexBlock,
- ListBlock,
- MiddleJson,
- PageAuxTextBlock,
- PageBlock,
- ParagraphTitleBlock,
- RefTextBlock,
- TableAnnotationBlock,
- TableBlock,
- TableBodyBlock,
- TextBlock,
-)
+from mineru.render.contracts import MarkdownRenderMode
+from mineru.render._internal.common.planner import PlannedBlock, build_render_plan
+from mineru.render._internal.markdown.blocks import render_planned_block
+from mineru.types import PAGE_AUXILIARY_BLOCK_TYPES, MiddleJson
-_DEFAULT_HIDDEN_TYPES = {
- BlockType.HEADER,
- BlockType.FOOTER,
- BlockType.PAGE_NUMBER,
- BlockType.ASIDE_TEXT,
- BlockType.PAGE_FOOTNOTE,
-}
_PAGE_SEPARATOR = "\n\n---\n\n"
-_ALGORITHM_TOKEN_RE = re.compile(
- r"<eq>(?P<latex>.*?)</eq>|(?P<script_tag></?(?:sub|sup)>)",
- re.IGNORECASE | re.DOTALL,
-)
-_VALID_CODE_LANGUAGE_RE = re.compile(r"[A-Za-z0-9_.+#-]+")
def render_markdown(
@@ -100,456 +52,12 @@ def _render_page(
for planned in planned_blocks:
if planned.removed:
continue
- if mode is MarkdownRenderMode.DEFAULT and planned.block.type in _DEFAULT_HIDDEN_TYPES:
+ if mode is MarkdownRenderMode.DEFAULT and planned.block.type in PAGE_AUXILIARY_BLOCK_TYPES:
continue
- text = _render_planned_block(planned, delimiters=delimiters, asset_base_url=asset_base_url)
+ text = render_planned_block(planned, delimiters=delimiters, asset_base_url=asset_base_url)
if text and text.strip():
rendered.append(text.strip("\n"))
return "\n\n".join(rendered)
-def _render_planned_block(
- planned: PlannedBlock,
- *,
- delimiters: LatexDelimitersConfig,
- asset_base_url: str,
-) -> str:
- """按具体 Pydantic block 类型分发 Markdown 渲染。"""
- block = planned.block
- if isinstance(block, TextBlock):
- content = render_joined_inline_contents(planned.text_contents or [block.content], delimiters)
- return escape_standalone_marker_rule(escape_text_block_markdown_prefix(content))
- if isinstance(block, RefTextBlock):
- content = render_joined_inline_contents(planned.text_contents or [block.content], delimiters)
- return escape_standalone_marker_rule(content)
- if isinstance(block, (DocTitleBlock, ParagraphTitleBlock)):
- return _render_title(block, delimiters)
- if isinstance(block, PageAuxTextBlock):
- content = escape_text_block_markdown_prefix(render_inline_content(block.content, delimiters))
- return escape_standalone_marker_rule(content)
- if isinstance(block, EquationBlock):
- return _render_equation(block, delimiters, asset_base_url)
- if isinstance(block, ListBlock):
- return _render_list(block, delimiters)
- if isinstance(block, IndexBlock):
- return _render_index(block, delimiters)
- if isinstance(block, ImageBlock):
- return _render_image_block(block, delimiters, asset_base_url)
- if isinstance(block, TableBlock):
- return _render_table_block(block, delimiters, asset_base_url)
- if isinstance(block, ChartBlock):
- return _render_chart_block(block, delimiters, asset_base_url)
- if isinstance(block, CodeBlock):
- return _render_code_block(block, delimiters)
- 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,
-) -> str:
- """渲染带可选 HTML anchor 的 Markdown 标题。"""
- level = min(max(block.level, 1), 6)
- 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,
- asset_base_url: str,
-) -> str:
- """优先渲染行间 LaTeX,空公式内容回退到公式图片。"""
- latex = block.content.strip()
- if latex:
- return f"{delimiters.display.left}\n{latex}\n{delimiters.display.right}"
- source = resolve_image_source(block, asset_base_url)
- return build_markdown_image(source) if source else ""
-
-
-def _render_list(block: ListBlock, delimiters: LatexDelimitersConfig, depth: int = 0) -> str:
- """递归渲染列表,并给多数条目无数字前缀的参考文献补无序标记。"""
- add_ref_bullets = reference_list_needs_bullets(block)
- lines: list[str] = []
- for child in block.content:
- if isinstance(child, ListBlock):
- nested = _render_list(child, delimiters, depth + 1)
- if nested:
- lines.extend(nested.splitlines())
- continue
- item = render_inline_content(child.content, delimiters)
- if not item:
- continue
- item = escape_standalone_marker_rule(item)
- indent = " " * depth
- item_lines = item.splitlines() or [item]
- if add_ref_bullets and not has_markdown_unordered_marker(item):
- lines.append(f"{indent}- {item_lines[0]}")
- lines.extend(f"{indent} {line}" for line in item_lines[1:])
- else:
- lines.extend(f"{indent}{line}" for line in item_lines)
- return "\n".join(lines)
-
-def _render_index(block: IndexBlock, delimiters: LatexDelimitersConfig, depth: int = 0) -> str:
- """递归渲染目录列表,并给标题叶子添加内部 anchor 链接。"""
- lines: list[str] = []
- for child in block.content:
- if isinstance(child, IndexBlock):
- nested = _render_index(child, delimiters, depth + 1)
- if nested:
- lines.extend(nested.splitlines())
- continue
- content = strip_index_page_tail(child.content)
- label = render_inline_content(content, delimiters).strip()
- if not label:
- continue
- if isinstance(child, (DocTitleBlock, ParagraphTitleBlock)) and child.anchor:
- label = render_internal_link(label, child.anchor)
- lines.append(f"{' ' * depth}- {label}")
- return "\n".join(lines)
-
-def _render_image_block(
- block: ImageBlock,
- delimiters: LatexDelimitersConfig,
- asset_base_url: str,
-) -> str:
- """按原始子块顺序渲染图片主体及说明文本。"""
- parts: list[str] = []
- for child in block.content:
- if isinstance(child, ImageBodyBlock):
- body = _render_visual_body_child(
- block,
- child,
- delimiters=delimiters,
- asset_base_url=asset_base_url,
- )
- elif isinstance(child, ImageAnnotationBlock):
- body = _render_visual_annotation(child, delimiters)
- else:
- raise TypeError(f"Unsupported image child: {type(child).__name__}")
- if body:
- parts.append(body)
- return _join_visual_parts(parts)
-
-
-def _render_chart_block(
- block: ChartBlock,
- delimiters: LatexDelimitersConfig,
- asset_base_url: str,
-) -> str:
- """按原始子块顺序渲染图表图片、结构内容和说明文本。"""
- parts: list[str] = []
- for child in block.content:
- if isinstance(child, ChartBodyBlock):
- body = _render_visual_body_child(
- block,
- child,
- delimiters=delimiters,
- asset_base_url=asset_base_url,
- )
- elif isinstance(child, ChartAnnotationBlock):
- body = _render_visual_annotation(child, delimiters)
- else:
- raise TypeError(f"Unsupported chart child: {type(child).__name__}")
- if body:
- parts.append(body)
- return _join_visual_parts(parts)
-
-
-def _render_media_body(
- block: ImageBodyBlock,
- *,
- summary: str,
- delimiters: LatexDelimitersConfig,
- asset_base_url: str,
-) -> str:
- """渲染图片载荷,并将识别内容放入折叠详情。"""
- source = resolve_image_source(block, asset_base_url)
- rendered_content = _render_media_content(block, delimiters, asset_base_url)
- if source:
- parts = [build_markdown_image(source)]
- 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)
-
-
-def _render_chart_body(
- block: ChartBodyBlock,
- *,
- summary: str,
- delimiters: LatexDelimitersConfig,
- asset_base_url: str,
-) -> str:
- """渲染 chart 图片,并统一转换其 HTML 表格内容。"""
- source = resolve_image_source(block, asset_base_url)
- rendered_content = _render_chart_content(block.content, delimiters, asset_base_url)
- if source:
- parts = [build_markdown_image(source)]
- 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_chart_content(
- content: str,
- delimiters: LatexDelimitersConfig,
- asset_base_url: str,
-) -> str:
- """把 chart 内容中的简单 HTML 表格转为 GFM,其他内容保持原表示。"""
- normalized = content.strip()
- if not normalized:
- return ""
- html_table = render_html_table(
- normalized,
- asset_base_url=asset_base_url,
- delimiters=delimiters,
- )
- if html_table is not None:
- return html_table
- return format_embedded_html(normalized, asset_base_url=asset_base_url, delimiters=delimiters)
-
-
-def _render_details(content: str, summary: str) -> str:
- """构造保留已渲染视觉内容的折叠 HTML 详情块。"""
- safe_summary = html.escape(summary, quote=False)
- return f"<details>\n<summary>{safe_summary}</summary>\n\n{content.strip()}\n</details>"
-
-
-def _render_table_block(
- block: TableBlock,
- delimiters: LatexDelimitersConfig,
- asset_base_url: str,
-) -> str:
- """按原始子块顺序渲染表格主体及说明文本。"""
- parts: list[str] = []
- for child in block.content:
- if isinstance(child, TableBodyBlock):
- body = _render_visual_body_child(
- block,
- child,
- delimiters=delimiters,
- asset_base_url=asset_base_url,
- )
- elif isinstance(child, TableAnnotationBlock):
- body = _render_visual_annotation(child, delimiters)
- else:
- raise TypeError(f"Unsupported table child: {type(child).__name__}")
- if body:
- parts.append(body)
- return _join_visual_parts(parts)
-
-
-def _render_table_body(
- block: TableBodyBlock,
- delimiters: LatexDelimitersConfig,
- asset_base_url: str,
-) -> str:
- """按 HTML、空间投影文本、图片的优先级渲染表格主体。"""
- 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] = []
- for child in block.content:
- if isinstance(child, CodeBodyBlock):
- body = _render_visual_body_child(
- block,
- child,
- delimiters=delimiters,
- asset_base_url="",
- )
- elif isinstance(child, CodeAnnotationBlock):
- body = _render_visual_annotation(child, delimiters)
- else:
- raise TypeError(f"Unsupported code child: {type(child).__name__}")
- if body:
- parts.append(body)
- return _join_visual_parts(parts)
-
-
-def _render_visual_body_content(
- block: ImageBlock | TableBlock | ChartBlock | CodeBlock,
- *,
- delimiters: LatexDelimitersConfig,
- asset_base_url: str,
-) -> str:
- """查找视觉父块唯一 body,并只渲染可结构化消费的语义内容。"""
- for child in block.content:
- 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}")
-
-
-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()
- if not normalized or _VALID_CODE_LANGUAGE_RE.fullmatch(normalized) is None:
- return "txt"
- return normalized
-
-
-def _render_fenced_content(content: str, language: str | None = None) -> str:
- """使用长于正文反引号游程的围栏包裹原始内容。"""
- longest = max((len(match.group(0)) for match in re.finditer(r"`+", content)), default=0)
- fence = "`" * max(3, longest + 1)
- opening = f"{fence}{language or ''}"
- closing_prefix = "" if content.endswith("\n") else "\n"
- return f"{opening}\n{content}{closing_prefix}{fence}"
-
-
-def _render_algorithm_html(content: str, delimiters: LatexDelimitersConfig) -> str:
- """参考 dev 实现渲染保留空白、上下标和行内公式的算法 HTML。"""
- if not content.strip():
- return ""
- parts: list[str] = []
- cursor = 0
- previous_was_equation = False
- for match in _ALGORITHM_TOKEN_RE.finditer(content):
- plain = content[cursor : match.start()]
- if plain:
- parts.append(plain)
- previous_was_equation = False
- script_tag = match.group("script_tag")
- if script_tag is not None:
- parts.append(script_tag.lower())
- previous_was_equation = False
- cursor = match.end()
- continue
- latex = html.unescape(match.group("latex")).strip()
- if latex:
- if previous_was_equation and parts and not parts[-1].endswith((" ", "\n", "\t")):
- parts.append(" ")
- parts.append(f"{delimiters.inline.left}{latex}{delimiters.inline.right}")
- previous_was_equation = True
- cursor = match.end()
- parts.append(content[cursor:])
- body = "".join(parts)
- 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:
- """使用安全空行连接同一视觉父块中的有序子块。"""
- return "\n\n".join(part.strip("\n") for part in parts if part and part.strip())
-
-
__all__ = ["MarkdownRenderMode", "render_markdown"]
diff --git a/mineru/render/utils/__init__.py b/mineru/render/utils/__init__.py
deleted file mode 100644
index 1e17167c..00000000
--- a/mineru/render/utils/__init__.py
+++ /dev/null
@@ -1 +0,0 @@
-# Copyright (c) Opendatalab. All rights reserved.
diff --git a/tests/unittest/test_docx_assets.py b/tests/unittest/test_docx_assets.py
index 20e1f60f..823fbe2a 100644
--- a/tests/unittest/test_docx_assets.py
+++ b/tests/unittest/test_docx_assets.py
@@ -8,7 +8,7 @@ from pathlib import Path
from PIL import Image, features
import pytest
-from mineru.render.utils.docx_assets import (
+from mineru.render._internal.docx.assets import (
DocxAssetError,
PreparedImage,
prepare_block_image,
diff --git a/tests/unittest/test_docx_math.py b/tests/unittest/test_docx_math.py
index 8308fabd..1d97c5f1 100644
--- a/tests/unittest/test_docx_math.py
+++ b/tests/unittest/test_docx_math.py
@@ -3,7 +3,7 @@ from __future__ import annotations
import pytest
from lxml import etree
-from mineru.render.utils.docx_math import DocxFormulaError, latex_to_omml, split_formula_tag
+from mineru.render._internal.docx.math import DocxFormulaError, latex_to_omml, split_formula_tag
_OFFICE_MATH_NAMESPACE = "http://schemas.openxmlformats.org/officeDocument/2006/math"
diff --git a/tests/unittest/test_docx_table.py b/tests/unittest/test_docx_table.py
index ff436980..c021bdfa 100644
--- a/tests/unittest/test_docx_table.py
+++ b/tests/unittest/test_docx_table.py
@@ -8,7 +8,7 @@ from docx import Document
from docx.oxml.ns import qn
from docx.table import _Cell
-from mineru.render.utils.docx_table import (
+from mineru.render._internal.docx.table import (
DocxTableError,
NestedTableWriter,
materialize_docx_table,
diff --git a/tests/unittest/test_html_security.py b/tests/unittest/test_html_security.py
index f24829cb..9876460f 100644
--- a/tests/unittest/test_html_security.py
+++ b/tests/unittest/test_html_security.py
@@ -3,7 +3,7 @@ from __future__ import annotations
import pytest
from bs4 import BeautifulSoup, Tag
-from mineru.render.utils.html_sanitizer import (
+from mineru.render._internal.html.sanitizer import (
is_supported_html_markup,
sanitize_html_fragment,
sanitize_image_source,
@@ -255,7 +255,7 @@ def test_svg_data_uri_is_rejected_before_strict_xml_parsing(monkeypatch: pytest.
"""若被调用即证明 SVG 快速拒绝失效。"""
raise AssertionError("SVG parser must not run")
- monkeypatch.setattr("mineru.render.utils.html_sanitizer.parse_image_data_uri_strict", _unexpected_parse)
+ monkeypatch.setattr("mineru.render._internal.html.sanitizer.parse_image_data_uri_strict", _unexpected_parse)
assert sanitize_image_source("data:image/svg+xml;base64,PHN2Zz4=") is None
diff --git a/tests/unittest/test_render_api.py b/tests/unittest/test_render_api.py
new file mode 100644
index 00000000..322651ff
--- /dev/null
+++ b/tests/unittest/test_render_api.py
@@ -0,0 +1,200 @@
+from __future__ import annotations
+
+from copy import deepcopy
+from io import BytesIO
+
+from docx import Document
+from PIL import Image
+import pytest
+
+from mineru.render import (
+ ContentListRenderOptions,
+ DocxRenderError,
+ DocxRenderOptions,
+ HtmlRenderOptions,
+ MarkdownRenderMode,
+ MarkdownRenderOptions,
+ RenderFormat,
+ RenderMode,
+ render,
+)
+from mineru.types import ImageBlock, ImageBodyBlock, MiddleJson, PageBlock, PageInfo, TextBlock
+
+
+def _middle(*pages: PageInfo) -> MiddleJson:
+ """构造无需 PDF bbox 的最小严格 MiddleJson。"""
+ return MiddleJson(
+ pages=list(pages),
+ file_suffix="docx",
+ effort="flash",
+ parse_mode="txt",
+ mineru_version="test",
+ )
+
+
+def _page(page_idx: int, *blocks: PageBlock) -> PageInfo:
+ """按调用方顺序构造一页严格 MiddleJson 内容。"""
+ return PageInfo(page_idx=page_idx, blocks=list(blocks))
+
+
+def _png_bytes() -> bytes:
+ """生成可被 Pillow 与 python-docx 完整读取的 PNG。"""
+ output = BytesIO()
+ Image.new("RGB", (2, 2), (30, 60, 90)).save(output, format="PNG")
+ return output.getvalue()
+
+
+def test_unified_render_dispatches_all_native_output_types_without_mutation() -> None:
+ """验证统一入口默认分发四种原生结果且不修改输入。"""
+ middle = _middle(_page(0, TextBlock(type="text", index=0, content="hello")))
+ original = deepcopy(middle)
+
+ markdown = render(middle, RenderFormat.MARKDOWN)
+ html = render(middle, RenderFormat.HTML)
+ docx = render(middle, RenderFormat.DOCX)
+ content_list = render(middle, RenderFormat.CONTENT_LIST)
+
+ assert markdown == "hello"
+ assert isinstance(html, str) and "<html" in html and "hello" in html
+ assert isinstance(docx, bytes) and docx.startswith(b"PK\x03\x04")
+ assert Document(BytesIO(docx)).paragraphs[0].text == "hello"
+ assert content_list["pages"][0]["blocks"][0]["content"] == "hello"
+ assert middle == original
+
+
+def test_unified_render_forwards_format_specific_options() -> None:
+ """验证分页模式、HTML 文档形态和 Content List 资源地址分别透传。"""
+ middle = _middle(
+ _page(0, TextBlock(type="text", index=0, content="first-")),
+ _page(1, TextBlock(type="text", index=0, content="second", continues_prev=True)),
+ )
+ image_middle = _middle(
+ _page(
+ 0,
+ ImageBlock(
+ type="image",
+ index=0,
+ content=[
+ ImageBodyBlock(
+ type="image_body",
+ index=0,
+ content="",
+ image_path="images/a b.png",
+ )
+ ],
+ ),
+ )
+ )
+
+ markdown = render(
+ middle,
+ RenderFormat.MARKDOWN,
+ options=MarkdownRenderOptions(mode=RenderMode.FULL),
+ )
+ html = render(
+ middle,
+ RenderFormat.HTML,
+ options=HtmlRenderOptions(mode=RenderMode.FULL, standalone=False),
+ )
+ content_list = render(
+ image_middle,
+ RenderFormat.CONTENT_LIST,
+ options=ContentListRenderOptions(asset_base_url="https://cdn.example/doc"),
+ )
+ image_markdown = render(
+ image_middle,
+ RenderFormat.MARKDOWN,
+ options=MarkdownRenderOptions(asset_base_url="https://cdn.example/doc"),
+ )
+ html_document = render(
+ image_middle,
+ RenderFormat.HTML,
+ options=HtmlRenderOptions(
+ asset_base_url="https://cdn.example/doc",
+ document_title="Unified Render",
+ ),
+ )
+ original_tree = render(middle, RenderFormat.CONTENT_LIST)
+
+ assert "\n\n---\n\n" in markdown
+ assert html.startswith('<article class="crossnote markdown-preview mineru-document')
+ assert "<!doctype html>" not in html
+ assert content_list["pages"][0]["blocks"][0]["image_source"] == (
+ "https://cdn.example/doc/images/a%20b.png"
+ )
+ assert "https://cdn.example/doc/images/a%20b.png" in image_markdown
+ assert "<title>Unified Render</title>" in html_document
+ assert 'src="https://cdn.example/doc/images/a%20b.png"' in html_document
+ assert [page["blocks"][0]["content"] for page in original_tree["pages"]] == ["first-", "second"]
+ assert original_tree["pages"][1]["blocks"][0]["continues_prev"] is True
+
+
+def test_unified_docx_uses_typed_asset_resolver_and_propagates_public_errors() -> None:
+ """验证 DOCX Options 传递素材解析器,并保留带定位的公共异常。"""
+ requested_paths: list[str] = []
+
+ def resolve_asset(relative_path: str) -> bytes:
+ """记录统一入口请求的相对路径并返回有效 PNG。"""
+ requested_paths.append(relative_path)
+ return _png_bytes()
+
+ middle = _middle(
+ _page(
+ 7,
+ ImageBlock(
+ type="image",
+ index=3,
+ content=[
+ ImageBodyBlock(
+ type="image_body",
+ index=3,
+ content="description",
+ image_path="images/picture.png",
+ )
+ ],
+ ),
+ )
+ )
+
+ docx = render(
+ middle,
+ RenderFormat.DOCX,
+ options=DocxRenderOptions(asset_resolver=resolve_asset),
+ )
+
+ assert requested_paths == ["images/picture.png"]
+ assert len(Document(BytesIO(docx)).inline_shapes) == 1
+ with pytest.raises(DocxRenderError) as exc_info:
+ render(middle, RenderFormat.DOCX)
+ assert (exc_info.value.page_idx, exc_info.value.block_index, exc_info.value.block_type) == (7, 3, "image")
+
+
+def test_unified_render_rejects_legacy_format_and_mismatched_options() -> None:
+ """验证统一入口拒绝旧字典、字符串格式和跨格式 Options。"""
+ middle = _middle(_page(0))
+
+ with pytest.raises(TypeError, match="MiddleJson"):
+ render(middle.to_dict(), RenderFormat.MARKDOWN) # type: ignore[arg-type]
+ with pytest.raises(TypeError, match="RenderFormat"):
+ render(middle, "markdown") # type: ignore[arg-type]
+ with pytest.raises(TypeError, match="MarkdownRenderOptions"):
+ render(middle, RenderFormat.MARKDOWN, options=HtmlRenderOptions()) # type: ignore[arg-type]
+ with pytest.raises(TypeError, match="ContentListRenderOptions"):
+ render(middle, RenderFormat.CONTENT_LIST, options=DocxRenderOptions()) # type: ignore[arg-type]
+
+
+def test_public_options_validate_fields_and_preserve_mode_alias() -> None:
+ """验证 Options 构造期类型检查和既有 Markdown 模式别名。"""
+ assert MarkdownRenderMode is RenderMode
+ assert [item.value for item in RenderFormat] == ["markdown", "html", "docx", "content_list"]
+
+ with pytest.raises(TypeError, match="RenderMode"):
+ MarkdownRenderOptions(mode="default") # 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="standalone"):
+ HtmlRenderOptions(standalone=1) # type: ignore[arg-type]
+ with pytest.raises(TypeError, match="document_title"):
+ HtmlRenderOptions(document_title=1) # type: ignore[arg-type]
+ with pytest.raises(TypeError, match="asset_resolver"):
+ DocxRenderOptions(asset_resolver="images") # type: ignore[arg-type]
diff --git a/tests/unittest/test_render_html_table.py b/tests/unittest/test_render_html_table.py
index 86d57109..d80e862b 100644
--- a/tests/unittest/test_render_html_table.py
+++ b/tests/unittest/test_render_html_table.py
@@ -2,7 +2,7 @@ import markdown
from bs4 import BeautifulSoup
from mineru.config import LatexDelimitersConfig
-from mineru.render.utils.markdown_table import format_embedded_html, render_html_table
+from mineru.render._internal.markdown.table import format_embedded_html, render_html_table
DELIMITERS = LatexDelimitersConfig()
diff --git a/tests/unittest/test_render_list_index_utils.py b/tests/unittest/test_render_list_index_utils.py
index 5e1598ef..4295771f 100644
--- a/tests/unittest/test_render_list_index_utils.py
+++ b/tests/unittest/test_render_list_index_utils.py
@@ -2,8 +2,8 @@ from __future__ import annotations
import pytest
-from mineru.render.utils.index import looks_like_index_page_token, strip_index_page_tail
-from mineru.render.utils.list_items import (
+from mineru.render._internal.common.index import looks_like_index_page_token, strip_index_page_tail
+from mineru.render._internal.common.list_items import (
has_markdown_unordered_marker,
parse_list_item_marker,
reference_list_needs_bullets,