Skip to content

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

add anchor management for HTML/XHTML documents with visibility and identity policies

myhloli9db13fcfc119
diff --git a/CLAUDE.md b/CLAUDE.md
index 647cc31f..2661f334 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -78,8 +78,7 @@ from mineru.render import RenderMode
### 统一文档信息投影
-MinerU 文档解析的目标是保留具有跨格式价值的内容和结构,并通过统一 Middle JSON 稳定导出多种格式;目标不是逐输入格式、逐排版细节地 100% 复刻源文件。
-
+- 目标不是逐输入格式、逐排版细节地 100% 复刻源文件。
- 不为单一输入格式增加只用于还原罕见排版、编号样式或物理分页的私有 block、私有字段或 renderer 特判。
- Review 时,源格式细节未被 100% 还原不应自动视为缺陷。
- 禁止通过不断增加格式例外来追求源文件视觉级复刻。
diff --git a/mineru/model/flash/_shared/markup/__init__.py b/mineru/model/flash/_shared/markup/__init__.py
index 0facf68d..064cb8e1 100644
--- a/mineru/model/flash/_shared/markup/__init__.py
+++ b/mineru/model/flash/_shared/markup/__init__.py
@@ -1,21 +1,39 @@
# Copyright (c) Opendatalab. All rights reserved.
"""Flash EPUB 与 HTML 共用的静态标记文档投影能力。"""
+from .anchors import (
+ AnchorTextNormalization,
+ AnchorVisibilityScope,
+ MarkupAnchorDocument,
+ MarkupAnchorPolicy,
+ MarkupAnchorRegistry,
+ canonical_anchor,
+ element_id,
+ visible_element_text,
+)
from .formula import FormulaDisplay, FormulaExtraction, FormulaSourceKind, extract_formula, strip_formula_delimiters
from .projector import MarkupContext, MarkupProjector, ResolvedMarkupImage
from .styles import ElementStyle, MarkupStylesheet, TextStyle, TextStyleDelta
__all__ = [
+ "AnchorTextNormalization",
+ "AnchorVisibilityScope",
"ElementStyle",
"FormulaDisplay",
"FormulaExtraction",
"FormulaSourceKind",
+ "MarkupAnchorDocument",
+ "MarkupAnchorPolicy",
+ "MarkupAnchorRegistry",
"MarkupContext",
"MarkupProjector",
"MarkupStylesheet",
"ResolvedMarkupImage",
"TextStyle",
"TextStyleDelta",
+ "canonical_anchor",
+ "element_id",
"extract_formula",
"strip_formula_delimiters",
+ "visible_element_text",
]
diff --git a/mineru/model/flash/_shared/markup/anchors.py b/mineru/model/flash/_shared/markup/anchors.py
new file mode 100644
index 00000000..3cfdb37e
--- /dev/null
+++ b/mineru/model/flash/_shared/markup/anchors.py
@@ -0,0 +1,183 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""集中建立静态 HTML/XHTML 标题、脚注与 fragment anchor 索引。"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+import hashlib
+import html
+import re
+from typing import Literal, Protocol, TypeAlias
+
+from lxml import etree # type: ignore[reportMissingImports]
+
+from .projector import local_name, visible_raw_text_with_style
+from .styles import MarkupStylesheet, TextStyle
+
+
+AnchorVisibilityScope: TypeAlias = Literal["all_ancestors", "nearest_body"]
+AnchorTextNormalization: TypeAlias = Literal["unicode_whitespace", "xhtml_whitespace"]
+
+_HEADING_TAGS = frozenset({"h1", "h2", "h3", "h4", "h5", "h6"})
+_XHTML_WHITESPACE_RE = re.compile(r"[\t\r\n\f ]+")
+_XML_ID = "{http://www.w3.org/XML/1998/namespace}id"
+
+
+@dataclass(frozen=True, slots=True)
+class MarkupAnchorDocument:
+ """描述一个待建立 anchor 索引的 DOM、样式表与兼容可见性规则。"""
+
+ key: str
+ root: etree._Element
+ stylesheet: MarkupStylesheet
+ visibility_scope: AnchorVisibilityScope = "all_ancestors"
+ text_normalization: AnchorTextNormalization = "unicode_whitespace"
+
+
+class MarkupAnchorPolicy(Protocol):
+ """定义格式适配器生成标题、脚注 anchor 所需的稳定策略。"""
+
+ anchor_prefix: str
+ register_document_start: bool
+
+ def heading_identity(self, element: etree._Element, ordinal: int) -> str:
+ """返回当前标题参与稳定摘要的格式专属 identity。"""
+
+ def is_materializable_note(self, element: etree._Element, document: MarkupAnchorDocument) -> bool:
+ """判断当前元素是否是能够兑现文本 anchor 的格式专属脚注。"""
+
+ def note_identity(self, element: etree._Element, ordinal: int) -> str:
+ """返回当前脚注参与稳定摘要的格式专属 identity。"""
+
+
+def element_id(element: etree._Element) -> str | None:
+ """返回元素去除首尾空白后的 HTML id 或 xml:id。"""
+ value = (element.get("id") or element.get(_XML_ID) or "").strip()
+ return value or None
+
+
+def visible_element_text(element: etree._Element, document: MarkupAnchorDocument) -> str:
+ """按文档兼容配置解析祖先样式链,并返回最终可输出的纯文本。"""
+ inherited = TextStyle()
+ visibility_hidden = False
+ chain = [ancestor for ancestor in reversed(list(element.iterancestors())) if isinstance(ancestor.tag, str)]
+ if document.visibility_scope == "nearest_body":
+ body_index = next((index for index, ancestor in enumerate(chain) if local_name(ancestor) == "body"), None)
+ if body_index is not None:
+ chain = chain[body_index:]
+ chain.append(element)
+ for current in chain:
+ resolved = document.stylesheet.resolve(current, inherited, visibility_hidden)
+ if resolved.subtree_hidden:
+ return ""
+ inherited = resolved.text
+ visibility_hidden = resolved.visibility_hidden
+ value = visible_raw_text_with_style(element, document.stylesheet, inherited, visibility_hidden)
+ if document.text_normalization == "xhtml_whitespace":
+ return _XHTML_WHITESPACE_RE.sub(" ", html.unescape(value)).strip()
+ return " ".join(value.split())
+
+
+def canonical_anchor(prefix: str, document_key: str, identity: str) -> str:
+ """按格式前缀、文档 key 与 identity 生成稳定的二十位摘要 anchor。"""
+ digest = hashlib.sha256(f"{document_key}#{identity}".encode()).hexdigest()[:20]
+ return f"{prefix}-{digest}"
+
+
+class MarkupAnchorRegistry:
+ """统一登记多文档标题、脚注及源 fragment 到实际输出 anchor 的映射。"""
+
+ def __init__(self, documents: list[MarkupAnchorDocument], policy: MarkupAnchorPolicy) -> None:
+ """按调用方文档顺序建立稳定索引,并保留格式专属 identity 规则。"""
+ self._policy = policy
+ self._heading_anchors: dict[etree._Element, str] = {}
+ self._note_anchors: dict[etree._Element, str] = {}
+ self._targets: dict[tuple[str, str | None], str] = {}
+ self._heading_labels: dict[str, str] = {}
+ for document in documents:
+ self._register_document(document)
+
+ def _register_document(self, document: MarkupAnchorDocument) -> None:
+ """登记单个 DOM 的标题、脚注及全部可解析 fragment 别名。"""
+ headings: list[tuple[etree._Element, str]] = []
+ for element in document.root.iter():
+ if not isinstance(element.tag, str) or local_name(element) not in _HEADING_TAGS:
+ continue
+ if label := visible_element_text(element, document):
+ headings.append((element, label))
+ for ordinal, (heading, label) in enumerate(headings):
+ identity = self._policy.heading_identity(heading, ordinal)
+ anchor = canonical_anchor(self._policy.anchor_prefix, document.key, identity)
+ self._heading_anchors[heading] = anchor
+ self._heading_labels[anchor] = label
+
+ notes = [
+ element
+ for element in document.root.iter()
+ if isinstance(element.tag, str) and self._policy.is_materializable_note(element, document)
+ ]
+ for ordinal, note in enumerate(notes):
+ identity = self._policy.note_identity(note, ordinal)
+ self._note_anchors[note] = canonical_anchor(self._policy.anchor_prefix, document.key, identity)
+
+ if self._policy.register_document_start and headings:
+ self._targets[(document.key, None)] = self._heading_anchors[headings[0][0]]
+ for element in document.root.iter():
+ if not isinstance(element.tag, str) or not (fragment := element_id(element)):
+ continue
+ target_key = (document.key, fragment)
+ if target_key in self._targets:
+ continue
+ if anchor := self._target_anchor(element):
+ self._targets[target_key] = anchor
+
+ def _target_anchor(self, element: etree._Element) -> str | None:
+ """把任意 fragment 元素映射到自身、最近祖先或首个后代输出目标。"""
+ direct = self._heading_anchors.get(element) or self._note_anchors.get(element)
+ if direct is not None:
+ return direct
+ ancestor = next(
+ (parent for parent in element.iterancestors() if parent in self._heading_anchors or parent in self._note_anchors),
+ None,
+ )
+ if ancestor is not None:
+ return self._heading_anchors.get(ancestor) or self._note_anchors.get(ancestor)
+ descendant = next(
+ (
+ child
+ for child in element.iterdescendants()
+ if isinstance(child.tag, str) and (child in self._heading_anchors or child in self._note_anchors)
+ ),
+ None,
+ )
+ if descendant is None:
+ return None
+ return self._heading_anchors.get(descendant) or self._note_anchors.get(descendant)
+
+ def heading_anchor(self, heading: etree._Element) -> str | None:
+ """返回一个已登记标题的规范 anchor。"""
+ return self._heading_anchors.get(heading)
+
+ def heading_label(self, anchor: str) -> str | None:
+ """返回规范标题 anchor 对应的可见标题文本。"""
+ return self._heading_labels.get(anchor)
+
+ def note_anchor(self, note: etree._Element) -> str | None:
+ """返回一个已登记脚注的规范 anchor。"""
+ return self._note_anchors.get(note)
+
+ def resolve_target(self, document_key: str, fragment: str | None) -> str | None:
+ """按文档 key 与可选源 fragment 返回不带井号的规范 anchor。"""
+ return self._targets.get((document_key, fragment))
+
+
+__all__ = [
+ "AnchorTextNormalization",
+ "AnchorVisibilityScope",
+ "MarkupAnchorDocument",
+ "MarkupAnchorPolicy",
+ "MarkupAnchorRegistry",
+ "canonical_anchor",
+ "element_id",
+ "visible_element_text",
+]
diff --git a/mineru/model/flash/epub/xhtml.py b/mineru/model/flash/epub/xhtml.py
index 21b99ddb..9344e4ae 100644
--- a/mineru/model/flash/epub/xhtml.py
+++ b/mineru/model/flash/epub/xhtml.py
@@ -4,23 +4,27 @@
from __future__ import annotations
import base64
-import hashlib
-import html
-import re
from dataclasses import dataclass
from lxml import etree # type: ignore[reportMissingImports]
from ....utils.image_payload import parse_image_data_uri_strict
from .._shared.hyperlink import sanitize_hyperlink_target
-from .._shared.markup import MarkupProjector, MarkupStylesheet, ResolvedMarkupImage, TextStyle
+from .._shared.markup import (
+ MarkupAnchorDocument,
+ MarkupAnchorRegistry,
+ MarkupProjector,
+ MarkupStylesheet,
+ ResolvedMarkupImage,
+ element_id,
+ visible_element_text,
+)
from .._shared.markup.projector import (
BLOCK_TAGS as _BLOCK_TAGS,
SKIPPED_TAGS as _SKIPPED_TAGS,
clean_text_node as _clean_text_node,
entity_text as _entity_text,
local_name as _local_name,
- visible_raw_text_with_style as _visible_raw_text_with_style,
)
from .constants import IMAGE_MEDIA_BY_EXTENSION, SVG_MEDIA_TYPE
from .package import EpubPackage
@@ -47,14 +51,6 @@ _NOTE_NON_TEXT_SUBTREES = frozenset(
"ul",
}
)
-_WHITESPACE_RE = re.compile(r"[\t\r\n\f ]+")
-_XML_ID = "{http://www.w3.org/XML/1998/namespace}id"
-
-
-def _element_id(element: etree._Element) -> str | None:
- """返回元素的 HTML id 或 xml:id。"""
- value = (element.get("id") or element.get(_XML_ID) or "").strip()
- return value or None
def _epub_types(element: etree._Element) -> frozenset[str]:
@@ -111,20 +107,6 @@ def _note_has_text_block(element: etree._Element) -> bool:
return False
-def _canonical_anchor(chapter_path: str, identity: str) -> str:
- """为章节内标题或 note 生成稳定且适合各 renderer 的短锚点。"""
- digest = hashlib.sha256(f"{chapter_path}#{identity}".encode("utf-8")).hexdigest()[:20]
- return f"epub-{digest}"
-
-
-@dataclass(frozen=True, slots=True)
-class _ChapterTree:
- """保存一个已解析 spine XHTML 内容树。"""
-
- path: str
- root: etree._Element
-
-
def _load_chapter_stylesheet(package: EpubPackage, chapter_path: str, root: etree._Element) -> MarkupStylesheet:
"""按章节 head 顺序加载包内 CSS 与内联 style。"""
stylesheet = MarkupStylesheet()
@@ -144,114 +126,58 @@ def _load_chapter_stylesheet(package: EpubPackage, chapter_path: str, root: etre
return stylesheet
-def _element_visible_text(element: etree._Element, stylesheet: MarkupStylesheet) -> str:
- """按祖先到自身的样式链返回元素最终可输出的纯文本。"""
- inherited = TextStyle()
- inherited_visibility_hidden = False
- chain = [ancestor for ancestor in reversed(list(element.iterancestors())) if isinstance(ancestor.tag, str)]
- body_index = next((index for index, ancestor in enumerate(chain) if _local_name(ancestor) == "body"), None)
- if body_index is not None:
- chain = chain[body_index:]
- chain.append(element)
- for current in chain:
- resolved = stylesheet.resolve(current, inherited, inherited_visibility_hidden)
- if resolved.subtree_hidden:
- return ""
- inherited = resolved.text
- inherited_visibility_hidden = resolved.visibility_hidden
- value = _visible_raw_text_with_style(element, stylesheet, inherited, inherited_visibility_hidden)
- return _WHITESPACE_RE.sub(" ", html.unescape(value)).strip()
+class _EpubAnchorPolicy:
+ """保持 EPUB 标题、脚注 identity 与可落地性判定的既有契约。"""
+
+ anchor_prefix = "epub"
+ register_document_start = True
+ @staticmethod
+ def heading_identity(element: etree._Element, ordinal: int) -> str:
+ """按源 ID 或匿名标题序号生成 EPUB 标题 identity。"""
+ return f"{element_id(element) or 'heading'}-{ordinal}"
-def _element_is_hidden(element: etree._Element, stylesheet: MarkupStylesheet) -> bool:
- """判断元素是否不会产生任何最终可输出的文本。"""
- return not _element_visible_text(element, stylesheet)
+ @staticmethod
+ def is_materializable_note(element: etree._Element, document: MarkupAnchorDocument) -> bool:
+ """沿用 EPUB note 语义、文本块能力和最终可见性判断。"""
+ return _is_individual_note(element) and _note_has_text_block(element) and bool(visible_element_text(element, document))
+
+ @staticmethod
+ def note_identity(element: etree._Element, ordinal: int) -> str:
+ """按 note 类型、源 ID 与章节内序号生成 EPUB 脚注 identity。"""
+ source_id = element_id(element)
+ return f"note-{_note_semantic(element)}-{source_id or 'anonymous'}-{ordinal}"
class EpubAnchorRegistry:
"""建立章节路径、标题与 note fragment 到实际 canonical anchor 的别名表。"""
- def __init__(self, chapters: list[_ChapterTree], package: EpubPackage) -> None:
+ def __init__(self, chapters: list[tuple[str, etree._Element]], package: EpubPackage) -> None:
"""预扫描全部选中 XHTML 章节,建立标题、note 与章节起点映射。"""
self._package = package
- self._heading_anchors: dict[etree._Element, str] = {}
- self._note_anchors: dict[etree._Element, str] = {}
- self._targets: dict[tuple[str, str | None], str] = {}
- self._heading_labels: dict[str, str] = {}
- for chapter in chapters:
- stylesheet = _load_chapter_stylesheet(package, chapter.path, chapter.root)
- headings: list[tuple[etree._Element, str]] = []
- for element in chapter.root.iter():
- if not isinstance(element.tag, str) or _local_name(element) not in {"h1", "h2", "h3", "h4", "h5", "h6"}:
- continue
- if label := _element_visible_text(element, stylesheet):
- headings.append((element, label))
- for ordinal, (heading, label) in enumerate(headings):
- source_id = _element_id(heading)
- identity = f"{source_id or 'heading'}-{ordinal}"
- anchor = _canonical_anchor(chapter.path, identity)
- self._heading_anchors[heading] = anchor
- self._heading_labels[anchor] = label
- notes = [
- element
- for element in chapter.root.iter()
- if isinstance(element.tag, str)
- and _is_individual_note(element)
- and _note_has_text_block(element)
- and not _element_is_hidden(element, stylesheet)
- ]
- for ordinal, note in enumerate(notes):
- source_id = _element_id(note)
- note_type = _note_semantic(note)
- identity = f"note-{note_type}-{source_id or 'anonymous'}-{ordinal}"
- self._note_anchors[note] = _canonical_anchor(chapter.path, identity)
-
- if headings:
- first_anchor = self._heading_anchors[headings[0][0]]
- self._targets[(chapter.path, None)] = first_anchor
- for element in chapter.root.iter():
- if not isinstance(element.tag, str) or not (fragment := _element_id(element)):
- continue
- if (chapter.path, fragment) in self._targets:
- continue
- target_anchor = self._target_anchor_for_element(element)
- if target_anchor is not None:
- self._targets[(chapter.path, fragment)] = target_anchor
-
- def _target_anchor_for_element(self, element: etree._Element) -> str | None:
- """把任意 fragment 元素映射到自身、祖先或后代的可输出标题与脚注。"""
- direct = self._heading_anchors.get(element) or self._note_anchors.get(element)
- if direct is not None:
- return direct
- ancestor = next(
- (parent for parent in element.iterancestors() if parent in self._heading_anchors or parent in self._note_anchors),
- None,
- )
- if ancestor is not None:
- return self._heading_anchors.get(ancestor) or self._note_anchors.get(ancestor)
- descendant = next(
- (
- child
- for child in element.iterdescendants()
- if isinstance(child.tag, str) and (child in self._heading_anchors or child in self._note_anchors)
- ),
- None,
- )
- if descendant is None:
- return None
- return self._heading_anchors.get(descendant) or self._note_anchors.get(descendant)
+ documents = [
+ MarkupAnchorDocument(
+ key=chapter_path,
+ root=root,
+ stylesheet=_load_chapter_stylesheet(package, chapter_path, root),
+ visibility_scope="nearest_body",
+ text_normalization="xhtml_whitespace",
+ )
+ for chapter_path, root in chapters
+ ]
+ self._registry = MarkupAnchorRegistry(documents, _EpubAnchorPolicy())
def heading_anchor(self, heading: etree._Element) -> str | None:
- """返回一个已预扫描标题的规范 anchor。"""
- return self._heading_anchors.get(heading)
+ """返回一个已预扫描 EPUB 标题的规范 anchor。"""
+ return self._registry.heading_anchor(heading)
def heading_label(self, anchor: str) -> str | None:
- """返回 canonical 标题 anchor 对应的可见标题文本。"""
- return self._heading_labels.get(anchor)
+ """返回规范 EPUB 标题 anchor 对应的可见标签。"""
+ return self._registry.heading_label(anchor)
def note_anchor(self, note: etree._Element) -> str | None:
- """返回一个已预扫描 Footnote/Endnote 的 canonical anchor。"""
- return self._note_anchors.get(note)
+ """返回一个已预扫描 EPUB Footnote/Endnote anchor。"""
+ return self._registry.note_anchor(note)
def resolve_anchor(self, href: str, *, base_part: str) -> str | None:
"""解析指向正文标题或 note 的 EPUB 包内链接,并返回不带井号的 anchor。"""
@@ -266,7 +192,7 @@ class EpubAnchorRegistry:
target = self._package.resolve_reference(normalized, base_part=base_part)
if target is None:
return None
- return self._targets.get((target.path, target.fragment))
+ return self._registry.resolve_target(target.path, target.fragment)
def resolve_link(self, href: str, *, base_part: str) -> str | None:
"""解析安全外部链接或指向已输出标题/note 的 EPUB 内部链接。"""
@@ -279,7 +205,7 @@ class EpubAnchorRegistry:
def build_anchor_registry(chapters: list[tuple[str, etree._Element]], package: EpubPackage) -> EpubAnchorRegistry:
"""从已解析章节元组建立跨章节锚点注册表。"""
- return EpubAnchorRegistry([_ChapterTree(path, root) for path, root in chapters], package)
+ return EpubAnchorRegistry(chapters, package)
@dataclass(frozen=True, slots=True)
diff --git a/mineru/model/flash/html/anchors.py b/mineru/model/flash/html/anchors.py
index 5b44870e..70daad6d 100644
--- a/mineru/model/flash/html/anchors.py
+++ b/mineru/model/flash/html/anchors.py
@@ -5,18 +5,15 @@ from __future__ import annotations
from collections.abc import Callable
from copy import deepcopy
-import hashlib
from lxml import etree # type: ignore[reportMissingImports]
-from .._shared.markup import MarkupStylesheet, TextStyle
+from .._shared.markup import MarkupAnchorDocument, MarkupAnchorRegistry, MarkupStylesheet, TextStyle, element_id
from .._shared.markup.projector import BLOCK_TAGS, SKIPPED_TAGS, local_name, visible_raw_text_with_style
-_HEADING_TAGS = frozenset({"h1", "h2", "h3", "h4", "h5", "h6"})
_NOTE_TYPES = frozenset({"footnote", "endnote", "rearnote"})
_NOTE_ROLES = frozenset({"doc-footnote", "doc-endnote"})
-_XML_ID = "{http://www.w3.org/XML/1998/namespace}id"
_NON_TEXT_BLOCK_TAGS = frozenset(
{
"figure",
@@ -51,12 +48,6 @@ def is_note_element(element: etree._Element) -> bool:
return bool(roles & _NOTE_ROLES or types & _NOTE_TYPES)
-def element_id(element: etree._Element) -> str | None:
- """返回元素的 HTML id 或 xml:id。"""
- value = (element.get("id") or element.get(_XML_ID) or "").strip()
- return value or None
-
-
def append_referenced_notes(
selected_root: etree._Element,
original_body: etree._Element,
@@ -147,6 +138,30 @@ def _copy_note_with_source_visibility(
return wrapper
+class _HtmlAnchorPolicy:
+ """保持 standalone HTML 标题与脚注 identity 的既有生成规则。"""
+
+ anchor_prefix = "html"
+ register_document_start = False
+
+ @staticmethod
+ def heading_identity(element: etree._Element, ordinal: int) -> str:
+ """按源 ID 或匿名标题序号生成 HTML 标题 identity。"""
+ identity = element_id(element) or f"heading-{ordinal}"
+ return f"heading-{identity}-{ordinal}"
+
+ @staticmethod
+ def is_materializable_note(element: etree._Element, document: MarkupAnchorDocument) -> bool:
+ """沿用 HTML note marker 与顶层文本可落地性判断。"""
+ return is_note_element(element) and _note_has_materializable_text_target(element, document.stylesheet)
+
+ @staticmethod
+ def note_identity(element: etree._Element, ordinal: int) -> str:
+ """按源 ID 或匿名脚注序号生成 HTML 脚注 identity。"""
+ identity = element_id(element) or f"note-{ordinal}"
+ return f"note-{identity}-{ordinal}"
+
+
class HtmlAnchorRegistry:
"""把选中 DOM 的标题、note 和源 fragment 映射到稳定 anchor。"""
@@ -158,94 +173,35 @@ class HtmlAnchorRegistry:
source_key: str = "html",
) -> None:
"""预扫描选中内容,建立 document-wide 唯一 anchor 映射。"""
- self._heading_anchors: dict[etree._Element, str] = {}
- self._note_anchors: dict[etree._Element, str] = {}
- self._heading_labels: dict[str, str] = {}
- self._targets: dict[str, str] = {}
- headings = [
- element
- for element in root.iter()
- if isinstance(element.tag, str)
- and local_name(element) in _HEADING_TAGS
- and _visible_element_text(element, stylesheet)
- ]
- for ordinal, heading in enumerate(headings):
- identity = element_id(heading) or f"heading-{ordinal}"
- anchor = _canonical_anchor(source_key, f"heading-{identity}-{ordinal}")
- self._heading_anchors[heading] = anchor
- self._heading_labels[anchor] = _visible_element_text(heading, stylesheet)
- notes = [
- element
- for element in root.iter()
- if isinstance(element.tag, str)
- and is_note_element(element)
- and _note_has_materializable_text_target(element, stylesheet)
- ]
- for ordinal, note in enumerate(notes):
- identity = element_id(note) or f"note-{ordinal}"
- self._note_anchors[note] = _canonical_anchor(source_key, f"note-{identity}-{ordinal}")
- for element in root.iter():
- if not isinstance(element.tag, str) or not (identity := element_id(element)) or identity in self._targets:
- continue
- if anchor := self._target_anchor(element):
- self._targets[identity] = anchor
-
- def _target_anchor(self, element: etree._Element) -> str | None:
- """把任意 fragment 元素映射到自身、祖先或后代的可输出目标。"""
- direct = self._heading_anchors.get(element) or self._note_anchors.get(element)
- if direct:
- return direct
- for parent in element.iterancestors():
- anchor = self._heading_anchors.get(parent) or self._note_anchors.get(parent)
- if anchor:
- return anchor
- for child in element.iterdescendants():
- anchor = self._heading_anchors.get(child) or self._note_anchors.get(child)
- if anchor:
- return anchor
- return None
+ self._source_key = source_key
+ document = MarkupAnchorDocument(
+ key=source_key,
+ root=root,
+ stylesheet=stylesheet,
+ visibility_scope="all_ancestors",
+ text_normalization="unicode_whitespace",
+ )
+ self._registry = MarkupAnchorRegistry([document], _HtmlAnchorPolicy())
def heading_anchor(self, heading: etree._Element) -> str | None:
"""返回标题的规范 anchor。"""
- return self._heading_anchors.get(heading)
+ return self._registry.heading_anchor(heading)
def heading_label(self, anchor: str) -> str | None:
"""返回规范标题 anchor 对应的可见标签。"""
- return self._heading_labels.get(anchor)
+ return self._registry.heading_label(anchor)
def note_anchor(self, note: etree._Element) -> str | None:
"""返回单条 Footnote/Endnote 的规范 anchor。"""
- return self._note_anchors.get(note)
+ return self._registry.note_anchor(note)
def resolve_fragment(self, fragment: str) -> str | None:
"""把源文档 fragment 转换为实际可输出的内部链接。"""
normalized = fragment.removeprefix("#").strip()
- anchor = self._targets.get(normalized)
+ anchor = self._registry.resolve_target(self._source_key, normalized)
return f"#{anchor}" if anchor else None
-def _canonical_anchor(source_key: str, identity: str) -> str:
- """为 HTML 标题或脚注生成短而稳定的规范 anchor。"""
- digest = hashlib.sha256(f"{source_key}#{identity}".encode()).hexdigest()[:20]
- return f"html-{digest}"
-
-
-def _visible_element_text(element: etree._Element, stylesheet: MarkupStylesheet) -> str:
- """按祖先样式链提取元素最终会由 projector 输出的可见文本。"""
- inherited = TextStyle()
- visibility_hidden = False
- chain = [ancestor for ancestor in reversed(list(element.iterancestors())) if isinstance(ancestor.tag, str)]
- chain.append(element)
- for current in chain:
- resolved = stylesheet.resolve(current, inherited, visibility_hidden)
- if resolved.subtree_hidden:
- return ""
- inherited = resolved.text
- visibility_hidden = resolved.visibility_hidden
- value = visible_raw_text_with_style(element, stylesheet, inherited, visibility_hidden)
- return " ".join(value.split())
-
-
def _note_has_materializable_text_target(element: etree._Element, stylesheet: MarkupStylesheet) -> bool:
"""判断 note 是否会投影出可挂载 anchor 的顶层文本 block。"""
inherited = TextStyle()
@@ -313,4 +269,4 @@ def _container_materializes_text_block(
return False
-__all__ = ["HtmlAnchorRegistry", "append_referenced_notes", "element_id", "is_note_element"]
+__all__ = ["HtmlAnchorRegistry", "append_referenced_notes", "is_note_element"]
diff --git a/mineru/model/flash/html/contracts.py b/mineru/model/flash/html/contracts.py
index 6efe19c1..bc877b43 100644
--- a/mineru/model/flash/html/contracts.py
+++ b/mineru/model/flash/html/contracts.py
@@ -9,10 +9,11 @@ from pathlib import Path
@dataclass(frozen=True, slots=True)
class HtmlSourceContext:
- """保存相对链接解析所需的来源 URI 与本地安全根目录。"""
+ """保存相对链接解析及 HTML 解码所需的来源上下文。"""
source_uri: str | None = None
local_resource_root: Path | None = None
+ transport_encoding: str | None = None
__all__ = ["HtmlSourceContext"]
diff --git a/mineru/model/flash/html/document.py b/mineru/model/flash/html/document.py
index 32fe44df..07aefab1 100644
--- a/mineru/model/flash/html/document.py
+++ b/mineru/model/flash/html/document.py
@@ -3,6 +3,7 @@
from __future__ import annotations
+import codecs
from copy import deepcopy
from dataclasses import dataclass
import re
@@ -78,14 +79,19 @@ def parse_html_document(file_bytes: bytes, source_context: HtmlSourceContext | N
body = etree.SubElement(root, "body")
return HtmlDocument(root, body, (), None, None, None, None, context)
+ transport_encoding = _normalize_transport_encoding(context.transport_encoding)
parser = lxml_html.HTMLParser(
recover=True,
no_network=True,
remove_comments=False,
huge_tree=False,
+ encoding=transport_encoding,
)
try:
- root = lxml_html.document_fromstring(_html_parser_input(file_bytes), parser=parser)
+ root = lxml_html.document_fromstring(
+ _html_parser_input(file_bytes, transport_encoding=transport_encoding),
+ parser=parser,
+ )
except (etree.ParserError, etree.XMLSyntaxError, UnicodeError, ValueError) as exc:
raise HtmlParseError(f"Malformed HTML document: {exc}") from exc
_validate_dom_shape(root)
@@ -142,8 +148,20 @@ def parse_html_document(file_bytes: bytes, source_context: HtmlSourceContext | N
)
-def _html_parser_input(file_bytes: bytes) -> bytes | str:
+def _normalize_transport_encoding(value: str | None) -> str | None:
+ """把 HTTP 声明编码规范化为 lxml 可用名称,未知标签继续走文档内探测。"""
+ if not value:
+ return None
+ try:
+ return codecs.lookup(value).name
+ except LookupError:
+ return None
+
+
+def _html_parser_input(file_bytes: bytes, *, transport_encoding: str | None = None) -> bytes | str:
"""无显式编码且符合 UTF-8 时先解码,避免 lxml 按单字节旧编码解释正文。"""
+ if transport_encoding is not None:
+ return file_bytes
if file_bytes.startswith(_UNICODE_BOMS) or _HTML_ENCODING_DECLARATION_RE.search(file_bytes[:4096]):
return file_bytes
try:
diff --git a/mineru/model/flash/html/wire.py b/mineru/model/flash/html/wire.py
index 23ab4c01..55605cee 100644
--- a/mineru/model/flash/html/wire.py
+++ b/mineru/model/flash/html/wire.py
@@ -525,6 +525,7 @@ def _validate_list_container(container: etree._Element, *, top_wrapper: etree._E
if item_type not in _LIST_LEAF_TYPES:
raise _WireValidationError("invalid_list_leaf_type")
_non_negative_integer(item, "data-block-index", required=False)
+ _validate_list_item_content_shape(item, nested_lists)
for marker in _descendant_markers(item):
if marker is item or _is_within_any(marker, nested_lists):
continue
@@ -541,6 +542,34 @@ def _validate_list_container(container: etree._Element, *, top_wrapper: etree._E
_validate_list_container(nested)
+def _validate_list_item_content_shape(item: etree._Element, nested_lists: list[etree._Element]) -> None:
+ """校验列表项的 marker/content carrier 唯一且不会遗漏旁路可见内容。"""
+ _validate_element_only_content(item)
+ candidates = [
+ child for child in item.iterdescendants() if isinstance(child.tag, str) and not _is_within_any(child, nested_lists)
+ ]
+ content_carriers = [child for child in candidates if "mineru-list-content" in _class_tokens(child)]
+ marker_carriers = [child for child in candidates if "mineru-list-marker" in _class_tokens(child)]
+ if len(content_carriers) > 1 or len(marker_carriers) > 1:
+ raise _WireValidationError("invalid_list_content_shape")
+
+ allowed_children = [*nested_lists, *content_carriers, *marker_carriers]
+ if any(child not in allowed_children for child in _element_children(item)):
+ raise _WireValidationError("invalid_list_content_shape")
+ if not content_carriers:
+ if marker_carriers:
+ raise _WireValidationError("invalid_list_content_shape")
+ return
+
+ content_carrier = content_carriers[0]
+ if content_carrier.getparent() is not item or local_name(content_carrier) != "span":
+ raise _WireValidationError("invalid_list_content_shape")
+ if marker_carriers:
+ marker_carrier = marker_carriers[0]
+ if marker_carrier.getparent() is not item or local_name(marker_carrier) != "span" or _element_children(marker_carrier):
+ raise _WireValidationError("invalid_list_content_shape")
+
+
def _validate_index_root(content_root: etree._Element, wrapper: etree._Element) -> None:
"""校验目录根 nav 与递归目录叶子元数据。"""
if local_name(content_root) != "nav" or (content_root.get("data-block-type") or "").strip() != BlockType.INDEX:
diff --git a/mineru/parser/api_server.py b/mineru/parser/api_server.py
index b98f9d88..f9b1b73e 100644
--- a/mineru/parser/api_server.py
+++ b/mineru/parser/api_server.py
@@ -1287,11 +1287,12 @@ def _count_pages_in_range(page_range: str) -> int:
@dataclass(frozen=True, slots=True)
class _ExtractedSource:
- """保存 API 输入字节及 HTML 相对资源解析所需的原始来源。"""
+ """保存 API 输入字节及 HTML 来源上下文。"""
data: bytes
source_uri: str | None = None
local_resource_root: pathlib.Path | None = None
+ transport_encoding: str | None = None
async def _extract_bytes(
@@ -1319,7 +1320,11 @@ async def _extract_bytes(
async with httpx.AsyncClient(timeout=url_timeout) as cli:
r = await cli.get(source.url)
r.raise_for_status()
- return _ExtractedSource(r.content, source_uri=str(r.url))
+ return _ExtractedSource(
+ r.content,
+ source_uri=str(r.url),
+ transport_encoding=r.charset_encoding,
+ )
if isinstance(source, InlineSource):
return _ExtractedSource(_decode_inline_data(source.data))
if isinstance(source, LocalSource):
@@ -1386,6 +1391,7 @@ async def _run_job(
source_context = HtmlSourceContext(
source_uri=extracted.source_uri,
local_resource_root=extracted.local_resource_root,
+ transport_encoding=extracted.transport_encoding,
)
result = await parse_async(
str(tmp_path),
diff --git a/tests/unittest/test_flash_epub.py b/tests/unittest/test_flash_epub.py
index f3fb14dc..16fb8ce9 100644
--- a/tests/unittest/test_flash_epub.py
+++ b/tests/unittest/test_flash_epub.py
@@ -106,6 +106,10 @@ def test_epub_notes_use_page_footnote_and_document_wide_anchors() -> None:
duplicate_first = footnote_by_text["First duplicate note."]
duplicate_second = footnote_by_text["Second duplicate note."]
assert first.anchor and endnote.anchor and duplicate_first.anchor # type: ignore[union-attr]
+ assert first.anchor == "epub-5da65ec1e273b731b44c" # type: ignore[union-attr]
+ assert endnote.anchor == "epub-b7ab2fcf9373c09c71d6" # type: ignore[union-attr]
+ assert duplicate_first.anchor == "epub-2bd2576dd7c5d3cf58f4" # type: ignore[union-attr]
+ assert duplicate_second.anchor == "epub-2b154ee53d6a59bb32f7" # type: ignore[union-attr]
assert second.anchor is None # type: ignore[union-attr]
assert duplicate_second.anchor and duplicate_second.anchor != duplicate_first.anchor # type: ignore[union-attr]
assert footnote_by_text["ARIA footnote."].anchor # type: ignore[union-attr]
@@ -167,6 +171,8 @@ def test_epub_internal_links_and_lists_use_cross_renderer_projection() -> None:
first_title = first_page.blocks[0]
second_title = second_page.blocks[0]
assert first_title.anchor and second_title.anchor # type: ignore[union-attr]
+ assert first_title.anchor == "epub-1daacccca5bf43833643" # type: ignore[union-attr]
+ assert second_title.anchor == "epub-8d7fe965e2d714cf08ae" # type: ignore[union-attr]
markdown = render_markdown(middle)
assert markdown.startswith(f'<a id="{first_title.anchor}"></a>\n# Chapter One') # type: ignore[union-attr]
assert "NAV Chapter One" not in markdown
diff --git a/tests/unittest/test_flash_html.py b/tests/unittest/test_flash_html.py
index 1e88e505..c75036a2 100644
--- a/tests/unittest/test_flash_html.py
+++ b/tests/unittest/test_flash_html.py
@@ -6,8 +6,11 @@ from copy import copy
from io import BytesIO
import json
from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
from zipfile import ZipFile
+import httpx
import pytest
from bs4 import BeautifulSoup
from lxml import etree, html as lxml_html # type: ignore[reportMissingImports]
@@ -223,6 +226,8 @@ def test_html_doc_analyze_projects_static_semantics_and_renderers() -> None:
assert middle.is_full_document is True
assert [page.page_idx for page in middle.pages] == [0]
assert all(block.bbox is None for block in middle.pages[0].blocks)
+ title = next(block for block in middle.pages[0].blocks if block.type == BlockType.DOC_TITLE)
+ assert title.anchor == "html-39fc7010518f54fa3fa9" # type: ignore[union-attr]
raw_blocks = _all_raw_blocks(model.pages)
raw_types = {block["type"] for block in raw_blocks}
@@ -275,6 +280,49 @@ def test_html_declared_legacy_charset_remains_supported() -> None:
assert "café" in markdown
+def test_html_parse_server_url_preserves_http_declared_charset(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ """验证 URL HTML 使用 HTTP Content-Type 声明编码而不依赖文档内 meta。"""
+ expected = "日本語テスト"
+ url = "https://example.com/sample.html"
+ response = httpx.Response(
+ 200,
+ content=f"<html><body><p>{expected}</p></body></html>".encode("shift_jis"),
+ headers={"Content-Type": "text/html; charset=shift_jis"},
+ request=httpx.Request("GET", url),
+ )
+ client = AsyncMock()
+ client.__aenter__.return_value = client
+ client.get.return_value = response
+ monkeypatch.setattr(api_server, "httpx", SimpleNamespace(AsyncClient=lambda **_: client))
+ file_store = FileStore(tmp_path / "api-files")
+ request = CreateJobRequest.model_validate(
+ {
+ "files": [{"source": {"type": "url", "url": url}}],
+ "tier": "standard",
+ "output_formats": ["middle_json"],
+ }
+ )
+ record = api_server.JobStore().create(request, file_store)
+
+ asyncio.run(
+ api_server._run_job(
+ record,
+ request,
+ file_store,
+ ocr_mode="auto",
+ image_analysis=True,
+ )
+ )
+
+ parsed_file = record.files[0]
+ assert parsed_file.status == "completed"
+ assert parsed_file.output_files is not None and parsed_file.output_files.middle_json is not None
+ middle_record = file_store.get_file(parsed_file.output_files.middle_json.file_id)
+ assert middle_record.sha256sum is not None
+ middle_payload = json.loads(file_store.read_blob(middle_record.sha256sum))
+ assert middle_payload["pages"][0]["blocks"][0]["content"] == expected
+
+
def test_html_auto_selection_preserves_all_repeated_forum_posts() -> None:
"""验证重复 article 场景不会只保留论坛中的首个帖子。"""
payload = b"""<html><body><header>Forum</header><main>
@@ -395,6 +443,7 @@ def test_html_referenced_external_footnote_keeps_anchor_and_content() -> None:
footnote = next(block for block in middle.pages[0].blocks if block.type == BlockType.PAGE_FOOTNOTE)
assert footnote.anchor is not None # type: ignore[union-attr]
+ assert footnote.anchor == "html-e31e5112c08d4945a7af" # type: ignore[union-attr]
assert "Footnote body." in footnote.content # type: ignore[union-attr]
assert f"](#{footnote.anchor})" in markdown # type: ignore[union-attr]
assert f'id="{footnote.anchor}" class="mineru-page-footnote"' in markdown # type: ignore[union-attr]
@@ -1284,6 +1333,46 @@ def test_html_versioned_wire_roundtrips_all_semantic_types() -> None:
assert roundtrip_text == "Text & value < 3 <eq>x+1</eq> &lt;eq&gt;literal&lt;/eq&gt;"
[email protected]("outside_kind", ["text", "inline"])
+def test_html_versioned_list_content_outside_carrier_falls_back_without_loss(outside_kind: str) -> None:
+ """验证列表 carrier 外的编辑内容触发通用投影并完整保留。"""
+ source = MiddleJson.model_validate(
+ {
+ "pages": [
+ {
+ "page_idx": 0,
+ "blocks": [
+ {
+ "type": "list",
+ "index": 0,
+ "content": [{"type": "text", "index": 0, "content": "- Original"}],
+ }
+ ],
+ }
+ ],
+ "is_full_document": True,
+ "file_suffix": "html",
+ "effort": "flash",
+ "parse_mode": "txt",
+ "mineru_version": "test",
+ }
+ )
+ soup = BeautifulSoup(render_html(source, standalone=False), "html.parser")
+ item = soup.select_one('li[data-block-type="text"]')
+ assert item is not None
+ if outside_kind == "text":
+ item.append(" ADDED")
+ else:
+ added = soup.new_tag("span")
+ added.string = " ADDED"
+ item.append(added)
+
+ middle, model = doc_analyze(str(soup).encode(), file_suffix="html")
+
+ assert model.pages[0][0]["content"][0]["content"] == "Original ADDED"
+ assert render_markdown(middle) == "- Original ADDED"
+
+
def test_html_invalid_versioned_markers_fallback_without_partial_results() -> None:
"""验证未知版本和多类非法 marker 都整体回退,且可见正文不会重复。"""
source = MiddleJson.model_validate(
diff --git a/tests/unittest/test_flash_markup_anchors.py b/tests/unittest/test_flash_markup_anchors.py
new file mode 100644
index 00000000..e6ed7030
--- /dev/null
+++ b/tests/unittest/test_flash_markup_anchors.py
@@ -0,0 +1,156 @@
+from __future__ import annotations
+
+from dataclasses import dataclass
+
+from lxml import etree
+
+from mineru.model.flash._shared.markup import (
+ AnchorVisibilityScope,
+ MarkupAnchorDocument,
+ MarkupAnchorRegistry,
+ MarkupStylesheet,
+ canonical_anchor,
+ element_id,
+ visible_element_text,
+)
+
+
+@dataclass(frozen=True, slots=True)
+class _TestAnchorPolicy:
+ """为共享 anchor 单元测试提供可切换的脚注语义策略。"""
+
+ anchor_prefix: str = "test"
+ register_document_start: bool = True
+ note_marker: str = "primary"
+
+ @staticmethod
+ def heading_identity(element: etree._Element, ordinal: int) -> str:
+ """按源 ID 与文档内序号生成测试标题 identity。"""
+ return f"heading-{element_id(element) or 'anonymous'}-{ordinal}"
+
+ def is_materializable_note(self, element: etree._Element, document: MarkupAnchorDocument) -> bool:
+ """只登记匹配当前策略且具有最终可见文本的测试脚注。"""
+ return element.get("data-note") == self.note_marker and bool(visible_element_text(element, document))
+
+ @staticmethod
+ def note_identity(element: etree._Element, ordinal: int) -> str:
+ """按源 ID 与文档内序号生成测试脚注 identity。"""
+ return f"note-{element_id(element) or 'anonymous'}-{ordinal}"
+
+
+def _document(
+ key: str,
+ root: etree._Element,
+ *,
+ visibility_scope: AnchorVisibilityScope = "all_ancestors",
+) -> MarkupAnchorDocument:
+ """用空样式表构造一份共享 anchor 测试文档。"""
+ return MarkupAnchorDocument(
+ key=key,
+ root=root,
+ stylesheet=MarkupStylesheet(),
+ visibility_scope=visibility_scope,
+ )
+
+
+def test_markup_anchor_element_id_and_canonical_digest_are_stable() -> None:
+ """验证 id/xml:id 优先级、空白清理及二十位 SHA-256 anchor 契约。"""
+ html_id = etree.fromstring(b'<p id=" html-id " xml:id="xml-id"/>')
+ xml_id = etree.fromstring(b'<p xml:id="xml-only"/>')
+ anonymous = etree.fromstring(b"<p/>")
+
+ assert element_id(html_id) == "html-id"
+ assert element_id(xml_id) == "xml-only"
+ assert element_id(anonymous) is None
+ assert canonical_anchor("epub", "EPUB/text/ch1.xhtml", "chapter-one-0") == "epub-1daacccca5bf43833643"
+ assert canonical_anchor("html", "html", "heading-top-0") == "html-39fc7010518f54fa3fa9"
+
+
+def test_markup_anchor_registry_filters_hidden_targets_and_keeps_visible_descendants() -> None:
+ """验证隐藏标题/脚注不注册,而 visibility:visible 后代仍可提供可落地文本。"""
+ root = etree.fromstring(
+ b"""<html><body>
+ <h1 id="visible">Visible title</h1>
+ <h2 id="hidden" hidden="hidden">Hidden title</h2>
+ <h3 id="recovered" style="visibility:hidden">Hidden <span style="visibility:visible">Recovered title</span></h3>
+ <aside id="visible-note" data-note="primary">Visible note</aside>
+ <aside id="hidden-note" data-note="primary" style="display:none">Hidden note</aside>
+ <aside data-note="primary" style="visibility:hidden"><span style="visibility:visible">Recovered note</span></aside>
+ </body></html>"""
+ )
+ registry = MarkupAnchorRegistry([_document("doc", root)], _TestAnchorPolicy())
+ elements = {element_id(element): element for element in root.iter() if element_id(element) is not None}
+ anonymous_note = next(element for element in root.iter("aside") if element_id(element) is None)
+
+ visible_anchor = registry.heading_anchor(elements["visible"])
+ recovered_anchor = registry.heading_anchor(elements["recovered"])
+ assert visible_anchor is not None
+ assert recovered_anchor is not None
+ assert registry.heading_label(visible_anchor) == "Visible title"
+ assert registry.heading_label(recovered_anchor) == "Recovered title"
+ assert registry.heading_anchor(elements["hidden"]) is None
+ assert registry.resolve_target("doc", "hidden") is None
+ assert registry.note_anchor(elements["visible-note"]) is not None
+ assert registry.note_anchor(elements["hidden-note"]) is None
+ assert registry.note_anchor(anonymous_note) is not None
+
+
+def test_markup_anchor_registry_resolves_direct_ancestor_descendant_and_duplicate_fragments() -> None:
+ """验证 fragment 依次映射到直接、最近祖先和首个后代目标,且重复 ID 首个映射优先。"""
+ first_root = etree.fromstring(
+ b"""<body>
+ <h1 id="direct">Direct</h1>
+ <h2>Ancestor target <span id="inside-heading">inside</span></h2>
+ <section id="container"><h3>Descendant target</h3></section>
+ <section id="duplicate"><h4>First duplicate</h4></section>
+ <h5 id="duplicate">Second duplicate</h5>
+ </body>"""
+ )
+ second_root = etree.fromstring(b'<body><h1 id="direct">Other document</h1></body>')
+ first_document = _document("doc-a", first_root)
+ second_document = _document("doc-b", second_root)
+ registry = MarkupAnchorRegistry([first_document, second_document], _TestAnchorPolicy())
+ headings = list(first_root.iter("h1", "h2", "h3", "h4", "h5"))
+ second_heading = next(second_root.iter("h1"))
+
+ assert registry.resolve_target("doc-a", "direct") == registry.heading_anchor(headings[0])
+ assert registry.resolve_target("doc-a", "inside-heading") == registry.heading_anchor(headings[1])
+ assert registry.resolve_target("doc-a", "container") == registry.heading_anchor(headings[2])
+ assert registry.resolve_target("doc-a", "duplicate") == registry.heading_anchor(headings[3])
+ assert registry.resolve_target("doc-a", "duplicate") != registry.heading_anchor(headings[4])
+ assert registry.resolve_target("doc-b", "direct") == registry.heading_anchor(second_heading)
+ assert registry.resolve_target("doc-a", None) == registry.heading_anchor(headings[0])
+ assert registry.resolve_target("doc-b", None) == registry.heading_anchor(second_heading)
+
+
+def test_markup_anchor_document_start_visibility_scope_and_policy_do_not_leak() -> None:
+ """验证可选文档起点、祖先范围和不同脚注 policy 彼此隔离。"""
+ root = etree.fromstring(
+ b"""<html hidden="hidden"><body><h1 id="title">Visible in body scope</h1>
+ <aside id="primary" data-note="primary">Primary note</aside>
+ <aside id="secondary" data-note="secondary">Secondary note</aside>
+ </body></html>"""
+ )
+ all_ancestors = _document("all", root)
+ body_scope = _document("body", root, visibility_scope="nearest_body")
+ assert visible_element_text(next(root.iter("h1")), all_ancestors) == ""
+ assert visible_element_text(next(root.iter("h1")), body_scope) == "Visible in body scope"
+
+ primary = MarkupAnchorRegistry(
+ [body_scope],
+ _TestAnchorPolicy(anchor_prefix="primary", register_document_start=False, note_marker="primary"),
+ )
+ secondary = MarkupAnchorRegistry(
+ [body_scope],
+ _TestAnchorPolicy(anchor_prefix="secondary", register_document_start=True, note_marker="secondary"),
+ )
+ elements = {element_id(element): element for element in root.iter() if element_id(element) is not None}
+
+ assert primary.resolve_target("body", None) is None
+ assert secondary.resolve_target("body", None) == secondary.heading_anchor(elements["title"])
+ assert primary.note_anchor(elements["primary"]) is not None
+ assert primary.note_anchor(elements["secondary"]) is None
+ assert secondary.note_anchor(elements["primary"]) is None
+ assert secondary.note_anchor(elements["secondary"]) is not None
+ assert primary.note_anchor(elements["primary"]).startswith("primary-") # type: ignore[union-attr]
+ assert secondary.note_anchor(elements["secondary"]).startswith("secondary-") # type: ignore[union-attr]