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
fix: preserve mixed formula wrapper content
myhloli47c1fcd7c86e
diff --git a/mineru/model/flash/html/document.py b/mineru/model/flash/html/document.pyindex 2c9c61e8..27b9ecf6 100644--- a/mineru/model/flash/html/document.py+++ b/mineru/model/flash/html/document.py@@ -36,7 +36,11 @@ _ACTIVE_TAGS = frozenset("video",})-_FORMULA_CLASS_TOKENS = frozenset({"formula", "katex", "math", "mathjax", "mineru-math", "tex"})+_FORMULA_GENERATOR_CLASS_TOKENS = frozenset({"katex", "mathjax", "mineru-math"})+_GENERIC_FORMULA_CLASS_TOKENS = frozenset({"formula", "math", "tex"})+_MEANINGFUL_FORMULA_SIBLING_TAGS = frozenset(+ {"audio", "br", "canvas", "figure", "hr", "iframe", "image", "img", "object", "svg", "table", "video"}+)_ASCIIMATH_SCRIPT_TYPE_RE = re.compile(r"^math/asciimath(?:\s*;.*)?$", re.IGNORECASE)@@ -174,13 +178,9 @@ def _normalize_formula_sources(root: etree._Element) -> None:for element in list(root.iter()):if not isinstance(element.tag, str) or not _is_attached(root, element):continue- name = local_name(element)classes = frozenset((element.get("class") or "").casefold().split())- is_candidate = (- name == "math"- or is_tex_script(element)- or any((element.get(attribute) or "").strip() for attribute in ("data-mineru-latex", "data-tex", "data-expr"))- or bool(classes & _FORMULA_CLASS_TOKENS)+ is_candidate = _is_formula_carrier(element) or (+ bool(classes & _GENERIC_FORMULA_CLASS_TOKENS) and _formula_wrapper_contains_only_carrier(element))if not is_candidate:continue@@ -188,6 +188,50 @@ def _normalize_formula_sources(root: etree._Element) -> None:_replace_with_formula(element, formula)+def _is_formula_carrier(element: etree._Element) -> bool:+ """判断元素自身是否携带公式来源,而不是仅从任意后代继承。"""+ if local_name(element) == "math" or is_tex_script(element):+ return True+ if any((element.get(attribute) or "").strip() for attribute in ("data-mineru-latex", "data-tex", "data-expr")):+ return True+ classes = frozenset((element.get("class") or "").casefold().split())+ return bool(classes & _FORMULA_GENERATOR_CLASS_TOKENS)+++def _formula_wrapper_contains_only_carrier(element: etree._Element) -> bool:+ """仅允许恰好一个 carrier 且其外没有可见文本或媒体的通用 wrapper 整体折叠。"""+ carriers: list[etree._Element] = []+ for candidate in element.iterdescendants():+ if not isinstance(candidate.tag, str) or not _is_formula_carrier(candidate):+ continue+ if any(ancestor in carriers for ancestor in candidate.iterancestors()):+ continue+ carriers.append(candidate)+ if len(carriers) != 1:+ return False+ carrier = carriers[0]++ def inside_carrier(candidate: etree._Element | None) -> bool:+ """判断节点正文是否位于唯一 carrier 子树内。"""+ return candidate is not None and (+ candidate is carrier or any(ancestor is carrier for ancestor in candidate.iterancestors())+ )++ outside_text = [element.text or ""]+ for candidate in element.iterdescendants():+ if not isinstance(candidate.tag, str):+ if not inside_carrier(candidate.getparent()):+ outside_text.append(candidate.tail or "")+ continue+ if not inside_carrier(candidate):+ outside_text.append(candidate.text or "")+ if local_name(candidate) in _MEANINGFUL_FORMULA_SIBLING_TAGS:+ return False+ if not inside_carrier(candidate.getparent()):+ outside_text.append(candidate.tail or "")+ return not any(value.strip() for value in outside_text)++def _preserve_asciimath_text(root: etree._Element) -> None:"""把暂不支持的 AsciiMath script 转为可见静态文本,避免活动内容清理时丢失。"""for element in list(root.iter()):diff --git a/tests/unittest/test_flash_html.py b/tests/unittest/test_flash_html.pyindex 44f2f35f..074ecd81 100644--- a/tests/unittest/test_flash_html.py+++ b/tests/unittest/test_flash_html.py@@ -439,24 +439,60 @@ def test_html_unsafe_or_malformed_note_urls_do_not_append_notes(href: str) -> Nodef test_html_formula_sources_are_normalized_without_duplicate_katex_text() -> None:- """验证 MathML、KaTeX annotation 与 data-expr 按统一公式协议输出且不重复。"""+ """验证 MathML、公式生成器 wrapper 与 data-expr 按统一公式协议输出且不重复。"""payload = rb"""<html><body><h1>Math</h1><p>Inline<math><semantics><mi>x</mi><annotation encoding="application/x-tex">x+1</annotation></semantics></math><span class="katex"><span class="katex-mathml"><math><semantics><mi>y</mi><annotation encoding="application/x-tex">y^2</annotation></semantics></math></span><span class="katex-html">duplicate visible</span></span>+ <span class="mathjax"><math><semantics><mi>q</mi>+ <annotation encoding="application/x-tex">q_4</annotation></semantics></math>+ <span>mathjax duplicate</span></span><span data-expr="z_3">formula fallback</span></p><div class="mineru-math mineru-math--block">\[w^4\]</div></body></html>"""middle = doc_analyze(payload, file_suffix="html")[0]markdown = render_markdown(middle)- assert "x+1" in markdown and "y^2" in markdown and "z_3" in markdown and "w^4" in markdown+ assert "x+1" in markdown and "y^2" in markdown and "q_4" in markdown and "z_3" in markdown and "w^4" in markdownassert any(block.type == BlockType.EQUATION and block.content == "w^4" for block in middle.pages[0].blocks) # type: ignore[union-attr]assert "duplicate visible" not in markdown+ assert "mathjax duplicate" not in markdownassert "formula fallback" not in markdown+def test_html_generic_formula_class_wrappers_preserve_mixed_content() -> None:+ """验证通用公式 class 只规范化真实 carrier,不吞掉外层说明内容。"""+ payload = b"""<html><body><main>+ <div class="math"><p>Before explanation.</p><math><mi>x</mi></math><p>After explanation.</p></div>+ <div class="formula">Prefix <span><math data-tex="y"></math></span> suffix.</div>+ <div class="tex"><p>Script before.</p><script type="math/tex; mode=display">z</script>+ <p>Script after.</p></div>+ <p>Exclusive before<span class="math math-display"><span><math data-tex="u"></math></span></span>Exclusive after</p>+ <div class="math"><math data-tex="a"></math><math data-tex="b"></math></div></main></body></html>"""++ middle, model = doc_analyze(payload, file_suffix="html")+ raw = [(block["type"], block.get("content")) for block in model.pages[0]]++ assert raw == [+ (BlockType.TEXT, "Before explanation."),+ (BlockType.EQUATION, "x"),+ (BlockType.TEXT, "After explanation."),+ (BlockType.TEXT, "Prefix <eq>y</eq> suffix."),+ (BlockType.TEXT, "Script before."),+ (BlockType.EQUATION, "z"),+ (BlockType.TEXT, "Script after."),+ (BlockType.TEXT, "Exclusive before"),+ (BlockType.EQUATION, "u"),+ (BlockType.TEXT, "Exclusive after"),+ (BlockType.EQUATION, "a"),+ (BlockType.EQUATION, "b"),+ ]+ markdown = render_markdown(middle)+ assert markdown.index("Before explanation.") < markdown.index("$$\nx\n$$") < markdown.index("After explanation.")+ assert markdown.index("Script before.") < markdown.index("$$\nz\n$$") < markdown.index("Script after.")++def test_html_mineru_page_footnote_marker_roundtrips_as_page_footnote() -> None:"""验证 MinerU HTML renderer 的轻量脚注 marker 可恢复统一 page_footnote block。"""payload = b"""<html><body><h1>Footnote</h1>