Skip to content

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

precompute html penalties and local links

myhloli58036ae00e07
diff --git a/mineru/model/flash/html/resources.py b/mineru/model/flash/html/resources.py
index ed24b03b..259af2d1 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 SplitResult, unquote, urljoin, urlsplit
+from urllib.parse import SplitResult, unquote, urljoin, urlsplit, urlunsplit
from lxml import etree # type: ignore[reportMissingImports]
@@ -148,6 +148,16 @@ class HtmlResourceContext:
if self._remote_base:
resolved = urljoin(self._remote_base, normalized)
return sanitize_hyperlink_target(resolved)
+ if self._local_root is not None and self._local_base is not None and parsed.path and not parsed.path.startswith("/"):
+ local_path = self._resolve_local_path(normalized)
+ if local_path is None:
+ return None
+ relative_path = local_path.relative_to(self._local_root).as_posix()
+ return sanitize_hyperlink_target(
+ urlunsplit(("", "", relative_path, parsed.query, parsed.fragment)),
+ allow_relative=True,
+ allow_fragment=True,
+ )
return sanitize_hyperlink_target(normalized, allow_relative=True, allow_fragment=True)
def resolve_image(self, source: str, *, alt: str = "") -> ResolvedMarkupImage | None:
diff --git a/mineru/model/flash/html/selector.py b/mineru/model/flash/html/selector.py
index 8f2bb080..bc72b7cd 100644
--- a/mineru/model/flash/html/selector.py
+++ b/mineru/model/flash/html/selector.py
@@ -90,6 +90,7 @@ def select_auto_content(body: etree._Element, stylesheet: MarkupStylesheet) -> C
"""高置信选择正文候选,任一保守门槛失败时回退完整 body。"""
metrics_by_element: dict[etree._Element, CandidateMetrics] = {}
body_metrics = _collect_metrics(body, stylesheet, metrics_by_element, TextStyle(), False, False)
+ repeated_penalties = _repeated_short_sibling_penalties(body)
candidates: list[_ScoredCandidate] = []
for element in body.iter():
if not isinstance(element.tag, str) or element is body:
@@ -101,7 +102,14 @@ def select_auto_content(body: etree._Element, stylesheet: MarkupStylesheet) -> C
continue
if not explicit and metrics.text_chars < _MIN_TEXT_CHARS and metrics.semantic_count < _MIN_SEMANTIC_OBJECTS:
continue
- candidates.append(_ScoredCandidate(element, metrics, _candidate_score(element, metrics), explicit))
+ candidates.append(
+ _ScoredCandidate(
+ element,
+ metrics,
+ _candidate_score(element, metrics, repeated_penalties.get(element, 0)),
+ explicit,
+ )
+ )
candidates.sort(key=lambda item: (-item.score, _document_order(item.element)))
repeated_candidate_items = _repeated_candidate_items(candidates, metrics_by_element)
@@ -212,13 +220,12 @@ def _collect_metrics(
return metrics
-def _candidate_score(element: etree._Element, metrics: CandidateMetrics) -> float:
+def _candidate_score(element: etree._Element, metrics: CandidateMetrics, repeated_penalty: int) -> float:
"""按正文、结构对象、链接与模板噪声计算确定性候选分数。"""
tokens = _tokens(element)
token_bonus = 200 if tokens & _POSITIVE_TOKENS else 0
token_penalty = 240 if tokens & _NEGATIVE_TOKENS else 0
link_density = metrics.link_chars / max(1, metrics.text_chars)
- repeated_penalty = _repeated_short_sibling_penalty(element)
return (
metrics.text_chars
+ metrics.paragraph_chars
@@ -246,23 +253,30 @@ def _tokens(element: etree._Element) -> frozenset[str]:
return frozenset(token for token in _TOKEN_RE.split(value) if token)
-def _repeated_short_sibling_penalty(element: etree._Element) -> int:
- """统计候选内部重复短同级节点簇,降低菜单和文章列表分数。"""
- penalty = 0
- for parent in element.iter():
- if not isinstance(parent.tag, str):
- continue
+def _repeated_short_sibling_penalties(root: etree._Element) -> dict[etree._Element, int]:
+ """单次后序遍历预计算各子树的重复短同级惩罚,供嵌套候选共享。"""
+ elements = [element for element in root.iter() if isinstance(element.tag, str)]
+ short_text_lengths: dict[etree._Element, int] = {}
+ penalties: dict[etree._Element, int] = {}
+ for parent in reversed(elements):
+ text_length = min(len(_normalized_text(parent.text)), 161)
+ subtree_penalty = 0
groups: dict[tuple[str, tuple[str, ...]], int] = {}
for child in parent:
- if not isinstance(child.tag, str):
- continue
- text = _normalized_text(" ".join(child.itertext()))
- if not text or len(text) > 160:
- continue
- signature = (local_name(child), tuple(sorted(_tokens(child))))
- groups[signature] = groups.get(signature, 0) + 1
- penalty += sum(count - 2 for count in groups.values() if count > 2)
- return penalty
+ if isinstance(child.tag, str):
+ child_text_length = short_text_lengths[child]
+ if child_text_length:
+ text_length = min(text_length + (1 if text_length else 0) + child_text_length, 161)
+ subtree_penalty += penalties[child]
+ if child_text_length <= 160 and child_text_length > 0:
+ signature = (local_name(child), tuple(sorted(_tokens(child))))
+ groups[signature] = groups.get(signature, 0) + 1
+ tail_length = len(_normalized_text(child.tail))
+ if tail_length:
+ text_length = min(text_length + (1 if text_length else 0) + tail_length, 161)
+ short_text_lengths[parent] = text_length
+ penalties[parent] = subtree_penalty + sum(count - 2 for count in groups.values() if count > 2)
+ return penalties
def _repeated_candidate_items(
diff --git a/tests/unittest/test_flash_html.py b/tests/unittest/test_flash_html.py
index 557dcba7..9b9e7e37 100644
--- a/tests/unittest/test_flash_html.py
+++ b/tests/unittest/test_flash_html.py
@@ -360,6 +360,29 @@ def test_html_auto_selection_precomputes_repeated_candidate_groups(monkeypatch:
assert token_calls < item_count * 20
+def test_html_auto_selection_precomputes_nested_subtree_penalties(monkeypatch: pytest.MonkeyPatch) -> None:
+ """验证嵌套候选共享子树的短同级惩罚只线性统计文本。"""
+ depth = 20
+ leaf_count = 500
+ original_normalized_text = html_selector_module._normalized_text
+ normalization_calls = 0
+
+ def counted_normalized_text(value: str | None) -> str:
+ """统计正文选择期间的文本规范化次数。"""
+ nonlocal normalization_calls
+ normalization_calls += 1
+ return original_normalized_text(value)
+
+ monkeypatch.setattr(html_selector_module, "_normalized_text", counted_normalized_text)
+ nested_start = '<div class="content">' * depth
+ nested_end = "</div>" * depth
+ leaves = "".join(f"<span>item {index}</span>" for index in range(leaf_count))
+
+ doc_analyze(f"<html><body>{nested_start}{leaves}{nested_end}</body></html>".encode(), file_suffix="html")
+
+ assert normalization_calls < leaf_count * 8
+
+
def test_html_referenced_external_footnote_keeps_anchor_and_content() -> None:
"""验证正文候选外但被引用的 HTML footnote 会追加并生成可兑现 anchor。"""
payload = b"""<html><body><article><h1>Notes</h1>
@@ -943,6 +966,20 @@ def test_html_local_base_images_styles_and_escape_are_bounded(tmp_path: Path) ->
assert _image_body(exported.middle_json).image_path is not None
+def test_html_local_base_resolves_relative_links(tmp_path: Path) -> None:
+ """验证本地 HTML 的普通相对链接同样按安全 base 目录解析。"""
+ (tmp_path / "subdir").mkdir()
+ source = tmp_path / "sample.html"
+ source.write_text(
+ '<html><head><base href="subdir/"></head><body><p><a href="next.html">Next</a></p></body></html>',
+ encoding="utf-8",
+ )
+
+ markdown = parse(source).markdown()
+
+ assert "[Next](subdir/next.html)" in markdown
+
+
def test_html_remote_source_resolves_relative_links_without_fetching_images() -> None:
"""验证 URL 来源只把相对链接与图片规范为绝对 URL,不下载远程图片。"""
context = HtmlSourceContext(source_uri="https://example.com/news/page.html")