Skip to content

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

feat: enhance HTML note resolution and contextual handling for figures

myhloli0729928a0f5c
diff --git a/mineru/model/flash/_shared/markup/projector.py b/mineru/model/flash/_shared/markup/projector.py
index 2f4453af..3f04782d 100644
--- a/mineru/model/flash/_shared/markup/projector.py
+++ b/mineru/model/flash/_shared/markup/projector.py
@@ -235,6 +235,9 @@ class MarkupProjector:
resolved = self.stylesheet.resolve(self.root, TextStyle())
if resolved.subtree_hidden:
return []
+ name = local_name(self.root)
+ if name == "figure" or (name in {"aside", "div", "section"} and self._has_contextual_visual_annotation(self.root)):
+ return self._parse_figure(self.root, resolved.text, resolved.visibility_hidden)
return self._parse_container_contents(self.root, resolved.text, resolved.visibility_hidden)
def convert_svg(self) -> list[dict[str, object]]:
diff --git a/mineru/model/flash/html/anchors.py b/mineru/model/flash/html/anchors.py
index d5cce85b..b4acc7f4 100644
--- a/mineru/model/flash/html/anchors.py
+++ b/mineru/model/flash/html/anchors.py
@@ -3,6 +3,7 @@
from __future__ import annotations
+from collections.abc import Callable
from copy import deepcopy
import hashlib
@@ -38,7 +39,12 @@ def element_id(element: etree._Element) -> str | None:
return value or None
-def append_referenced_notes(selected_root: etree._Element, original_body: etree._Element) -> etree._Element:
+def append_referenced_notes(
+ selected_root: etree._Element,
+ original_body: etree._Element,
+ *,
+ resolve_same_document_fragment: Callable[[str], str | None],
+) -> etree._Element:
"""把正文候选引用但位于候选外的脚注副本追加到内容根末尾。"""
selected_ids = {
identity
@@ -51,12 +57,11 @@ def append_referenced_notes(selected_root: etree._Element, original_body: etree.
if isinstance(element.tag, str) and (identity := element_id(element)) is not None and is_note_element(element)
}
referenced_ids = dict.fromkeys(
- href[1:]
+ fragment
for element in selected_root.iter()
if isinstance(element.tag, str)
and local_name(element) == "a"
- and (href := (element.get("href") or "").strip()).startswith("#")
- and len(href) > 1
+ and (fragment := resolve_same_document_fragment(element.get("href") or "")) is not None
)
companions = [
element for identity, element in targets.items() if identity in referenced_ids and identity not in selected_ids
diff --git a/mineru/model/flash/html/converter.py b/mineru/model/flash/html/converter.py
index caceffe9..80b74f19 100644
--- a/mineru/model/flash/html/converter.py
+++ b/mineru/model/flash/html/converter.py
@@ -50,7 +50,11 @@ class HtmlConverter:
logger.warning("MinerU HTML marker fallback reason={}", inspection.fallback_reason)
stylesheet = _load_stylesheet(document, resources)
selection = select_auto_content(document.body, stylesheet)
- selected_root = append_referenced_notes(selection.root, document.body)
+ selected_root = append_referenced_notes(
+ selection.root,
+ document.body,
+ resolve_same_document_fragment=resources.same_document_fragment,
+ )
source_key = document.source_context.source_uri or "html"
anchors = HtmlAnchorRegistry(selected_root, stylesheet, source_key=source_key)
resources.bind_anchors(anchors)
diff --git a/mineru/model/flash/html/resources.py b/mineru/model/flash/html/resources.py
index 0947113b..69cee028 100644
--- a/mineru/model/flash/html/resources.py
+++ b/mineru/model/flash/html/resources.py
@@ -6,7 +6,7 @@ from __future__ import annotations
import base64
from pathlib import Path
from typing import Protocol
-from urllib.parse import unquote, urljoin, urlsplit
+from urllib.parse import SplitResult, unquote, urljoin, urlsplit
from lxml import etree # type: ignore[reportMissingImports]
@@ -34,6 +34,7 @@ _IMAGE_MIME_SIGNATURES: tuple[tuple[str, tuple[bytes, ...]], ...] = (
("image/bmp", (b"BM",)),
("image/tiff", (b"II*\x00", b"MM\x00*")),
)
+_SAME_DOCUMENT_SCHEMES = frozenset({"file", "http", "https"})
class HtmlAnchorResolver(Protocol):
@@ -78,8 +79,39 @@ class HtmlResourceContext:
"""在正文选择完成后绑定仅包含实际输出目标的 anchor 表。"""
self.anchors = anchors
+ def same_document_fragment(self, href: str) -> str | None:
+ """解析纯 fragment 或与来源文档身份相同的相对、绝对 URL fragment。"""
+ normalized = sanitize_hyperlink_target(
+ href,
+ allowed_schemes=_SAME_DOCUMENT_SCHEMES,
+ allow_relative=True,
+ allow_fragment=True,
+ allow_root_relative=True,
+ )
+ if normalized is None:
+ return None
+ if normalized.startswith("#"):
+ fragment = normalized[1:].strip()
+ return fragment or None
+ source_uri = (self.source_context.source_uri or "").strip()
+ if not source_uri:
+ return None
+ try:
+ source_parts = urlsplit(source_uri)
+ base_uri = urljoin(source_uri, (self.base_href or "").strip())
+ target_parts = urlsplit(urljoin(base_uri, normalized))
+ except ValueError:
+ return None
+ fragment = target_parts.fragment.strip()
+ if not fragment or _document_url_identity(target_parts) != _document_url_identity(source_parts):
+ return None
+ return fragment
+
def resolve_link(self, href: str) -> str | None:
"""解析安全外链、相对链接或实际存在的文档内 fragment。"""
+ if self.anchors is not None and (fragment := self.same_document_fragment(href)) is not None:
+ if internal := self.anchors.resolve_fragment(fragment):
+ return internal
normalized = sanitize_hyperlink_target(
href,
allow_relative=True,
@@ -95,18 +127,6 @@ class HtmlResourceContext:
return normalized
if self._remote_base:
resolved = urljoin(self._remote_base, normalized)
- resolved_parts = urlsplit(resolved)
- source_parts = urlsplit(self._remote_base)
- if (
- resolved_parts.fragment
- and resolved_parts.scheme == source_parts.scheme
- and resolved_parts.netloc == source_parts.netloc
- and resolved_parts.path == source_parts.path
- and self.anchors is not None
- ):
- internal = self.anchors.resolve_fragment(resolved_parts.fragment)
- if internal:
- return internal
return sanitize_hyperlink_target(resolved)
return sanitize_hyperlink_target(normalized, allow_relative=True, allow_fragment=True)
@@ -295,6 +315,13 @@ def _image_data_uri(payload: bytes) -> str | None:
return data_uri
+def _document_url_identity(parts: SplitResult) -> tuple[str, str, str, str]:
+ """返回忽略 fragment 的确定文档身份,并规范层级 URL 的空路径。"""
+ scheme = parts.scheme.casefold()
+ path = parts.path or ("/" if scheme in {"http", "https"} else "")
+ return scheme, parts.netloc.casefold(), unquote(path), parts.query
+
+
def _is_within(path: Path, root: Path) -> bool:
"""判断已解析路径是否等于安全根或位于其内部。"""
return path == root or root in path.parents
diff --git a/tests/unittest/test_flash_html.py b/tests/unittest/test_flash_html.py
index 5467b422..055f0643 100644
--- a/tests/unittest/test_flash_html.py
+++ b/tests/unittest/test_flash_html.py
@@ -305,6 +305,113 @@ def test_html_referenced_external_footnote_keeps_anchor_and_content() -> None:
assert f'id="{footnote.anchor}" class="mineru-page-footnote"' in markdown # type: ignore[union-attr]
+ "href",
+ [
+ "#fn1",
+ "page.html#fn1",
+ "https://example.com/page.html#fn1",
+ ],
+)
+def test_html_auto_selection_appends_notes_for_all_same_document_url_forms(href: str) -> None:
+ """验证 auto 正文外脚注可由纯 fragment、相对或绝对同文档 URL 引用。"""
+ detail = "Useful main article text " * 20
+ payload = f"""<html><body><main><article><h1>Title</h1><p>{detail}
+ <a href="{href}">[1]</a></p></article></main>
+ <footer><aside id="fn1" role="doc-footnote"><p>Outside footnote.</p></aside></footer>
+ </body></html>""".encode()
+ context = HtmlSourceContext(source_uri="https://example.com/page.html")
+
+ middle = doc_analyze(payload, file_suffix="html", source_context=context)[0]
+ markdown = render_markdown(middle)
+ footnote = next(block for block in middle.pages[0].blocks if block.type == BlockType.PAGE_FOOTNOTE)
+
+ assert footnote.content == "Outside footnote." # type: ignore[union-attr]
+ assert f"](#{footnote.anchor})" in markdown # type: ignore[union-attr]
+ assert "https://example.com/page.html#fn1" not in markdown
+
+
+ ("href", "expected_target"),
+ [
+ ("other.html#fn1", "https://example.com/other.html#fn1"),
+ ("https://other.example/page.html#fn1", "https://other.example/page.html#fn1"),
+ ("page.html?view=2#fn1", "https://example.com/page.html?view=2#fn1"),
+ ],
+)
+def test_html_auto_selection_does_not_append_notes_for_other_documents(href: str, expected_target: str) -> None:
+ """验证不同 path、origin 或 query 的 URL 不会借 fragment 追加当前文档脚注。"""
+ detail = "Useful main article text " * 20
+ payload = f"""<html><body><main><article><h1>Title</h1><p>{detail}
+ <a href="{href}">[1]</a></p></article></main>
+ <footer><aside id="fn1" role="doc-footnote"><p>Outside footnote.</p></aside></footer>
+ </body></html>""".encode()
+ context = HtmlSourceContext(source_uri="https://example.com/page.html")
+
+ middle = doc_analyze(payload, file_suffix="html", source_context=context)[0]
+ markdown = render_markdown(middle)
+
+ assert "Outside footnote." not in markdown
+ assert not any(block.type == BlockType.PAGE_FOOTNOTE for block in middle.pages[0].blocks)
+ assert expected_target in markdown
+
+
+ ("base_href", "expected_note"),
+ [
+ ("/docs/", True),
+ ("/other/", False),
+ ],
+)
+def test_html_same_document_note_resolution_honors_base_href(base_href: str, expected_note: bool) -> None:
+ """验证 base href 参与相对脚注 URL 的文档身份判定。"""
+ detail = "Useful main article text " * 20
+ payload = f"""<html><head><base href="{base_href}"></head><body><main><article><h1>Title</h1>
+ <p>{detail}<a href="page.html#fn1">[1]</a></p></article></main>
+ <footer><aside id="fn1" role="doc-footnote"><p>Outside footnote.</p></aside></footer>
+ </body></html>""".encode()
+ context = HtmlSourceContext(source_uri="https://example.com/docs/page.html")
+
+ markdown = render_markdown(doc_analyze(payload, file_suffix="html", source_context=context)[0])
+
+ assert ("Outside footnote." in markdown) is expected_note
+
+
+def test_html_local_self_url_appends_referenced_note(tmp_path: Path) -> None:
+ """验证本地 HTML 使用自身文件名 fragment 时同样保留正文选择外脚注。"""
+ detail = "Useful main article text " * 20
+ source = tmp_path / "page.html"
+ source.write_text(
+ f"""<html><body><main><article><h1>Title</h1><p>{detail}
+ <a href="page.html#fn1">[1]</a></p></article></main>
+ <footer><aside id="fn1" role="doc-footnote"><p>Outside footnote.</p></aside></footer>
+ </body></html>""",
+ encoding="utf-8",
+ )
+
+ markdown = parse(source).markdown()
+
+ assert "Outside footnote." in markdown
+ assert "file:" not in markdown
+
+
[email protected]("href", ["javascript:alert(1)#fn1", "http://["])
+def test_html_unsafe_or_malformed_note_urls_do_not_append_notes(href: str) -> None:
+ """验证危险协议与畸形 URL 不参与同文档脚注关联,且不会中断正文解析。"""
+ detail = "Useful main article text " * 20
+ payload = f"""<html><body><main><article><h1>Title</h1><p>{detail}
+ <a href="{href}">[1]</a></p></article></main>
+ <footer><aside id="fn1" role="doc-footnote"><p>Outside footnote.</p></aside></footer>
+ </body></html>""".encode()
+ context = HtmlSourceContext(source_uri="https://example.com/page.html")
+
+ markdown = render_markdown(doc_analyze(payload, file_suffix="html", source_context=context)[0])
+
+ assert "Title" in markdown and "[1]" in markdown
+ assert "Outside footnote." not in markdown
+ assert href not in markdown
+
+
def test_html_formula_sources_are_normalized_without_duplicate_katex_text() -> None:
"""验证 MathML、KaTeX annotation 与 data-expr 按统一公式协议输出且不重复。"""
payload = rb"""<html><body><h1>Math</h1><p>Inline
@@ -447,6 +554,54 @@ def test_html_interleaved_figure_captions_bind_to_each_nearest_image() -> None:
assert [child.content for child in images[1].content if child.type == BlockType.IMAGE_CAPTION] == ["Caption B"]
+def test_html_auto_selected_contextual_div_keeps_figure_caption_relation() -> None:
+ """验证 auto 直接选中 visual wrapper div 时仍执行根节点 caption 关联。"""
+ payload = b"""<html><body><div><figure><img src="https://example.com/a.png"></figure>
+ <p class="caption">Div caption</p></div></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, "Div caption"),
+ ]
+ image = next(block for block in middle.pages[0].blocks if isinstance(block, ImageBlock))
+ assert [child.content for child in image.content if child.type == BlockType.IMAGE_CAPTION] == ["Div caption"]
+
+
+def test_html_caption_does_not_cross_unrelated_parent_container() -> None:
+ """验证 caption 与 visual 不共享明确语义父容器时不会跨容器猜测归属。"""
+ detail = b"Useful main article text " * 20
+ payload = (
+ b'<html><body><main><div><figure><img src="https://example.com/a.png"></figure></div>'
+ b'<p class="caption">Outside caption</p><p>' + detail + b"</p></main></body></html>"
+ )
+
+ middle = doc_analyze(payload, file_suffix="html")[0]
+ image = next(block for block in middle.pages[0].blocks if isinstance(block, ImageBlock))
+
+ assert all(child.type != BlockType.IMAGE_CAPTION for child in image.content)
+ assert "Outside caption" in render_markdown(middle)
+
+
+def test_html_alt_caption_fallback_policy_distinguishes_generic_and_mineru_figures() -> None:
+ """验证普通图片可用 alt 兜底,但显式 caption 与 MinerU figure 不重复提升 alt。"""
+ payload = b"""<html><body>
+ <figure><img src="https://example.com/a.png" alt="Generic alt"></figure>
+ <figure><img src="https://example.com/b.png" alt="Hidden alt"><figcaption>Explicit caption</figcaption></figure>
+ <figure class="mineru-figure"><img src="https://example.com/c.png" alt="Accessibility alt"></figure>
+ </body></html>"""
+
+ middle = doc_analyze(payload, file_suffix="html")[0]
+ images = [block for block in middle.pages[0].blocks if isinstance(block, ImageBlock)]
+ captions = [[child.content for child in image.content if child.type == BlockType.IMAGE_CAPTION] for image in images]
+
+ assert captions == [["Generic alt"], ["Explicit caption"], []]
+ markdown = render_markdown(middle)
+ assert "Generic alt" in markdown and "Explicit caption" in markdown
+ assert "Hidden alt" not in markdown and "Accessibility alt" not in markdown
+
+
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>'