Skip to content

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

harden html selection hot paths

myhloli206c3bb193be
diff --git a/mineru/model/flash/html/document.py b/mineru/model/flash/html/document.py
index 5a6aed4b..275f8bc9 100644
--- a/mineru/model/flash/html/document.py
+++ b/mineru/model/flash/html/document.py
@@ -202,16 +202,18 @@ def _is_formula_carrier(element: etree._Element) -> bool:
def _formula_wrapper_contains_only_carrier(element: etree._Element) -> bool:
"""仅允许恰好一个 carrier 且其外没有可见文本或媒体的通用 wrapper 整体折叠。"""
- carriers: list[etree._Element] = []
+ carrier: etree._Element | None = None
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()):
+ if carrier is None:
+ carrier = candidate
continue
- carriers.append(candidate)
- if len(carriers) != 1:
+ if any(ancestor is carrier for ancestor in candidate.iterancestors()):
+ continue
+ return False
+ if carrier is None:
return False
- carrier = carriers[0]
def inside_carrier(candidate: etree._Element | None) -> bool:
"""判断节点正文是否位于唯一 carrier 子树内。"""
diff --git a/mineru/model/flash/html/resources.py b/mineru/model/flash/html/resources.py
index 4ecd148c..6222ff5d 100644
--- a/mineru/model/flash/html/resources.py
+++ b/mineru/model/flash/html/resources.py
@@ -90,7 +90,8 @@ class HtmlResourceContext:
)
if normalized is None:
return None
- if normalized.startswith("#"):
+ base_href = (self.base_href or "").strip()
+ if normalized.startswith("#") and (not base_href or base_href.startswith("#")):
fragment = unquote(normalized[1:]).strip()
return fragment or None
source_uri = (self.source_context.source_uri or "").strip()
@@ -98,7 +99,7 @@ class HtmlResourceContext:
return None
try:
source_parts = urlsplit(source_uri)
- base_uri = urljoin(source_uri, (self.base_href or "").strip())
+ base_uri = urljoin(source_uri, base_href)
target_parts = urlsplit(urljoin(base_uri, normalized))
except ValueError:
return None
@@ -121,6 +122,19 @@ class HtmlResourceContext:
if normalized is None:
return None
if normalized.startswith("#"):
+ base_href = (self.base_href or "").strip()
+ if base_href:
+ source_uri = (self.source_context.source_uri or "").strip()
+ try:
+ target = urljoin(urljoin(source_uri, base_href), normalized)
+ except ValueError:
+ return None
+ return sanitize_hyperlink_target(
+ target,
+ allow_relative=True,
+ allow_fragment=True,
+ allow_root_relative=True,
+ )
return self.anchors.resolve_fragment(normalized) if self.anchors else None
parsed = urlsplit(normalized)
if parsed.scheme:
diff --git a/mineru/model/flash/html/selector.py b/mineru/model/flash/html/selector.py
index d06b504b..8f2bb080 100644
--- a/mineru/model/flash/html/selector.py
+++ b/mineru/model/flash/html/selector.py
@@ -103,11 +103,12 @@ def select_auto_content(body: etree._Element, stylesheet: MarkupStylesheet) -> C
continue
candidates.append(_ScoredCandidate(element, metrics, _candidate_score(element, metrics), explicit))
candidates.sort(key=lambda item: (-item.score, _document_order(item.element)))
+ repeated_candidate_items = _repeated_candidate_items(candidates, metrics_by_element)
for candidate in candidates:
if candidate.score <= 0:
continue
- if _is_repeated_candidate_item(candidate.element, metrics_by_element):
+ if candidate.element in repeated_candidate_items:
continue
second = next(
(
@@ -264,26 +265,34 @@ def _repeated_short_sibling_penalty(element: etree._Element) -> int:
return penalty
-def _is_repeated_candidate_item(
- element: etree._Element,
+def _repeated_candidate_items(
+ candidates: list[_ScoredCandidate],
metrics_by_element: dict[etree._Element, CandidateMetrics],
-) -> bool:
- """拒绝论坛、文档页或聚合页中只代表单个重复同级条目的候选。"""
- parent = element.getparent()
- if parent is None:
- return False
- element_name = local_name(element)
- repeated = [
- child
- for child in parent
- if isinstance(child.tag, str)
- and (
- local_name(child) == element_name
- or bool(_tokens(child) & _tokens(element) & {"article", "content", "entry", "post", "section"})
+) -> frozenset[etree._Element]:
+ """一次预计算论坛、文档页或聚合页中的重复同级候选,避免逐候选重扫兄弟节点。"""
+ semantic_tokens = frozenset({"article", "content", "entry", "post", "section"})
+ parents = {parent for candidate in candidates if (parent := candidate.element.getparent()) is not None}
+ repeated: set[etree._Element] = set()
+ for parent in parents:
+ eligible = [
+ child
+ for child in parent
+ if isinstance(child.tag, str) and metrics_by_element.get(child, CandidateMetrics()).text_chars >= 100
+ ]
+ names = {child: local_name(child) for child in eligible}
+ tokens = {child: _tokens(child) & semantic_tokens for child in eligible}
+ name_counts: dict[str, int] = {}
+ token_counts: dict[str, int] = {}
+ for child in eligible:
+ name_counts[names[child]] = name_counts.get(names[child], 0) + 1
+ for token in tokens[child]:
+ token_counts[token] = token_counts.get(token, 0) + 1
+ repeated.update(
+ child
+ for child in eligible
+ if name_counts[names[child]] >= 2 or any(token_counts[token] >= 2 for token in tokens[child])
)
- and metrics_by_element.get(child, CandidateMetrics()).text_chars >= 100
- ]
- return len(repeated) >= 2 and element in repeated
+ return frozenset(repeated)
def _is_containment_equivalent(first: _ScoredCandidate, second: _ScoredCandidate) -> bool:
diff --git a/tests/unittest/test_flash_html.py b/tests/unittest/test_flash_html.py
index 66fca63a..3d73fa3e 100644
--- a/tests/unittest/test_flash_html.py
+++ b/tests/unittest/test_flash_html.py
@@ -10,6 +10,7 @@ from zipfile import ZipFile
import pytest
from bs4 import BeautifulSoup
+from lxml import etree, html as lxml_html # type: ignore[reportMissingImports]
from PIL import Image
from mineru.backend.analyze import aio_doc_analyze, doc_analyze
@@ -20,6 +21,7 @@ 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 import selector as html_selector_module
from mineru.model.flash.html.resources import HtmlResourceContext
from mineru.parser import ParseResult, parse, parse_async
from mineru.parser import api_server
@@ -317,6 +319,29 @@ def test_html_auto_selection_rejects_single_section_from_document_index() -> Non
assert "Third section" in markdown and "third code" in markdown
+def test_html_auto_selection_precomputes_repeated_candidate_groups(monkeypatch: pytest.MonkeyPatch) -> None:
+ """验证大量异构重复候选只线性计算同级 token,不为每个候选重扫全部兄弟节点。"""
+ item_count = 200
+ original_tokens = html_selector_module._tokens
+ token_calls = 0
+
+ def counted_tokens(element: etree._Element) -> frozenset[str]:
+ """统计正文选择期间的 token 计算次数。"""
+ nonlocal token_calls
+ token_calls += 1
+ return original_tokens(element)
+
+ monkeypatch.setattr(html_selector_module, "_tokens", counted_tokens)
+ items = "".join(
+ f'<{tag} class="post"><p>{"candidate text " * 16}</p></{tag}>'
+ for tag in ("div", "section") * (item_count // 2)
+ )
+
+ doc_analyze(f"<html><body>{items}</body></html>".encode(), file_suffix="html")
+
+ assert token_calls < item_count * 20
+
+
def test_html_referenced_external_footnote_keeps_anchor_and_content() -> None:
"""验证正文候选外但被引用的 HTML footnote 会追加并生成可兑现 anchor。"""
payload = b"""<html><body><article><h1>Notes</h1>
@@ -479,6 +504,41 @@ def test_html_same_document_note_resolution_honors_base_href(base_href: str, exp
assert ("Outside footnote." in markdown) is expected_note
+def test_html_fragment_only_link_honors_external_base_document() -> None:
+ """验证 fragment-only 链接按外部 base 解析,不会误关联当前 DOM 中同名脚注。"""
+ detail = "Useful main article text " * 20
+ payload = f"""<html><head><base href="other.html"></head><body><main><article><h1>Title</h1>
+ <p>{detail}<a href="#fn1">[1]</a></p></article></main>
+ <footer><aside id="fn1" role="doc-footnote"><p>Unrelated local 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 "Unrelated local footnote." not in markdown
+ assert not any(block.type == BlockType.PAGE_FOOTNOTE for block in middle.pages[0].blocks)
+ assert "https://example.com/other.html#fn1" in markdown
+
+
+def test_html_formula_wrapper_stops_after_second_non_nested_carrier(monkeypatch: pytest.MonkeyPatch) -> None:
+ """验证通用公式 wrapper 发现第二个并列 carrier 后立即失败,不继续扫描全部公式。"""
+ wrapper = lxml_html.fromstring('<div class="math">' + "<math></math>" * 1_000 + "</div>")
+ original_is_carrier = html_document_module._is_formula_carrier
+ carrier_checks = 0
+
+ def counted_is_carrier(element: etree._Element) -> bool:
+ """统计 wrapper 唯一 carrier 判定次数。"""
+ nonlocal carrier_checks
+ carrier_checks += 1
+ return original_is_carrier(element)
+
+ monkeypatch.setattr(html_document_module, "_is_formula_carrier", counted_is_carrier)
+
+ assert html_document_module._formula_wrapper_contains_only_carrier(wrapper) is False
+ assert carrier_checks == 2
+
+
def test_html_local_self_url_appends_referenced_note(tmp_path: Path) -> None:
"""验证本地 HTML 使用自身文件名 fragment 时同样保留正文选择外脚注。"""
detail = "Useful main article text " * 20