Skip to content

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

fix: enforce HTML style and note visibility limits

myhloli1e842264f2c1
diff --git a/mineru/model/flash/html/anchors.py b/mineru/model/flash/html/anchors.py
index b4acc7f4..807aec29 100644
--- a/mineru/model/flash/html/anchors.py
+++ b/mineru/model/flash/html/anchors.py
@@ -43,6 +43,7 @@ def append_referenced_notes(
selected_root: etree._Element,
original_body: etree._Element,
*,
+ stylesheet: MarkupStylesheet,
resolve_same_document_fragment: Callable[[str], str | None],
) -> etree._Element:
"""把正文候选引用但位于候选外的脚注副本追加到内容根末尾。"""
@@ -66,15 +67,41 @@ def append_referenced_notes(
companions = [
element for identity, element in targets.items() if identity in referenced_ids and identity not in selected_ids
]
- if not companions:
+ companion_copies = [
+ copy for companion in companions if (copy := _copy_note_with_source_visibility(companion, stylesheet)) is not None
+ ]
+ if not companion_copies:
return selected_root
wrapper = etree.Element("div")
wrapper.append(selected_root)
- for companion in companions:
- wrapper.append(deepcopy(companion))
+ for companion in companion_copies:
+ wrapper.append(companion)
return wrapper
+def _copy_note_with_source_visibility(
+ note: etree._Element,
+ stylesheet: MarkupStylesheet,
+) -> etree._Element | None:
+ """按原始祖先链复制 note;整树隐藏时丢弃,继承 visibility 隐藏时保留状态。"""
+ inherited = TextStyle()
+ visibility_hidden = False
+ chain = [ancestor for ancestor in reversed(list(note.iterancestors())) if isinstance(ancestor.tag, str)]
+ chain.append(note)
+ for current in chain:
+ resolved = stylesheet.resolve(current, inherited, visibility_hidden)
+ if resolved.subtree_hidden:
+ return None
+ inherited = resolved.text
+ visibility_hidden = resolved.visibility_hidden
+ copied = deepcopy(note)
+ if visibility_hidden:
+ style = (copied.get("style") or "").strip()
+ separator = "" if not style or style.endswith(";") else ";"
+ copied.set("style", f"{style}{separator}visibility:hidden")
+ return copied
+
+
class HtmlAnchorRegistry:
"""把选中 DOM 的标题、note 和源 fragment 映射到稳定 anchor。"""
diff --git a/mineru/model/flash/html/converter.py b/mineru/model/flash/html/converter.py
index 80b74f19..f568c7a7 100644
--- a/mineru/model/flash/html/converter.py
+++ b/mineru/model/flash/html/converter.py
@@ -53,6 +53,7 @@ class HtmlConverter:
selected_root = append_referenced_notes(
selection.root,
document.body,
+ stylesheet=stylesheet,
resolve_same_document_fragment=resources.same_document_fragment,
)
source_key = document.source_context.source_uri or "html"
@@ -88,6 +89,7 @@ def _load_stylesheet(document: HtmlDocument, resources: HtmlResourceContext) ->
stylesheet = MarkupStylesheet()
for source in document.stylesheets:
if source.kind == "inline":
+ resources.charge_inline_stylesheet(source.value)
stylesheet.add(source.value)
elif css := resources.load_stylesheet(source.value):
stylesheet.add(css)
diff --git a/mineru/model/flash/html/resources.py b/mineru/model/flash/html/resources.py
index 065ef13c..4ecd148c 100644
--- a/mineru/model/flash/html/resources.py
+++ b/mineru/model/flash/html/resources.py
@@ -166,16 +166,25 @@ class HtmlResourceContext:
return cached
with path.open("rb") as source_file:
payload = source_file.read(MAX_HTML_STYLESHEET_BYTES + 1)
- if len(payload) > MAX_HTML_STYLESHEET_BYTES:
+ self._charge_stylesheet_bytes(len(payload))
+ stylesheet = payload.decode("utf-8-sig", errors="replace")
+ self._stylesheet_cache[path] = stylesheet
+ return stylesheet
+
+ def charge_inline_stylesheet(self, stylesheet: str) -> None:
+ """把一段内联 CSS 的 UTF-8 字节数计入统一 stylesheet 预算。"""
+ self._charge_stylesheet_bytes(len(stylesheet.encode("utf-8")))
+
+ def _charge_stylesheet_bytes(self, byte_count: int) -> None:
+ """执行单份和整文档 stylesheet 字节限制,并只在校验通过后累计。"""
+ if byte_count > MAX_HTML_STYLESHEET_BYTES:
raise HtmlResourceLimitError(f"HTML stylesheet exceeds max_html_stylesheet_bytes={MAX_HTML_STYLESHEET_BYTES}")
- self._stylesheet_bytes += len(payload)
- if self._stylesheet_bytes > MAX_HTML_STYLESHEET_TOTAL_BYTES:
+ total_bytes = self._stylesheet_bytes + byte_count
+ if total_bytes > MAX_HTML_STYLESHEET_TOTAL_BYTES:
raise HtmlResourceLimitError(
f"HTML stylesheets exceed max_html_stylesheet_total_bytes={MAX_HTML_STYLESHEET_TOTAL_BYTES}"
)
- stylesheet = payload.decode("utf-8-sig", errors="replace")
- self._stylesheet_cache[path] = stylesheet
- return stylesheet
+ self._stylesheet_bytes = total_bytes
def heading_anchor(self, heading: etree._Element) -> str | None:
"""把标题 anchor 查询委托给已绑定的注册表。"""
diff --git a/tests/unittest/test_flash_html.py b/tests/unittest/test_flash_html.py
index 88cd7027..7696b6c4 100644
--- a/tests/unittest/test_flash_html.py
+++ b/tests/unittest/test_flash_html.py
@@ -18,6 +18,7 @@ from mineru.doclib.services.parse_svc import ParseService
from mineru.model.flash import HtmlModel
from mineru.model.flash.html import HtmlResourceLimitError, HtmlSourceContext
from mineru.model.flash.html import converter as html_converter_module
+from mineru.model.flash.html import resources as html_resources_module
from mineru.model.flash.html.resources import HtmlResourceContext
from mineru.parser import ParseResult, parse, parse_async
from mineru.parser import api_server
@@ -305,6 +306,40 @@ 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]
+ "ancestor_attributes",
+ ['style="display:none"', 'style="opacity:0"', "hidden", 'aria-hidden="true"'],
+)
+def test_html_referenced_external_footnote_respects_hidden_ancestor(ancestor_attributes: str) -> None:
+ """验证正文外引用脚注不会脱离原始整树隐藏祖先后泄漏到输出。"""
+ detail = "Useful main article text " * 20
+ payload = f"""<html><body><main><h1>Title</h1><p>{detail}<a href="#fn1">[1]</a></p></main>
+ <aside {ancestor_attributes}><div id="fn1" role="doc-footnote">HIDDEN NOTE</div></aside>
+ </body></html>""".encode()
+
+ middle = doc_analyze(payload, file_suffix="html")[0]
+ markdown = render_markdown(middle)
+
+ assert "HIDDEN NOTE" not in markdown
+ assert not any(block.type == BlockType.PAGE_FOOTNOTE for block in middle.pages[0].blocks)
+
+
+def test_html_referenced_external_footnote_preserves_inherited_visibility() -> None:
+ """验证复制脚注保留祖先 visibility:hidden,同时允许后代显式恢复可见。"""
+ detail = "Useful main article text " * 20
+ payload = f"""<html><body><main><h1>Title</h1><p>{detail}<a href="#fn1">[1]</a></p></main>
+ <aside style="visibility:hidden"><div id="fn1" role="doc-footnote">HIDDEN NOTE
+ <span style="visibility:visible">VISIBLE NOTE</span></div></aside></body></html>""".encode()
+
+ middle = doc_analyze(payload, file_suffix="html")[0]
+ markdown = render_markdown(middle)
+ footnote = next(block for block in middle.pages[0].blocks if block.type == BlockType.PAGE_FOOTNOTE)
+
+ assert "HIDDEN NOTE" not in markdown
+ assert footnote.content == "VISIBLE NOTE" # type: ignore[union-attr]
+ assert f"](#{footnote.anchor})" in markdown # type: ignore[union-attr]
+
+
@pytest.mark.parametrize(
"href",
[
@@ -899,6 +934,47 @@ def test_html_rejects_page_range_and_resource_overflow(tmp_path: Path, monkeypat
HtmlModel().predict(BytesIO(b"<p>x</p>"))
+ ("styles", "single_limit", "total_limit", "expected_limit"),
+ [
+ ("<style>.large{display:none}</style>", 8, 128, "max_html_stylesheet_bytes"),
+ (
+ "<style>.a{display:none}</style><style>.b{display:none}</style>",
+ 16,
+ 24,
+ "max_html_stylesheet_total_bytes",
+ ),
+ ],
+)
+def test_html_inline_stylesheets_enforce_resource_budgets(
+ styles: str,
+ single_limit: int,
+ total_limit: int,
+ expected_limit: str,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """验证内联 CSS 同时受单份和整文档 stylesheet 字节预算约束。"""
+ monkeypatch.setattr(html_resources_module, "MAX_HTML_STYLESHEET_BYTES", single_limit)
+ monkeypatch.setattr(html_resources_module, "MAX_HTML_STYLESHEET_TOTAL_BYTES", total_limit)
+ payload = f"<html><head>{styles}</head><body><p>Visible</p></body></html>".encode()
+
+ with pytest.raises(HtmlResourceLimitError, match=expected_limit):
+ doc_analyze(payload, file_suffix="html")
+
+
+def test_html_inline_and_local_stylesheets_share_total_budget(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ """验证内联与本地外链 CSS 按文档顺序共享累计 stylesheet 预算。"""
+ (tmp_path / "styles.css").write_text(".a{display:none}", encoding="utf-8")
+ monkeypatch.setattr(html_resources_module, "MAX_HTML_STYLESHEET_BYTES", 16)
+ monkeypatch.setattr(html_resources_module, "MAX_HTML_STYLESHEET_TOTAL_BYTES", 24)
+ payload = b"""<html><head><link rel="stylesheet" href="styles.css">
+ <style>.b{display:none}</style></head><body><p>Visible</p></body></html>"""
+ context = HtmlSourceContext(local_resource_root=tmp_path)
+
+ with pytest.raises(HtmlResourceLimitError, match="max_html_stylesheet_total_bytes"):
+ doc_analyze(payload, file_suffix="html", source_context=context)
+
+
@pytest.mark.parametrize(
"image_url",
[