Skip to content

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

fix: handle legacy HTML names and figure captions

myhloli1d75bcf04330
diff --git a/mineru/model/flash/_shared/markup/formula.py b/mineru/model/flash/_shared/markup/formula.py
index 146fe094..c3aecc9e 100644
--- a/mineru/model/flash/_shared/markup/formula.py
+++ b/mineru/model/flash/_shared/markup/formula.py
@@ -10,6 +10,7 @@ from typing import Literal, TypeAlias
from lxml import etree # type: ignore[reportMissingImports]
from ..mathml import mathml_to_latex
+from ..names import local_name
FormulaDisplay: TypeAlias = Literal["inline", "block"]
@@ -111,10 +112,10 @@ def extract_formula(element: etree._Element) -> FormulaExtraction | None:
if latex := _mathml_alttext(element):
return FormulaExtraction(latex, display, "mathml_alttext")
- name = _local_name(element)
+ name = local_name(element)
if name != "math":
math_element = next(
- (child for child in element.iterdescendants() if isinstance(child.tag, str) and _local_name(child) == "math"),
+ (child for child in element.iterdescendants() if isinstance(child.tag, str) and local_name(child) == "math"),
None,
)
if math_element is not None and (latex := _presentation_mathml(math_element)):
@@ -145,7 +146,7 @@ def strip_formula_delimiters(value: str) -> str:
def is_tex_script(element: etree._Element) -> bool:
"""判断元素是否是受支持的静态 TeX/LaTeX script carrier。"""
- return _local_name(element) == "script" and _MATH_SCRIPT_TYPE_RE.fullmatch((element.get("type") or "").strip()) is not None
+ return local_name(element) == "script" and _MATH_SCRIPT_TYPE_RE.fullmatch((element.get("type") or "").strip()) is not None
def _normalized_attribute(element: etree._Element, name: str) -> str | None:
@@ -166,7 +167,7 @@ def _tex_annotation(element: etree._Element) -> str | None:
"""返回节点子树中首个受支持 TeX annotation。"""
candidates = [element, *element.iterdescendants()]
for candidate in candidates:
- if not isinstance(candidate.tag, str) or _local_name(candidate) != "annotation":
+ if not isinstance(candidate.tag, str) or local_name(candidate) != "annotation":
continue
encoding = (candidate.get("encoding") or "").strip().casefold()
if encoding not in _TEX_ANNOTATION_ENCODINGS:
@@ -203,7 +204,7 @@ def _data_formula(element: etree._Element) -> str | None:
def _mathml_alttext(element: etree._Element) -> str | None:
"""返回首个 MathML alttext 中声明的 LaTeX。"""
for candidate in [element, *element.iterdescendants()]:
- if not isinstance(candidate.tag, str) or _local_name(candidate) != "math":
+ if not isinstance(candidate.tag, str) or local_name(candidate) != "math":
continue
if latex := _normalized_attribute(candidate, "alttext"):
return latex
@@ -221,12 +222,12 @@ def _presentation_mathml(element: etree._Element) -> str | None:
def _is_supported_presentation_mathml(element: etree._Element) -> bool:
"""拒绝未知节点和畸形固定元数结构,避免把普通 XML 文本冒充为 LaTeX。"""
- if _local_name(element) != "math":
+ if local_name(element) != "math":
return False
for candidate in [element, *element.iterdescendants()]:
if not isinstance(candidate.tag, str):
continue
- name = _local_name(candidate)
+ name = local_name(candidate)
if name not in _PRESENTATION_MATHML_TAGS:
return False
children = [child for child in candidate if isinstance(child.tag, str)]
@@ -234,7 +235,7 @@ def _is_supported_presentation_mathml(element: etree._Element) -> bool:
return False
if name in {"mi", "mn", "mo", "mtext", "mspace"} and children:
return False
- if name == "semantics" and (not children or _local_name(children[0]) in {"annotation", "annotation-xml"}):
+ if name == "semantics" and (not children or local_name(children[0]) in {"annotation", "annotation-xml"}):
return False
return True
@@ -261,11 +262,6 @@ def _script_display(element: etree._Element, default: FormulaDisplay) -> Formula
return default
-def _local_name(element: etree._Element) -> str:
- """返回不含命名空间的小写本地标签名。"""
- return etree.QName(element).localname.casefold()
-
-
def _class_tokens(element: etree._Element) -> frozenset[str]:
"""返回不做任意 substring 匹配的完整 class token。"""
return frozenset((element.get("class") or "").casefold().split())
diff --git a/mineru/model/flash/_shared/markup/projector.py b/mineru/model/flash/_shared/markup/projector.py
index 723c9d59..2f4453af 100644
--- a/mineru/model/flash/_shared/markup/projector.py
+++ b/mineru/model/flash/_shared/markup/projector.py
@@ -12,6 +12,7 @@ from lxml import etree # type: ignore[reportMissingImports]
from .....types import RAW_ALGORITHM, BlockType, VISUAL_TYPE_MAPPING
from ..hyperlink import render_inline_hyperlink
+from ..names import local_name
from .formula import FormulaExtraction, extract_formula
from .styles import MarkupStylesheet, TextStyle
@@ -102,11 +103,6 @@ _LIST_PAGE_BLOCK_TAGS = frozenset({"figure", "image", "img", "pre", "svg", "tabl
_InlineProjectionSegment: TypeAlias = str | dict[str, object]
-def local_name(element: etree._Element) -> str:
- """返回元素不含命名空间的小写本地名。"""
- return etree.QName(element).localname.casefold()
-
-
def clean_text_node(value: str | None) -> str:
"""折叠普通标记文档文本节点中的排版空白。"""
return _WHITESPACE_RE.sub(" ", value) if value else ""
@@ -560,7 +556,7 @@ class MarkupProjector:
]
annotation_elements = {child for child, _ in annotations}
mineru_figure = "mineru-figure" in (element.get("class") or "").casefold().split()
- blocks = self._parse_figure_contents(
+ blocks, visual_blocks_by_child = self._parse_figure_contents(
element,
style,
visibility_hidden,
@@ -568,19 +564,22 @@ class MarkupProjector:
emit_alt_caption=not mineru_figure and not annotations,
)
- visual_types = {
- _raw_visual_type(block.get("type")) for block in blocks if _raw_visual_type(block.get("type")) is not None
- }
- visual_type = next(iter(visual_types)) if len(visual_types) == 1 else None
- annotation_blocks: list[dict[str, object]] = []
+ annotations_by_visual: dict[int, list[dict[str, object]]] = {}
+ unbound_annotations: list[dict[str, object]] = []
for annotation, kind in annotations:
resolved = self.stylesheet.resolve(annotation, style, visibility_hidden)
if resolved.subtree_hidden:
continue
content, extras = self._render_inline_children(annotation, resolved.text, resolved.visibility_hidden)
- annotation_blocks.extend(extras)
+ target = self._figure_annotation_target(annotation, element, visual_blocks_by_child)
+ annotation_blocks = list(extras)
if not content.strip():
+ if target is not None:
+ annotations_by_visual.setdefault(id(target), []).extend(annotation_blocks)
+ else:
+ unbound_annotations.extend(annotation_blocks)
continue
+ visual_type = _raw_visual_type(target.get("type")) if target is not None else None
if visual_type is not None:
annotation_blocks.append(
{
@@ -590,15 +589,17 @@ class MarkupProjector:
)
else:
annotation_blocks.append({"type": BlockType.TEXT, "content": content.strip()})
- if visual_type is None or not annotation_blocks:
- blocks.extend(annotation_blocks)
- return blocks
-
- visual_positions = [index for index, block in enumerate(blocks) if _raw_visual_type(block.get("type")) == visual_type]
- assert visual_positions
- insert_at = visual_positions[-1] + 1
- blocks[insert_at:insert_at] = annotation_blocks
- return blocks
+ if target is not None and visual_type is not None:
+ annotations_by_visual.setdefault(id(target), []).extend(annotation_blocks)
+ else:
+ unbound_annotations.extend(annotation_blocks)
+
+ output: list[dict[str, object]] = []
+ for block in blocks:
+ output.append(block)
+ output.extend(annotations_by_visual.get(id(block), ()))
+ output.extend(unbound_annotations)
+ return output
def _parse_figure_contents(
self,
@@ -608,9 +609,10 @@ class MarkupProjector:
*,
annotation_elements: set[etree._Element],
emit_alt_caption: bool,
- ) -> list[dict[str, object]]:
+ ) -> tuple[list[dict[str, object]], dict[etree._Element, list[dict[str, object]]]]:
"""按 DOM 顺序缓冲 figure 文本,并在 visual extras 前后切分正文 block。"""
blocks: list[dict[str, object]] = []
+ visual_blocks_by_child: dict[etree._Element, list[dict[str, object]]] = {}
inline_parts: list[str] = [] if visibility_hidden else [self._render_text(element.text, style)]
def flush_inline() -> None:
@@ -631,6 +633,7 @@ class MarkupProjector:
inline_parts.append(self._render_text(child.tail, style))
continue
+ first_child_block = len(blocks)
name = local_name(child)
if name in {"img", "image"}:
flush_inline()
@@ -649,8 +652,28 @@ class MarkupProjector:
blocks.append(segment)
if not visibility_hidden:
inline_parts.append(self._render_text(child.tail, style))
+ child_visuals = [block for block in blocks[first_child_block:] if _raw_visual_type(block.get("type")) is not None]
+ if child_visuals:
+ visual_blocks_by_child[child] = child_visuals
flush_inline()
- return blocks
+ return blocks, visual_blocks_by_child
+
+ @staticmethod
+ def _figure_annotation_target(
+ annotation: etree._Element,
+ figure: etree._Element,
+ visual_blocks_by_child: dict[etree._Element, list[dict[str, object]]],
+ ) -> dict[str, object] | None:
+ """把 annotation 绑定到最近前序 visual;没有前序时使用最近后序 visual。"""
+ children = [child for child in figure if isinstance(child.tag, str)]
+ position = children.index(annotation)
+ for child in reversed(children[:position]):
+ if visuals := visual_blocks_by_child.get(child):
+ return visuals[-1]
+ for child in children[position + 1 :]:
+ if visuals := visual_blocks_by_child.get(child):
+ return visuals[0]
+ return None
def _has_contextual_visual_annotation(self, element: etree._Element) -> bool:
"""仅在直属完整 token annotation 与 visual 后代并存时启用非标准容器解析。"""
diff --git a/mineru/model/flash/_shared/markup/styles.py b/mineru/model/flash/_shared/markup/styles.py
index 2d6c158a..0b7fa5ce 100644
--- a/mineru/model/flash/_shared/markup/styles.py
+++ b/mineru/model/flash/_shared/markup/styles.py
@@ -8,6 +8,8 @@ from dataclasses import dataclass, field
from lxml import etree # type: ignore[reportMissingImports]
+from ..names import local_name
+
_CSS_COMMENT_RE = re.compile(r"/\*.*?\*/", re.DOTALL)
_CSS_IMPORTANT_RE = re.compile(r"!\s*important\s*$", re.IGNORECASE)
@@ -132,11 +134,6 @@ class _ParsedDeclarations:
visibility: dict[str, tuple[bool, bool]]
-def _local_name(element: etree._Element) -> str:
- """返回 XHTML 元素不含命名空间的小写本地名。"""
- return etree.QName(element).localname.casefold()
-
-
def _numeric_font_weight(value: str) -> int | None:
"""在整数转换前解析 CSS Fonts 允许的一到一千字重。"""
if not value.isascii() or not value.isdigit() or len(value) > 4:
@@ -263,7 +260,7 @@ class MarkupStylesheet:
inherited_visibility_hidden: bool = False,
) -> ElementStyle:
"""计算元素的继承样式、标签默认样式、CSS 规则和 inline style。"""
- tag = _local_name(element)
+ tag = local_name(element)
classes = frozenset((element.get("class") or "").split())
tag_style = TextStyle(
bold=tag in {"b", "strong"},
diff --git a/mineru/model/flash/_shared/mathml.py b/mineru/model/flash/_shared/mathml.py
index 39c88738..0a3205b2 100644
--- a/mineru/model/flash/_shared/mathml.py
+++ b/mineru/model/flash/_shared/mathml.py
@@ -7,6 +7,8 @@ import re
from lxml import etree # type: ignore[reportMissingImports]
+from .names import local_name
+
_OPERATOR_MAP = {
"−": "-",
@@ -73,11 +75,6 @@ _LATEX_MATH_TOKEN_ESCAPES = {
}
-def _local_name(element: etree._Element) -> str:
- """返回 XML 元素不含命名空间的本地名。"""
- return etree.QName(element).localname
-
-
def _escape_text(value: str) -> str:
"""转义进入 LaTeX 文本命令的保留字符。"""
return _LATEX_ESCAPE_RE.sub(r"\\\1", value)
@@ -100,11 +97,11 @@ def _join_children(element: etree._Element) -> str:
def _convert(element: etree._Element) -> str:
"""递归转换一个常用 MathML 节点,未知容器保留其可解析子项。"""
- name = _local_name(element)
+ name = local_name(element)
children = _children(element)
text = (element.text or "").strip()
if name == "semantics":
- if not children or _local_name(children[0]) in {"annotation", "annotation-xml"}:
+ if not children or local_name(children[0]) in {"annotation", "annotation-xml"}:
return ""
return _convert(children[0])
if name in {"math", "mrow", "mstyle", "mpadded", "mphantom"}:
@@ -143,7 +140,7 @@ def _convert(element: etree._Element) -> str:
values = [_convert(child) for child in children]
return rf"\left{opening}{separators[0].join(values)}\right{closing}"
if name == "mtable":
- rows = [_convert(child) for child in children if _local_name(child) in {"mtr", "mlabeledtr"}]
+ rows = [_convert(child) for child in children if local_name(child) in {"mtr", "mlabeledtr"}]
return r"\begin{matrix}" + r" \\ ".join(rows) + r"\end{matrix}"
if name in {"mtr", "mlabeledtr"}:
return " & ".join(_convert(child) for child in children)
@@ -159,7 +156,7 @@ def mathml_to_latex(math_element: etree._Element) -> str | None:
for annotation in math_element.iter():
if not isinstance(annotation.tag, str):
continue
- if _local_name(annotation) != "annotation":
+ if local_name(annotation) != "annotation":
continue
encoding = (annotation.get("encoding") or "").casefold()
if "tex" in encoding and (annotation.text or "").strip():
diff --git a/mineru/model/flash/_shared/names.py b/mineru/model/flash/_shared/names.py
new file mode 100644
index 00000000..0dfecda6
--- /dev/null
+++ b/mineru/model/flash/_shared/names.py
@@ -0,0 +1,21 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""安全归一化 XML namespace 与 legacy HTML 前缀标签名。"""
+
+from __future__ import annotations
+
+from lxml import etree # type: ignore[reportMissingImports]
+
+
+def local_name(element: etree._Element) -> str:
+ """返回 Clark notation、普通或冒号前缀标签的小写本地名。"""
+ tag = element.tag
+ if not isinstance(tag, str):
+ return ""
+ if tag.startswith("{") and "}" in tag:
+ tag = tag.split("}", 1)[1]
+ elif ":" in tag:
+ tag = tag.rsplit(":", 1)[1]
+ return tag.casefold()
+
+
+__all__ = ["local_name"]
diff --git a/tests/unittest/test_flash_html.py b/tests/unittest/test_flash_html.py
index 6ded7dff..5467b422 100644
--- a/tests/unittest/test_flash_html.py
+++ b/tests/unittest/test_flash_html.py
@@ -408,6 +408,45 @@ def test_html_figure_preserves_direct_and_inline_text_around_visuals() -> None:
assert markdown.index("BeforeInline") < markdown.index("Cap") < markdown.index("After Tail")
+def test_html_colonized_office_svg_and_math_tags_preserve_visible_content() -> None:
+ """验证 legacy HTML 冒号标签不会触发 QName 异常,并按本地名恢复正文、SVG 与公式。"""
+ payload = b"""<html><body><o:p>Legacy Office text</o:p>
+ <svg:svg><svg:text>Visible SVG text</svg:text></svg:svg>
+ <m:math><m:mi>x</m:mi></m:math></body></html>"""
+
+ middle, model = doc_analyze(payload, file_suffix="html")
+
+ assert [(block["type"], block.get("content")) for block in model.pages[0]] == [
+ (BlockType.TEXT, "Legacy Office text"),
+ (BlockType.TEXT, "Visible SVG text"),
+ (BlockType.EQUATION, "x"),
+ ]
+ markdown = render_markdown(middle)
+ assert "Legacy Office text" in markdown and "Visible SVG text" in markdown
+ assert "$$\nx\n$$" in markdown
+
+
+def test_html_interleaved_figure_captions_bind_to_each_nearest_image() -> None:
+ """验证同一 figure 的多张图片分别保留其相邻 caption,不会全部归到末图。"""
+ payload = b"""<html><body><figure>
+ <img src="https://example.com/a.png"><figcaption>Caption A</figcaption>
+ <img src="https://example.com/b.png"><figcaption>Caption B</figcaption>
+ </figure></body></html>"""
+
+ middle, model = doc_analyze(payload, file_suffix="html")
+
+ assert [(block["type"], block.get("content")) for block in model.pages[0]] == [
+ (BlockType.IMAGE, ""),
+ (BlockType.IMAGE_CAPTION, "Caption A"),
+ (BlockType.IMAGE, ""),
+ (BlockType.IMAGE_CAPTION, "Caption B"),
+ ]
+ images = [block for block in middle.pages[0].blocks if isinstance(block, ImageBlock)]
+ assert len(images) == 2
+ assert [child.content for child in images[0].content if child.type == BlockType.IMAGE_CAPTION] == ["Caption A"]
+ assert [child.content for child in images[1].content if child.type == BlockType.IMAGE_CAPTION] == ["Caption B"]
+
+
def test_html_inline_visual_splits_paragraph_text_in_dom_order() -> None:
"""验证段落内 visual 会切开前后文本,而不是把图片移到合并文本之后。"""
payload = b'<html><body><p>Before<img src="https://example.com/a.png">After</p></body></html>'