Skip to content

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

feat: implement visible space markers for ASCII whitespace in Markdown rendering

myhloli8f73eec2b078
diff --git a/docs/next/middle-json/rendering.md b/docs/next/middle-json/rendering.md
index 445a06a6..285e1fd6 100644
--- a/docs/next/middle-json/rendering.md
+++ b/docs/next/middle-json/rendering.md
@@ -49,7 +49,7 @@ text 合并允许跨越任意其他 block,后一个 text 的内容被吸收到
- `list`: 递归缩进,直接使用 content 已内化的有序或无序前缀。
- `index`: 递归输出 GFM 列表;标题叶子使用 anchor 生成内部链接,不当作 heading 输出。
- `equation`: content 非空时输出行间 LaTeX,空 content 回退图片。
-- `image/chart`: 图片优先,识别内容放入折叠 details;无图片时输出已有 HTML/GFM 内容。
+- `image/chart`: 图片优先,识别内容放入折叠 details;chart 的简单 HTML 表格转为 GFM,复杂表格保留 HTML,无图片时直接输出转换后的内容。
- `table`: 简单单层 HTML 转 GFM;合并单元格或不可无损结构保留 HTML;空间投影文本使用动态 fenced block;空 content 回退图片。
- `code`: 使用 `guess_lang` 和动态 fenced block。
- `algorithm`: 使用等宽、`white-space: pre-wrap` 的 HTML div,只把 `<eq>` 转为行内公式。
@@ -61,6 +61,8 @@ text 合并允许跨越任意其他 block,后一个 text 的内容被吸收到
行内 parser 只解释白名单标签,包括 `<eq>`、`<text style>`、
`<hyperlink>/<url>`、`<sup>/<sub>`。未知或损坏标签作为普通文本转义保留。
普通字体样式使用 Markdown;underline、emphasis、上下标和复杂组合使用安全 HTML。
+underline/strikethrough 包裹的 ASCII 空格按 dev 规则转为 `_`/`-` marker;
+整块 marker 会转义首字符,避免被识别为 Markdown 分割线。
LaTeX 定界符来自 `$MINERU_HOME/config.yaml`:
diff --git a/mineru/render/markdown.py b/mineru/render/markdown.py
index 3b8fd9c0..0041579e 100644
--- a/mineru/render/markdown.py
+++ b/mineru/render/markdown.py
@@ -17,7 +17,7 @@ from mineru.render.utils.inline import (
)
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.render.utils.markdown_utils import escape_standalone_marker_rule, escape_text_block_markdown_prefix
from mineru.types import (
RAW_ALGORITHM,
BlockType,
@@ -118,13 +118,14 @@ def _render_planned_block(
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)
+ return escape_standalone_marker_rule(escape_text_block_markdown_prefix(content))
if isinstance(block, RefTextBlock):
- return render_inline_content(block.content, delimiters)
+ return escape_standalone_marker_rule(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))
+ 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):
@@ -180,6 +181,7 @@ def _render_list(block: ListBlock, delimiters: LatexDelimitersConfig, depth: int
item = render_inline_content(child.content, delimiters)
if not item:
continue
+ item = escape_standalone_marker_rule(item)
indent = " " * depth
lines.extend(f"{indent}{line}" for line in item.splitlines() or [item])
return "\n".join(lines)
@@ -238,7 +240,7 @@ def _render_image_block(
asset_base_url=asset_base_url,
)
elif isinstance(child, ImageAnnotationBlock):
- body = render_inline_content(child.content, delimiters)
+ body = escape_standalone_marker_rule(render_inline_content(child.content, delimiters))
else:
raise TypeError(f"Unsupported image child: {type(child).__name__}")
if body:
@@ -255,14 +257,14 @@ def _render_chart_block(
parts: list[str] = []
for child in block.content:
if isinstance(child, ChartBodyBlock):
- body = _render_media_body(
+ body = _render_chart_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)
+ body = escape_standalone_marker_rule(render_inline_content(child.content, delimiters))
else:
raise TypeError(f"Unsupported chart child: {type(child).__name__}")
if body:
@@ -271,7 +273,7 @@ def _render_chart_block(
def _render_media_body(
- block: ImageBodyBlock | ChartBodyBlock,
+ block: ImageBodyBlock,
*,
summary: str,
delimiters: LatexDelimitersConfig,
@@ -283,23 +285,59 @@ def _render_media_body(
if source:
parts = [build_markdown_image(source)]
if content:
- parts.append(_render_details(content, summary, delimiters, asset_base_url))
+ normalized = format_embedded_html(
+ content,
+ asset_base_url=asset_base_url,
+ delimiters=delimiters,
+ )
+ parts.append(_render_details(normalized, summary))
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,
+def _render_chart_body(
+ block: ChartBodyBlock,
+ *,
summary: str,
delimiters: LatexDelimitersConfig,
asset_base_url: str,
) -> str:
- """构造保留视觉识别内容的折叠 HTML 详情块。"""
- normalized = format_embedded_html(content.strip(), asset_base_url=asset_base_url, delimiters=delimiters)
+ """渲染 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{normalized}\n</details>"
+ return f"<details>\n<summary>{safe_summary}</summary>\n\n{content.strip()}\n</details>"
def _render_table_block(
@@ -313,7 +351,7 @@ def _render_table_block(
if isinstance(child, TableBodyBlock):
body = _render_table_body(child, delimiters, asset_base_url)
elif isinstance(child, TableAnnotationBlock):
- body = render_inline_content(child.content, delimiters)
+ body = escape_standalone_marker_rule(render_inline_content(child.content, delimiters))
else:
raise TypeError(f"Unsupported table child: {type(child).__name__}")
if body:
@@ -352,7 +390,7 @@ def _render_code_block(block: CodeBlock, delimiters: LatexDelimitersConfig) -> s
else:
raise ValueError(f"Unsupported code subtype: {block.sub_type}")
elif isinstance(child, CodeAnnotationBlock):
- body = render_inline_content(child.content, delimiters)
+ body = escape_standalone_marker_rule(render_inline_content(child.content, delimiters))
else:
raise TypeError(f"Unsupported code child: {type(child).__name__}")
if body:
diff --git a/mineru/render/utils/inline.py b/mineru/render/utils/inline.py
index 06a36a29..cfd81bb7 100644
--- a/mineru/render/utils/inline.py
+++ b/mineru/render/utils/inline.py
@@ -302,11 +302,70 @@ 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")
@@ -315,13 +374,13 @@ def _apply_styles(content: str, plain_text: str, styles: tuple[str, ...]) -> str
style_key = frozenset(styles)
wrapper = _SIMPLE_STYLE_WRAPPERS.get(style_key)
- if wrapper is not None:
+ 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)
diff --git a/mineru/render/utils/markdown_utils.py b/mineru/render/utils/markdown_utils.py
index 471f2b21..bc95f625 100644
--- a/mineru/render/utils/markdown_utils.py
+++ b/mineru/render/utils/markdown_utils.py
@@ -42,3 +42,10 @@ def escape_text_block_markdown_prefix(content: str) -> str:
marker_start = match.start("marker")
return f"{content[:marker_start]}\\{content[marker_start:]}"
+
+
+def escape_standalone_marker_rule(content: str) -> str:
+ """转义独立的下划线或短横线序列,避免被 Markdown 识别为分割线。"""
+ if content and (set(content) == {"_"} or set(content) == {"-"}):
+ return f"\\{content}"
+ return content
diff --git a/tests/unittest/test_markdown_render.py b/tests/unittest/test_markdown_render.py
index e83a471a..adf0185c 100644
--- a/tests/unittest/test_markdown_render.py
+++ b/tests/unittest/test_markdown_render.py
@@ -188,7 +188,61 @@ def test_inline_rich_text_unknown_tags_and_visible_spaces() -> None:
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
+ assert rendered.endswith("<sup>2</sup>__")
+
+
+ ("style", "expected"),
+ [
+ ("underline", "A___B"),
+ ("strikethrough", "A---B"),
+ ("underline,strikethrough", "A<s>___</s>B"),
+ ("bold,underline", "A<strong>___</strong>B"),
+ ],
+)
+def test_visible_style_ascii_spaces_use_dev_markers(style: str, expected: str) -> None:
+ """验证纯 ASCII 样式空格使用 dev 的下划线或短横线 marker。"""
+ content = f'A<text style="{style}"> </text>B'
+
+ assert render_markdown(_middle(_page(0, TextBlock(type="text", index=0, content=content)))) == expected
+
+
+ ("style", "expected"),
+ [
+ ("underline", "<u>___广东__</u>"),
+ ("strikethrough", "~~---广东--~~"),
+ ("underline,strikethrough", "<s><u>___广东__</u></s>"),
+ ],
+)
+def test_visible_style_edge_spaces_use_dev_markers(style: str, expected: str) -> None:
+ """验证非空样式文本只替换首尾 ASCII 空格。"""
+ content = f'<text style="{style}"> 广东 </text>'
+
+ assert render_markdown(_middle(_page(0, TextBlock(type="text", index=0, content=content)))) == expected
+
+
+ ("style", "expected"),
+ [
+ ("underline", r"\___"),
+ ("strikethrough", r"\---"),
+ ],
+)
+def test_standalone_visible_space_markers_are_escaped(style: str, expected: str) -> None:
+ """验证整块 marker 会转义首字符,避免被当作 Markdown 分割线。"""
+ content = f'<text style="{style}"> </text>'
+
+ assert render_markdown(_middle(_page(0, TextBlock(type="text", index=0, content=content)))) == expected
+
+
+def test_emphasis_only_spaces_keep_existing_html_behavior() -> None:
+ """验证 emphasis-only 空格不进入 underline/strikethrough marker 规则。"""
+ content = '<text style="emphasis"> </text>'
+
+ rendered = render_markdown(_middle(_page(0, TextBlock(type="text", index=0, content=content))))
+
+ assert "&nbsp;&nbsp;" in rendered
def test_text_block_escapes_markdown_prefix_and_malformed_tag() -> None:
@@ -413,6 +467,66 @@ def test_chart_without_image_outputs_existing_gfm_content() -> None:
assert render_markdown(_middle(_page(0, chart))) == "| A |\n| --- |\n| 1 |"
+def test_chart_without_image_converts_simple_html_table_to_gfm() -> None:
+ """验证无图片 chart 的简单 HTML table 直接转换为 GFM。"""
+ chart = ChartBlock(
+ type="chart",
+ index=0,
+ content=[
+ ChartBodyBlock(
+ type="chart_body",
+ index=0,
+ content="<table><tr><th>A</th></tr><tr><td>1</td></tr></table>",
+ )
+ ],
+ )
+
+ assert render_markdown(_middle(_page(0, chart))) == "| A |\n| --- |\n| 1 |"
+
+
+def test_chart_with_image_places_converted_gfm_in_details() -> None:
+ """验证有图片 chart 保留图片,并把简单表格 GFM 放入 details。"""
+ chart = ChartBlock(
+ type="chart",
+ index=0,
+ sub_type="line chart",
+ content=[
+ ChartBodyBlock(
+ type="chart_body",
+ index=0,
+ content="<table><tr><th>A</th></tr><tr><td>1</td></tr></table>",
+ image_path="images/chart.png",
+ )
+ ],
+ )
+
+ rendered = render_markdown(_middle(_page(0, chart)))
+
+ assert rendered.startswith("![](images/chart.png)\n\n<details>")
+ assert "| A |\n| --- |\n| 1 |" in rendered
+ assert "<table>" not in rendered
+
+
+def test_chart_complex_html_table_remains_html() -> None:
+ """验证 chart 的复杂 HTML table 不会被有损转换为 GFM。"""
+ chart = ChartBlock(
+ type="chart",
+ index=0,
+ content=[
+ ChartBodyBlock(
+ type="chart_body",
+ index=0,
+ content='<table><tr><td colspan="2">A</td></tr></table>',
+ )
+ ],
+ )
+
+ rendered = render_markdown(_middle(_page(0, chart)))
+
+ assert rendered.startswith("<table>")
+ assert 'colspan="2"' in rendered
+
+
def test_direct_base64_image_fallback() -> None:
"""验证未外置图片时 Markdown 直接使用 data URI。"""
image = ImageBlock(