Skip to content

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

fix: enforce HTML node limits and preserve styles

myhloli3dc7de78deab
diff --git a/mineru/model/flash/html/document.py b/mineru/model/flash/html/document.py
index 27b9ecf6..5a6aed4b 100644
--- a/mineru/model/flash/html/document.py
+++ b/mineru/model/flash/html/document.py
@@ -145,13 +145,15 @@ def _validate_dom_shape(root: etree._Element) -> None:
node_count = 0
stack: list[tuple[etree._Element, int]] = [(root, 1)]
while stack:
- element, depth = stack.pop()
+ node, depth = stack.pop()
node_count += 1
if node_count > MAX_HTML_NODES:
raise HtmlResourceLimitError(f"HTML resource limit exceeded: max_html_nodes={MAX_HTML_NODES}")
+ if not isinstance(node.tag, str):
+ continue
if depth > MAX_HTML_DEPTH:
raise HtmlResourceLimitError(f"HTML resource limit exceeded: max_html_depth={MAX_HTML_DEPTH}")
- stack.extend((child, depth + 1) for child in element if isinstance(child.tag, str))
+ stack.extend((child, depth + 1) for child in node)
def _meta_content(root: etree._Element, *, property_name: str) -> str | None:
diff --git a/mineru/model/flash/html/selector.py b/mineru/model/flash/html/selector.py
index ae7f7689..af7d40de 100644
--- a/mineru/model/flash/html/selector.py
+++ b/mineru/model/flash/html/selector.py
@@ -119,8 +119,7 @@ def select_auto_content(body: etree._Element, stylesheet: MarkupStylesheet) -> C
)
if not candidate.explicit and second is not None and candidate.score < second.score * _MIN_SCORE_MARGIN:
continue
- selected = deepcopy(candidate.element)
- _soft_prune(selected)
+ selected = _copy_candidate_with_ancestors(candidate.element, body)
selected_metrics: dict[etree._Element, CandidateMetrics] = {}
final_metrics = _collect_metrics(selected, stylesheet, selected_metrics, TextStyle(), False, False)
retained_ratio = final_metrics.text_chars / max(1, body_metrics.text_chars)
@@ -136,6 +135,25 @@ def select_auto_content(body: etree._Element, stylesheet: MarkupStylesheet) -> C
return ContentSelection(deepcopy(body), "document", 0.0, 1.0, "body_fallback")
+def _copy_candidate_with_ancestors(candidate: etree._Element, body: etree._Element) -> etree._Element:
+ """复制正文候选及其到 body 的空祖先链,保留继承样式但不带入周边正文。"""
+ selected = deepcopy(candidate)
+ selected.tail = None
+ _soft_prune(selected)
+ root = selected
+ for ancestor in candidate.iterancestors():
+ if not isinstance(ancestor.tag, str):
+ continue
+ wrapper = etree.Element(ancestor.tag, nsmap=ancestor.nsmap)
+ for name, value in ancestor.attrib.items():
+ wrapper.set(name, value)
+ wrapper.append(root)
+ root = wrapper
+ if ancestor is body:
+ return root
+ return root
+
+
def _collect_metrics(
element: etree._Element,
stylesheet: MarkupStylesheet,
diff --git a/tests/unittest/test_flash_html.py b/tests/unittest/test_flash_html.py
index 7696b6c4..340bc83a 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 document as html_document_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
@@ -266,6 +267,22 @@ def test_html_auto_selection_preserves_all_repeated_forum_posts() -> None:
assert "Second post" in markdown and "Second body" in markdown
+def test_html_auto_selection_preserves_ancestor_text_styles() -> None:
+ """验证正文候选复制后仍继承 body 与外层容器的受支持文字样式。"""
+ detail = "Inherited text " * 20
+ payload = f"""<html><body style="font-weight:bold"><aside style="font-style:italic;text-decoration:underline">
+ <main><p>{detail}</p></main></aside></body></html>""".encode()
+
+ _, model = doc_analyze(payload, file_suffix="html")
+
+ assert model.pages[0] == [
+ {
+ "type": BlockType.TEXT,
+ "content": f'<text style="bold,italic,underline">{detail}</text>',
+ }
+ ]
+
+
def test_html_auto_selection_rejects_single_section_from_document_index() -> None:
"""验证多个同级 section 构成的文档索引会保留全部章节而非选择最长一节。"""
detail = b" useful explanatory content with enough words to qualify as an independent scored candidate" * 4
@@ -934,6 +951,14 @@ def test_html_rejects_page_range_and_resource_overflow(tmp_path: Path, monkeypat
HtmlModel().predict(BytesIO(b"<p>x</p>"))
+def test_html_comments_count_toward_dom_node_budget(monkeypatch: pytest.MonkeyPatch) -> None:
+ """验证 comment 等非元素 DOM 节点同样受总节点预算约束。"""
+ monkeypatch.setattr(html_document_module, "MAX_HTML_NODES", 4)
+
+ with pytest.raises(HtmlResourceLimitError, match="max_html_nodes"):
+ doc_analyze(b"<html><body><!--1--><!--2--><!--3--></body></html>", file_suffix="html")
+
+
@pytest.mark.parametrize(
("styles", "single_limit", "total_limit", "expected_limit"),
[