Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.
Python ai4sciencedocument-analysisdocxextract-datalayout-analysisocrparserpdfpdf-converterpdf-extractor-llmpdf-extractor-pretrainpdf-extractor-ragpdf-parserpptxpythonxlsx
feat: enhance algorithm rendering with HTML inline syntax and support for additional styles
myhloli5b8f6cf6f277
diff --git a/mineru/render/_internal/markdown/blocks.py b/mineru/render/_internal/markdown/blocks.pyindex b3554b56..96f34a8f 100644--- a/mineru/render/_internal/markdown/blocks.py+++ b/mineru/render/_internal/markdown/blocks.py@@ -15,6 +15,7 @@ from .escaping import escape_standalone_marker_rule, escape_text_block_markdown_from .inline import (render_inline_content,render_inline_spans,+ render_inline_spans_in_html_context,render_internal_link,render_joined_inline_contents,)@@ -466,7 +467,7 @@ def render_visual_body_content(if isinstance(block, ChartBlock) and isinstance(child, ChartBodyBlock):return _render_chart_content(child.content, delimiters, asset_base_url)if isinstance(block, CodeBlock) and isinstance(child, (CodeBodyBlock, AlgorithmBodyBlock)):- return _render_code_body(block, child, delimiters)+ return _render_code_semantic_content(block, child, delimiters)raise ValueError(f"Missing visual body: {block.type}")@@ -518,6 +519,19 @@ def _render_code_body(delimiters: LatexDelimitersConfig,) -> str:"""依据父块 subtype 渲染代码或算法 body。"""+ if block.sub_type == RAW_ALGORITHM:+ if not isinstance(child, AlgorithmBodyBlock):+ raise TypeError("algorithm subtype requires AlgorithmBodyBlock")+ return _render_algorithm_html(child.content, delimiters)+ return _render_code_semantic_content(block, child, delimiters)+++def _render_code_semantic_content(+ block: CodeBlock,+ child: CodeBodyBlock | AlgorithmBodyBlock,+ delimiters: LatexDelimitersConfig,+) -> str:+ """把代码或算法 body 渲染为 Structured Content 可消费的类 Markdown 字符串。"""if block.sub_type == BlockType.CODE:if not isinstance(child, CodeBodyBlock):raise TypeError("code subtype requires CodeBodyBlock")@@ -525,7 +539,7 @@ def _render_code_body(if block.sub_type == RAW_ALGORITHM:if not isinstance(child, AlgorithmBodyBlock):raise TypeError("algorithm subtype requires AlgorithmBodyBlock")- return _render_algorithm_html(child.content, delimiters)+ return _render_algorithm_markdown(child.content, delimiters)raise ValueError(f"Unsupported code subtype: {block.sub_type}")@@ -554,7 +568,7 @@ def _render_algorithm_html(content: list[InlineSpan], delimiters: LatexDelimitercurrent_equation = str(span.type) == "equation_inline"if previous_equation and current_equation:parts.append(" ")- parts.append(render_inline_spans([span], delimiters))+ parts.append(render_inline_spans_in_html_context([span], delimiters))previous_equation = current_equationbody = "".join(parts)if not body.strip():@@ -562,6 +576,19 @@ def _render_algorithm_html(content: list[InlineSpan], delimiters: LatexDelimiterreturn f'<div class="mineru-algorithm" style="white-space: pre-wrap; font-family:monospace;">\n{body}\n</div>'+def _render_algorithm_markdown(content: list[InlineSpan], delimiters: LatexDelimitersConfig) -> str:+ """把算法 Span 渲染为类 Markdown 内容,并分隔相邻行内公式。"""+ parts: list[str] = []+ previous_equation = False+ for span in content:+ current_equation = str(span.type) == "equation_inline"+ if previous_equation and current_equation:+ parts.append(" ")+ parts.append(render_inline_spans([span], delimiters))+ previous_equation = current_equation+ return "".join(parts)++def _join_visual_parts(parts: list[str]) -> str:"""使用安全空行连接同一视觉父块中的有序子块。"""return "\n\n".join(part.strip("\n") for part in parts if part and part.strip())diff --git a/mineru/render/_internal/markdown/inline.py b/mineru/render/_internal/markdown/inline.pyindex 4802af85..8fac0e6d 100644--- a/mineru/render/_internal/markdown/inline.py+++ b/mineru/render/_internal/markdown/inline.py@@ -39,6 +39,11 @@ def render_inline_spans(spans: list[InlineSpan], delimiters: LatexDelimitersConfreturn "".join(_render_inline_span(span, delimiters) for span in spans)+def render_inline_spans_in_html_context(spans: list[InlineSpan], delimiters: LatexDelimitersConfig) -> str:+ """把 Markdown raw HTML 容器内的 Span 全部序列化为安全 HTML 行内语法。"""+ return "".join(_render_inline_span_in_html_context(span, delimiters) for span in spans)++def _render_inline_span(span: InlineSpan, delimiters: LatexDelimitersConfig) -> str:"""渲染单个结构化行内 Span。"""if isinstance(span, TextSpan):@@ -54,6 +59,20 @@ def _render_inline_span(span: InlineSpan, delimiters: LatexDelimitersConfig) ->raise TypeError(f"Unsupported inline span: {type(span).__name__}")+def _render_inline_span_in_html_context(span: InlineSpan, delimiters: LatexDelimitersConfig) -> str:+ """渲染一个嵌入 Markdown raw HTML block 的结构化行内 Span。"""+ if isinstance(span, TextSpan):+ return _apply_html_styles(html.escape(span.content, quote=False), span.styles)+ if isinstance(span, CodeInlineSpan):+ return f"<code>{html.escape(span.content, quote=False)}</code>"+ if isinstance(span, EquationInlineSpan):+ return html.escape(f"{delimiters.inline.left}{span.content}{delimiters.inline.right}", quote=False)+ if isinstance(span, HyperlinkSpan):+ label = render_inline_spans_in_html_context(list(span.content), delimiters)+ return _render_link(label, span.url, True)+ raise TypeError(f"Unsupported inline span: {type(span).__name__}")++def _render_inline_code(content: str) -> str:"""选择长于内容中反引号游程的 fence,稳定输出 Markdown 行内代码。"""normalized = content.replace("\r\n", " ").replace("\r", " ").replace("\n", " ")@@ -226,6 +245,7 @@ def _escape_markdown_link_label(label: str) -> str:__all__ = ["render_inline_content","render_inline_spans",+ "render_inline_spans_in_html_context","render_internal_link","render_joined_inline_contents",]diff --git a/tests/unittest/test_html_render.py b/tests/unittest/test_html_render.pyindex ddfe9a43..7ffa1ef7 100644--- a/tests/unittest/test_html_render.py+++ b/tests/unittest/test_html_render.py@@ -761,6 +761,11 @@ def test_chart_gfm_details_code_prism_and_algorithm_html() -> None:index=2,content=[{"type": "text", "content": "if a < b:\n T"},+ {"type": "text", "content": "bold", "styles": ["bold"]},+ {"type": "text", "content": "italic", "styles": ["italic"]},+ {"type": "text", "content": "strike", "styles": ["strikethrough"]},+ {"type": "text", "content": "under", "styles": ["underline"]},+ {"type": "text", "content": "dot", "styles": ["emphasis"]},{"type": "text", "content": "q", "styles": ["subscript"]},{"type": "text", "content": " = "},{"type": "equation_inline", "content": "x"},@@ -782,11 +787,19 @@ def test_chart_gfm_details_code_prism_and_algorithm_html() -> None:assert "sha384-zLRFO4dw" in result and "sha384-Uq05+JLk" in resultalgorithm_html = soup.select_one(".mineru-algorithm")assert "if a < b:" in algorithm_html.get_text()+ assert algorithm_html.select_one("strong").get_text() == "bold"+ assert algorithm_html.select_one("em").get_text() == "italic"+ assert algorithm_html.select_one("s").get_text() == "strike"+ assert algorithm_html.select_one("u").get_text() == "under"+ assert algorithm_html.select_one(".mineru-text-emphasis").get_text() == "dot"assert algorithm_html.select_one("sub").get_text() == "q"assert len(algorithm_html.select(".mineru-math")) == 2assert r"\(x\) \(y\)" in algorithm_html.get_text()assert "<br" not in str(algorithm_html)assert "if a < b:\n " in str(algorithm_html)+ assert "**bold**" not in str(algorithm_html)+ assert "*italic*" not in str(algorithm_html)+ assert "~~strike~~" not in str(algorithm_html)@pytest.mark.parametrize("guess_lang", ["python bad/../../x", "constructor", "prototype", "__proto__"])diff --git a/tests/unittest/test_markdown_render.py b/tests/unittest/test_markdown_render.pyindex f42dd827..b6091888 100644--- a/tests/unittest/test_markdown_render.py+++ b/tests/unittest/test_markdown_render.py@@ -769,7 +769,7 @@ def test_code_uses_language_and_dynamic_fence() -> None:def test_algorithm_preserves_whitespace_comparisons_scripts_and_formula() -> None:- """验证算法 HTML 原样保留缩进、比较符、上下标并支持相邻公式。"""+ """验证算法 raw HTML 使用 HTML 行内语法并保留缩进与相邻公式。"""algorithm = CodeBlock(type="code",index=0,@@ -779,9 +779,27 @@ def test_algorithm_preserves_whitespace_comparisons_scripts_and_formula() -> Nontype="algorithm_body",index=0,content=[- {"type": "text", "content": "if a < b and c > d:\n T"},- {"type": "text", "content": "queue", "styles": ["subscript"]},+ {"type": "text", "content": "if a < b and c * d:\n "},+ {"type": "text", "content": "bold", "styles": ["bold"]},+ {"type": "text", "content": " / "},+ {"type": "text", "content": "italic", "styles": ["italic"]},+ {"type": "text", "content": " / "},+ {"type": "text", "content": "strike", "styles": ["strikethrough"]},+ {"type": "text", "content": " / "},+ {"type": "text", "content": "under", "styles": ["underline"]},+ {"type": "text", "content": " / "},+ {"type": "text", "content": "dot", "styles": ["emphasis"]},+ {"type": "text", "content": " "},+ {"type": "text", "content": "q", "styles": ["subscript"]},{"type": "text", "content": "2", "styles": ["superscript"]},+ {"type": "text", "content": " "},+ {"type": "code_inline", "content": "x * y"},+ {"type": "text", "content": " "},+ {+ "type": "hyperlink",+ "url": "https://example.com/a b",+ "content": [{"type": "text", "content": "link", "styles": ["bold"]}],+ },{"type": "text", "content": " = "},{"type": "equation_inline", "content": "a < b"},{"type": "equation_inline", "content": "c > d"},@@ -793,9 +811,16 @@ def test_algorithm_preserves_whitespace_comparisons_scripts_and_formula() -> Nonrendered = render_markdown(_middle(_page(0, algorithm)))assert 'class="mineru-algorithm"' in rendered- assert "if a < b and c > d:\n T<sub>queue</sub><sup>2</sup> = $a < b$ $c > d$" in rendered- assert "<" not in rendered- assert ">" not in rendered+ assert (+ "if a < b and c * d:\n <strong>bold</strong> / <em>italic</em> / <s>strike</s> / "+ '<u>under</u> / <span style="text-emphasis: dot; text-emphasis-position: under;">dot</span> '+ '<sub>q</sub><sup>2</sup> <code>x * y</code> <a href="https://example.com/a b"><strong>link</strong></a> '+ "= $a < b$ $c > d$"+ ) in rendered+ assert "**bold**" not in rendered+ assert "*italic*" not in rendered+ assert "~~strike~~" not in rendered+ assert r"\*" not in rendereddef test_image_path_precedes_base64_and_visual_child_order_is_preserved() -> None:diff --git a/tests/unittest/test_structured_content_render.py b/tests/unittest/test_structured_content_render.pyindex a8272161..bd61bec6 100644--- a/tests/unittest/test_structured_content_render.py+++ b/tests/unittest/test_structured_content_render.py@@ -9,6 +9,7 @@ import pytestfrom mineru.config import Configfrom mineru.render import render_markdown, render_structured_contentfrom mineru.types import (+ AlgorithmBodyBlock,ChartAnnotationBlock,ChartBlock,ChartBodyBlock,@@ -190,6 +191,49 @@ def test_structured_content_flattens_recursive_list_index_and_code_metadata() ->_assert_output_field_contract(blocks)+def test_structured_content_renders_algorithm_as_markdown_like_content() -> None:+ """验证算法 content 使用简单 Markdown 样式并为复杂样式降级到 HTML。"""+ algorithm = CodeBlock(+ type="code",+ index=0,+ sub_type="algorithm",+ content=[+ AlgorithmBodyBlock(+ type="algorithm_body",+ index=0,+ content=[+ {"type": "text", "content": "if x:\n "},+ {"type": "text", "content": "bold", "styles": ["bold"]},+ {"type": "text", "content": " / "},+ {"type": "text", "content": "italic", "styles": ["italic"]},+ {"type": "text", "content": " / "},+ {"type": "text", "content": "strike", "styles": ["strikethrough"]},+ {"type": "text", "content": " / "},+ {"type": "text", "content": "under", "styles": ["underline"]},+ {"type": "text", "content": " / "},+ {"type": "text", "content": "dot", "styles": ["emphasis"]},+ {"type": "text", "content": " "},+ {"type": "text", "content": "q", "styles": ["subscript"]},+ {"type": "text", "content": "2", "styles": ["superscript"]},+ {"type": "text", "content": " = "},+ {"type": "equation_inline", "content": "x"},+ {"type": "equation_inline", "content": "y"},+ ],+ )+ ],+ )++ output = render_structured_content(_middle(_page(0, algorithm)))["pages"][0]["blocks"][0]++ assert output["content"] == (+ "if x:\n **bold** / *italic* / ~~strike~~ / <u>under</u> / "+ '<span style="text-emphasis: dot; text-emphasis-position: under;">dot</span> '+ "<sub>q</sub><sup>2</sup> = $x$ $y$"+ )+ assert "mineru-algorithm" not in output["content"]+ _assert_output_field_contract(output)++def test_structured_content_sorts_visual_annotations_and_selects_image_source() -> None:"""验证视觉说明稳定排序、空项保留及图片 path 优先规则。"""image = ImageBlock.model_validate(