Skip to content

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

feat: enhance Markdown rendering with new inline parsing and HTML table support

myhlolie78fa9fae098
diff --git a/docs/next/config.md b/docs/next/config.md
index ee64aceb..5663801c 100644
--- a/docs/next/config.md
+++ b/docs/next/config.md
@@ -22,6 +22,22 @@ MinerU 有两类配置:
- 默认 DB、日志和 UDS socket 从 `MINERU_HOME` 派生;默认 `data_dir` 是 `$MINERU_HOME/doclib`,其下包含 `parsed/` 和 `temp/`。
- `MINERU_CONFIG` 仍可显式指定配置文件路径;`MINERU_HOME` 只影响默认 home 和默认配置文件位置。
+Markdown render 同样读取启动前 `config.yaml`,当前支持以下配置:
+
+```yaml
+render:
+ latex_delimiters:
+ display:
+ left: "$$"
+ right: "$$"
+ inline:
+ left: "$"
+ right: "$"
+```
+
+四个 delimiter 必须为非空字符串。缺省值如上;环境变量可按现有字段路径规则覆盖,
+例如 `MINERU_RENDER_LATEX_DELIMITERS_INLINE_LEFT`。
+
配置必须服务两个产品原则:
- 隐私优先:任何配置都不能导致静默上传文档。
diff --git a/docs/next/middle-json/current-medium.md b/docs/next/middle-json/current-medium.md
index f929da58..9f5c28a1 100644
--- a/docs/next/middle-json/current-medium.md
+++ b/docs/next/middle-json/current-medium.md
@@ -123,11 +123,12 @@ TextBlock | RefTextBlock | ListBlock
`IndexBlock.content` 同样递归:
```text
-TextBlock | IndexBlock
+TextBlock | DocTitleBlock | ParagraphTitleBlock | IndexBlock
```
-Office 目录规范化会递归移除普通 TextBlock 的 `anchor`。递归结构始终序列化到
-`content`,不产生通用 `blocks` 字段。
+Office 目录规范化会按 document-wide anchor 把匹配到真实目标标题的目录叶子
+转换为对应 TitleBlock,并继承目标 level;未匹配 anchor 的叶子降级为普通
+TextBlock。递归结构始终序列化到 `content`,不产生通用 `blocks` 字段。
## 视觉容器
diff --git a/docs/next/middle-json/rendering.md b/docs/next/middle-json/rendering.md
index 70aa6374..445a06a6 100644
--- a/docs/next/middle-json/rendering.md
+++ b/docs/next/middle-json/rendering.md
@@ -1,143 +1,82 @@
# Rendering Contract
-状态: Draft
+状态: Markdown v1
读者: render 开发者、backend 开发者、SDK 开发者
-范围: Markdown / Content List / Structured Content 对 Middle JSON 的消费约束和收敛计划
-来源: 由根目录旧 Middle JSON 底稿迁移整理而来
+范围: 严格 MiddleJson 到 Markdown 的消费契约
-## 当前状态
-
-当前已有统一入口:
-
-```python
-from mineru.render import render_markdown, render_content_list, render_structured_content
-```
-
-`ParseResult` 也通过这些入口生成输出:
-
-- `ParseResult.markdown()`
-- `ParseResult.content_list()`
-- `ParseResult.structured_content()`
-
-`structured_content` 是当前代码和 NEXT 版公开格式名,命名决策见 [ADR-0001](../decisions/0001-json-output-formats.md)。
-
-这说明底稿中“三套 union_make 完全割裂”的问题已经部分解决。
-
-## 仍未完全收敛
-
-统一入口内部仍存在 backend dispatch:
-
-| 输出 | 当前状态 |
-|------|----------|
-| Markdown | 有统一 facade;Office 仍走 office-specific markdown。 |
-| Content List v1 | 有统一 facade;Office 仍走 office-specific converter。 |
-| Structured Content | PDF 后端共用 `render/structured_content.py`;Office 仍走 office-specific converter。 |
-
-此外,render 当前通过 `PageInfo._backend` 判断 backend。这是临时实现,不应成为长期 schema。
-
-## Render 输入契约
-
-render 函数应接受:
+## 公共入口
```python
-list[PageInfo]
-```
-
-或 canonical envelope 经解析后的:
+from mineru.render import MarkdownRenderMode, render_markdown
-```python
-payload["pages"] -> list[PageInfo]
+markdown = render_markdown(
+ middle_json,
+ mode=MarkdownRenderMode.DEFAULT,
+ asset_base_url="",
+)
```
-render 不应直接依赖:
-
-- 原始模型输出。
-- doclib 数据库。
-- 文件系统路径,除非渲染图片链接需要 `img_bucket_path`。
-- 私有 `_meta` 之外的 backend-specific hidden state。
-
-## Block 消费规则
-
-| Block type | Markdown | Content List |
-|------------|----------|--------------|
-| `text` | 普通段落。 | text item。 |
-| `title` | heading,使用 `level`。 | text item with level。 |
-| `list` | 列表。 | list item。 |
-| `index` | 目录。 | index/list item。 |
-| `equation` | display math。 | equation item。 |
-| `image` | image markdown,包含 caption/footnote。 | image item。 |
-| `table` | HTML 或 table image。 | table item。 |
-| `chart` | chart image/content。 | chart item。 |
-| `code` | fenced code block。 | code item。 |
-| `header/footer/page_number` | 默认可忽略或作为 discarded。 | 可进入 content list,但需标注类型。 |
-
-## Unknown BBox
-
-render 不应因为 `bbox=EMPTY_BBOX` 失败。Content List 若输出 bbox,应遵循:
-
-- 已知 bbox: 输出 bbox。
-- unknown bbox: 省略 bbox 或输出 null。
-- 不应把 `(0,0,0,0)` 当成真实 bbox 给 UI 画框。
-
-## `_backend` 迁移
+`render_markdown()` 只接受 `MiddleJson`,不兼容旧 dict、`list[PageInfo]`、
+backend 参数或旧 `Line/Span` renderer。渲染过程基于深拷贝,不修改输入对象,
+也不负责把图片写到文件系统。
-当前:
+图片优先使用 `image_path`,缺失时使用 `image_base64` data URI。
+`asset_base_url` 只给相对 `image_path` 和 HTML 内相对 `img src` 添加前缀。
-```python
-backend = pages[0]._backend
-```
-
-目标:
-
-```python
-backend = envelope["_meta"]["backend"]
-```
+## 展示模式
-迁移策略:
+`MarkdownRenderMode.DEFAULT`:
-1. render facade 新增可选 `backend` 参数。
-2. 如果传入 envelope,则从 `_meta.backend` 读取。
-3. 如果只传 pages,短期继续 fallback 到 `PageInfo._backend`。
-4. validator 提醒 `_backend` 是 legacy/internal。
-5. backend-specific 逻辑收敛后,render 不再需要 backend 判断。
+- 隐藏 `header/footer/page_number/aside_text/page_footnote`。
+- 合并页内和跨页 `text.continues_prev`。
+- 只合并跨页 `table.continues_prev`。
+- 页面之间不输出分割线。
-## Structured Content 收敛
+`MarkdownRenderMode.FULL`:
-P0:
+- 展示全部顶层 block。
+- 只合并页内 `text.continues_prev`。
+- 不合并跨页 text/table。
+- 每两个相邻 `PageInfo` 之间输出 `---`,空白页边界同样保留。
-- 明确 Structured Content 的目标 schema。
-- 确保所有 backend 输出都能生成 structured_content。
-- 保留当前 Office dispatch,先补 validator。
+text 合并允许跨越任意其他 block,后一个 text 的内容被吸收到前一个 text,
+后块不再在原位置输出。table 只接受跨页合并;失败时保留两张原表。
-P1:
+## Block 规则
-- PDF 已抽出通用 block-to-structured-content 映射。
-- 将 Office 特殊逻辑逐步变成 type-specific helper,而不是 backend-specific module。
+- `text/ref_text`: 解析行内公式、样式和超链接;普通 text 转义可能误触发的 Markdown block 前缀。
+- `doc_title/paragraph_title`: 使用全局 `level`,Markdown 标题最多六级;anchor 输出为 HTML id。
+- `list`: 递归缩进,直接使用 content 已内化的有序或无序前缀。
+- `index`: 递归输出 GFM 列表;标题叶子使用 anchor 生成内部链接,不当作 heading 输出。
+- `equation`: content 非空时输出行间 LaTeX,空 content 回退图片。
+- `image/chart`: 图片优先,识别内容放入折叠 details;无图片时输出已有 HTML/GFM 内容。
+- `table`: 简单单层 HTML 转 GFM;合并单元格或不可无损结构保留 HTML;空间投影文本使用动态 fenced block;空 content 回退图片。
+- `code`: 使用 `guess_lang` 和动态 fenced block。
+- `algorithm`: 使用等宽、`white-space: pre-wrap` 的 HTML div,只把 `<eq>` 转为行内公式。
-P2:
+视觉父块严格按 `content` 原顺序渲染,body、重复 caption 和 footnote 不重新排序。
-- 删除 backend-specific structured_content converter。
-- render 只依赖 block type,不依赖 backend。
+## 行内语义
-## Agent Marker
+行内 parser 只解释白名单标签,包括 `<eq>`、`<text style>`、
+`<hyperlink>/<url>`、`<sup>/<sub>`。未知或损坏标签作为普通文本转义保留。
+普通字体样式使用 Markdown;underline、emphasis、上下标和复杂组合使用安全 HTML。
-为了 Agent 引用,Markdown 可以支持可选 locator marker:
+LaTeX 定界符来自 `$MINERU_HOME/config.yaml`:
-```markdown
-<!-- mineru:locator doc:ab12cd3/tier:medium/page:3/block:12 -->
-正文内容
+```yaml
+render:
+ latex_delimiters:
+ display:
+ left: "$$"
+ right: "$$"
+ inline:
+ left: "$"
+ right: "$"
```
-要求:
-
-- 默认不输出,避免影响普通用户。
-- SDK/Agent 可显式开启。
-- marker 中不得包含本地文件路径或 filename。
-
-## 验收
+## Index anchor
-- `render_markdown()` 可消费 migrated canonical envelope 的 pages。
-- `render_content_list()` 不依赖旧 `pdf_info`。
-- Office unknown bbox 不导致 content list 坐标错误。
-- 所有 render 输出可以带可选 Agent locator。
-- 逐步减少 backend-specific dispatch。
+Office model-list 在对象化前按 document-wide anchor 查找真实目标标题。匹配成功的
+目录 text 叶子改成相同的 `doc_title/paragraph_title` 类型与 level,同时保留目录
+显示文本;未匹配 anchor 降级为普通 TextBlock。已有旧 MiddleJson 不补造已丢失的 anchor。
diff --git a/mineru/backend/postprocess/lists.py b/mineru/backend/postprocess/lists.py
index 9f424006..64d3b681 100644
--- a/mineru/backend/postprocess/lists.py
+++ b/mineru/backend/postprocess/lists.py
@@ -50,6 +50,51 @@ def fix_office_paragraph_titles(model_list: list[list[dict[str, Any]]]) -> None:
_clear_deeper_title_counters(counters, numbering_depth)
+def fix_office_index_title_blocks(model_list: list[list[dict[str, Any]]]) -> None:
+ """按目标标题 anchor 将 Office 目录文本叶子转换为对应标题类型。"""
+ title_by_anchor: dict[str, tuple[str, int]] = {}
+ for page_model_list in model_list:
+ for block in page_model_list:
+ if block.get("type") not in {BlockType.DOC_TITLE, BlockType.PARAGRAPH_TITLE}:
+ continue
+ anchor = block.get("anchor")
+ level = block.get("level")
+ if not isinstance(anchor, str) or not anchor.strip() or type(level) is not int:
+ continue
+ title_by_anchor.setdefault(anchor.strip(), (block["type"], level))
+
+ for page_model_list in model_list:
+ for block in page_model_list:
+ if block.get("type") == BlockType.INDEX:
+ _rewrite_office_index_title_leaves(block, title_by_anchor)
+
+
+def _rewrite_office_index_title_leaves(
+ index_block: dict[str, Any],
+ title_by_anchor: dict[str, tuple[str, int]],
+) -> None:
+ """递归改写目录叶子;未匹配 anchor 时降级为不带 anchor 的普通文本。"""
+ content = index_block.get("content")
+ if not isinstance(content, list):
+ return
+ for child in content:
+ if not isinstance(child, dict):
+ continue
+ if child.get("type") == BlockType.INDEX:
+ _rewrite_office_index_title_leaves(child, title_by_anchor)
+ continue
+ if child.get("type") != BlockType.TEXT:
+ continue
+ anchor = child.get("anchor")
+ normalized_anchor = anchor.strip() if isinstance(anchor, str) else ""
+ target = title_by_anchor.get(normalized_anchor)
+ if target is None:
+ child.pop("anchor", None)
+ continue
+ child["type"], child["level"] = target
+ child["anchor"] = normalized_anchor
+
+
def fix_pdf_list_blocks(
list_blocks: list[dict[str, Any]],
text_blocks: list[dict[str, Any]],
@@ -94,13 +139,11 @@ def fix_pdf_index_blocks(index_blocks: list[dict[str, Any]]) -> list[dict[str, A
def fix_office_index_blocks(index_blocks: list[dict[str, Any]]) -> list[dict[str, Any]]:
- """递归移除 Office 目录私有字段,并禁止普通 text 子块携带 anchor。"""
+ """递归移除 Office 目录层级私有字段,保留已规范化的标题叶子。"""
pending_blocks = list(index_blocks)
while pending_blocks:
block = pending_blocks.pop()
block.pop("ilevel", None)
- if block.get("type") == BlockType.TEXT:
- block.pop("anchor", None)
content = block.get("content")
if isinstance(content, list):
pending_blocks.extend(child for child in content if isinstance(child, dict))
diff --git a/mineru/backend/postprocess/pages.py b/mineru/backend/postprocess/pages.py
index e9e63b36..19c0f56c 100644
--- a/mineru/backend/postprocess/pages.py
+++ b/mineru/backend/postprocess/pages.py
@@ -8,7 +8,7 @@ from typing import Any
from pydantic import TypeAdapter
-from mineru.backend.postprocess.lists import fix_office_paragraph_titles
+from mineru.backend.postprocess.lists import fix_office_index_title_blocks, fix_office_paragraph_titles
from mineru.backend.postprocess.page_blocks import process_page_blocks
from mineru.backend.postprocess.paragraphs import merge_para_text_blocks
from mineru.backend.postprocess.table_merge import merge_table
@@ -76,6 +76,7 @@ def blocks_to_page_info(
resolved_use_bbox = _document_uses_bbox([copied_blocks]) if use_bbox is None else use_bbox
if not resolved_use_bbox:
fix_office_paragraph_titles([copied_blocks])
+ fix_office_index_title_blocks([copied_blocks])
raw_page = _blocks_to_raw_page_info(
copied_blocks,
page_idx=page_idx,
@@ -96,6 +97,7 @@ def model_list_to_pages(
use_bbox = _document_uses_bbox(copied_model_list)
if not use_bbox:
fix_office_paragraph_titles(copied_model_list)
+ fix_office_index_title_blocks(copied_model_list)
raw_pages = [
_blocks_to_raw_page_info(
diff --git a/mineru/config.py b/mineru/config.py
index a7f1408a..6665fab0 100644
--- a/mineru/config.py
+++ b/mineru/config.py
@@ -241,6 +241,36 @@ class ManagedParseServerConfig(BaseModel):
port_probe_count: int = Field(default=100, ge=1)
+class LatexDelimiterConfig(BaseModel):
+ """单组 LaTeX 左右定界符配置。"""
+
+ left: str = Field(min_length=1)
+ right: str = Field(min_length=1)
+
+
+def _default_display_latex_delimiter() -> LatexDelimiterConfig:
+ """构造缺省行间公式定界符。"""
+ return LatexDelimiterConfig(left="$$", right="$$")
+
+
+def _default_inline_latex_delimiter() -> LatexDelimiterConfig:
+ """构造缺省行内公式定界符。"""
+ return LatexDelimiterConfig(left="$", right="$")
+
+
+class LatexDelimitersConfig(BaseModel):
+ """Markdown 行内与行间公式定界符配置。"""
+
+ display: LatexDelimiterConfig = Field(default_factory=_default_display_latex_delimiter)
+ inline: LatexDelimiterConfig = Field(default_factory=_default_inline_latex_delimiter)
+
+
+class RenderConfig(BaseModel):
+ """MiddleJson 输出渲染配置。"""
+
+ latex_delimiters: LatexDelimitersConfig = Field(default_factory=LatexDelimitersConfig)
+
+
class DoclibConfig(BaseModel):
"""Doclib startup configuration.
@@ -286,7 +316,7 @@ class Config(BaseModel):
"""Top-level MinerU startup configuration."""
doclib: DoclibConfig = Field(default_factory=DoclibConfig)
- # render: RenderConfig
+ render: RenderConfig = Field(default_factory=RenderConfig)
config = _apply_env_overrides(Config(**_read_config()))
@@ -302,6 +332,9 @@ __all__ = [
"config",
"Config",
"DoclibConfig",
+ "LatexDelimiterConfig",
+ "LatexDelimitersConfig",
+ "RenderConfig",
"TCPConfig",
"LogConfig",
"SQLiteConfig",
diff --git a/mineru/render/__init__.py b/mineru/render/__init__.py
index f64ba567..c55a9d78 100644
--- a/mineru/render/__init__.py
+++ b/mineru/render/__init__.py
@@ -1 +1,5 @@
-# Copyright (c) Opendatalab. All rights reserved.
\ No newline at end of file
+# Copyright (c) Opendatalab. All rights reserved.
+
+from .markdown import MarkdownRenderMode, render_markdown
+
+__all__ = ["MarkdownRenderMode", "render_markdown"]
diff --git a/mineru/render/markdown.py b/mineru/render/markdown.py
new file mode 100644
index 00000000..3b8fd9c0
--- /dev/null
+++ b/mineru/render/markdown.py
@@ -0,0 +1,421 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""严格 MiddleJson 到 Markdown 的公共渲染实现。"""
+
+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 (
+ inline_plain_text,
+ parse_inline_content,
+ render_inline_content,
+ render_internal_link,
+ render_joined_inline_contents,
+)
+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_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,
+ ParagraphTitleBlock,
+ RefTextBlock,
+ TableAnnotationBlock,
+ TableBlock,
+ TableBodyBlock,
+ TextBlock,
+)
+
+_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_.+#-]+")
+_INDEX_ROMAN_RE = re.compile(r"[ivxlcdm]+", re.IGNORECASE)
+
+
+def render_markdown(
+ middle_json: MiddleJson,
+ *,
+ mode: MarkdownRenderMode = MarkdownRenderMode.DEFAULT,
+ asset_base_url: str = "",
+) -> str:
+ """把严格 MiddleJson 纯函数式渲染为 Markdown 字符串。"""
+ if not isinstance(middle_json, MiddleJson):
+ raise TypeError("render_markdown expects a MiddleJson instance")
+ if not isinstance(mode, MarkdownRenderMode):
+ raise TypeError("mode must be a MarkdownRenderMode value")
+
+ delimiters = config.render.latex_delimiters
+ planned_pages = build_render_plan(middle_json, mode)
+ rendered_pages = [
+ _render_page(
+ page,
+ mode=mode,
+ delimiters=delimiters,
+ asset_base_url=asset_base_url,
+ )
+ for page in planned_pages
+ ]
+ if mode is MarkdownRenderMode.FULL:
+ return _PAGE_SEPARATOR.join(rendered_pages)
+ return "\n\n".join(page for page in rendered_pages if page)
+
+
+def _render_page(
+ planned_blocks: list[PlannedBlock],
+ *,
+ mode: MarkdownRenderMode,
+ delimiters: LatexDelimitersConfig,
+ asset_base_url: str,
+) -> str:
+ """渲染单页逻辑块,并在默认模式中过滤重复页元素。"""
+ rendered: list[str] = []
+ for planned in planned_blocks:
+ if planned.removed:
+ continue
+ if mode is MarkdownRenderMode.DEFAULT and planned.block.type in _DEFAULT_HIDDEN_TYPES:
+ continue
+ 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_text_block_markdown_prefix(content)
+ if isinstance(block, RefTextBlock):
+ return render_inline_content(block.content, delimiters)
+ if isinstance(block, (DocTitleBlock, ParagraphTitleBlock)):
+ return _render_title(block, delimiters)
+ if isinstance(block, PageAuxTextBlock):
+ return escape_text_block_markdown_prefix(render_inline_content(block.content, delimiters))
+ 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_title(
+ block: DocTitleBlock | ParagraphTitleBlock,
+ delimiters: LatexDelimitersConfig,
+) -> str:
+ """渲染带可选 HTML anchor 的 Markdown 标题。"""
+ level = min(max(block.level, 1), 6)
+ title = f"{'#' * level} {render_inline_content(block.content, 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_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:
+ """递归渲染已在 content 中内化编号的列表。"""
+ 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
+ indent = " " * depth
+ lines.extend(f"{indent}{line}" for line in item.splitlines() or [item])
+ 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 _strip_index_page_tail(content: str) -> str:
+ """删除目录末尾可信页码,并把其余 tab 转换为普通空格。"""
+ if "\t" not in content:
+ return content
+ head, tail = content.rsplit("\t", 1)
+ tail_text = inline_plain_text(parse_inline_content(tail)).strip()
+ if _looks_like_index_page_token(tail_text):
+ content = head
+ return content.replace("\t", " ")
+
+
+def _looks_like_index_page_token(content: str) -> bool:
+ """判断目录 tab 后缀是否为数字、罗马数字或单字母页码。"""
+ if not content or len(content) > 12:
+ return False
+ return bool(content.isdigit() or _INDEX_ROMAN_RE.fullmatch(content) or re.fullmatch(r"[A-Za-z]", content))
+
+
+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_media_body(
+ child,
+ summary=block.sub_type or "image content",
+ delimiters=delimiters,
+ asset_base_url=asset_base_url,
+ )
+ elif isinstance(child, ImageAnnotationBlock):
+ body = render_inline_content(child.content, 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_media_body(
+ child,
+ summary=block.sub_type or "chart content",
+ delimiters=delimiters,
+ asset_base_url=asset_base_url,
+ )
+ elif isinstance(child, ChartAnnotationBlock):
+ body = render_inline_content(child.content, 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 | ChartBodyBlock,
+ *,
+ summary: str,
+ delimiters: LatexDelimitersConfig,
+ asset_base_url: str,
+) -> str:
+ """渲染图片载荷,并将识别内容放入折叠详情。"""
+ source = resolve_image_source(block, asset_base_url)
+ content = block.content.strip()
+ if source:
+ parts = [build_markdown_image(source)]
+ if content:
+ parts.append(_render_details(content, summary, delimiters, asset_base_url))
+ return "\n\n".join(part for part in parts if part)
+ if not content:
+ return ""
+ return format_embedded_html(content, asset_base_url=asset_base_url, delimiters=delimiters)
+
+
+def _render_details(
+ content: str,
+ summary: str,
+ delimiters: LatexDelimitersConfig,
+ asset_base_url: str,
+) -> str:
+ """构造保留视觉识别内容的折叠 HTML 详情块。"""
+ normalized = format_embedded_html(content.strip(), asset_base_url=asset_base_url, delimiters=delimiters)
+ safe_summary = html.escape(summary, quote=False)
+ return f"<details>\n<summary>{safe_summary}</summary>\n\n{normalized}\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_table_body(child, delimiters, asset_base_url)
+ elif isinstance(child, TableAnnotationBlock):
+ body = render_inline_content(child.content, 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、空间投影文本、图片的优先级渲染表格主体。"""
+ if block.content:
+ html_table = render_html_table(
+ block.content,
+ asset_base_url=asset_base_url,
+ delimiters=delimiters,
+ )
+ if html_table is not None:
+ return html_table
+ return _render_fenced_content(block.content)
+ source = resolve_image_source(block, asset_base_url)
+ return build_markdown_image(source) if source else ""
+
+
+def _render_code_block(block: CodeBlock, delimiters: LatexDelimitersConfig) -> str:
+ """按父块 subtype 渲染普通代码或支持公式的算法。"""
+ parts: list[str] = []
+ for child in block.content:
+ if isinstance(child, CodeBodyBlock):
+ if block.sub_type == BlockType.CODE:
+ body = _render_fenced_content(child.content, _normalize_code_language(block.guess_lang))
+ elif block.sub_type == RAW_ALGORITHM:
+ body = _render_algorithm_html(child.content, delimiters)
+ else:
+ raise ValueError(f"Unsupported code subtype: {block.sub_type}")
+ elif isinstance(child, CodeAnnotationBlock):
+ body = render_inline_content(child.content, delimiters)
+ else:
+ raise TypeError(f"Unsupported code child: {type(child).__name__}")
+ if body:
+ parts.append(body)
+ return _join_visual_parts(parts)
+
+
+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(html.escape(plain, quote=False))
+ 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}{html.escape(latex, quote=False)}{delimiters.inline.right}"
+ )
+ previous_was_equation = True
+ cursor = match.end()
+ parts.append(html.escape(content[cursor:], quote=False))
+ body = "".join(parts)
+ return (
+ '<div class="mineru-algorithm" style="white-space: pre-wrap; font-family:monospace;">\n'
+ f"{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
index f64ba567..1e17167c 100644
--- a/mineru/render/utils/__init__.py
+++ b/mineru/render/utils/__init__.py
@@ -1 +1 @@
-# Copyright (c) Opendatalab. All rights reserved.
\ No newline at end of file
+# Copyright (c) Opendatalab. All rights reserved.
diff --git a/mineru/render/utils/assets.py b/mineru/render/utils/assets.py
new file mode 100644
index 00000000..7088214e
--- /dev/null
+++ b/mineru/render/utils/assets.py
@@ -0,0 +1,72 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""Markdown 与嵌入 HTML 共用的图片资源解析。"""
+
+from __future__ import annotations
+
+import re
+from urllib.parse import quote
+
+from mineru.types import ImagePayloadBlock
+
+_HTML_IMAGE_SRC_RE = re.compile(
+ r"(?P<prefix>\bsrc\s*=\s*)(?P<quote>[\"'])(?P<src>.*?)(?P=quote)",
+ re.IGNORECASE | re.DOTALL,
+)
+
+
+def resolve_image_source(block: ImagePayloadBlock, asset_base_url: str = "") -> str | None:
+ """按 image_path 优先、image_base64 兜底解析图片来源。"""
+ if block.image_path:
+ return join_asset_base_url(asset_base_url, block.image_path)
+ if block.image_base64:
+ return block.image_base64
+ return None
+
+
+def join_asset_base_url(asset_base_url: str, relative_path: str) -> str:
+ """使用 POSIX 语义拼接资源根地址与安全相对路径。"""
+ if not asset_base_url:
+ return relative_path
+ return f"{asset_base_url.rstrip('/')}/{relative_path.lstrip('/')}"
+
+
+def build_markdown_image(source: str, alt: str = "") -> str:
+ """构造不会被空格或括号截断的 Markdown 图片语法。"""
+ if not source:
+ return ""
+ safe_alt = alt.replace("[", r"\[").replace("]", r"\]")
+ if source.startswith("data:"):
+ destination = source
+ else:
+ destination = quote(source, safe="/:#?&=%@+~,;!$'*-._")
+ return f"![{safe_alt}]({destination})"
+
+
+def prefix_html_image_sources(markup: str, asset_base_url: str = "") -> str:
+ """给 HTML 中的相对图片地址添加资源根地址。"""
+ if not markup or not asset_base_url:
+ return markup
+
+ def _replace(match: re.Match[str]) -> str:
+ """只重写相对 src,保留 data URI、绝对 URL 与根路径。"""
+ source = match.group("src")
+ if _is_absolute_image_source(source):
+ return match.group(0)
+ resolved = join_asset_base_url(asset_base_url, source)
+ return f"{match.group('prefix')}{match.group('quote')}{resolved}{match.group('quote')}"
+
+ return _HTML_IMAGE_SRC_RE.sub(_replace, markup)
+
+
+def _is_absolute_image_source(source: str) -> bool:
+ """判断 HTML 图片地址是否已经是绝对或不可前缀化的来源。"""
+ normalized = source.strip().lower()
+ return normalized.startswith(("data:", "http://", "https://", "//", "/", "#"))
+
+
+__all__ = [
+ "build_markdown_image",
+ "join_asset_base_url",
+ "prefix_html_image_sources",
+ "resolve_image_source",
+]
diff --git a/mineru/render/utils/inline.py b/mineru/render/utils/inline.py
new file mode 100644
index 00000000..06a36a29
--- /dev/null
+++ b/mineru/render/utils/inline.py
@@ -0,0 +1,405 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""MiddleJson 行内语义解析与 Markdown 序列化。"""
+
+from __future__ import annotations
+
+import html
+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
+
+_INLINE_START_RE = re.compile(
+ r"<(?P<tag>eq|text|hyperlink|sup|sub|strong|b|em|i|s|u)(?P<attrs>\s[^<>]*?)?>",
+ re.IGNORECASE,
+)
+_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",
+ "underline",
+ "emphasis",
+ "strikethrough",
+ "superscript",
+ "subscript",
+}
+_DIRECT_TAG_STYLES = {
+ "strong": "bold",
+ "b": "bold",
+ "em": "italic",
+ "i": "italic",
+ "s": "strikethrough",
+ "u": "underline",
+ "sup": "superscript",
+ "sub": "subscript",
+}
+
+
+@dataclass(slots=True)
+class InlineText:
+ """保存普通行内文本。"""
+
+ content: str
+
+
+@dataclass(slots=True)
+class InlineEquation:
+ """保存不含外层定界符的行内 LaTeX。"""
+
+ latex: str
+
+
+@dataclass(slots=True)
+class InlineStyled:
+ """保存带 Office 字体样式的行内子节点。"""
+
+ children: list[InlineNode]
+ styles: tuple[str, ...]
+
+
+@dataclass(slots=True)
+class InlineLink:
+ """保存超链接标签节点及目标地址。"""
+
+ children: list[InlineNode]
+ url: str
+
+
+InlineNode: TypeAlias = Union[InlineText, InlineEquation, InlineStyled, InlineLink]
+
+
+def parse_inline_content(content: str) -> list[InlineNode]:
+ """把 MiddleJson 字符串解析为白名单行内语义节点。"""
+ return _parse_inline_range(content or "")
+
+
+def _parse_inline_range(content: str) -> list[InlineNode]:
+ """解析当前字符串范围,未知标签始终保留为普通文本。"""
+ nodes: list[InlineNode] = []
+ cursor = 0
+ while match := _INLINE_START_RE.search(content, cursor):
+ _append_text(nodes, content[cursor : match.start()])
+ tag = match.group("tag").lower()
+ close = _find_matching_close(content, tag, match.end())
+ if close is None:
+ _append_text(nodes, match.group(0))
+ cursor = match.end()
+ continue
+
+ inner = content[match.end() : close[0]]
+ original = content[match.start() : close[1]]
+ parsed = _parse_inline_element(tag, match.group("attrs") or "", inner)
+ if parsed is None:
+ _append_text(nodes, original)
+ elif isinstance(parsed, list):
+ nodes.extend(parsed)
+ else:
+ nodes.append(parsed)
+ cursor = close[1]
+ _append_text(nodes, content[cursor:])
+ return nodes
+
+
+def _find_matching_close(content: str, tag: str, start: int) -> tuple[int, int] | None:
+ """查找同名结束标签,并兼容极少出现的同名嵌套。"""
+ token_re = re.compile(rf"<(?P<close>/)?{re.escape(tag)}(?:\s[^<>]*?)?>", re.IGNORECASE)
+ depth = 1
+ for match in token_re.finditer(content, start):
+ depth += -1 if match.group("close") else 1
+ if depth == 0:
+ return match.start(), match.end()
+ return None
+
+
+def _parse_inline_element(
+ tag: str,
+ attrs: str,
+ inner: str,
+) -> InlineNode | list[InlineNode] | None:
+ """把一个已闭合白名单元素转换为对应行内节点。"""
+ if tag == "eq":
+ latex = html.unescape(inner).strip()
+ return InlineEquation(latex) if latex else []
+ if tag == "hyperlink":
+ return _parse_hyperlink(inner)
+
+ children = _parse_inline_range(inner)
+ if tag == "text":
+ styles = _parse_styles(attrs)
+ return InlineStyled(children, styles) if styles else children
+ style = _DIRECT_TAG_STYLES[tag]
+ return InlineStyled(children, (style,))
+
+
+def _parse_hyperlink(inner: str) -> InlineLink | None:
+ """解析 hyperlink 的标签与 URL,结构损坏时交由调用方保留原文。"""
+ match = _URL_RE.search(inner)
+ if match is None:
+ return None
+ label_content = f"{inner[:match.start()]}{inner[match.end():]}"
+ url = html.unescape(match.group("url")).strip()
+ if not url:
+ return None
+ children = _parse_inline_range(label_content)
+ if not children:
+ return None
+ return InlineLink(children=children, url=url)
+
+
+def _parse_styles(attrs: str) -> tuple[str, ...]:
+ """从 text 标签属性中提取去重后的已知样式。"""
+ match = _STYLE_ATTR_RE.search(attrs)
+ if match is None:
+ return ()
+ styles: list[str] = []
+ for value in match.group("style").split(","):
+ style = value.strip().lower()
+ if style in _KNOWN_STYLES and style not in styles:
+ styles.append(style)
+ return tuple(styles)
+
+
+def _append_text(nodes: list[InlineNode], content: str) -> None:
+ """追加普通文本,并合并相邻文本节点。"""
+ if not content:
+ return
+ if nodes and isinstance(nodes[-1], InlineText):
+ nodes[-1].content += content
+ else:
+ 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。"""
+ merged: list[InlineNode] = []
+ for content in contents:
+ current = parse_inline_content(content)
+ if not current:
+ continue
+ if merged:
+ _join_inline_node_sequences(merged, current)
+ merged.extend(current)
+ return render_inline_nodes(merged, delimiters)
+
+
+def _join_inline_node_sequences(previous: list[InlineNode], current: list[InlineNode]) -> None:
+ """在两组行内节点之间插入安全的语言相关边界。"""
+ previous_visible = inline_plain_text(previous).rstrip()
+ current_visible = inline_plain_text(current).lstrip()
+ if not previous_visible or not current_visible:
+ return
+
+ last_text = _last_text_node(previous)
+ first_text = _first_text_node(current)
+ if last_text is not None:
+ last_text.content = last_text.content.rstrip()
+ if first_text is not None:
+ first_text.content = first_text.content.lstrip()
+
+ language = _detect_boundary_language(f"{previous_visible}{current_visible}")
+ next_starts_lowercase = current_visible[0].islower()
+ if last_text is not None:
+ processed, separator = resolve_text_line_boundary(
+ last_text.content,
+ block_language=language,
+ next_starts_with_lowercase=next_starts_lowercase,
+ )
+ last_text.content = processed
+ else:
+ separator = "" if language in CJK_LANGS else " "
+ if separator:
+ previous.append(InlineText(separator))
+
+
+def _detect_boundary_language(content: str) -> str:
+ """检测段落边界语言,短 CJK 文本优先使用字符范围兜底。"""
+ if _CJK_RE.search(content):
+ return "zh"
+ try:
+ return detect_lang(content)
+ except Exception:
+ return ""
+
+
+def _first_text_node(nodes: list[InlineNode]) -> InlineText | None:
+ """仅当首个可见行内叶子是普通文本时返回该节点。"""
+ for node in nodes:
+ if not inline_plain_text([node]):
+ continue
+ if isinstance(node, InlineText):
+ return node
+ if isinstance(node, (InlineStyled, InlineLink)):
+ return _first_text_node(node.children)
+ return None
+ return None
+
+
+def _last_text_node(nodes: list[InlineNode]) -> InlineText | None:
+ """仅当末个可见行内叶子是普通文本时返回该节点。"""
+ for node in reversed(nodes):
+ if not inline_plain_text([node]):
+ continue
+ if isinstance(node, InlineText):
+ return node
+ if isinstance(node, (InlineStyled, InlineLink)):
+ return _last_text_node(node.children)
+ return 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
+ 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)
+
+ 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:
+ 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:
+ """使用不换行空格保留带可见样式的纯空白。"""
+ 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] = []
+ for node in nodes:
+ if isinstance(node, InlineText):
+ parts.append(node.content)
+ elif isinstance(node, InlineEquation):
+ parts.append(node.latex)
+ elif isinstance(node, (InlineStyled, InlineLink)):
+ parts.append(inline_plain_text(node.children))
+ return "".join(parts)
+
+
+__all__ = [
+ "InlineNode",
+ "inline_plain_text",
+ "parse_inline_content",
+ "render_inline_content",
+ "render_inline_nodes",
+ "render_internal_link",
+ "render_joined_inline_contents",
+]
diff --git a/mineru/render/utils/logical_blocks.py b/mineru/render/utils/logical_blocks.py
new file mode 100644
index 00000000..b903ce73
--- /dev/null
+++ b/mineru/render/utils/logical_blocks.py
@@ -0,0 +1,103 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""Markdown 渲染前的逻辑块复制、延续合并与页面规划。"""
+
+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.types import MiddleJson, PageBlock, TableBlock, TextBlock
+
+
+class MarkdownRenderMode(str, Enum):
+ """Markdown 的默认合并视图与完整分页视图。"""
+
+ DEFAULT = "default"
+ FULL = "full"
+
+
+@dataclass(slots=True)
+class PlannedBlock:
+ """保存一个待渲染块及其来源页和文本延续片段。"""
+
+ page_idx: int
+ block: PageBlock
+ text_contents: list[str] = field(default_factory=list)
+ removed: bool = False
+
+
+def build_render_plan(middle_json: MiddleJson, mode: MarkdownRenderMode) -> list[list[PlannedBlock]]:
+ """深拷贝 MiddleJson,并按模式生成不污染输入的逐页逻辑块计划。"""
+ copied = middle_json.model_copy(deep=True)
+ pages = [
+ [
+ PlannedBlock(
+ page_idx=page.page_idx,
+ block=block,
+ text_contents=[block.content] if isinstance(block, TextBlock) else [],
+ )
+ for block in page.blocks
+ ]
+ for page in copied.pages
+ ]
+ flattened = [planned for page in pages for planned in page]
+ _merge_continued_text_blocks(flattened, mode)
+ if mode is MarkdownRenderMode.DEFAULT:
+ _merge_continued_table_blocks(flattened)
+ return pages
+
+
+def _merge_continued_text_blocks(blocks: list[PlannedBlock], mode: MarkdownRenderMode) -> None:
+ """把 continues_prev 文本吸收到最近的前序文本逻辑块。"""
+ for current_index, current in enumerate(blocks):
+ if current.removed or not isinstance(current.block, TextBlock) or current.block.continues_prev is not True:
+ continue
+ previous = _find_previous_planned_text(blocks, current_index)
+ if previous is None:
+ continue
+ is_cross_page = previous.page_idx != current.page_idx
+ if is_cross_page and mode is MarkdownRenderMode.FULL:
+ continue
+ previous.text_contents.extend(current.text_contents)
+ current.removed = True
+
+
+def _find_previous_planned_text(blocks: list[PlannedBlock], current_index: int) -> PlannedBlock | None:
+ """跨越任意类型查找最近且仍参与输出的前序文本。"""
+ for candidate in reversed(blocks[:current_index]):
+ if not candidate.removed and isinstance(candidate.block, TextBlock):
+ return candidate
+ return None
+
+
+def _merge_continued_table_blocks(blocks: list[PlannedBlock]) -> None:
+ """在默认模式中把跨页续表合并到最近的前序表格。"""
+ for current_index, current in enumerate(blocks):
+ if current.removed or not isinstance(current.block, TableBlock) or current.block.continues_prev is not True:
+ continue
+ previous = _find_previous_planned_table(blocks, current_index)
+ if previous is None or previous.page_idx == current.page_idx:
+ continue
+ merged = merge_table_content(
+ previous.block.model_dump(mode="python", exclude_none=True),
+ current.block.model_dump(mode="python", exclude_none=True),
+ )
+ if merged is None:
+ continue
+ try:
+ previous.block = TableBlock.model_validate(merged)
+ except (TypeError, ValueError):
+ continue
+ current.removed = True
+
+
+def _find_previous_planned_table(blocks: list[PlannedBlock], current_index: int) -> PlannedBlock | None:
+ """查找最近且仍参与输出的前序表格。"""
+ for candidate in reversed(blocks[:current_index]):
+ if not candidate.removed and isinstance(candidate.block, TableBlock):
+ return candidate
+ return None
+
+
+__all__ = ["MarkdownRenderMode", "PlannedBlock", "build_render_plan"]
diff --git a/mineru/render/utils/markdown_table.py b/mineru/render/utils/markdown_table.py
new file mode 100644
index 00000000..372ec132
--- /dev/null
+++ b/mineru/render/utils/markdown_table.py
@@ -0,0 +1,234 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""HTML 表格判型、内嵌资源处理与无损 GFM 转换。"""
+
+from __future__ import annotations
+
+import html
+import re
+
+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
+
+_INLINE_EQ_RE = re.compile(r"<eq>(?P<latex>.*?)</eq>", re.IGNORECASE | re.DOTALL)
+_COMPLEX_CELL_TAGS = {
+ "blockquote",
+ "div",
+ "dl",
+ "figure",
+ "h1",
+ "h2",
+ "h3",
+ "h4",
+ "h5",
+ "h6",
+ "img",
+ "li",
+ "math",
+ "object",
+ "ol",
+ "pre",
+ "svg",
+ "table",
+ "ul",
+}
+_ALLOWED_INLINE_TAGS = {
+ "a",
+ "b",
+ "br",
+ "code",
+ "em",
+ "eq",
+ "i",
+ "p",
+ "s",
+ "span",
+ "strong",
+ "sub",
+ "sup",
+ "u",
+}
+
+
+def render_html_table(
+ content: str,
+ *,
+ asset_base_url: str,
+ delimiters: LatexDelimitersConfig,
+) -> str | None:
+ """将 HTML table 按复杂度输出原 HTML 或转换为 GFM 表格。"""
+ prefixed = prefix_html_image_sources(content, asset_base_url)
+ soup = BeautifulSoup(prefixed, "html.parser")
+ tables = soup.find_all("table")
+ if not tables:
+ return None
+ table = tables[0]
+ if len(tables) != 1 or _is_complex_table(table):
+ return format_embedded_html(prefixed, asset_base_url="", delimiters=delimiters).strip()
+ markdown = _convert_simple_table(table, delimiters)
+ if markdown is not None:
+ return markdown
+ return format_embedded_html(prefixed, asset_base_url="", delimiters=delimiters).strip()
+
+
+def format_embedded_html(
+ markup: str,
+ *,
+ asset_base_url: str,
+ delimiters: LatexDelimitersConfig,
+) -> str:
+ """统一处理嵌入 HTML 的图片地址与行内公式标签。"""
+ prefixed = prefix_html_image_sources(markup, asset_base_url)
+
+ def _replace_inline_equation(match: re.Match[str]) -> str:
+ """把单个 HTML eq 标签替换为配置的行内公式定界符。"""
+ return (
+ f" {delimiters.inline.left}"
+ f"{html.unescape(match.group('latex')).strip()}"
+ f"{delimiters.inline.right} "
+ )
+
+ return _INLINE_EQ_RE.sub(_replace_inline_equation, prefixed)
+
+
+def _is_complex_table(table: Tag) -> bool:
+ """判断表格是否包含 GFM 无法无损表达的结构。"""
+ if table.find("table") is not None:
+ return True
+ thead = table.find("thead")
+ if thead is not None and len(thead.find_all("tr", recursive=False)) > 1:
+ return True
+ for cell in table.find_all(("th", "td")):
+ if cell.has_attr("rowspan") or cell.has_attr("colspan"):
+ return True
+ if len(cell.find_all("p")) > 1:
+ return True
+ for descendant in cell.descendants:
+ if not isinstance(descendant, Tag):
+ continue
+ if descendant.name in _COMPLEX_CELL_TAGS:
+ return True
+ if descendant.name not in _ALLOWED_INLINE_TAGS:
+ return True
+ if descendant.name == "span" and descendant.attrs:
+ return True
+ return False
+
+
+def _convert_simple_table(table: Tag, delimiters: LatexDelimitersConfig) -> str | None:
+ """把已确认简单的单层 HTML table 转换为 GFM。"""
+ rows = table.find_all("tr")
+ if not rows:
+ return None
+ rendered_rows: list[list[str]] = []
+ header_flags: list[list[bool]] = []
+ for row in rows:
+ cells = row.find_all(("th", "td"), recursive=False)
+ if not cells:
+ return None
+ rendered_rows.append(
+ [_normalize_cell_text(_render_inline_children(cell, delimiters)) for cell in cells]
+ )
+ header_flags.append([cell.name == "th" for cell in cells])
+
+ width = max(len(row) for row in rendered_rows)
+ for row in rendered_rows:
+ row.extend([""] * (width - len(row)))
+ header_index = _detect_header_index(table, header_flags)
+ header = rendered_rows[header_index]
+ body = rendered_rows[:header_index] + rendered_rows[header_index + 1 :]
+ return "\n".join(
+ [
+ _format_markdown_row(header),
+ _format_markdown_row(["---"] * width),
+ *[_format_markdown_row(row) for row in body],
+ ]
+ )
+
+
+def _detect_header_index(table: Tag, header_flags: list[list[bool]]) -> int:
+ """优先选择 thead 或全 th 行,否则使用首行作为 GFM 表头。"""
+ thead = table.find("thead")
+ if thead is not None and thead.find("tr", recursive=False) is not None:
+ return 0
+ for index, flags in enumerate(header_flags):
+ if flags and all(flags):
+ return index
+ return 0
+
+
+def _render_inline_children(node: Tag, delimiters: LatexDelimitersConfig) -> str:
+ """递归渲染简单单元格中的安全行内 HTML。"""
+ parts: list[str] = []
+ for child in node.children:
+ if isinstance(child, NavigableString):
+ parts.append(_escape_cell_text(str(child)))
+ continue
+ if not isinstance(child, Tag):
+ continue
+ name = child.name
+ rendered = _render_inline_children(child, delimiters)
+ if name in {"p", "span"}:
+ parts.append(rendered)
+ elif name == "br":
+ parts.append("<br>")
+ elif name == "code":
+ parts.append(_render_inline_code(child.get_text()))
+ elif name == "eq":
+ latex = html.unescape(child.get_text()).strip()
+ parts.append(f"{delimiters.inline.left}{latex}{delimiters.inline.right}" if latex else "")
+ elif name == "a":
+ href = str(child.get("href", "")).strip()
+ parts.append(f"[{rendered}]({_escape_link_url(href)})" if href else rendered)
+ elif name in {"b", "strong"}:
+ parts.append(f"**{rendered.strip()}**")
+ elif name in {"em", "i"}:
+ parts.append(f"*{rendered.strip()}*")
+ elif name == "s":
+ parts.append(f"~~{rendered.strip()}~~")
+ elif name in {"u", "sub", "sup"}:
+ parts.append(f"<{name}>{rendered}</{name}>")
+ else:
+ parts.append(rendered)
+ return "".join(parts)
+
+
+def _render_inline_code(content: str) -> str:
+ """使用足够长的反引号包装表格单元格内代码。"""
+ longest = max((len(match.group(0)) for match in re.finditer(r"`+", content)), default=0)
+ fence = "`" * max(1, longest + 1)
+ return f"{fence}{_escape_cell_text(content)}{fence}"
+
+
+def _escape_link_url(url: str) -> str:
+ """转义 GFM 表格链接目标中的空格、反斜杠和括号。"""
+ return (
+ url.replace("\\", "%5C")
+ .replace(" ", "%20")
+ .replace("(", "%28")
+ .replace(")", "%29")
+ .replace("|", "%7C")
+ )
+
+
+def _escape_cell_text(content: str) -> str:
+ """转义 GFM 单元格中的反斜杠与管道符。"""
+ return content.replace("\\", "\\\\").replace("|", r"\|")
+
+
+def _normalize_cell_text(content: str) -> str:
+ """压缩普通空白,同时保留显式 br 换行。"""
+ content = re.sub(r"[ \t\r\f\v]+", " ", content)
+ content = re.sub(r" *\n+ *", " ", content)
+ content = re.sub(r" *<br> *", "<br>", content)
+ return content.strip()
+
+
+def _format_markdown_row(row: list[str]) -> str:
+ """把一行单元格格式化为 GFM 行。"""
+ return f"| {' | '.join(row)} |"
+
+
+__all__ = ["format_embedded_html", "render_html_table"]
diff --git a/mineru/types.py b/mineru/types.py
index 8fe3f531..4027a7fb 100644
--- a/mineru/types.py
+++ b/mineru/types.py
@@ -493,7 +493,7 @@ class ListBlock(BlockBase):
IndexChildBlock: TypeAlias = Annotated[
- Union[TextBlock, "IndexBlock"],
+ Union[TextBlock, DocTitleBlock, ParagraphTitleBlock, "IndexBlock"],
Field(discriminator="type"),
]
diff --git a/tests/unittest/test_markdown_render.py b/tests/unittest/test_markdown_render.py
new file mode 100644
index 00000000..e83a471a
--- /dev/null
+++ b/tests/unittest/test_markdown_render.py
@@ -0,0 +1,431 @@
+from __future__ import annotations
+
+from copy import deepcopy
+
+import pytest
+
+from mineru.config import Config
+from mineru.render import MarkdownRenderMode, render_markdown
+from mineru.types import (
+ ChartBlock,
+ ChartBodyBlock,
+ CodeBlock,
+ CodeBodyBlock,
+ EquationBlock,
+ ImageBlock,
+ ImageBodyBlock,
+ IndexBlock,
+ MiddleJson,
+ PageAuxTextBlock,
+ PageBlock,
+ PageInfo,
+ ParagraphTitleBlock,
+ TableBlock,
+ TableBodyBlock,
+ TextBlock,
+)
+
+
+def _middle(*pages: PageInfo, file_suffix: str = "docx") -> MiddleJson:
+ """构造最小严格 MiddleJson 测试对象。"""
+ return MiddleJson(
+ pages=list(pages),
+ file_suffix=file_suffix,
+ effort="flash",
+ parse_mode="txt",
+ mineru_version="test",
+ )
+
+
+def _page(page_idx: int, *blocks: PageBlock) -> PageInfo:
+ """构造一页并保留调用方给定的 block 顺序。"""
+ return PageInfo(page_idx=page_idx, blocks=list(blocks))
+
+
+def _image(index: int, path: str = "images/a.png") -> ImageBlock:
+ """构造带 path 的图片父块。"""
+ return ImageBlock(
+ type="image",
+ index=index,
+ content=[ImageBodyBlock(type="image_body", index=index, content="", image_path=path)],
+ )
+
+
+def _table(index: int, content: str, *, continues_prev: bool | None = None) -> TableBlock:
+ """构造无 bbox 的 Office 表格父块。"""
+ return TableBlock(
+ type="table",
+ index=index,
+ continues_prev=continues_prev,
+ content=[TableBodyBlock(type="table_body", index=index, content=content)],
+ )
+
+
+def _pdf_table(
+ index: int,
+ content: str,
+ *,
+ continues_prev: bool | None = None,
+) -> TableBlock:
+ """构造带归一化 bbox 的 PDF 表格父块。"""
+ bbox = (0.1, 0.1, 0.9, 0.9)
+ return TableBlock(
+ type="table",
+ index=index,
+ bbox=bbox,
+ continues_prev=continues_prev,
+ content=[TableBodyBlock(type="table_body", index=index, bbox=bbox, content=content)],
+ )
+
+
+def test_render_modes_filter_merge_and_preserve_input() -> None:
+ """验证两种模式的过滤、页内/跨页合并、分页线及无副作用。"""
+ middle = _middle(
+ _page(
+ 0,
+ PageAuxTextBlock(type="header", index=0, content="HEADER"),
+ TextBlock(type="text", index=1, content="Hello"),
+ _image(2),
+ TextBlock(type="text", index=3, content="world", continues_prev=True),
+ PageAuxTextBlock(type="footer", index=4, content="FOOTER"),
+ ),
+ _page(
+ 1,
+ PageAuxTextBlock(type="page_number", index=0, content="2"),
+ TextBlock(type="text", index=1, content="again", continues_prev=True),
+ PageAuxTextBlock(type="page_footnote", index=2, content="NOTE"),
+ ),
+ )
+ before = middle.to_json(skip_defaults=False)
+
+ default = render_markdown(middle)
+ full = render_markdown(middle, mode=MarkdownRenderMode.FULL)
+
+ assert default == "Hello world again\n\n![](images/a.png)"
+ assert full == "\n\n---\n\n".join(
+ [
+ "HEADER\n\nHello world\n\n![](images/a.png)\n\nFOOTER",
+ "2\n\nagain\n\nNOTE",
+ ]
+ )
+ assert middle.to_json(skip_defaults=False) == before
+
+
+def test_full_mode_preserves_empty_page_boundaries() -> None:
+ """验证 FULL 对空白页仍保留相邻页分割线。"""
+ middle = _middle(_page(0), _page(1, TextBlock(type="text", index=0, content="x")), _page(2))
+
+ assert render_markdown(middle, mode=MarkdownRenderMode.FULL) == "\n\n---\n\nx\n\n---\n\n"
+ assert render_markdown(middle) == "x"
+
+
+def test_text_continuation_handles_hyphen_and_cjk_boundaries() -> None:
+ """验证续写文本沿用西文断词与 CJK 直接连接规则。"""
+ western = _middle(
+ _page(
+ 0,
+ TextBlock(type="text", index=0, content="inter-"),
+ TextBlock(type="text", index=1, content="national", continues_prev=True),
+ )
+ )
+ cjk = _middle(
+ _page(
+ 0,
+ TextBlock(type="text", index=0, content="中文"),
+ TextBlock(type="text", index=1, content="继续", continues_prev=True),
+ )
+ )
+
+ assert render_markdown(western) == "international"
+ assert render_markdown(cjk) == "中文继续"
+
+
+def test_text_continuation_does_not_rewrite_formula_or_style_wrappers() -> None:
+ """验证续写边界不会越过末尾公式或破坏样式节点。"""
+ formula = _middle(
+ _page(
+ 0,
+ TextBlock(type="text", index=0, content="before <eq>x</eq>"),
+ TextBlock(type="text", index=1, content="after", continues_prev=True),
+ )
+ )
+ styled = _middle(
+ _page(
+ 0,
+ TextBlock(type="text", index=0, content='<text style="bold">inter-</text>'),
+ TextBlock(type="text", index=1, content="national", continues_prev=True),
+ )
+ )
+
+ assert render_markdown(formula) == "before $x$ after"
+ assert render_markdown(styled) == "**inter**national"
+
+
+def test_render_rejects_legacy_inputs_and_string_mode() -> None:
+ """验证公共入口不兼容旧 dict/pages 输入或字符串模式。"""
+ middle = _middle(_page(0))
+
+ with pytest.raises(TypeError, match="MiddleJson"):
+ render_markdown(middle.to_dict()) # type: ignore[arg-type]
+ with pytest.raises(TypeError, match="MarkdownRenderMode"):
+ render_markdown(middle, mode="full") # type: ignore[arg-type]
+
+
+def test_inline_rich_text_unknown_tags_and_visible_spaces() -> None:
+ """验证富文本、公式、链接、未知标签与可见空白。"""
+ content = (
+ 'A <text style="bold">B</text> '
+ '<hyperlink><text style="underline">link</text><url>https://example.com/a b</url></hyperlink> '
+ '<eq>x_1</eq> <local_dir> p <0.05 and x > 0 <sup>2</sup><text style="underline"> </text>'
+ )
+ middle = _middle(_page(0, TextBlock(type="text", index=0, content=content)))
+
+ rendered = render_markdown(middle)
+
+ assert "**B**" in rendered
+ assert '<a href="https://example.com/a b"><u>link</u></a>' in rendered
+ assert "$x_1$" in rendered
+ assert "<local_dir>" in rendered
+ assert "p <0.05 and x > 0" in rendered
+ assert "<sup>2</sup>" in rendered
+ assert "<u>&nbsp;&nbsp;</u>" in rendered
+
+
+def test_text_block_escapes_markdown_prefix_and_malformed_tag() -> None:
+ """验证普通 text 不会误变列表,损坏白名单标签按原文转义。"""
+ middle = _middle(
+ _page(
+ 0,
+ TextBlock(type="text", index=0, content="- plain"),
+ TextBlock(type="text", index=1, content='<text style="bold">broken'),
+ )
+ )
+
+ assert render_markdown(middle) == '\\- plain\n\n<text style="bold">broken'
+
+
+def test_title_and_index_render_anchor_links_without_heading_leaves() -> None:
+ """验证标题 anchor 与递归目录 title leaf 的链接输出。"""
+ index = IndexBlock(
+ type="index",
+ index=0,
+ content=[
+ ParagraphTitleBlock(
+ type="paragraph_title",
+ level=2,
+ anchor="toc-a",
+ content="1 Section\t12",
+ ),
+ IndexBlock(
+ type="index",
+ content=[TextBlock(type="text", content="Plain")],
+ ),
+ ],
+ )
+ title = ParagraphTitleBlock(
+ type="paragraph_title",
+ index=1,
+ level=8,
+ anchor="toc-a",
+ content="Section",
+ )
+
+ rendered = render_markdown(_middle(_page(0, index, title)))
+
+ assert rendered.startswith("- [1 Section](#toc-a)\n - Plain")
+ assert '<a id="toc-a"></a>\n###### Section' in rendered
+
+
+def test_equation_uses_content_then_image_fallback(monkeypatch: pytest.MonkeyPatch) -> None:
+ """验证行间公式定界符配置及空公式图片回退。"""
+ configured = Config(
+ render={
+ "latex_delimiters": {
+ "display": {"left": "\\[", "right": "\\]"},
+ "inline": {"left": "\\(", "right": "\\)"},
+ }
+ }
+ )
+ monkeypatch.setattr("mineru.render.markdown.config", configured)
+ middle = _middle(
+ _page(
+ 0,
+ EquationBlock(type="equation", index=0, content="x=1"),
+ EquationBlock(type="equation", index=1, content="", image_path="images/e.png"),
+ TextBlock(type="text", index=2, content="inline <eq>y</eq>"),
+ )
+ )
+
+ assert render_markdown(middle) == "\\[\nx=1\n\\]\n\n![](images/e.png)\n\ninline \\(y\\)"
+
+
+ "html_table",
+ [
+ "<table><tr><td rowspan='2'>A</td></tr><tr><td>B</td></tr></table>",
+ "<table><tr><td colspan='2'>A</td></tr></table>",
+ "<table><tr><td><table><tr><td>N</td></tr></table></td></tr></table>",
+ "<table><tr><td><img src='images/a.png'></td></tr></table>",
+ "<table><tr><td><ul><li>A</li></ul></td></tr></table>",
+ "<table><tr><td><p>A</p><p>B</p></td></tr></table>",
+ ],
+)
+def test_complex_html_tables_fall_back_to_html(html_table: str) -> None:
+ """验证不可无损转换的表格结构保持 HTML。"""
+ rendered = render_markdown(_middle(_page(0, _table(0, html_table))), asset_base_url="assets")
+
+ assert rendered.startswith("<table")
+ assert "| --- |" not in rendered
+ if "<img" in html_table:
+ assert "assets/images/a.png" in rendered
+
+
+def test_simple_html_table_converts_to_gfm_and_preserves_inline_formula() -> None:
+ """验证简单 HTML table 转 GFM,并保留单元格公式反斜杠。"""
+ content = (
+ "<table><tr><th>Name</th><th>Value</th></tr>"
+ "<tr><td>A|B</td><td><eq>\\frac{1}{2}</eq></td></tr></table>"
+ )
+
+ assert render_markdown(_middle(_page(0, _table(0, content)))) == "\n".join(
+ [
+ "| Name | Value |",
+ "| --- | --- |",
+ r"| A\|B | $\frac{1}{2}$ |",
+ ]
+ )
+
+
+def test_spatial_table_uses_dynamic_fence_and_empty_table_uses_image() -> None:
+ """验证空间投影文本保留空白,且空表回退图片。"""
+ spatial = _table(0, "A B\n```\n1 2")
+ empty = TableBlock(
+ type="table",
+ index=1,
+ content=[TableBodyBlock(type="table_body", index=1, content="", image_path="images/t.png")],
+ )
+
+ rendered = render_markdown(_middle(_page(0, spatial, empty)))
+
+ assert rendered.startswith("````\nA B\n```\n1 2\n````")
+ assert rendered.endswith("![](images/t.png)")
+
+
+def test_cross_page_table_merges_only_in_default_mode() -> None:
+ """验证续表只在 DEFAULT 跨页合并,FULL 保持分页。"""
+ previous_html = "<table><tr><th>H</th></tr><tr><td>A</td></tr></table>"
+ current_html = "<table><tr><th>H</th></tr><tr><td>B</td></tr></table>"
+ middle = _middle(
+ _page(0, _pdf_table(0, previous_html)),
+ _page(1, _pdf_table(0, current_html, continues_prev=True)),
+ file_suffix="pdf",
+ )
+ original = deepcopy(middle)
+
+ default = render_markdown(middle)
+ full = render_markdown(middle, mode=MarkdownRenderMode.FULL)
+
+ assert default == "\n".join(["| H |", "| --- |", "| A |", "| B |"])
+ assert full.count("| --- |") == 2
+ assert "\n\n---\n\n" in full
+ assert middle == original
+
+
+def test_code_uses_language_and_dynamic_fence() -> None:
+ """验证普通代码使用 guess_lang 和足够长的 fenced block。"""
+ code = CodeBlock(
+ type="code",
+ index=0,
+ sub_type="code",
+ guess_lang="python",
+ content=[CodeBodyBlock(type="code_body", index=0, content="print('x')\n```")],
+ )
+ invalid_language = CodeBlock(
+ type="code",
+ index=1,
+ sub_type="code",
+ guess_lang="python bad",
+ content=[CodeBodyBlock(type="code_body", index=1, content="x")],
+ )
+
+ rendered = render_markdown(_middle(_page(0, code, invalid_language)))
+
+ assert rendered.startswith("````python\nprint('x')\n```\n````")
+ assert rendered.endswith("```txt\nx\n```")
+
+
+def test_algorithm_preserves_whitespace_escapes_html_and_renders_formula() -> None:
+ """验证算法 HTML 同时保留缩进、转义文本并支持相邻公式。"""
+ algorithm = CodeBlock(
+ type="code",
+ index=0,
+ sub_type="algorithm",
+ content=[
+ CodeBodyBlock(
+ type="code_body",
+ index=0,
+ content="if <x>:\n T<sub>queue</sub><sup>2</sup> = <eq>a < b</eq><eq>c</eq>",
+ )
+ ],
+ )
+
+ rendered = render_markdown(_middle(_page(0, algorithm)))
+
+ assert 'class="mineru-algorithm"' in rendered
+ assert "if &lt;x&gt;:\n T<sub>queue</sub><sup>2</sup> = $a &lt; b$ $c$" in rendered
+
+
+def test_image_path_precedes_base64_and_visual_child_order_is_preserved() -> None:
+ """验证图片资源优先级、base URL 和视觉子块原始顺序。"""
+ image = ImageBlock.model_validate(
+ {
+ "type": "image",
+ "index": 0,
+ "content": [
+ {"type": "image_caption", "content": "before"},
+ {
+ "type": "image_body",
+ "index": 0,
+ "content": "description",
+ "image_path": "images/a b.png",
+ "image_base64": "data:image/png;base64,AAAA",
+ },
+ {"type": "image_footnote", "content": "after"},
+ ],
+ }
+ )
+
+ rendered = render_markdown(_middle(_page(0, image)), asset_base_url="https://cdn.example/doc")
+
+ assert rendered.index("before") < rendered.index("https://cdn.example/doc/images/a%20b.png")
+ assert rendered.index("description") < rendered.index("after")
+ assert "data:image" not in rendered
+
+
+def test_chart_without_image_outputs_existing_gfm_content() -> None:
+ """验证无图片图表直接输出已有 GFM 内容。"""
+ chart = ChartBlock(
+ type="chart",
+ index=0,
+ content=[ChartBodyBlock(type="chart_body", index=0, content="| A |\n| --- |\n| 1 |")],
+ )
+
+ assert render_markdown(_middle(_page(0, chart))) == "| A |\n| --- |\n| 1 |"
+
+
+def test_direct_base64_image_fallback() -> None:
+ """验证未外置图片时 Markdown 直接使用 data URI。"""
+ image = ImageBlock(
+ type="image",
+ index=0,
+ content=[
+ ImageBodyBlock(
+ type="image_body",
+ index=0,
+ content="",
+ image_base64="data:image/png;base64,AAAA",
+ )
+ ],
+ )
+
+ assert render_markdown(_middle(_page(0, image))) == "![](data:image/png;base64,AAAA)"
diff --git a/tests/unittest/test_postprocess_pages.py b/tests/unittest/test_postprocess_pages.py
index 061d16cb..2bfa80dd 100644
--- a/tests/unittest/test_postprocess_pages.py
+++ b/tests/unittest/test_postprocess_pages.py
@@ -5,6 +5,7 @@ import pytest
from mineru.backend.postprocess.pages import model_list_to_pages
from mineru.types import (
ChartBlock,
+ DocTitleBlock,
EquationBlock,
ImageBlock,
ListBlock,
@@ -70,7 +71,7 @@ def test_model_list_to_pages_returns_typed_pdf_tree_without_mutating_input() ->
def test_model_list_to_pages_preserves_recursive_office_list_and_index() -> None:
- """验证 Office list/index 任意深度递归对象化,并删除目录 text 的 anchor。"""
+ """验证 Office list/index 任意深度递归对象化,并清理未匹配目录 anchor。"""
model_list = [
[
{
@@ -116,6 +117,73 @@ def test_model_list_to_pages_preserves_recursive_office_list_and_index() -> None
assert "anchor" not in index_block.content[0].content[0].model_fields_set
+def test_model_list_to_pages_maps_index_anchor_to_document_title_type_and_level() -> None:
+ """验证 Office 目录叶子按跨页目标 anchor 继承真实标题类型与层级。"""
+ model_list = [
+ [
+ {
+ "type": "index",
+ "content": [
+ {"type": "text", "content": "Document", "anchor": "doc-anchor"},
+ {
+ "type": "index",
+ "content": [
+ {"type": "text", "content": "Section", "anchor": "section-anchor"},
+ {"type": "text", "content": "Missing", "anchor": "missing-anchor"},
+ ],
+ },
+ ],
+ },
+ ],
+ [
+ {"type": "doc_title", "content": "Document title", "level": 1, "anchor": "doc-anchor"},
+ {
+ "type": "paragraph_title",
+ "content": "Section title",
+ "level": 3,
+ "anchor": "section-anchor",
+ },
+ ],
+ ]
+
+ pages = model_list_to_pages(model_list)
+ index = pages[0].blocks[0]
+ doc_leaf = index.content[0]
+ section_leaf = index.content[1].content[0]
+ missing_leaf = index.content[1].content[1]
+
+ assert isinstance(doc_leaf, DocTitleBlock)
+ assert doc_leaf.level == 1
+ assert doc_leaf.anchor == "doc-anchor"
+ assert doc_leaf.content == "Document"
+ assert isinstance(section_leaf, ParagraphTitleBlock)
+ assert section_leaf.level == 3
+ assert section_leaf.anchor == "section-anchor"
+ assert section_leaf.content == "Section"
+ assert isinstance(missing_leaf, TextBlock)
+ assert "anchor" not in missing_leaf.model_fields_set
+
+
+def test_model_list_to_pages_uses_first_title_for_duplicate_anchor() -> None:
+ """验证重复 anchor 按文档顺序使用首个标题目标。"""
+ model_list = [
+ [
+ {"type": "paragraph_title", "content": "First", "level": 2, "anchor": "same"},
+ {"type": "paragraph_title", "content": "Second", "level": 4, "anchor": "same"},
+ {
+ "type": "index",
+ "content": [{"type": "text", "content": "Entry", "anchor": "same"}],
+ },
+ ]
+ ]
+
+ page = model_list_to_pages(model_list)[0]
+ index = page.blocks[2]
+
+ assert isinstance(index.content[0], ParagraphTitleBlock)
+ assert index.content[0].level == 2
+
+
def test_office_paragraph_numbering_is_document_wide_and_copy_only() -> None:
"""验证 Office 标题跨页编号、显式编号同步和 raw 元数据保留。"""
model_list = [
diff --git a/tests/unittest/test_render_config.py b/tests/unittest/test_render_config.py
new file mode 100644
index 00000000..76d03d62
--- /dev/null
+++ b/tests/unittest/test_render_config.py
@@ -0,0 +1,76 @@
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+from pydantic import ValidationError
+
+from mineru.config import Config, _apply_env_overrides, _load_config
+
+
+def test_render_config_defaults() -> None:
+ """验证 config.yaml 缺省时使用美元公式定界符。"""
+ delimiters = Config().render.latex_delimiters
+
+ assert delimiters.display.left == "$$"
+ assert delimiters.display.right == "$$"
+ assert delimiters.inline.left == "$"
+ assert delimiters.inline.right == "$"
+
+
+def test_render_config_reads_yaml_shape(tmp_path: Path) -> None:
+ """验证 render.latex_delimiters YAML 结构能进入 typed Config。"""
+ config_file = tmp_path / "config.yaml"
+ config_file.write_text(
+ """
+render:
+ latex_delimiters:
+ display:
+ left: '\\['
+ right: '\\]'
+ inline:
+ left: '\\('
+ right: '\\)'
+""".strip(),
+ encoding="utf-8",
+ )
+
+ config = Config(**_load_config(str(config_file)))
+
+ assert config.render.latex_delimiters.display.left == r"\["
+ assert config.render.latex_delimiters.inline.right == r"\)"
+
+
+def test_render_config_supports_environment_overrides(monkeypatch: pytest.MonkeyPatch) -> None:
+ """验证现有环境变量递归覆盖机制可定位 render delimiter。"""
+ prefix = "TEST_MINERU_"
+ monkeypatch.setenv(f"{prefix}RENDER_LATEX_DELIMITERS_INLINE_LEFT", r"\(")
+ monkeypatch.setenv(f"{prefix}RENDER_LATEX_DELIMITERS_INLINE_RIGHT", r"\)")
+
+ config = _apply_env_overrides(Config(), prefix=prefix)
+
+ assert config.render.latex_delimiters.inline.left == r"\("
+ assert config.render.latex_delimiters.inline.right == r"\)"
+
+
[email protected]("side", ["left", "right"])
+def test_render_config_rejects_empty_delimiters(side: str) -> None:
+ """验证任一空定界符都会在 typed config 边界报错。"""
+ pair = {"left": "$", "right": "$"}
+ pair[side] = ""
+
+ with pytest.raises(ValidationError):
+ Config(render={"latex_delimiters": {"inline": pair}})
+
+
+def test_render_config_does_not_read_legacy_root_key() -> None:
+ """验证旧根级 latex-delimiter-config 不影响新 render 配置。"""
+ config = Config.model_validate(
+ {
+ "latex-delimiter-config": {
+ "inline": {"left": "OLD", "right": "OLD"},
+ }
+ }
+ )
+
+ assert config.render.latex_delimiters.inline.left == "$"
diff --git a/tests/unittest/test_render_html_table.py b/tests/unittest/test_render_html_table.py
index 9b385276..2936e6d3 100644
--- a/tests/unittest/test_render_html_table.py
+++ b/tests/unittest/test_render_html_table.py
@@ -1,243 +1,62 @@
-from mineru.render import render_markdown
-from mineru.render.markdown import blocks_to_markdown
-from mineru.render.markdown_table import to_markdown_table
-from mineru.types import Block, BlockType, ContentType, Line, PageInfo, Span
-
-
-def test_table_span_ignores_legacy_html_payload_alias() -> None:
- """表格 span 只接受 content 承载 HTML,不再兼容旧 html 别名。"""
- span = Span.from_dict(
- {
- "type": ContentType.TABLE,
- "bbox": [0.0, 0.0, 10.0, 10.0],
- "html": "<table><tr><td>A</td></tr></table>",
- }
- )
-
- assert span.content == ""
- assert span.to_dict() == {
- "type": ContentType.TABLE,
- "bbox": (0.0, 0.0, 10.0, 10.0),
- }
+from mineru.config import LatexDelimitersConfig
+from mineru.render.utils.markdown_table import format_embedded_html, render_html_table
-def test_to_markdown_table_renders_simple_table() -> None:
- html = """
- <table>
- <tr><th>Name</th><th>Score</th></tr>
- <tr><td>Alice</td><td>90</td></tr>
- <tr><td>Bob</td><td>85</td></tr>
- </table>
- """
+DELIMITERS = LatexDelimitersConfig()
- assert to_markdown_table(html) == "\n".join(
- [
- "| Name | Score |",
- "| --- | --- |",
- "| Alice | 90 |",
- "| Bob | 85 |",
- ]
- )
+def test_render_html_table_uses_first_row_when_th_is_absent() -> None:
+ """验证普通 td 首行可作为 GFM 表头。"""
+ html = "<table><tr><td>A</td><td>B</td></tr><tr><td>1</td><td>2</td></tr></table>"
-def test_to_markdown_table_falls_back_for_colspan_cells() -> None:
- html = """
- <table>
- <tr><th colspan="2">User</th><th>Score</th></tr>
- <tr><td>Alice</td><td>Math</td><td>90</td></tr>
- </table>
- """
-
- assert to_markdown_table(html) == html.strip()
-
-
-def test_to_markdown_table_falls_back_for_rowspan_cells() -> None:
- html = """
- <table>
- <tr><th>Name</th><th>Subject</th><th>Score</th></tr>
- <tr><td rowspan="2">Alice</td><td>Math</td><td>90</td></tr>
- <tr><td>English</td><td>95</td></tr>
- </table>
- """
-
- assert to_markdown_table(html) == html.strip()
+ assert render_html_table(html, asset_base_url="", delimiters=DELIMITERS) == "\n".join(
+ ["| A | B |", "| --- | --- |", "| 1 | 2 |"]
+ )
-def test_to_markdown_table_preserves_simple_inline_markup() -> None:
- html = """
- <table>
- <tr><th>Item</th><th>Note</th></tr>
- <tr><td><code>x|y</code></td><td><a href="https://example.com">docs</a><br>ready</td></tr>
- </table>
- """
+def test_render_html_table_preserves_supported_inline_markup() -> None:
+ """验证简单单元格保留链接、强调、代码、换行和上下标。"""
+ html = (
+ "<table><tr><th>Item</th><th>Note</th></tr>"
+ "<tr><td><code>x|y</code></td>"
+ '<td><a href="https://example.com">docs</a><br><strong>ready</strong><sup>2</sup></td></tr>'
+ "</table>"
+ )
- assert to_markdown_table(html) == "\n".join(
+ assert render_html_table(html, asset_base_url="", delimiters=DELIMITERS) == "\n".join(
[
"| Item | Note |",
"| --- | --- |",
- r"| `x\|y` | [docs](https://example.com)<br>ready |",
+ r"| `x\|y` | [docs](https://example.com)<br>**ready**<sup>2</sup> |",
]
)
-def test_to_markdown_table_falls_back_for_nested_tables() -> None:
- html = """
- <table>
- <tr>
- <td>
- <table><tr><td>nested</td></tr></table>
- </td>
- </tr>
- </table>
- """
-
- assert to_markdown_table(html) == html.strip()
-
-
-def test_to_markdown_table_falls_back_for_complex_block_content() -> None:
- html = """
- <table>
- <tr><th>Item</th><th>Details</th></tr>
- <tr><td>A</td><td><ul><li>one</li><li>two</li></ul></td></tr>
- </table>
- """
-
- assert to_markdown_table(html) == html.strip()
-
-
-def test_blocks_to_markdown_prefers_markdown_table_when_enabled() -> None:
- html = """
- <table>
- <tr><th>Name</th><th>Score</th></tr>
- <tr><td>Alice</td><td>90</td></tr>
- </table>
- """.strip()
- table_block = Block(
- index=0,
- type=BlockType.TABLE,
- bbox=(0.0, 0.0, 10.0, 10.0),
- blocks=[
- Block(
- index=0,
- type=BlockType.TABLE_BODY,
- bbox=(0.0, 0.0, 10.0, 10.0),
- lines=[
- Line(
- bbox=(0.0, 0.0, 10.0, 10.0),
- spans=[Span(type=ContentType.TABLE, bbox=(0.0, 0.0, 10.0, 10.0), content=html)],
- )
- ],
- )
- ],
- )
+def test_render_html_table_falls_back_for_span_attribute_even_when_value_is_one() -> None:
+ """验证只要显式出现 rowspan/colspan 就按复杂 HTML 输出。"""
+ html = '<table><tr><td colspan="1">A</td></tr></table>'
- assert blocks_to_markdown([table_block], prefer_markdown_table=False) == [html]
- assert blocks_to_markdown([table_block], prefer_markdown_table=True) == [
- "\n".join(
- [
- "| Name | Score |",
- "| --- | --- |",
- "| Alice | 90 |",
- ]
- )
- ]
-
-
-def test_blocks_to_markdown_keeps_merged_cell_tables_as_html() -> None:
- html = """
- <table>
- <tr><th colspan="2">User</th><th>Score</th></tr>
- <tr><td>Alice</td><td>Math</td><td>90</td></tr>
- </table>
- """.strip()
- table_block = Block(
- index=0,
- type=BlockType.TABLE,
- bbox=(0.0, 0.0, 10.0, 10.0),
- blocks=[
- Block(
- index=0,
- type=BlockType.TABLE_BODY,
- bbox=(0.0, 0.0, 10.0, 10.0),
- lines=[
- Line(
- bbox=(0.0, 0.0, 10.0, 10.0),
- spans=[Span(type=ContentType.TABLE, bbox=(0.0, 0.0, 10.0, 10.0), content=html)],
- )
- ],
- )
- ],
- )
+ assert render_html_table(html, asset_base_url="", delimiters=DELIMITERS) == html
- assert blocks_to_markdown([table_block], prefer_markdown_table=True) == [html]
-
-
-def test_render_markdown_prefers_markdown_table_when_enabled() -> None:
- html = """
- <table>
- <tr><th>Name</th><th>Score</th></tr>
- <tr><td>Alice</td><td>90</td></tr>
- </table>
- """.strip()
- table_block = Block(
- index=0,
- type=BlockType.TABLE,
- bbox=(0.0, 0.0, 10.0, 10.0),
- blocks=[
- Block(
- index=0,
- type=BlockType.TABLE_BODY,
- bbox=(0.0, 0.0, 10.0, 10.0),
- lines=[
- Line(
- bbox=(0.0, 0.0, 10.0, 10.0),
- spans=[Span(type=ContentType.TABLE, bbox=(0.0, 0.0, 10.0, 10.0), content=html)],
- )
- ],
- )
- ],
- )
- page = PageInfo(page_idx=0, para_blocks=[table_block], _backend="hybrid")
- assert render_markdown([page], prefer_markdown_table=False) == html
- assert render_markdown([page], prefer_markdown_table=True) == "\n".join(
- [
- "| Name | Score |",
- "| --- | --- |",
- "| Alice | 90 |",
- ]
- )
+def test_format_embedded_html_rewrites_relative_images_and_equations() -> None:
+ """验证复杂 HTML 的相对图片和行内公式统一改写。"""
+ html = '<table><tr><td><img src="images/a.png"><eq>x&lt;y</eq></td></tr></table>'
+
+ formatted = format_embedded_html(html, asset_base_url="https://cdn.example/doc", delimiters=DELIMITERS)
+ assert 'src="https://cdn.example/doc/images/a.png"' in formatted
+ assert "$x<y$" in formatted
-def test_blocks_to_markdown_prefers_table_content_without_html_attribute() -> None:
- html = """
- <table>
- <tr><th>Page</th><th>Status</th></tr>
- <tr><td>10</td><td>ready</td></tr>
- </table>
- """.strip()
- table_span = Span(type=ContentType.TABLE, bbox=(0.0, 0.0, 10.0, 10.0), content=html)
- table_block = Block(
- index=0,
- type=BlockType.TABLE,
- bbox=(0.0, 0.0, 10.0, 10.0),
- blocks=[
- Block(
- index=0,
- type=BlockType.TABLE_BODY,
- bbox=(0.0, 0.0, 10.0, 10.0),
- lines=[Line(bbox=(0.0, 0.0, 10.0, 10.0), spans=[table_span])],
- )
- ],
+
+def test_format_embedded_html_keeps_absolute_and_data_images() -> None:
+ """验证已经可访问的绝对图片来源不会重复添加 base URL。"""
+ html = (
+ '<table><tr><td><img src="https://example.com/a.png">'
+ '<img src="data:image/png;base64,AAAA"></td></tr></table>'
)
- assert not hasattr(table_span, "html")
- assert blocks_to_markdown([table_block], prefer_markdown_table=True) == [
- "\n".join(
- [
- "| Page | Status |",
- "| --- | --- |",
- "| 10 | ready |",
- ]
- )
- ]
+ formatted = format_embedded_html(html, asset_base_url="https://cdn.example/doc", delimiters=DELIMITERS)
+
+ assert "https://cdn.example/doc/https://" not in formatted
+ assert 'src="data:image/png;base64,AAAA"' in formatted