Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.
Python ai4sciencedocument-analysisdocxextract-datalayout-analysisocrparserpdfpdf-converterpdf-extractor-llmpdf-extractor-pretrainpdf-extractor-ragpdf-parserpptxpythonxlsx
add MinerU HTML v1 wire decoding and materialization logic
myhloliead99aef1db7
diff --git a/docs/next/decisions/0031-html-native-semantic-parsing.md b/docs/next/decisions/0031-html-native-semantic-parsing.mdindex 31afba51..3aeadb39 100644--- a/docs/next/decisions/0031-html-native-semantic-parsing.md+++ b/docs/next/decisions/0031-html-native-semantic-parsing.md@@ -15,12 +15,14 @@- HTML 规范后缀统一为 `html`,使用 `flash/txt`、整本文档、单逻辑页、无 bbox 的 ModelJson/MiddleJson 2.0 路径。- 只解析静态源码,不执行 JavaScript、不启动浏览器、不生成布局坐标。- 默认固定使用保守 `auto` 正文选择:高置信候选进入正文投影,其余情况回退完整 body;首版不公开模式参数。-- MinerU 自身 renderer 输出版本化 `data-mineru-html-version="1"` 机器契约。版本匹配且整棵 marker 树合法时,- parser 跳过 `auto` 裁剪,按 `data-block-type` 精确恢复顶层 block、visual child、列表/目录叶子及关键元数据。+- MinerU 自身 renderer 输出版本化 `data-mineru-html-version="1"` 机器契约。只有当前 renderer 能生成的 canonical+ marker 树进入精确路径,parser 跳过 `auto` 裁剪并按 `data-block-type` 恢复顶层 block、visual child、列表/目录叶子及关键元数据。- `data-block-type` 使用原始下划线形式的 `BlockType` 值,是新版 MinerU HTML 的唯一机器类型来源;`mineru-caption`、`mineru-footnote` 和 `mineru-figure--*` 等 class 只负责样式。-- 精确解码先完成无资源副作用的全树校验,再加载图片并一次性物化 raw blocks。未知版本、缺失/重复 body、- 非法类型或父子类型不匹配均丢弃整条精确路径,从干净 DOM 进入通用解析,不保留部分结果。+- 精确解码先把固定 DOM grammar 解析为无资源副作用的 typed plan,再加载图片并一次性物化 raw blocks。未知版本或+ 非 canonical v1 均丢弃整条精确路径,从干净 DOM 进入通用解析;人工编辑后的机器 HTML 不承诺保留原 block 类型和元数据。+- Image/Chart body 的 renderer-owned 图片恢复为唯一主图片载荷;rich-content carrier 内的安全 HTML(包括嵌套图片)+ 按语义规范化后保留在 `content`,不会提升为额外主图片载荷。- 旧 MinerU HTML 与普通互联网 HTML 都走通用路径,只承诺正文、图片、表格、链接及可识别公式的内容兼容,不承诺按旧 class suffix 精确恢复 Chart、Index 或 annotation 类型。- EPUB XHTML 与 standalone HTML 共用静态 markup projector,继续输出既有标题、正文、列表、表格、图片、代码、diff --git a/mineru/model/flash/html/converter.py b/mineru/model/flash/html/converter.pyindex f568c7a7..325a2950 100644--- a/mineru/model/flash/html/converter.py+++ b/mineru/model/flash/html/converter.py@@ -19,7 +19,7 @@ from .document import HtmlDocument, parse_html_documentfrom .errors import HtmlResourceLimitErrorfrom .resources import HtmlResourceContextfrom .selector import select_auto_content-from .wire import inspect_mineru_html_wire, materialize_mineru_html_wire+from .wire import decode_mineru_html_wireclass HtmlConverter:@@ -40,14 +40,14 @@ class HtmlConverter:if len(file_bytes) > MAX_HTML_BYTES:raise HtmlResourceLimitError(f"HTML resource limit exceeded: max_html_bytes={MAX_HTML_BYTES}")document = parse_html_document(file_bytes, source_context)- inspection = inspect_mineru_html_wire(document.body)resources = HtmlResourceContext(document.source_context, base_href=document.base_href)- if inspection.plan is not None:- blocks = materialize_mineru_html_wire(inspection.plan, resources)+ wire_result = decode_mineru_html_wire(document.body, resources)+ if wire_result.blocks is not None:+ blocks = wire_result.blockslog_values = ("mineru_exact", 1.0, 1.0, "version_1")else:- if inspection.fallback_reason is not None:- logger.warning("MinerU HTML marker fallback reason={}", inspection.fallback_reason)+ if wire_result.fallback_reason is not None:+ logger.warning("MinerU HTML marker fallback reason={}", wire_result.fallback_reason)stylesheet = _load_stylesheet(document, resources)selection = select_auto_content(document.body, stylesheet)selected_root = append_referenced_notes(diff --git a/mineru/model/flash/html/document.py b/mineru/model/flash/html/document.pyindex 07aefab1..ce9ba827 100644--- a/mineru/model/flash/html/document.py+++ b/mineru/model/flash/html/document.py@@ -43,7 +43,9 @@ _MEANINGFUL_FORMULA_SIBLING_TAGS = frozenset({"audio", "br", "canvas", "figure", "hr", "iframe", "image", "img", "object", "svg", "table", "video"})_ASCIIMATH_SCRIPT_TYPE_RE = re.compile(r"^math/asciimath(?:\s*;.*)?$", re.IGNORECASE)-_HTML_ENCODING_DECLARATION_RE = re.compile(rb"(?is)<(?:meta\b[^>]*\bcharset\s*=|\?xml\b[^>]*\bencoding\s*=)")+_HTML_ENCODING_DECLARATION_CANDIDATE_RE = re.compile(rb"(?is)<(?:meta\b[^>]*\bcharset\s*=|\?xml\b[^>]*\bencoding\s*=)")+_XML_ENCODING_DECLARATION_RE = re.compile(rb"(?is)^<\?xml\b[^>]*\bencoding\s*=")+_META_CONTENT_CHARSET_RE = re.compile(r"\bcharset\s*=", re.IGNORECASE)_UNICODE_BOMS = (b"\x00\x00\xfe\xff", b"\xff\xfe\x00\x00", b"\xef\xbb\xbf", b"\xfe\xff", b"\xff\xfe")@@ -158,11 +160,41 @@ def _normalize_transport_encoding(value: str | None) -> str | None:return None+def _has_html_encoding_declaration(file_bytes: bytes) -> bool:+ """只承认首个 4 KiB 内由 HTML 语法解析出的真实编码声明。"""+ prefix = file_bytes[:4096]+ if not _HTML_ENCODING_DECLARATION_CANDIDATE_RE.search(prefix):+ return False+ if _XML_ENCODING_DECLARATION_RE.match(prefix):+ return True++ declaration_parser = lxml_html.HTMLParser(+ recover=True,+ no_network=True,+ remove_comments=False,+ huge_tree=False,+ encoding="iso-8859-1",+ )+ try:+ root = lxml_html.document_fromstring(prefix, parser=declaration_parser)+ except (etree.ParserError, etree.XMLSyntaxError, UnicodeError, ValueError):+ return False+ for element in root.iter():+ if not isinstance(element.tag, str) or local_name(element) != "meta":+ continue+ if (element.get("charset") or "").strip():+ return True+ http_equiv = (element.get("http-equiv") or "").strip().casefold()+ if http_equiv == "content-type" and _META_CONTENT_CHARSET_RE.search(element.get("content") or ""):+ return True+ return False++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]):+ if file_bytes.startswith(_UNICODE_BOMS) or _has_html_encoding_declaration(file_bytes):return file_bytestry:return file_bytes.decode("utf-8")diff --git a/mineru/model/flash/html/wire.py b/mineru/model/flash/html/wire.pydeleted file mode 100644index 55605cee..00000000--- a/mineru/model/flash/html/wire.py+++ /dev/null@@ -1,1077 +0,0 @@-# Copyright (c) Opendatalab. All rights reserved.-"""校验并解码版本化 MinerU HTML 机器语义契约。"""--from __future__ import annotations--from copy import deepcopy-from dataclasses import dataclass-import html-from typing import Literal, TypeAlias--from lxml import etree # type: ignore[reportMissingImports]--from ....types import PAGE_BLOCK_TYPES, RAW_ALGORITHM, BlockType, VISUAL_TYPE_MAPPING-from .._shared.markup import MarkupProjector, MarkupStylesheet, extract_formula-from .._shared.markup.projector import BLOCK_TAGS, local_name-from .resources import HtmlResourceContext---MineruHtmlRenderMode: TypeAlias = Literal["default", "full"]--_MINERU_HTML_VERSION = "1"-_VISUAL_TYPES = frozenset(VISUAL_TYPE_MAPPING)-_SIMPLE_TEXT_TYPES = frozenset(- {- BlockType.TEXT,- BlockType.REF_TEXT,- BlockType.DOC_TITLE,- BlockType.PARAGRAPH_TITLE,- BlockType.HEADER,- BlockType.FOOTER,- BlockType.PAGE_NUMBER,- BlockType.ASIDE_TEXT,- BlockType.PAGE_FOOTNOTE,- }-)-_PAGE_AUXILIARY_TYPES = frozenset(- {- BlockType.HEADER,- BlockType.FOOTER,- BlockType.PAGE_NUMBER,- BlockType.ASIDE_TEXT,- }-)-_LIST_LEAF_TYPES = frozenset({BlockType.TEXT, BlockType.REF_TEXT})-_INDEX_LEAF_TYPES = frozenset({BlockType.TEXT, BlockType.DOC_TITLE, BlockType.PARAGRAPH_TITLE})-_OWNED_VISUAL_IMAGE_TOKENS = frozenset(- {"mineru-chart-image", "mineru-flowchart-fallback", "mineru-image", "mineru-table-image"}-)---@dataclass(frozen=True, slots=True)-class MineruHtmlBlockSpec:- """保存一个已完整校验但尚未加载资源的顶层机器 block。"""-- wrapper: etree._Element- content_root: etree._Element- block_type: BlockType- page_idx: int- block_index: int | None---@dataclass(frozen=True, slots=True)-class MineruHtmlWirePlan:- """保存一次版本化 MinerU HTML 的只读验证结果。"""-- root: etree._Element- render_mode: MineruHtmlRenderMode- blocks: tuple[MineruHtmlBlockSpec, ...]---@dataclass(frozen=True, slots=True)-class MineruHtmlWireInspection:- """区分无 marker、有效 marker 和需通用回退的非法 marker。"""-- plan: MineruHtmlWirePlan | None- fallback_reason: str | None = None---class _WireValidationError(ValueError):- """携带不包含正文或属性值的稳定 marker 失败原因。"""-- def __init__(self, reason: str) -> None:- """保存固定诊断码。"""- super().__init__(reason)- self.reason = reason---class _ExactAnchorResolver:- """把 renderer 生成的 DOM id 恢复为 wire 中保存的原始 anchor。"""-- def __init__(self, plan: MineruHtmlWirePlan) -> None:- """预扫描标题和页面脚注的 id、标签及原始 anchor。"""- self._targets: dict[str, str] = {}- self._heading_anchors: dict[etree._Element, str] = {}- self._heading_labels: dict[str, str] = {}- self._note_anchors: dict[etree._Element, str] = {}- for spec in plan.blocks:- anchor = (spec.wrapper.get("data-anchor") or "").strip()- if not anchor:- continue- self._targets.setdefault(anchor, anchor)- for candidate in [spec.content_root, *spec.content_root.iterdescendants()]:- identity = (candidate.get("id") or "").strip()- if identity:- self._targets.setdefault(identity, anchor)- if spec.block_type in {BlockType.DOC_TITLE, BlockType.PARAGRAPH_TITLE}:- self._heading_anchors[spec.content_root] = anchor- self._heading_labels[anchor] = " ".join(spec.content_root.itertext()).strip()- elif spec.block_type == BlockType.PAGE_FOOTNOTE:- self._note_anchors[spec.content_root] = anchor-- def resolve_fragment(self, fragment: str) -> str | None:- """把 renderer id 或原始 anchor 统一还原为内部 fragment。"""- identity = fragment.removeprefix("#").strip()- return f"#{anchor}" if (anchor := self._targets.get(identity)) else None-- 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 inspect_mineru_html_wire(body: etree._Element) -> MineruHtmlWireInspection:- """发现并事务式校验 MinerU HTML marker,失败只返回固定诊断码。"""- roots = [- element- for element in body.iter()- if isinstance(element.tag, str) and element.get("data-mineru-html-version") is not None- ]- if not roots:- return MineruHtmlWireInspection(None)- if len(roots) != 1:- return MineruHtmlWireInspection(None, "multiple_version_roots")- root = roots[0]- if (root.get("data-mineru-html-version") or "").strip() != _MINERU_HTML_VERSION:- return MineruHtmlWireInspection(None, "unsupported_version")- try:- _validate_wire_root_ownership(body, root)- return MineruHtmlWireInspection(_validate_wire_root(root))- except _WireValidationError as exc:- return MineruHtmlWireInspection(None, exc.reason)---def materialize_mineru_html_wire(- plan: MineruHtmlWirePlan,- resources: HtmlResourceContext,-) -> list[dict[str, object]]:- """在结构验证成功后一次性加载资源并物化单页 raw blocks。"""- resources.bind_anchors(_ExactAnchorResolver(plan))- stylesheet = MarkupStylesheet()- projector = MarkupProjector(plan.root, resources, stylesheet, single_document_title=True)- blocks: list[dict[str, object]] = []- for spec in plan.blocks:- if spec.block_type in _SIMPLE_TEXT_TYPES:- blocks.append(_materialize_text_block(spec, projector))- elif spec.block_type == BlockType.EQUATION:- blocks.append(_materialize_equation(spec, resources))- elif spec.block_type == BlockType.LIST:- blocks.append(_materialize_list(spec.content_root, projector))- elif spec.block_type == BlockType.INDEX:- blocks.append(_materialize_index(spec.content_root, projector))- elif spec.block_type in _VISUAL_TYPES:- blocks.extend(_materialize_visual(spec, resources, stylesheet, projector))- else: # pragma: no cover - 根验证已经穷尽公开 PageBlock 类型。- raise AssertionError(f"unhandled wire block type: {spec.block_type}")- return blocks---def _validate_wire_root(root: etree._Element) -> MineruHtmlWirePlan:- """校验根版本、渲染模式、页面容器与顶层 block 完整性。"""- if local_name(root) != "article" or "mineru-document" not in _class_tokens(root):- raise _WireValidationError("invalid_root")- _validate_element_only_content(root)- mode = (root.get("data-render-mode") or "").strip()- if mode not in {"default", "full"}:- raise _WireValidationError("invalid_render_mode")- wrappers: list[tuple[etree._Element, int | None]] = []- if mode == "default":- for child in _element_children(root):- if local_name(child) != "div" or "mineru-block" not in _class_tokens(child):- raise _WireValidationError("invalid_default_child")- wrappers.append((child, None))- else:- for child in _element_children(root):- if local_name(child) == "hr" and "mineru-page-break" in _class_tokens(child):- continue- if local_name(child) != "section" or "mineru-page" not in _class_tokens(child):- raise _WireValidationError("invalid_full_child")- _validate_element_only_content(child)- section_page_idx = _non_negative_integer(child, "data-page-idx", required=True)- for wrapper in _element_children(child):- if local_name(wrapper) != "div" or "mineru-block" not in _class_tokens(wrapper):- raise _WireValidationError("invalid_page_child")- wrappers.append((wrapper, section_page_idx))-- nested_wrappers = [- element- for element in root.iterdescendants()- if isinstance(element.tag, str) and "mineru-block" in _class_tokens(element)- ]- if len(nested_wrappers) != len(wrappers):- raise _WireValidationError("nested_block_wrapper")-- specs = tuple(_validate_top_block(wrapper, section_page_idx) for wrapper, section_page_idx in wrappers)- return MineruHtmlWirePlan(root, mode, specs) # type: ignore[arg-type]---def _validate_wire_root_ownership(body: etree._Element, root: etree._Element) -> None:- """要求 wire 根独占通往 body 的内容路径,避免精确物化丢弃外部正文。"""- current = root- while current is not body:- parent = current.getparent()- if parent is None:- raise _WireValidationError("invalid_root_location")- if (parent.text or "").strip():- raise _WireValidationError("content_outside_wire_root")- for sibling in parent:- if sibling is current:- if (sibling.tail or "").strip():- raise _WireValidationError("content_outside_wire_root")- continue- if isinstance(sibling.tag, str) or (sibling.tail or "").strip():- raise _WireValidationError("content_outside_wire_root")- current = parent---def _validate_top_block(wrapper: etree._Element, section_page_idx: int | None) -> MineruHtmlBlockSpec:- """校验单个顶层 wrapper 的公开类型、元数据与内部机器树。"""- _validate_element_only_content(wrapper)- block_type = _page_block_type(wrapper)- page_idx = _non_negative_integer(wrapper, "data-page-idx", required=True)- if section_page_idx is not None and page_idx != section_page_idx:- raise _WireValidationError("page_index_mismatch")- block_index = _non_negative_integer(wrapper, "data-block-index", required=False)- children = _element_children(wrapper)- if len(children) != 1:- raise _WireValidationError("invalid_block_content_count")- content_root = children[0]- _validate_top_metadata(wrapper, block_type)- if block_type in _SIMPLE_TEXT_TYPES:- _validate_simple_content(content_root, block_type)- elif block_type == BlockType.EQUATION:- _validate_equation_content(content_root)- elif block_type == BlockType.LIST:- _validate_list_container(content_root, top_wrapper=wrapper)- elif block_type == BlockType.INDEX:- _validate_index_root(content_root, wrapper)- elif block_type in _VISUAL_TYPES:- _validate_visual_content(content_root, wrapper, block_type)- else:- raise _WireValidationError("unsupported_block_type")- return MineruHtmlBlockSpec(wrapper, content_root, block_type, page_idx, block_index)---def _validate_top_metadata(wrapper: etree._Element, block_type: BlockType) -> None:- """校验 subtype、语言、anchor 和 level 只出现在合法父类型上。"""- sub_type = (wrapper.get("data-block-sub-type") or "").strip()- guess_lang = (wrapper.get("data-guess-lang") or "").strip()- anchor = (wrapper.get("data-anchor") or "").strip()- level = _optional_integer(wrapper, "data-level")-- if block_type == BlockType.CODE:- if sub_type not in {BlockType.CODE, RAW_ALGORITHM}:- raise _WireValidationError("invalid_code_sub_type")- if sub_type == BlockType.CODE and not guess_lang:- raise _WireValidationError("missing_code_language")- if sub_type == RAW_ALGORITHM and guess_lang:- raise _WireValidationError("algorithm_language_mismatch")- elif block_type == BlockType.LIST:- if sub_type and sub_type not in _LIST_LEAF_TYPES:- raise _WireValidationError("invalid_list_sub_type")- if guess_lang:- raise _WireValidationError("unexpected_guess_lang")- elif block_type in {BlockType.IMAGE, BlockType.CHART}:- if guess_lang:- raise _WireValidationError("unexpected_guess_lang")- elif sub_type or guess_lang:- raise _WireValidationError("unexpected_block_metadata")-- if block_type == BlockType.DOC_TITLE:- if level != 1:- raise _WireValidationError("invalid_title_level")- elif block_type == BlockType.PARAGRAPH_TITLE:- if level is None or not 2 <= level <= 6:- raise _WireValidationError("invalid_title_level")- elif level is not None:- raise _WireValidationError("unexpected_title_level")-- if anchor and block_type not in {BlockType.DOC_TITLE, BlockType.PARAGRAPH_TITLE, BlockType.PAGE_FOOTNOTE}:- raise _WireValidationError("unexpected_anchor")---def _validate_simple_content(content_root: etree._Element, block_type: BlockType) -> None:- """校验文本、标题、页面辅助块只含允许的内部公式 marker。"""- expected_tags: dict[BlockType, frozenset[str]] = {- BlockType.TEXT: frozenset({"p"}),- BlockType.REF_TEXT: frozenset({"p"}),- BlockType.DOC_TITLE: frozenset({"h1"}),- BlockType.PARAGRAPH_TITLE: frozenset({"h2", "h3", "h4", "h5", "h6"}),- BlockType.PAGE_FOOTNOTE: frozenset({"div"}),- **{block_type_value: frozenset({"div"}) for block_type_value in _PAGE_AUXILIARY_TYPES},- }- if local_name(content_root) not in expected_tags[block_type]:- raise _WireValidationError("invalid_simple_shape")- for marker in _descendant_markers(content_root):- marker_type = (marker.get("data-block-type") or "").strip()- if marker is content_root and marker_type == block_type:- continue- if marker_type != BlockType.EQUATION:- raise _WireValidationError("invalid_nested_marker")- _validate_formula_carrier(marker, expected_display="inline")- _validate_inline_content_shape(content_root)---def _validate_equation_content(content_root: etree._Element) -> None:- """校验行间公式为规范 carrier,或为无 LaTeX 的安全图片回退。"""- if local_name(content_root) == "math":- _validate_formula_carrier(content_root, expected_display="block")- return- if local_name(content_root) != "img" or "mineru-equation-image" not in _class_tokens(content_root):- raise _WireValidationError("invalid_equation_shape")---def _validate_formula_carrier(- element: etree._Element,- *,- expected_display: Literal["inline", "block"] | None,-) -> None:- """校验公式 marker 含非空裸 LaTeX 和合法显示方式。"""- if local_name(element) != "math" or (element.get("data-block-type") or "").strip() != BlockType.EQUATION:- raise _WireValidationError("invalid_formula_marker")- display = (element.get("data-formula-display") or "").strip()- if display not in {"inline", "block"} or (expected_display is not None and display != expected_display):- raise _WireValidationError("invalid_formula_display")- formula = extract_formula(element)- if formula is None or not formula.latex:- raise _WireValidationError("missing_formula_latex")---def _validate_visual_content(content_root: etree._Element, wrapper: etree._Element, parent_type: BlockType) -> None:- """校验视觉父块只有匹配 body,并拒绝跨父类型 annotation。"""- if local_name(content_root) != "figure":- raise _WireValidationError("invalid_visual_root")- _validate_element_only_content(content_root)- mapping = VISUAL_TYPE_MAPPING[parent_type]- allowed_types = frozenset(mapping.values())- children = _element_children(content_root)- child_types = [(child.get("data-block-type") or "").strip() for child in children]- if child_types.count(mapping["body"]) != 1:- raise _WireValidationError("invalid_visual_body_count")- if any(child_type not in allowed_types for child_type in child_types):- raise _WireValidationError("annotation_parent_mismatch")- parent_index = _non_negative_integer(wrapper, "data-block-index", required=False)- for child, child_type in zip(children, child_types, strict=True):- child_index = _non_negative_integer(child, "data-block-index", required=False)- if child_type == mapping["body"]:- if local_name(child) != "div":- raise _WireValidationError("invalid_visual_body_shape")- if parent_index is not None and child_index != parent_index:- raise _WireValidationError("visual_body_index_mismatch")- sub_type = (wrapper.get("data-block-sub-type") or "").strip()- if parent_type == BlockType.CODE and sub_type == BlockType.CODE:- _validate_code_body_shape(child)- elif parent_type == BlockType.CODE and sub_type == RAW_ALGORITHM:- _validate_algorithm_body_shape(child)- elif parent_type == BlockType.TABLE:- _validate_table_body_shape(child)- elif parent_type == BlockType.IMAGE and sub_type == "flowchart":- _validate_flowchart_body_shape(child)- elif parent_type in {BlockType.IMAGE, BlockType.CHART}:- _validate_owned_visual_image_shape(child, parent_type)- for marker in _descendant_markers(child):- if marker is child:- continue- if (marker.get("data-block-type") or "").strip() != BlockType.EQUATION:- raise _WireValidationError("invalid_visual_nested_marker")- _validate_formula_carrier(marker, expected_display="inline")- else:- if local_name(child) != "p":- raise _WireValidationError("invalid_annotation_shape")- for marker in _descendant_markers(child):- if marker is child:- continue- if (marker.get("data-block-type") or "").strip() != BlockType.EQUATION:- raise _WireValidationError("invalid_annotation_nested_marker")- _validate_formula_carrier(marker, expected_display="inline")- _validate_inline_content_shape(child)---def _validate_code_body_shape(body: etree._Element) -> None:- """校验普通代码 body 只含规范 pre/code,避免精确物化静默丢弃编辑内容。"""- _validate_element_only_content(body)- children = _element_children(body)- if len(children) != 1 or local_name(children[0]) != "pre":- raise _WireValidationError("invalid_code_body_shape")- pre = children[0]- _validate_element_only_content(pre)- code_children = _element_children(pre)- if len(code_children) != 1 or local_name(code_children[0]) != "code":- raise _WireValidationError("invalid_code_body_shape")- if _element_children(code_children[0]):- raise _WireValidationError("invalid_code_body_shape")---def _validate_algorithm_body_shape(body: etree._Element) -> None:- """校验 algorithm body 只含规范行内容器,避免精确物化静默丢弃编辑内容。"""- _validate_element_only_content(body)- children = _element_children(body)- if not children:- return- if len(children) != 1:- raise _WireValidationError("invalid_algorithm_body_shape")- algorithm = children[0]- if local_name(algorithm) != "div" or "mineru-algorithm" not in _class_tokens(algorithm):- raise _WireValidationError("invalid_algorithm_body_shape")- _validate_inline_content_shape(algorithm)---def _validate_table_body_shape(body: etree._Element) -> None:- """校验表格 body 只含一种规范载荷,避免精确物化静默丢弃旁路内容。"""- _validate_element_only_content(body)- children = _element_children(body)- if not children:- return- if len(children) != 1:- raise _WireValidationError("invalid_table_body_shape")- child = children[0]- name = local_name(child)- classes = _class_tokens(child)- if name == "table":- return- if name == "pre" and bool(classes & {"mineru-table-text", "mineru-raw-fallback"}):- if not _element_children(child):- return- elif name == "img" and "mineru-table-image" in classes:- return- raise _WireValidationError("invalid_table_body_shape")---def _validate_owned_visual_image_shape(body: etree._Element, parent_type: BlockType) -> None:- """限制普通图片和图表 body 只能携带一个与父类型匹配的 renderer 图片。"""- allowed_token = "mineru-image" if parent_type == BlockType.IMAGE else "mineru-chart-image"- owned_images: list[etree._Element] = []- for element in body.iterdescendants():- if not isinstance(element.tag, str) or local_name(element) != "img":- continue- owned_tokens = _class_tokens(element) & _OWNED_VISUAL_IMAGE_TOKENS- if not owned_tokens:- continue- if owned_tokens != {allowed_token}:- raise _WireValidationError("invalid_owned_visual_image_shape")- owned_images.append(element)- if len(owned_images) > 1:- raise _WireValidationError("invalid_owned_visual_image_shape")---def _validate_flowchart_body_shape(body: etree._Element) -> None:- """校验流程图 body 的展示与源码载体,避免精确物化静默丢弃旁路内容。"""- _validate_element_only_content(body)- children = _element_children(body)- if len(children) != 2:- raise _WireValidationError("invalid_flowchart_body_shape")- display, details = children- if local_name(display) != "div" or "mineru-flowchart" not in _class_tokens(display):- raise _WireValidationError("invalid_flowchart_body_shape")- _validate_element_only_content(display)- display_children = _element_children(display)- if not 1 <= len(display_children) <= 2:- raise _WireValidationError("invalid_flowchart_body_shape")- canvas = display_children[0]- if local_name(canvas) != "div" or "mineru-flowchart-canvas" not in _class_tokens(canvas):- raise _WireValidationError("invalid_flowchart_body_shape")- _validate_element_only_content(canvas)- if _element_children(canvas):- raise _WireValidationError("invalid_flowchart_body_shape")- if len(display_children) == 2:- fallback = display_children[1]- if local_name(fallback) != "img" or "mineru-flowchart-fallback" not in _class_tokens(fallback):- raise _WireValidationError("invalid_flowchart_body_shape")-- if local_name(details) != "details" or "mineru-flowchart-details" not in _class_tokens(details):- raise _WireValidationError("invalid_flowchart_body_shape")- _validate_element_only_content(details)- details_children = _element_children(details)- if len(details_children) != 2:- raise _WireValidationError("invalid_flowchart_body_shape")- summary, source = details_children- summary_text = " ".join(summary.itertext()).strip()- if local_name(summary) != "summary" or _element_children(summary) or summary_text != "flowchart source":- raise _WireValidationError("invalid_flowchart_body_shape")- if local_name(source) != "pre" or "mineru-flowchart-source" not in _class_tokens(source):- raise _WireValidationError("invalid_flowchart_body_shape")- _validate_element_only_content(source)- code_children = _element_children(source)- if len(code_children) != 1 or local_name(code_children[0]) != "code" or _element_children(code_children[0]):- raise _WireValidationError("invalid_flowchart_body_shape")---def _validate_list_container(container: etree._Element, *, top_wrapper: etree._Element | None = None) -> None:- """递归校验列表容器、叶子类型和嵌套列表 marker。"""- if local_name(container) not in {"ol", "ul"} or (container.get("data-block-type") or "").strip() != BlockType.LIST:- raise _WireValidationError("invalid_list_root")- _validate_element_only_content(container)- _non_negative_integer(container, "data-block-index", required=False)- sub_type = (container.get("data-block-sub-type") or "").strip()- if sub_type and sub_type not in _LIST_LEAF_TYPES:- raise _WireValidationError("invalid_nested_list_sub_type")- if top_wrapper is not None:- wrapper_sub_type = (top_wrapper.get("data-block-sub-type") or "").strip()- if sub_type != wrapper_sub_type:- raise _WireValidationError("list_sub_type_mismatch")- for item in _element_children(container):- if local_name(item) != "li":- raise _WireValidationError("invalid_list_item")- item_type = (item.get("data-block-type") or "").strip()- nested_lists = [child for child in _element_children(item) if local_name(child) in {"ol", "ul"}]- if item_type:- 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- marker_type = (marker.get("data-block-type") or "").strip()- if marker_type == BlockType.LIST and local_name(marker) in {"ol", "ul"}:- continue- if marker_type != BlockType.EQUATION:- raise _WireValidationError("invalid_list_nested_marker")- _validate_formula_carrier(marker, expected_display="inline")- _validate_inline_content_shape(item, excluded_roots=nested_lists)- elif not nested_lists:- raise _WireValidationError("markerless_list_leaf")- for nested in nested_lists:- _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:- raise _WireValidationError("invalid_index_root")- _validate_element_only_content(content_root)- root_index = _non_negative_integer(content_root, "data-block-index", required=False)- wrapper_index = _non_negative_integer(wrapper, "data-block-index", required=False)- if wrapper_index is not None and root_index != wrapper_index:- raise _WireValidationError("index_root_mismatch")- lists = _element_children(content_root)- if len(lists) != 1 or local_name(lists[0]) != "ul":- raise _WireValidationError("invalid_index_list")- _validate_index_list(lists[0], nested=False)---def _validate_index_list(container: etree._Element, *, nested: bool) -> None:- """递归校验目录 li 类型、anchor、level 和嵌套 IndexBlock。"""- _validate_element_only_content(container)- if nested and (container.get("data-block-type") or "").strip() != BlockType.INDEX:- raise _WireValidationError("missing_nested_index_marker")- if nested:- _non_negative_integer(container, "data-block-index", required=False)- for item in _element_children(container):- if local_name(item) != "li":- raise _WireValidationError("invalid_index_item")- item_type_value = (item.get("data-block-type") or "").strip()- nested_lists = [child for child in _element_children(item) if local_name(child) == "ul"]- if item_type_value:- try:- item_type = BlockType(item_type_value)- except ValueError as exc:- raise _WireValidationError("invalid_index_leaf_type") from exc- if item_type not in _INDEX_LEAF_TYPES:- raise _WireValidationError("invalid_index_leaf_type")- _non_negative_integer(item, "data-block-index", required=False)- _validate_index_leaf_metadata(item, item_type)- for marker in _descendant_markers(item):- if marker is item or _is_within_any(marker, nested_lists):- continue- marker_type = (marker.get("data-block-type") or "").strip()- if marker_type == BlockType.INDEX and local_name(marker) == "ul":- continue- if marker_type != BlockType.EQUATION:- raise _WireValidationError("invalid_index_nested_marker")- _validate_formula_carrier(marker, expected_display="inline")- _validate_inline_content_shape(item, excluded_roots=nested_lists)- elif not nested_lists:- raise _WireValidationError("markerless_index_leaf")- for child in nested_lists:- _validate_index_list(child, nested=True)---def _validate_index_leaf_metadata(item: etree._Element, item_type: BlockType) -> None:- """校验目录标题叶子的 anchor 与 level,不允许普通文本伪装标题。"""- anchor = (item.get("data-anchor") or "").strip()- level = _optional_integer(item, "data-level")- if item_type == BlockType.TEXT:- if anchor or level is not None:- raise _WireValidationError("unexpected_index_text_metadata")- return- if not anchor:- raise _WireValidationError("missing_index_anchor")- if item_type == BlockType.DOC_TITLE and level != 1:- raise _WireValidationError("invalid_index_level")- if item_type == BlockType.PARAGRAPH_TITLE and (level is None or not 2 <= level <= 6):- raise _WireValidationError("invalid_index_level")---def _materialize_text_block(spec: MineruHtmlBlockSpec, projector: MarkupProjector) -> dict[str, object]:- """恢复文本、标题、页面辅助块和页面脚注 raw 字段。"""- block: dict[str, object] = {- "type": spec.block_type,- "content": _project_inline_content(projector, spec.content_root),- }- if spec.block_type in {BlockType.DOC_TITLE, BlockType.PARAGRAPH_TITLE}:- block["level"] = int(spec.wrapper.get("data-level") or 1)- if spec.block_type in {BlockType.DOC_TITLE, BlockType.PARAGRAPH_TITLE, BlockType.PAGE_FOOTNOTE}:- anchor = (spec.wrapper.get("data-anchor") or "").strip()- if anchor:- block["anchor"] = anchor- return block---def _materialize_equation(spec: MineruHtmlBlockSpec, resources: HtmlResourceContext) -> dict[str, object]:- """恢复行间公式裸 LaTeX,图片公式只保留经安全解析的载荷。"""- formula = extract_formula(spec.content_root)- block: dict[str, object] = {- "type": BlockType.EQUATION,- "content": formula.latex if formula is not None else "",- }- if formula is None:- block.update(_resolved_image_payload(spec.content_root, resources))- return block---def _materialize_visual(- spec: MineruHtmlBlockSpec,- resources: HtmlResourceContext,- stylesheet: MarkupStylesheet,- projector: MarkupProjector,-) -> list[dict[str, object]]:- """按原始子节点顺序把 visual body、caption 和 footnote 展平成 raw blocks。"""- mapping = VISUAL_TYPE_MAPPING[spec.block_type]- output: list[dict[str, object]] = []- for child in _element_children(spec.content_root):- child_type = (child.get("data-block-type") or "").strip()- if child_type == mapping["body"]:- output.append(_materialize_visual_body(spec, child, resources, stylesheet))- continue- output.append(- {- "type": BlockType(child_type),- "content": _project_inline_content(projector, child),- }- )- return output---def _materialize_visual_body(- spec: MineruHtmlBlockSpec,- body: etree._Element,- resources: HtmlResourceContext,- stylesheet: MarkupStylesheet,-) -> dict[str, object]:- """按父 visual 类型恢复主体内容、图片载荷和 subtype/lang 元数据。"""- sub_type = (spec.wrapper.get("data-block-sub-type") or "").strip()- if spec.block_type == BlockType.CODE:- return _materialize_code_body(spec, body, resources, stylesheet)- if spec.block_type == BlockType.TABLE:- block = _materialize_table_body(body, resources, stylesheet)- else:- content = _flowchart_content(body) if spec.block_type == BlockType.IMAGE and sub_type == "flowchart" else None- image_classes = (- frozenset({"mineru-image", "mineru-flowchart-fallback"})- if spec.block_type == BlockType.IMAGE- else frozenset({"mineru-chart-image"})- )- block = {- "type": spec.block_type,- "content": content if content is not None else _project_visual_body_content(body, resources, stylesheet),- **_resolved_image_payload(body, resources, allowed_classes=image_classes),- }- if sub_type:- block["sub_type"] = sub_type- return block---def _materialize_code_body(- spec: MineruHtmlBlockSpec,- body: etree._Element,- resources: HtmlResourceContext,- stylesheet: MarkupStylesheet,-) -> dict[str, object]:- """恢复普通代码或 algorithm,并保持语言只属于普通代码。"""- sub_type = (spec.wrapper.get("data-block-sub-type") or "").strip()- if sub_type == BlockType.CODE:- code = next(- (element for element in body.iterdescendants() if isinstance(element.tag, str) and local_name(element) == "code"),- None,- )- content = "".join(code.itertext()) if code is not None else ""- block: dict[str, object] = {- "type": BlockType.CODE,- "content": content,- "guess_lang": (spec.wrapper.get("data-guess-lang") or "").strip(),- }- return block- algorithm = next(- (- element- for element in body.iterdescendants()- if isinstance(element.tag, str) and "mineru-algorithm" in _class_tokens(element)- ),- body,- )- projector = MarkupProjector(algorithm, resources, stylesheet)- return {"type": RAW_ALGORITHM, "content": _project_inline_content(projector, algorithm)}---def _materialize_table_body(- body: etree._Element,- resources: HtmlResourceContext,- stylesheet: MarkupStylesheet,-) -> dict[str, object]:- """优先恢复结构表格,其次恢复空间文本或安全图片载荷。"""- table = next(- (element for element in body.iterdescendants() if isinstance(element.tag, str) and local_name(element) == "table"),- None,- )- content = ""- if table is not None:- projected = MarkupProjector(table, resources, stylesheet).project_block(table)- table_block = next((block for block in projected if block.get("type") == BlockType.TABLE), None)- if table_block is not None:- content = str(table_block.get("content") or "")- if not content:- text_fallback = next(- (- element- for element in body.iterdescendants()- if isinstance(element.tag, str) and bool(_class_tokens(element) & {"mineru-table-text", "mineru-raw-fallback"})- ),- None,- )- if text_fallback is not None:- content = "".join(text_fallback.itertext())- return {- "type": BlockType.TABLE,- "content": content,- **_resolved_image_payload(body, resources, allowed_classes=frozenset({"mineru-table-image"})),- }---def _materialize_list(container: etree._Element, projector: MarkupProjector) -> dict[str, object]:- """递归恢复列表叶子精确类型,并让既有无坐标后处理生成规范 marker。"""- children: list[dict[str, object]] = []- classes = _class_tokens(container)- for item in _element_children(container):- item_type = (item.get("data-block-type") or "").strip()- nested_lists = [child for child in _element_children(item) if local_name(child) in {"ol", "ul"}]- if item_type:- content_host = next(- (- child- for child in item.iterdescendants()- if isinstance(child.tag, str) and "mineru-list-content" in _class_tokens(child)- ),- None,- )- content_element = content_host if content_host is not None else _without_nested_lists(item)- content = _project_inline_content(projector, content_element)- marker_host = next(- (- child- for child in item.iterdescendants()- if isinstance(child.tag, str) and "mineru-list-marker" in _class_tokens(child)- ),- None,- )- marker = "".join(marker_host.itertext()).strip() if marker_host is not None else ""- if "mineru-list--reference" in classes and marker:- content = f"{marker} {content}".strip()- elif "mineru-list--explicit" in classes and marker:- content = f"{marker} {content}".strip()- child_block: dict[str, object] = {"type": BlockType(item_type), "content": content}- if (index := _non_negative_integer(item, "data-block-index", required=False)) is not None:- child_block["index"] = index- children.append(child_block)- children.extend(_materialize_list(nested, projector) for nested in nested_lists)- block: dict[str, object] = {- "type": BlockType.LIST,- "attribute": "ordered" if local_name(container) == "ol" else "unordered",- "content": children,- }- if local_name(container) == "ol":- block["start"] = _html_list_start(container)- sub_type = (container.get("data-block-sub-type") or "").strip()- if sub_type:- block["sub_type"] = sub_type- return block---def _materialize_index(content_root: etree._Element, projector: MarkupProjector) -> dict[str, object]:- """恢复目录根及其精确标题/文本叶子。"""- root_list = _element_children(content_root)[0]- return {"type": BlockType.INDEX, "content": _materialize_index_children(root_list, projector)}---def _materialize_index_children(container: etree._Element, projector: MarkupProjector) -> list[dict[str, object]]:- """递归恢复目录 li 与嵌套 IndexBlock。"""- children: list[dict[str, object]] = []- for item in _element_children(container):- item_type = (item.get("data-block-type") or "").strip()- nested_lists = [child for child in _element_children(item) if local_name(child) == "ul"]- if item_type:- content_host = next(- (child for child in _element_children(item) if local_name(child) == "a"),- None,- )- content_element = content_host if content_host is not None else _without_nested_lists(item)- content = _project_inline_content(projector, content_element)- block: dict[str, object] = {"type": BlockType(item_type), "content": content}- if item_type in {BlockType.DOC_TITLE, BlockType.PARAGRAPH_TITLE}:- block["anchor"] = (item.get("data-anchor") or "").strip()- block["level"] = int(item.get("data-level") or 1)- if (index := _non_negative_integer(item, "data-block-index", required=False)) is not None:- block["index"] = index- children.append(block)- for nested in nested_lists:- nested_block: dict[str, object] = {- "type": BlockType.INDEX,- "content": _materialize_index_children(nested, projector),- }- if (index := _non_negative_integer(nested, "data-block-index", required=False)) is not None:- nested_block["index"] = index- children.append(nested_block)- return children---def _project_visual_body_content(- body: etree._Element,- resources: HtmlResourceContext,- stylesheet: MarkupStylesheet,-) -> str:- """删除展示性图片/summary 后,用通用 projector 恢复 visual 的结构内容。"""- clone = deepcopy(body)- for element in list(clone.iterdescendants()):- if not isinstance(element.tag, str):- continue- name = local_name(element)- classes = _class_tokens(element)- is_owned_image = name == "img" and bool(classes & _OWNED_VISUAL_IMAGE_TOKENS)- if name == "summary" or "mineru-flowchart-canvas" in classes or is_owned_image:- _drop_tree_preserve_tail(element)- blocks = MarkupProjector(clone, resources, stylesheet).convert()- parts: list[str] = []- for block in blocks:- block_type = block.get("type")- content = str(block.get("content") or "")- if block_type == BlockType.EQUATION and content:- parts.append(f"<eq>{html.escape(content, quote=False)}</eq>")- elif content:- parts.append(content if block_type == BlockType.TABLE else html.unescape(content))- return "\n".join(parts)---def _project_inline_content(projector: MarkupProjector, element: etree._Element) -> str:- """恢复 projector 为内部标签安全转义的一层实体,避免二次 HTML escape。"""- return html.unescape(projector.project_inline_content(element))---def _flowchart_content(body: etree._Element) -> str | None:- """从 renderer 的受限 Mermaid 源码回退恢复标准 fence。"""- source = next(- (- element- for element in body.iterdescendants()- if isinstance(element.tag, str) and "mineru-flowchart-source" in _class_tokens(element)- ),- None,- )- if source is None:- return None- value = "".join(source.itertext()).strip("\n")- return f"```mermaid\n{value}\n```" if value else None---def _resolved_image_payload(- element: etree._Element,- resources: HtmlResourceContext,- *,- allowed_classes: frozenset[str] | None = None,-) -> dict[str, object]:- """解析子树中首个图片来源,并仅返回统一安全载荷字段。"""- candidates = [element] if local_name(element) == "img" else list(element.iterdescendants())- image = next(- (- child- for child in candidates- if isinstance(child.tag, str)- and local_name(child) == "img"- and (allowed_classes is None or bool(_class_tokens(child) & allowed_classes))- ),- None,- )- if image is None:- return {}- resolved = resources.resolve_image(image.get("src") or "", alt=image.get("alt") or "")- if resolved is None:- return {}- if resolved.image_base64:- return {"image_base64": resolved.image_base64}- if resolved.image_url:- return {"image_url": resolved.image_url}- return {}---def _without_nested_lists(element: etree._Element) -> etree._Element:- """复制 li 并移除直属嵌套列表,避免叶子内容重复包含子列表。"""- clone = deepcopy(element)- for child in list(_element_children(clone)):- if local_name(child) in {"ol", "ul"}:- _drop_tree_preserve_tail(child)- return clone---def _drop_tree_preserve_tail(element: etree._Element) -> None:- """删除展示节点并把 tail 归还到相邻文本位置。"""- parent = element.getparent()- if parent is None:- return- tail = element.tail or ""- previous = element.getprevious()- if tail:- if previous is not None:- previous.tail = (previous.tail or "") + tail- else:- parent.text = (parent.text or "") + tail- parent.remove(element)---def _page_block_type(wrapper: etree._Element) -> BlockType:- """把顶层 data-block-type 严格转换为公开 PageBlock 类型。"""- value = (wrapper.get("data-block-type") or "").strip()- try:- block_type = BlockType(value)- except ValueError as exc:- raise _WireValidationError("invalid_block_type") from exc- if block_type not in PAGE_BLOCK_TYPES:- raise _WireValidationError("invalid_top_level_type")- return block_type---def _element_children(element: etree._Element) -> list[etree._Element]:- """返回元素直属的真实标签子节点。"""- return [child for child in element if isinstance(child.tag, str)]---def _validate_element_only_content(element: etree._Element) -> None:- """拒绝机器结构容器直属的可见文本,避免精确物化静默丢弃内容。"""- if (element.text or "").strip() or any((child.tail or "").strip() for child in element):- raise _WireValidationError("unexpected_wire_text")---def _validate_inline_content_shape(- element: etree._Element,- *,- excluded_roots: list[etree._Element] | None = None,-) -> None:- """拒绝行内物化区域中的块级或图片后代,确保校验失败时事务式回退。"""- excluded = excluded_roots or []- for candidate in element.iterdescendants():- if not isinstance(candidate.tag, str) or (excluded and _is_within_any(candidate, excluded)):- continue- name = local_name(candidate)- marker_type = (candidate.get("data-block-type") or "").strip()- if name == "math" and marker_type == BlockType.EQUATION:- continue- if name in BLOCK_TAGS or name in {"image", "img"}:- raise _WireValidationError("invalid_inline_child")---def _descendant_markers(element: etree._Element) -> list[etree._Element]:- """返回自身及后代中声明 data-block-type 的元素。"""- return [- candidate- for candidate in [element, *element.iterdescendants()]- if isinstance(candidate.tag, str) and candidate.get("data-block-type") is not None- ]---def _is_within_any(element: etree._Element, roots: list[etree._Element]) -> bool:- """判断元素是否等于或位于任一嵌套语义根之内。"""- ancestors = set(element.iterancestors())- return any(root is element or root in ancestors for root in roots)---def _class_tokens(element: etree._Element) -> frozenset[str]:- """按 HTML class 空白边界返回完整小写 token,不做 substring 推断。"""- return frozenset((element.get("class") or "").casefold().split())---def _non_negative_integer(element: etree._Element, name: str, *, required: bool) -> int | None:- """读取非负整数 data 属性,缺失或非法时按契约失败。"""- value = element.get(name)- if value is None:- if required:- raise _WireValidationError("missing_integer_attribute")- return None- try:- parsed = int(value)- except (TypeError, ValueError) as exc:- raise _WireValidationError("invalid_integer_attribute") from exc- if parsed < 0 or str(parsed) != value.strip():- raise _WireValidationError("invalid_integer_attribute")- return parsed---def _optional_integer(element: etree._Element, name: str) -> int | None:- """读取可选整数属性,非法文本不允许静默降级。"""- value = element.get(name)- if value is None:- return None- try:- return int(value)- except (TypeError, ValueError) as exc:- raise _WireValidationError("invalid_integer_attribute") from exc---def _html_list_start(element: etree._Element) -> int:- """读取 renderer 原生有序列表起始值,非法值保守回退为一。"""- try:- value = int(element.get("start") or 1)- except ValueError:- return 1- return value if value >= 0 else 1---__all__ = [- "MineruHtmlBlockSpec",- "MineruHtmlWireInspection",- "MineruHtmlWirePlan",- "inspect_mineru_html_wire",- "materialize_mineru_html_wire",-]diff --git a/mineru/model/flash/html/wire/__init__.py b/mineru/model/flash/html/wire/__init__.pynew file mode 100644index 00000000..29589c9a--- /dev/null+++ b/mineru/model/flash/html/wire/__init__.py@@ -0,0 +1,23 @@+# Copyright (c) Opendatalab. All rights reserved.+"""MinerU HTML v1 canonical wire 的轻量内部入口。"""++from __future__ import annotations++from lxml import etree # type: ignore[reportMissingImports]++from ..resources import HtmlResourceContext+from .contracts import MINERU_HTML_VERSION, WireDecodeResult+++def decode_mineru_html_wire(body: etree._Element, resources: HtmlResourceContext) -> WireDecodeResult:+ """只对 canonical v1 wire 精确解码,其余输入返回通用投影信号。"""+ from .materializer import materialize_mineru_html_wire+ from .parser import parse_mineru_html_wire++ plan, fallback_reason = parse_mineru_html_wire(body)+ if plan is None:+ return WireDecodeResult(None, fallback_reason)+ return WireDecodeResult(materialize_mineru_html_wire(plan, resources))+++__all__ = ["MINERU_HTML_VERSION", "WireDecodeResult", "decode_mineru_html_wire"]diff --git a/mineru/model/flash/html/wire/contracts.py b/mineru/model/flash/html/wire/contracts.pynew file mode 100644index 00000000..4022262b--- /dev/null+++ b/mineru/model/flash/html/wire/contracts.py@@ -0,0 +1,237 @@+# Copyright (c) Opendatalab. All rights reserved.+"""MinerU HTML v1 canonical wire 的内部类型契约。"""++from __future__ import annotations++from dataclasses import dataclass+from typing import Literal, TypeAlias, Union++from lxml import etree # type: ignore[reportMissingImports]++from .....types import BlockType+++MINERU_HTML_VERSION = "1"+WIRE_BLOCK_CLASS = "mineru-block"+WIRE_DOCUMENT_CLASS = "mineru-document"+WIRE_INDEX_CLASS = "mineru-index"+WIRE_LIST_CONTENT_CLASS = "mineru-list-content"+WIRE_LIST_MARKER_CLASS = "mineru-list-marker"+WIRE_PAGE_BREAK_CLASS = "mineru-page-break"+WIRE_PAGE_CLASS = "mineru-page"+WIRE_VISUAL_BODY_CLASS = "mineru-visual-body"+WireRenderMode: TypeAlias = Literal["default", "full"]+WireFallbackReason: TypeAlias = Literal["unsupported_version", "non_canonical_wire"]+++@dataclass(frozen=True, slots=True)+class TextWireSpec:+ """保存一个文本类顶层 block 的 canonical 节点与元数据。"""++ wrapper: etree._Element+ content_root: etree._Element+ block_type: BlockType+ page_idx: int+ block_index: int | None+++@dataclass(frozen=True, slots=True)+class EquationWireSpec:+ """保存一个行间公式或公式图片 carrier。"""++ wrapper: etree._Element+ content_root: etree._Element+ page_idx: int+ block_index: int | None+++@dataclass(frozen=True, slots=True)+class AnnotationWireSpec:+ """保存 visual caption/footnote 的 canonical 行内容器。"""++ element: etree._Element+ block_type: BlockType+++@dataclass(frozen=True, slots=True)+class RichVisualBodyWireSpec:+ """保存普通 image/chart body 的主图片与规范化富内容片段。"""++ element: etree._Element+ parent_type: BlockType+ sub_type: str+ primary_image: etree._Element | None+ content_fragment: etree._Element | None+++@dataclass(frozen=True, slots=True)+class FlowchartBodyWireSpec:+ """保存 flowchart 源码与可选 raster fallback。"""++ element: etree._Element+ source_element: etree._Element+ fallback_image: etree._Element | None+++@dataclass(frozen=True, slots=True)+class TableBodyWireSpec:+ """保存 table body 的唯一 canonical 载荷。"""++ element: etree._Element+ kind: Literal["empty", "html", "text", "image"]+ payload_element: etree._Element | None+++@dataclass(frozen=True, slots=True)+class CodeBodyWireSpec:+ """保存 code/algorithm body 的唯一 canonical 内容载体。"""++ element: etree._Element+ kind: Literal["code", "algorithm"]+ content_element: etree._Element+++VisualBodyWireSpec: TypeAlias = Union[+ RichVisualBodyWireSpec,+ FlowchartBodyWireSpec,+ TableBodyWireSpec,+ CodeBodyWireSpec,+]+VisualChildWireSpec: TypeAlias = Union[VisualBodyWireSpec, AnnotationWireSpec]+++@dataclass(frozen=True, slots=True)+class VisualWireSpec:+ """保存 visual 顶层 block 与已按 DOM 顺序解析的子节点。"""++ wrapper: etree._Element+ content_root: etree._Element+ block_type: BlockType+ page_idx: int+ block_index: int | None+ sub_type: str+ guess_lang: str+ children: tuple[VisualChildWireSpec, ...]+++@dataclass(frozen=True, slots=True)+class ListLeafWireSpec:+ """保存一个列表叶子的内容 carrier、marker 与公开类型。"""++ block_type: BlockType+ block_index: int | None+ content_element: etree._Element | None+ marker: str+++@dataclass(frozen=True, slots=True)+class ListWireSpec:+ """保存一个 canonical 列表及其递归子项。"""++ element: etree._Element+ block_index: int | None+ ordered: bool+ start: int+ sub_type: str+ classes: frozenset[str]+ children: tuple[Union[ListLeafWireSpec, "ListWireSpec"], ...]+++@dataclass(frozen=True, slots=True)+class ListBlockWireSpec:+ """保存顶层 ListBlock wrapper 与列表树。"""++ wrapper: etree._Element+ page_idx: int+ block_index: int | None+ root: ListWireSpec+++@dataclass(frozen=True, slots=True)+class IndexLeafWireSpec:+ """保存一个目录叶子的 canonical 内容 carrier 与元数据。"""++ block_type: BlockType+ block_index: int | None+ content_element: etree._Element | None+ anchor: str+ level: int | None+++@dataclass(frozen=True, slots=True)+class IndexWireSpec:+ """保存一个 canonical 目录列表及其递归子项。"""++ element: etree._Element+ block_index: int | None+ children: tuple[Union[IndexLeafWireSpec, "IndexWireSpec"], ...]+++@dataclass(frozen=True, slots=True)+class IndexBlockWireSpec:+ """保存顶层 IndexBlock wrapper 与目录树。"""++ wrapper: etree._Element+ page_idx: int+ block_index: int | None+ root: IndexWireSpec+++PageWireSpec: TypeAlias = Union[+ TextWireSpec,+ EquationWireSpec,+ VisualWireSpec,+ ListBlockWireSpec,+ IndexBlockWireSpec,+]+++@dataclass(frozen=True, slots=True)+class MineruHtmlWirePlan:+ """保存一次无资源副作用的完整 canonical wire 解析结果。"""++ root: etree._Element+ render_mode: WireRenderMode+ blocks: tuple[PageWireSpec, ...]+++@dataclass(frozen=True, slots=True)+class WireDecodeResult:+ """区分未命中 wire、精确解码成功与需要通用回退。"""++ blocks: list[dict[str, object]] | None+ fallback_reason: WireFallbackReason | None = None+++__all__ = [+ "AnnotationWireSpec",+ "CodeBodyWireSpec",+ "EquationWireSpec",+ "FlowchartBodyWireSpec",+ "IndexBlockWireSpec",+ "IndexLeafWireSpec",+ "IndexWireSpec",+ "ListBlockWireSpec",+ "ListLeafWireSpec",+ "ListWireSpec",+ "MINERU_HTML_VERSION",+ "MineruHtmlWirePlan",+ "PageWireSpec",+ "RichVisualBodyWireSpec",+ "TableBodyWireSpec",+ "TextWireSpec",+ "VisualBodyWireSpec",+ "VisualChildWireSpec",+ "VisualWireSpec",+ "WireDecodeResult",+ "WireFallbackReason",+ "WireRenderMode",+ "WIRE_BLOCK_CLASS",+ "WIRE_DOCUMENT_CLASS",+ "WIRE_INDEX_CLASS",+ "WIRE_LIST_CONTENT_CLASS",+ "WIRE_LIST_MARKER_CLASS",+ "WIRE_PAGE_BREAK_CLASS",+ "WIRE_PAGE_CLASS",+ "WIRE_VISUAL_BODY_CLASS",+]diff --git a/mineru/model/flash/html/wire/materializer.py b/mineru/model/flash/html/wire/materializer.pynew file mode 100644index 00000000..f2d7f0a0--- /dev/null+++ b/mineru/model/flash/html/wire/materializer.py@@ -0,0 +1,330 @@+# Copyright (c) Opendatalab. All rights reserved.+"""把已验证的 MinerU HTML v1 typed plan 物化为 raw model-list。"""++from __future__ import annotations++from copy import deepcopy+import html++from lxml import etree # type: ignore[reportMissingImports]++from .....types import RAW_ALGORITHM, BlockType+from ..._shared.markup import MarkupProjector, MarkupStylesheet, extract_formula+from ..._shared.markup.projector import BLOCK_TAGS, local_name+from ..resources import HtmlResourceContext+from .contracts import (+ AnnotationWireSpec,+ CodeBodyWireSpec,+ EquationWireSpec,+ FlowchartBodyWireSpec,+ IndexBlockWireSpec,+ IndexLeafWireSpec,+ IndexWireSpec,+ ListBlockWireSpec,+ ListWireSpec,+ MineruHtmlWirePlan,+ RichVisualBodyWireSpec,+ TableBodyWireSpec,+ TextWireSpec,+ VisualWireSpec,+)+++class ExactAnchorResolver:+ """把 renderer DOM id 恢复为 typed plan 中保存的原始 anchor。"""++ def __init__(self, plan: MineruHtmlWirePlan) -> None:+ """预扫描标题和页面脚注的 id、文本及原始 anchor。"""+ self._targets: dict[str, str] = {}+ self._heading_anchors: dict[etree._Element, str] = {}+ self._heading_labels: dict[str, str] = {}+ self._note_anchors: dict[etree._Element, str] = {}+ for spec in plan.blocks:+ if not isinstance(spec, TextWireSpec):+ continue+ anchor = (spec.wrapper.get("data-anchor") or "").strip()+ if not anchor:+ continue+ self._targets.setdefault(anchor, anchor)+ for candidate in [spec.content_root, *spec.content_root.iterdescendants()]:+ identity = (candidate.get("id") or "").strip()+ if identity:+ self._targets.setdefault(identity, anchor)+ if spec.block_type in {BlockType.DOC_TITLE, BlockType.PARAGRAPH_TITLE}:+ self._heading_anchors[spec.content_root] = anchor+ self._heading_labels[anchor] = " ".join(spec.content_root.itertext()).strip()+ elif spec.block_type == BlockType.PAGE_FOOTNOTE:+ self._note_anchors[spec.content_root] = anchor++ def resolve_fragment(self, fragment: str) -> str | None:+ """把 renderer id 或原始 anchor 统一还原为内部 fragment。"""+ identity = fragment.removeprefix("#").strip()+ return f"#{anchor}" if (anchor := self._targets.get(identity)) else None++ 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 materialize_mineru_html_wire(+ plan: MineruHtmlWirePlan,+ resources: HtmlResourceContext,+) -> list[dict[str, object]]:+ """在整棵 canonical 树验证成功后一次性解析资源并生成 raw blocks。"""+ resources.bind_anchors(ExactAnchorResolver(plan))+ stylesheet = MarkupStylesheet()+ projector = MarkupProjector(plan.root, resources, stylesheet, single_document_title=True)+ blocks: list[dict[str, object]] = []+ for spec in plan.blocks:+ if isinstance(spec, TextWireSpec):+ blocks.append(_materialize_text(spec, projector))+ elif isinstance(spec, EquationWireSpec):+ blocks.append(_materialize_equation(spec, resources))+ elif isinstance(spec, VisualWireSpec):+ blocks.extend(_materialize_visual(spec, resources, projector))+ elif isinstance(spec, ListBlockWireSpec):+ blocks.append(_materialize_list(spec.root, projector))+ elif isinstance(spec, IndexBlockWireSpec):+ blocks.append(_materialize_index(spec.root, projector))+ else: # pragma: no cover - PageWireSpec 已穷尽。+ raise AssertionError(f"unsupported wire spec: {type(spec).__name__}")+ return blocks+++def _materialize_text(spec: TextWireSpec, projector: MarkupProjector) -> dict[str, object]:+ """恢复文本、标题、页面辅助块和页面脚注。"""+ block: dict[str, object] = {+ "type": spec.block_type,+ "content": _project_inline_content(projector, spec.content_root),+ }+ if spec.block_type in {BlockType.DOC_TITLE, BlockType.PARAGRAPH_TITLE}:+ block["level"] = int(spec.wrapper.get("data-level") or 1)+ if spec.block_type in {BlockType.DOC_TITLE, BlockType.PARAGRAPH_TITLE, BlockType.PAGE_FOOTNOTE}:+ anchor = (spec.wrapper.get("data-anchor") or "").strip()+ if anchor:+ block["anchor"] = anchor+ return block+++def _materialize_equation(spec: EquationWireSpec, resources: HtmlResourceContext) -> dict[str, object]:+ """恢复行间公式裸 LaTeX 或 renderer-owned 公式图片。"""+ formula = extract_formula(spec.content_root)+ block: dict[str, object] = {+ "type": BlockType.EQUATION,+ "content": formula.latex if formula is not None else "",+ }+ if formula is None:+ block.update(_resolve_image_payload(spec.content_root, resources))+ return block+++def _materialize_visual(+ spec: VisualWireSpec,+ resources: HtmlResourceContext,+ projector: MarkupProjector,+) -> list[dict[str, object]]:+ """按 renderer DOM 顺序恢复 visual body 与 annotations。"""+ blocks: list[dict[str, object]] = []+ for child in spec.children:+ if isinstance(child, AnnotationWireSpec):+ blocks.append(+ {+ "type": child.block_type,+ "content": _project_inline_content(projector, child.element),+ }+ )+ continue+ block = _materialize_visual_body(child, resources, projector)+ if spec.sub_type:+ block["sub_type"] = spec.sub_type+ if isinstance(child, CodeBodyWireSpec) and child.kind == "code":+ block["guess_lang"] = spec.guess_lang+ blocks.append(block)+ return blocks+++def _materialize_visual_body(+ spec: RichVisualBodyWireSpec | FlowchartBodyWireSpec | TableBodyWireSpec | CodeBodyWireSpec,+ resources: HtmlResourceContext,+ projector: MarkupProjector,+) -> dict[str, object]:+ """从 typed body spec 恢复唯一载荷,不重新判断 DOM 形状。"""+ if isinstance(spec, RichVisualBodyWireSpec):+ block: dict[str, object] = {+ "type": spec.parent_type,+ "content": _restore_content(spec.content_fragment, projector),+ }+ if spec.primary_image is not None:+ block.update(_resolve_image_payload(spec.primary_image, resources))+ return block+ if isinstance(spec, FlowchartBodyWireSpec):+ block = {+ "type": BlockType.IMAGE,+ "content": _flowchart_content(spec.source_element),+ }+ if spec.fallback_image is not None:+ block.update(_resolve_image_payload(spec.fallback_image, resources))+ return block+ if isinstance(spec, TableBodyWireSpec):+ return _materialize_table(spec, resources, projector)+ return _materialize_code(spec, projector)+++def _materialize_table(+ spec: TableBodyWireSpec,+ resources: HtmlResourceContext,+ projector: MarkupProjector,+) -> dict[str, object]:+ """恢复已判别的结构表格、文本、图片或空载荷。"""+ block: dict[str, object] = {"type": BlockType.TABLE, "content": ""}+ if spec.kind == "html" and spec.payload_element is not None:+ fragment = etree.Element("div")+ fragment.append(deepcopy(spec.payload_element))+ block["content"] = _restore_content(fragment, projector)+ elif spec.kind == "text" and spec.payload_element is not None:+ block["content"] = "".join(spec.payload_element.itertext())+ elif spec.kind == "image" and spec.payload_element is not None:+ block.update(_resolve_image_payload(spec.payload_element, resources))+ return block+++def _materialize_code(spec: CodeBodyWireSpec, projector: MarkupProjector) -> dict[str, object]:+ """恢复普通代码文本或 algorithm 行内语义。"""+ if spec.kind == "code":+ return {+ "type": BlockType.CODE,+ "content": "".join(spec.content_element.itertext()),+ }+ return {+ "type": RAW_ALGORITHM,+ "content": _restore_content(spec.content_element, projector),+ }+++def _materialize_list(spec: ListWireSpec, projector: MarkupProjector) -> dict[str, object]:+ """递归恢复列表叶子、marker 和嵌套 ListBlock。"""+ children: list[dict[str, object]] = []+ for child in spec.children:+ if isinstance(child, ListWireSpec):+ children.append(_materialize_list(child, projector))+ continue+ content = _project_inline_content(projector, child.content_element) if child.content_element is not None else ""+ if child.marker and ({"mineru-list--reference", "mineru-list--explicit"} & spec.classes):+ content = f"{child.marker} {content}".strip()+ block: dict[str, object] = {"type": child.block_type, "content": content}+ if child.block_index is not None:+ block["index"] = child.block_index+ children.append(block)+ block = {+ "type": BlockType.LIST,+ "attribute": "ordered" if spec.ordered else "unordered",+ "content": children,+ }+ if spec.ordered:+ block["start"] = spec.start+ if spec.sub_type:+ block["sub_type"] = spec.sub_type+ return block+++def _materialize_index(spec: IndexWireSpec, projector: MarkupProjector) -> dict[str, object]:+ """递归恢复目录叶子和嵌套 IndexBlock。"""+ children: list[dict[str, object]] = []+ for child in spec.children:+ if isinstance(child, IndexWireSpec):+ nested = _materialize_index(child, projector)+ if child.block_index is not None:+ nested["index"] = child.block_index+ children.append(nested)+ continue+ children.append(_materialize_index_leaf(child, projector))+ return {"type": BlockType.INDEX, "content": children}+++def _materialize_index_leaf(spec: IndexLeafWireSpec, projector: MarkupProjector) -> dict[str, object]:+ """恢复目录叶子的内容和标题元数据。"""+ content = _project_inline_content(projector, spec.content_element) if spec.content_element is not None else ""+ block: dict[str, object] = {"type": spec.block_type, "content": content}+ if spec.block_type in {BlockType.DOC_TITLE, BlockType.PARAGRAPH_TITLE}:+ block["anchor"] = spec.anchor+ block["level"] = spec.level or 1+ if spec.block_index is not None:+ block["index"] = spec.block_index+ return block+++def _restore_content(fragment: etree._Element | None, projector: MarkupProjector) -> str:+ """按 inline 或安全富 HTML 语义恢复 visual body content。"""+ if fragment is None:+ return ""+ if not _contains_rich_markup(fragment):+ return _project_inline_content(projector, fragment)+ clone = deepcopy(fragment)+ for carrier in list(clone.iterdescendants()):+ if not isinstance(carrier.tag, str):+ continue+ if local_name(carrier) != "math" or (carrier.get("data-block-type") or "").strip() != BlockType.EQUATION:+ continue+ formula = extract_formula(carrier)+ if formula is None or not formula.latex:+ continue+ replacement = etree.Element("eq")+ replacement.text = formula.latex+ replacement.tail = carrier.tail+ parent = carrier.getparent()+ if parent is not None:+ parent.replace(carrier, replacement)+ return _serialize_fragment(clone)+++def _contains_rich_markup(fragment: etree._Element) -> bool:+ """判断片段是否需要以结构化 HTML 而非内部 inline 字符串保存。"""+ return any(+ isinstance(element.tag, str) and (local_name(element) in BLOCK_TAGS or local_name(element) in {"image", "img"})+ for element in fragment.iterdescendants()+ )+++def _serialize_fragment(fragment: etree._Element) -> str:+ """把 synthetic fragment 的内容序列化为规范化安全 HTML。"""+ parts = [html.escape(fragment.text or "", quote=False)]+ parts.extend(+ etree.tostring(child, encoding="unicode", method="html", with_tail=True)+ for child in fragment+ if isinstance(child.tag, str)+ )+ return "".join(parts).strip()+++def _project_inline_content(projector: MarkupProjector, element: etree._Element) -> str:+ """恢复 projector 为内部标签安全转义的一层实体。"""+ return html.unescape(projector.project_inline_content(element))+++def _flowchart_content(source_element: etree._Element) -> str:+ """把 canonical Mermaid 源码恢复为标准 fence。"""+ value = "".join(source_element.itertext()).strip("\n")+ return f"```mermaid\n{value}\n```" if value else ""+++def _resolve_image_payload(element: etree._Element, resources: HtmlResourceContext) -> dict[str, object]:+ """解析已由 canonical parser 选定的单个 renderer-owned 图片。"""+ resolved = resources.resolve_image(element.get("src") or "", alt=element.get("alt") or "")+ if resolved is None:+ return {}+ if resolved.image_base64:+ return {"image_base64": resolved.image_base64}+ if resolved.image_url:+ return {"image_url": resolved.image_url}+ return {}+++__all__ = ["ExactAnchorResolver", "materialize_mineru_html_wire"]diff --git a/mineru/model/flash/html/wire/parser.py b/mineru/model/flash/html/wire/parser.pynew file mode 100644index 00000000..a6873f8a--- /dev/null+++ b/mineru/model/flash/html/wire/parser.py@@ -0,0 +1,758 @@+# Copyright (c) Opendatalab. All rights reserved.+"""把 MinerU HTML v1 固定 DOM 解析为无资源副作用的 typed plan。"""++from __future__ import annotations++from copy import deepcopy+from typing import cast+from urllib.parse import unquote++from lxml import etree # type: ignore[reportMissingImports]++from .....types import PAGE_BLOCK_TYPES, RAW_ALGORITHM, BlockType, VISUAL_TYPE_MAPPING+from ..._shared.markup import extract_formula+from ..._shared.markup.projector import BLOCK_TAGS, local_name+from .contracts import (+ AnnotationWireSpec,+ CodeBodyWireSpec,+ EquationWireSpec,+ FlowchartBodyWireSpec,+ IndexBlockWireSpec,+ IndexLeafWireSpec,+ IndexWireSpec,+ ListBlockWireSpec,+ ListLeafWireSpec,+ ListWireSpec,+ MINERU_HTML_VERSION,+ MineruHtmlWirePlan,+ PageWireSpec,+ RichVisualBodyWireSpec,+ TableBodyWireSpec,+ TextWireSpec,+ VisualBodyWireSpec,+ VisualWireSpec,+ WireFallbackReason,+ WireRenderMode,+ WIRE_BLOCK_CLASS,+ WIRE_DOCUMENT_CLASS,+ WIRE_INDEX_CLASS,+ WIRE_LIST_CONTENT_CLASS,+ WIRE_LIST_MARKER_CLASS,+ WIRE_PAGE_BREAK_CLASS,+ WIRE_PAGE_CLASS,+ WIRE_VISUAL_BODY_CLASS,+)+++_SIMPLE_TEXT_TYPES = frozenset(+ {+ BlockType.TEXT,+ BlockType.REF_TEXT,+ BlockType.DOC_TITLE,+ BlockType.PARAGRAPH_TITLE,+ BlockType.HEADER,+ BlockType.FOOTER,+ BlockType.PAGE_NUMBER,+ BlockType.ASIDE_TEXT,+ BlockType.PAGE_FOOTNOTE,+ }+)+_PAGE_AUXILIARY_TYPES = frozenset({BlockType.HEADER, BlockType.FOOTER, BlockType.PAGE_NUMBER, BlockType.ASIDE_TEXT})+_LIST_LEAF_TYPES = frozenset({BlockType.TEXT, BlockType.REF_TEXT})+_INDEX_LEAF_TYPES = frozenset({BlockType.TEXT, BlockType.DOC_TITLE, BlockType.PARAGRAPH_TITLE})+_OWNED_VISUAL_IMAGE_TOKENS = frozenset(+ {"mineru-chart-image", "mineru-flowchart-fallback", "mineru-image", "mineru-table-image"}+)+++class NonCanonicalWire(ValueError):+ """表示当前 DOM 不是 renderer 能生成的 canonical v1 wire。"""+++def parse_mineru_html_wire(body: etree._Element) -> tuple[MineruHtmlWirePlan | None, WireFallbackReason | None]:+ """发现并解析 canonical v1 wire,非法结构只返回统一回退原因。"""+ roots = [+ element+ for element in body.iter()+ if isinstance(element.tag, str) and element.get("data-mineru-html-version") is not None+ ]+ if not roots:+ return None, None+ if len(roots) != 1:+ return None, "non_canonical_wire"+ root = roots[0]+ if (root.get("data-mineru-html-version") or "").strip() != MINERU_HTML_VERSION:+ return None, "unsupported_version"+ try:+ _validate_wire_root_ownership(body, root)+ return _parse_wire_root(root), None+ except NonCanonicalWire:+ return None, "non_canonical_wire"+++def _parse_wire_root(root: etree._Element) -> MineruHtmlWirePlan:+ """解析根、渲染模式、页面容器和全部顶层 block。"""+ if local_name(root) != "article" or _class_tokens(root) != {+ WIRE_DOCUMENT_CLASS,+ f"{WIRE_DOCUMENT_CLASS}--{(root.get('data-render-mode') or '').strip()}",+ }:+ raise NonCanonicalWire+ _validate_structural_text(root)+ mode_value = (root.get("data-render-mode") or "").strip()+ if mode_value not in {"default", "full"}:+ raise NonCanonicalWire+ mode = cast(WireRenderMode, mode_value)+ wrappers: list[tuple[etree._Element, int | None]] = []+ if mode == "default":+ for child in _element_children(root):+ if local_name(child) != "div" or _class_tokens(child) != {WIRE_BLOCK_CLASS}:+ raise NonCanonicalWire+ wrappers.append((child, None))+ else:+ for child in _element_children(root):+ if local_name(child) == "hr" and _class_tokens(child) == {WIRE_PAGE_BREAK_CLASS}:+ continue+ if local_name(child) != "section" or _class_tokens(child) != {WIRE_PAGE_CLASS}:+ raise NonCanonicalWire+ _validate_structural_text(child)+ page_idx = _non_negative_integer(child, "data-page-idx", required=True)+ for wrapper in _element_children(child):+ if local_name(wrapper) != "div" or _class_tokens(wrapper) != {WIRE_BLOCK_CLASS}:+ raise NonCanonicalWire+ wrappers.append((wrapper, page_idx))+ nested_wrappers = [+ element+ for element in root.iterdescendants()+ if isinstance(element.tag, str) and WIRE_BLOCK_CLASS in _class_tokens(element)+ ]+ if len(nested_wrappers) != len(wrappers):+ raise NonCanonicalWire+ target_ids = _collect_title_target_ids(wrappers)+ blocks = tuple(_parse_top_block(wrapper, section_page_idx, target_ids) for wrapper, section_page_idx in wrappers)+ return MineruHtmlWirePlan(root, mode, blocks)+++def _validate_wire_root_ownership(body: etree._Element, root: etree._Element) -> None:+ """要求 canonical wire 根独占从自身到 body 的可见内容路径。"""+ current = root+ while current is not body:+ parent = current.getparent()+ if parent is None or (parent.text or "").strip():+ raise NonCanonicalWire+ for sibling in parent:+ if sibling is current:+ if (sibling.tail or "").strip():+ raise NonCanonicalWire+ continue+ if isinstance(sibling.tag, str) or (sibling.tail or "").strip():+ raise NonCanonicalWire+ current = parent+++def _parse_top_block(+ wrapper: etree._Element,+ section_page_idx: int | None,+ target_ids: dict[str, frozenset[str]],+) -> PageWireSpec:+ """解析一个顶层 wrapper,并构造与 block 家族匹配的 typed spec。"""+ _validate_structural_text(wrapper)+ block_type = _page_block_type(wrapper)+ page_idx = _non_negative_integer(wrapper, "data-page-idx", required=True)+ if section_page_idx is not None and page_idx != section_page_idx:+ raise NonCanonicalWire+ block_index = _non_negative_integer(wrapper, "data-block-index", required=False)+ _validate_top_metadata(wrapper, block_type)+ roots = _element_children(wrapper)+ if len(roots) != 1:+ raise NonCanonicalWire+ content_root = roots[0]+ if block_type in _SIMPLE_TEXT_TYPES:+ _validate_simple_content(content_root, block_type)+ return TextWireSpec(wrapper, content_root, block_type, page_idx, block_index)+ if block_type == BlockType.EQUATION:+ _validate_equation_content(content_root)+ return EquationWireSpec(wrapper, content_root, page_idx, block_index)+ if block_type == BlockType.LIST:+ root = _parse_list_container(content_root, top_wrapper=wrapper)+ return ListBlockWireSpec(wrapper, page_idx, block_index, root)+ if block_type == BlockType.INDEX:+ root = _parse_index_root(content_root, wrapper, target_ids)+ return IndexBlockWireSpec(wrapper, page_idx, block_index, root)+ if block_type in VISUAL_TYPE_MAPPING:+ return _parse_visual_content(wrapper, content_root, block_type, page_idx, block_index)+ raise NonCanonicalWire+++def _validate_top_metadata(wrapper: etree._Element, block_type: BlockType) -> None:+ """校验 subtype、语言、anchor 和 level 只出现在 renderer 定义的位置。"""+ sub_type = (wrapper.get("data-block-sub-type") or "").strip()+ guess_lang = (wrapper.get("data-guess-lang") or "").strip()+ anchor = (wrapper.get("data-anchor") or "").strip()+ level = _optional_integer(wrapper, "data-level")+ if block_type == BlockType.CODE:+ if sub_type not in {BlockType.CODE, RAW_ALGORITHM}:+ raise NonCanonicalWire+ if sub_type == BlockType.CODE and not guess_lang:+ raise NonCanonicalWire+ if sub_type == RAW_ALGORITHM and guess_lang:+ raise NonCanonicalWire+ elif block_type == BlockType.LIST:+ if sub_type and sub_type not in _LIST_LEAF_TYPES:+ raise NonCanonicalWire+ if guess_lang:+ raise NonCanonicalWire+ elif block_type in {BlockType.IMAGE, BlockType.CHART}:+ if guess_lang:+ raise NonCanonicalWire+ elif sub_type or guess_lang:+ raise NonCanonicalWire+ if block_type == BlockType.DOC_TITLE:+ if level != 1:+ raise NonCanonicalWire+ elif block_type == BlockType.PARAGRAPH_TITLE:+ if level is None or not 2 <= level <= 6:+ raise NonCanonicalWire+ elif level is not None:+ raise NonCanonicalWire+ if anchor and block_type not in {BlockType.DOC_TITLE, BlockType.PARAGRAPH_TITLE, BlockType.PAGE_FOOTNOTE}:+ raise NonCanonicalWire+++def _validate_simple_content(content_root: etree._Element, block_type: BlockType) -> None:+ """校验文本、标题、脚注和页面辅助 block 的固定行内容器。"""+ expected_tags: dict[BlockType, frozenset[str]] = {+ BlockType.TEXT: frozenset({"p"}),+ BlockType.REF_TEXT: frozenset({"p"}),+ BlockType.DOC_TITLE: frozenset({"h1"}),+ BlockType.PARAGRAPH_TITLE: frozenset({"h2", "h3", "h4", "h5", "h6"}),+ BlockType.PAGE_FOOTNOTE: frozenset({"div"}),+ **{value: frozenset({"div"}) for value in _PAGE_AUXILIARY_TYPES},+ }+ if local_name(content_root) not in expected_tags[block_type]:+ raise NonCanonicalWire+ _validate_inline_region(content_root)+++def _validate_equation_content(content_root: etree._Element) -> None:+ """校验行间公式为 renderer math carrier 或公式图片。"""+ if local_name(content_root) == "math":+ _validate_formula_carrier(content_root, expected_display="block")+ return+ if local_name(content_root) != "img" or _class_tokens(content_root) != {"mineru-equation-image"}:+ raise NonCanonicalWire+++def _validate_formula_carrier(element: etree._Element, *, expected_display: str) -> None:+ """校验公式 carrier 的类型、显示模式和非空 LaTeX。"""+ if local_name(element) != "math" or (element.get("data-block-type") or "").strip() != BlockType.EQUATION:+ raise NonCanonicalWire+ if (element.get("data-formula-display") or "").strip() != expected_display:+ raise NonCanonicalWire+ formula = extract_formula(element)+ if formula is None or not formula.latex:+ raise NonCanonicalWire+++def _parse_visual_content(+ wrapper: etree._Element,+ content_root: etree._Element,+ parent_type: BlockType,+ page_idx: int,+ block_index: int | None,+) -> VisualWireSpec:+ """解析 figure 下唯一 body 与有序 annotation 子节点。"""+ if local_name(content_root) != "figure":+ raise NonCanonicalWire+ _validate_structural_text(content_root)+ mapping = VISUAL_TYPE_MAPPING[parent_type]+ allowed_types = frozenset(mapping.values())+ children = _element_children(content_root)+ child_types = [(child.get("data-block-type") or "").strip() for child in children]+ if child_types.count(mapping["body"]) != 1 or any(value not in allowed_types for value in child_types):+ raise NonCanonicalWire+ sub_type = (wrapper.get("data-block-sub-type") or "").strip()+ guess_lang = (wrapper.get("data-guess-lang") or "").strip()+ parsed_children: list[VisualBodyWireSpec | AnnotationWireSpec] = []+ for child, child_type in zip(children, child_types, strict=True):+ child_index = _non_negative_integer(child, "data-block-index", required=False)+ if child_type == mapping["body"]:+ if local_name(child) != "div" or (block_index is not None and child_index != block_index):+ raise NonCanonicalWire+ parsed_children.append(_parse_visual_body(child, parent_type, sub_type))+ continue+ if local_name(child) != "p":+ raise NonCanonicalWire+ _validate_inline_region(child)+ parsed_children.append(AnnotationWireSpec(child, BlockType(child_type)))+ return VisualWireSpec(+ wrapper,+ content_root,+ parent_type,+ page_idx,+ block_index,+ sub_type,+ guess_lang,+ tuple(parsed_children),+ )+++def _parse_visual_body(body: etree._Element, parent_type: BlockType, sub_type: str) -> VisualBodyWireSpec:+ """按父 visual 类型解析唯一 canonical body 载荷。"""+ expected_class = f"{WIRE_VISUAL_BODY_CLASS}--{'image' if parent_type == BlockType.IMAGE else str(parent_type)}"+ if _class_tokens(body) != {WIRE_VISUAL_BODY_CLASS, expected_class}:+ raise NonCanonicalWire+ if parent_type == BlockType.CODE:+ return _parse_code_body(body, sub_type)+ if parent_type == BlockType.TABLE:+ return _parse_table_body(body)+ if parent_type == BlockType.IMAGE and _looks_like_flowchart_body(body):+ return _parse_flowchart_body(body)+ return _parse_rich_visual_body(body, parent_type, sub_type)+++def _parse_code_body(body: etree._Element, sub_type: str) -> CodeBodyWireSpec:+ """解析普通代码或 algorithm 的固定内容载体。"""+ _validate_structural_text(body)+ children = _element_children(body)+ if sub_type == BlockType.CODE:+ if len(children) != 1 or local_name(children[0]) != "pre":+ raise NonCanonicalWire+ pre = children[0]+ _validate_structural_text(pre)+ code_children = _element_children(pre)+ if len(code_children) != 1 or local_name(code_children[0]) != "code" or _element_children(code_children[0]):+ raise NonCanonicalWire+ return CodeBodyWireSpec(body, "code", code_children[0])+ if sub_type != RAW_ALGORITHM:+ raise NonCanonicalWire+ if not children:+ empty = etree.Element("div")+ return CodeBodyWireSpec(body, "algorithm", empty)+ if len(children) != 1 or local_name(children[0]) != "div" or _class_tokens(children[0]) != {"mineru-algorithm"}:+ raise NonCanonicalWire+ _validate_inline_region(children[0])+ return CodeBodyWireSpec(body, "algorithm", _clone_fragment(children[0]))+++def _parse_table_body(body: etree._Element) -> TableBodyWireSpec:+ """解析结构表格、空间文本、图片或空 table body。"""+ _validate_structural_text(body)+ children = _element_children(body)+ if not children:+ return TableBodyWireSpec(body, "empty", None)+ if len(children) != 1:+ raise NonCanonicalWire+ child = children[0]+ name = local_name(child)+ classes = _class_tokens(child)+ if name == "table":+ return TableBodyWireSpec(body, "html", child)+ if name == "pre" and classes in ({"mineru-table-text"}, {"mineru-raw-fallback"}) and not _element_children(child):+ return TableBodyWireSpec(body, "text", child)+ if name == "img" and classes == {"mineru-table-image"}:+ return TableBodyWireSpec(body, "image", child)+ raise NonCanonicalWire+++def _looks_like_flowchart_body(body: etree._Element) -> bool:+ """判断 body 是否使用 renderer 的 flowchart 固定外壳。"""+ children = _element_children(body)+ return bool(children and local_name(children[0]) == "div" and "mineru-flowchart" in _class_tokens(children[0]))+++def _parse_flowchart_body(body: etree._Element) -> FlowchartBodyWireSpec:+ """解析 flowchart canvas、可选 raster 和源码 details。"""+ _validate_structural_text(body)+ children = _element_children(body)+ if len(children) != 2:+ raise NonCanonicalWire+ display, details = children+ display_classes = _class_tokens(display)+ if local_name(display) != "div" or "mineru-flowchart" not in display_classes:+ raise NonCanonicalWire+ _validate_structural_text(display)+ display_children = _element_children(display)+ if not 1 <= len(display_children) <= 2:+ raise NonCanonicalWire+ canvas = display_children[0]+ if local_name(canvas) != "div" or _class_tokens(canvas) != {"mineru-flowchart-canvas"}:+ raise NonCanonicalWire+ _validate_structural_text(canvas)+ if _element_children(canvas):+ raise NonCanonicalWire+ fallback_image = None+ if len(display_children) == 2:+ fallback_image = display_children[1]+ if local_name(fallback_image) != "img" or _class_tokens(fallback_image) != {"mineru-flowchart-fallback"}:+ raise NonCanonicalWire+ if local_name(details) != "details" or _class_tokens(details) != {"mineru-details", "mineru-flowchart-details"}:+ raise NonCanonicalWire+ _validate_structural_text(details)+ details_children = _element_children(details)+ if len(details_children) != 2:+ raise NonCanonicalWire+ summary, source = details_children+ if (+ local_name(summary) != "summary"+ or _element_children(summary)+ or " ".join(summary.itertext()).strip() != "flowchart source"+ ):+ raise NonCanonicalWire+ if local_name(source) != "pre" or _class_tokens(source) != {"mineru-flowchart-source"}:+ raise NonCanonicalWire+ _validate_structural_text(source)+ code_children = _element_children(source)+ if len(code_children) != 1 or local_name(code_children[0]) != "code" or _element_children(code_children[0]):+ raise NonCanonicalWire+ return FlowchartBodyWireSpec(body, code_children[0], fallback_image)+++def _parse_rich_visual_body(body: etree._Element, parent_type: BlockType, sub_type: str) -> RichVisualBodyWireSpec:+ """区分 renderer-owned 主图与开放但受 sanitizer 约束的富内容 carrier。"""+ allowed_token = "mineru-image" if parent_type == BlockType.IMAGE else "mineru-chart-image"+ children = _element_children(body)+ primary_image = (+ children[0] if children and local_name(children[0]) == "img" and allowed_token in _class_tokens(children[0]) else None+ )+ if primary_image is not None and _class_tokens(primary_image) != {allowed_token}:+ raise NonCanonicalWire+ for element in body.iterdescendants():+ if not isinstance(element.tag, str) or element is primary_image:+ continue+ if _class_tokens(element) & _OWNED_VISUAL_IMAGE_TOKENS:+ raise NonCanonicalWire+ if primary_image is None:+ return RichVisualBodyWireSpec(body, parent_type, sub_type, None, _clone_fragment(body))+ if (body.text or "").strip() or (primary_image.tail or "").strip():+ raise NonCanonicalWire+ remaining = children[1:]+ if not remaining:+ return RichVisualBodyWireSpec(body, parent_type, sub_type, primary_image, None)+ if len(remaining) != 1:+ raise NonCanonicalWire+ details = remaining[0]+ if local_name(details) != "details" or _class_tokens(details) != {"mineru-details"}:+ raise NonCanonicalWire+ if (details.text or "").strip() or (details.tail or "").strip():+ raise NonCanonicalWire+ details_children = _element_children(details)+ if not details_children or local_name(details_children[0]) != "summary" or _element_children(details_children[0]):+ raise NonCanonicalWire+ expected_summary = sub_type or ("image content" if parent_type == BlockType.IMAGE else "chart content")+ if " ".join(details_children[0].itertext()).strip() != expected_summary:+ raise NonCanonicalWire+ fragment = _clone_fragment(details, after_child=details_children[0])+ return RichVisualBodyWireSpec(body, parent_type, sub_type, primary_image, fragment)+++def _parse_list_container(container: etree._Element, *, top_wrapper: etree._Element | None = None) -> ListWireSpec:+ """递归解析 renderer 生成的列表 carrier、叶子和嵌套列表。"""+ if local_name(container) not in {"ol", "ul"} or (container.get("data-block-type") or "").strip() != BlockType.LIST:+ raise NonCanonicalWire+ _validate_structural_text(container)+ block_index = _non_negative_integer(container, "data-block-index", required=False)+ sub_type = (container.get("data-block-sub-type") or "").strip()+ if sub_type and sub_type not in _LIST_LEAF_TYPES:+ raise NonCanonicalWire+ if top_wrapper is not None and sub_type != (top_wrapper.get("data-block-sub-type") or "").strip():+ raise NonCanonicalWire+ classes = _class_tokens(container)+ if "mineru-list" not in classes or len(classes) != 2:+ raise NonCanonicalWire+ children: list[ListLeafWireSpec | ListWireSpec] = []+ for item in _element_children(container):+ if local_name(item) != "li":+ raise NonCanonicalWire+ item_type = (item.get("data-block-type") or "").strip()+ nested_lists = [child for child in _element_children(item) if local_name(child) in {"ol", "ul"}]+ if item_type:+ if item_type not in _LIST_LEAF_TYPES:+ raise NonCanonicalWire+ leaf = _parse_list_leaf(item, BlockType(item_type), nested_lists)+ children.append(leaf)+ elif any(child not in nested_lists for child in _element_children(item)) or not nested_lists:+ raise NonCanonicalWire+ children.extend(_parse_list_container(nested) for nested in nested_lists)+ start = _canonical_list_start(container)+ return ListWireSpec(container, block_index, local_name(container) == "ol", start, sub_type, classes, tuple(children))+++def _parse_list_leaf(+ item: etree._Element,+ block_type: BlockType,+ nested_lists: list[etree._Element],+) -> ListLeafWireSpec:+ """解析一个列表叶子的唯一 marker/content carrier。"""+ block_index = _non_negative_integer(item, "data-block-index", required=False)+ candidates = [child for child in _element_children(item) if child not in nested_lists]+ content_carriers = [child for child in candidates if _class_tokens(child) == {WIRE_LIST_CONTENT_CLASS}]+ marker_carriers = [child for child in candidates if _class_tokens(child) == {WIRE_LIST_MARKER_CLASS}]+ if len(content_carriers) > 1 or len(marker_carriers) > 1:+ raise NonCanonicalWire+ allowed = [*content_carriers, *marker_carriers, *nested_lists]+ if any(child not in allowed for child in _element_children(item)):+ raise NonCanonicalWire+ if content_carriers:+ _validate_structural_text(item)+ content_element = content_carriers[0]+ if local_name(content_element) != "span":+ raise NonCanonicalWire+ _validate_inline_region(content_element)+ else:+ if marker_carriers or (item.text or "").strip() or any((child.tail or "").strip() for child in item):+ raise NonCanonicalWire+ content_element = None+ marker = ""+ if marker_carriers:+ marker_element = marker_carriers[0]+ if local_name(marker_element) != "span" or _element_children(marker_element):+ raise NonCanonicalWire+ marker = "".join(marker_element.itertext()).strip()+ return ListLeafWireSpec(block_type, block_index, content_element, marker)+++def _parse_index_root(+ content_root: etree._Element,+ wrapper: etree._Element,+ target_ids: dict[str, frozenset[str]],+) -> IndexWireSpec:+ """解析目录根与唯一直属 ul。"""+ if local_name(content_root) != "nav" or _class_tokens(content_root) != {WIRE_INDEX_CLASS}:+ raise NonCanonicalWire+ if (content_root.get("data-block-type") or "").strip() != BlockType.INDEX:+ raise NonCanonicalWire+ _validate_structural_text(content_root)+ root_index = _non_negative_integer(content_root, "data-block-index", required=False)+ wrapper_index = _non_negative_integer(wrapper, "data-block-index", required=False)+ if wrapper_index is not None and root_index != wrapper_index:+ raise NonCanonicalWire+ lists = _element_children(content_root)+ if len(lists) != 1 or local_name(lists[0]) != "ul":+ raise NonCanonicalWire+ return _parse_index_list(lists[0], nested=False, target_ids=target_ids, block_index=root_index)+++def _parse_index_list(+ container: etree._Element,+ *,+ nested: bool,+ target_ids: dict[str, frozenset[str]],+ block_index: int | None = None,+) -> IndexWireSpec:+ """递归解析目录叶子、linked carrier 和嵌套 IndexBlock。"""+ _validate_structural_text(container)+ if nested:+ if (container.get("data-block-type") or "").strip() != BlockType.INDEX:+ raise NonCanonicalWire+ block_index = _non_negative_integer(container, "data-block-index", required=False)+ children: list[IndexLeafWireSpec | IndexWireSpec] = []+ for item in _element_children(container):+ if local_name(item) != "li":+ raise NonCanonicalWire+ item_type_value = (item.get("data-block-type") or "").strip()+ nested_lists = [child for child in _element_children(item) if local_name(child) == "ul"]+ if item_type_value:+ try:+ item_type = BlockType(item_type_value)+ except ValueError as exc:+ raise NonCanonicalWire from exc+ if item_type not in _INDEX_LEAF_TYPES:+ raise NonCanonicalWire+ children.append(_parse_index_leaf(item, item_type, nested_lists, target_ids))+ elif any(child not in nested_lists for child in _element_children(item)) or not nested_lists:+ raise NonCanonicalWire+ children.extend(_parse_index_list(nested_list, nested=True, target_ids=target_ids) for nested_list in nested_lists)+ return IndexWireSpec(container, block_index, tuple(children))+++def _parse_index_leaf(+ item: etree._Element,+ item_type: BlockType,+ nested_lists: list[etree._Element],+ target_ids: dict[str, frozenset[str]],+) -> IndexLeafWireSpec:+ """解析 linked/unlinked 目录叶子并封闭 anchor 外结构。"""+ block_index = _non_negative_integer(item, "data-block-index", required=False)+ anchor = (item.get("data-anchor") or "").strip()+ level = _optional_integer(item, "data-level")+ _validate_index_leaf_metadata(item_type, anchor, level)+ direct_content = [child for child in _element_children(item) if child not in nested_lists]+ linked = [+ child+ for child in direct_content+ if _is_canonical_index_link(child, item_type=item_type, anchor=anchor, target_ids=target_ids)+ ]+ if linked:+ if len(linked) != 1 or len(direct_content) != 1:+ raise NonCanonicalWire+ _validate_structural_text(item)+ content_element = linked[0]+ _validate_inline_region(content_element)+ else:+ content_element = _clone_fragment(item, excluded_children=nested_lists)+ _validate_inline_region(content_element)+ return IndexLeafWireSpec(item_type, block_index, content_element, anchor, level)+++def _collect_title_target_ids(+ wrappers: list[tuple[etree._Element, int | None]],+) -> dict[str, frozenset[str]]:+ """预收集 renderer 标题 id,供目录 linked carrier 做确定性判定。"""+ collected: dict[str, set[str]] = {}+ for wrapper, _ in wrappers:+ block_type = (wrapper.get("data-block-type") or "").strip()+ if block_type not in {BlockType.DOC_TITLE, BlockType.PARAGRAPH_TITLE}:+ continue+ anchor = (wrapper.get("data-anchor") or "").strip()+ children = _element_children(wrapper)+ if not anchor or len(children) != 1:+ continue+ identities = {+ identity+ for element in [children[0], *children[0].iterdescendants()]+ if (identity := (element.get("id") or "").strip())+ }+ if identities:+ collected.setdefault(anchor, set()).update(identities)+ return {anchor: frozenset(identities) for anchor, identities in collected.items()}+++def _is_canonical_index_link(+ element: etree._Element,+ *,+ item_type: BlockType,+ anchor: str,+ target_ids: dict[str, frozenset[str]],+) -> bool:+ """判断直属 anchor 是否为 renderer 生成的目录目标外壳。"""+ if item_type not in {BlockType.DOC_TITLE, BlockType.PARAGRAPH_TITLE} or local_name(element) != "a":+ return False+ href = (element.get("href") or "").strip()+ if not href.startswith("#"):+ return False+ return unquote(href[1:]).strip() in target_ids.get(anchor, frozenset())+++def _validate_index_leaf_metadata(item_type: BlockType, anchor: str, level: int | None) -> None:+ """校验目录标题叶子的 anchor/level 与普通文本互斥。"""+ if item_type == BlockType.TEXT:+ if anchor or level is not None:+ raise NonCanonicalWire+ return+ if not anchor:+ raise NonCanonicalWire+ if item_type == BlockType.DOC_TITLE and level != 1:+ raise NonCanonicalWire+ if item_type == BlockType.PARAGRAPH_TITLE and (level is None or not 2 <= level <= 6):+ raise NonCanonicalWire+++def _validate_inline_region(element: etree._Element) -> None:+ """校验 canonical 行内区域只含行内节点和可信公式 carrier。"""+ for candidate in element.iterdescendants():+ if not isinstance(candidate.tag, str):+ continue+ name = local_name(candidate)+ marker_type = (candidate.get("data-block-type") or "").strip()+ if name == "math" and marker_type == BlockType.EQUATION:+ _validate_formula_carrier(candidate, expected_display="inline")+ continue+ if name in BLOCK_TAGS or name in {"image", "img"}:+ raise NonCanonicalWire+++def _clone_fragment(+ element: etree._Element,+ *,+ after_child: etree._Element | None = None,+ excluded_children: list[etree._Element] | None = None,+) -> etree._Element:+ """复制一个不含 renderer 外壳的富内容片段供 materializer 使用。"""+ fragment = etree.Element("div")+ excluded = excluded_children or []+ children = _element_children(element)+ start = 0+ if after_child is None:+ fragment.text = element.text+ else:+ try:+ start = children.index(after_child) + 1+ except ValueError as exc:+ raise NonCanonicalWire from exc+ fragment.text = after_child.tail+ for child in children[start:]:+ if child in excluded:+ continue+ fragment.append(deepcopy(child))+ return fragment+++def _validate_structural_text(element: etree._Element) -> None:+ """拒绝 renderer 结构容器直属的非空文本和 tail。"""+ if (element.text or "").strip() or any((child.tail or "").strip() for child in element):+ raise NonCanonicalWire+++def _page_block_type(wrapper: etree._Element) -> BlockType:+ """把顶层 data-block-type 转换为公开 PageBlock 类型。"""+ try:+ block_type = BlockType((wrapper.get("data-block-type") or "").strip())+ except ValueError as exc:+ raise NonCanonicalWire from exc+ if block_type not in PAGE_BLOCK_TYPES:+ raise NonCanonicalWire+ return block_type+++def _element_children(element: etree._Element) -> list[etree._Element]:+ """返回元素直属的真实标签子节点。"""+ return [child for child in element if isinstance(child.tag, str)]+++def _class_tokens(element: etree._Element) -> frozenset[str]:+ """按 HTML class 空白边界返回完整小写 token。"""+ return frozenset((element.get("class") or "").casefold().split())+++def _non_negative_integer(element: etree._Element, name: str, *, required: bool) -> int | None:+ """读取 canonical 非负整数 data 属性。"""+ value = element.get(name)+ if value is None:+ if required:+ raise NonCanonicalWire+ return None+ try:+ parsed = int(value)+ except (TypeError, ValueError) as exc:+ raise NonCanonicalWire from exc+ if parsed < 0 or str(parsed) != value.strip():+ raise NonCanonicalWire+ return parsed+++def _optional_integer(element: etree._Element, name: str) -> int | None:+ """读取可选整数属性并拒绝非法文本。"""+ value = element.get(name)+ if value is None:+ return None+ try:+ return int(value)+ except (TypeError, ValueError) as exc:+ raise NonCanonicalWire from exc+++def _canonical_list_start(element: etree._Element) -> int:+ """读取 renderer 生成的合法有序列表起始值。"""+ value = element.get("start")+ if value is None:+ return 1+ try:+ parsed = int(value)+ except ValueError as exc:+ raise NonCanonicalWire from exc+ if parsed < 0 or str(parsed) != value.strip():+ raise NonCanonicalWire+ return parsed+++__all__ = ["NonCanonicalWire", "parse_mineru_html_wire"]diff --git a/mineru/render/_internal/html/renderer.py b/mineru/render/_internal/html/renderer.pyindex faf56f9a..1474d55f 100644--- a/mineru/render/_internal/html/renderer.py+++ b/mineru/render/_internal/html/renderer.py@@ -14,6 +14,17 @@ from loguru import loggerfrom ..common.index import strip_index_page_tailfrom ....backend.postprocess.inline import inline_plain_text, parse_inline_content+from ....model.flash.html.wire import MINERU_HTML_VERSION+from ....model.flash.html.wire.contracts import (+ WIRE_BLOCK_CLASS,+ WIRE_DOCUMENT_CLASS,+ WIRE_INDEX_CLASS,+ WIRE_LIST_CONTENT_CLASS,+ WIRE_LIST_MARKER_CLASS,+ WIRE_PAGE_BREAK_CLASS,+ WIRE_PAGE_CLASS,+ WIRE_VISUAL_BODY_CLASS,+)from ..common.list_items import ListItem, parse_list_item_marker, reference_list_needs_bulletsfrom ..common.planner import PlannedBlock, build_render_planfrom .inline import (@@ -61,7 +72,6 @@ from ....types import ()_STYLE_RESOURCE_NAME = "mineru.min.css"-_MINERU_HTML_VERSION = "1"_MATHJAX_URL = "https://cdn.jsdelivr.net/npm/[email protected]/tex-chtml.js"_MATHJAX_INTEGRITY = "sha384-zAhQQhdaMeHsMProNntGGg6nOUVcfuF9F22C3d1qJ9NZAVzCplXk1X85D2O5iufn"_PRISM_CORE_URL = "https://cdn.jsdelivr.net/npm/[email protected]/components/prism-core.min.js"@@ -127,8 +137,8 @@ class _HtmlRenderer:else:body = self._render_default_pages(planned_pages)article = (- f'<article class="mineru-document mineru-document--{self.mode.value}" '- f'data-mineru-html-version="{_MINERU_HTML_VERSION}" data-render-mode="{self.mode.value}">\n{body}\n</article>'+ f'<article class="{WIRE_DOCUMENT_CLASS} {WIRE_DOCUMENT_CLASS}--{self.mode.value}" '+ f'data-mineru-html-version="{MINERU_HTML_VERSION}" data-render-mode="{self.mode.value}">\n{body}\n</article>')if not self.standalone:return article@@ -163,8 +173,8 @@ class _HtmlRenderer:page_idx = self.middle_json.pages[page_position].page_idxblocks = [rendered for planned in page if (rendered := self._render_planned_block(planned))]rendered_blocks = "\n".join(blocks)- sections.append(f'<section class="mineru-page" data-page-idx="{page_idx}">\n{rendered_blocks}\n</section>')- return '\n<hr class="mineru-page-break" aria-hidden="true">\n'.join(sections)+ sections.append(f'<section class="{WIRE_PAGE_CLASS}" data-page-idx="{page_idx}">\n{rendered_blocks}\n</section>')+ return f'\n<hr class="{WIRE_PAGE_BREAK_CLASS}" aria-hidden="true">\n'.join(sections)def _render_planned_block(self, planned: PlannedBlock) -> str:"""过滤计划块、分派类型 visitor,并添加稳定来源元数据。"""@@ -177,7 +187,7 @@ class _HtmlRenderer:if not content or not content.strip():return ""attrs = [- 'class="mineru-block"',+ f'class="{WIRE_BLOCK_CLASS}"',f'data-page-idx="{planned.page_idx}"',]attrs.extend(_wire_block_attributes(block))@@ -319,15 +329,15 @@ class _HtmlRenderer:attrs.append(f'value="{parsed.value}"')expected_value = parsed.value + 1marker_html = (- f'<span class="mineru-list-marker">{html.escape(_replace_html_controls(marker), quote=False)}</span>'+ f'<span class="{WIRE_LIST_MARKER_CLASS}">{html.escape(_replace_html_controls(marker), quote=False)}</span>'if markerelse "")if class_name == "mineru-list--explicit" and not marker_html:- marker_html = '<span class="mineru-list-marker"></span>'+ marker_html = f'<span class="{WIRE_LIST_MARKER_CLASS}"></span>'items.append({- "content": f'{marker_html}<span class="mineru-list-content">{rendered.html}</span>',+ "content": f'{marker_html}<span class="{WIRE_LIST_CONTENT_CLASS}">{rendered.html}</span>',"attrs": attrs,"nested": [],}@@ -371,7 +381,7 @@ class _HtmlRenderer:rendered, attrs = self._render_index_leaf(child)items.append({"content": rendered, "attrs": attrs, "nested": []})inner = _serialize_index_items(items)- attrs = ['class="mineru-index"', 'aria-label="Table of contents"', *_wire_block_attributes(block)]+ attrs = [f'class="{WIRE_INDEX_CLASS}"', 'aria-label="Table of contents"', *_wire_block_attributes(block)]return f"<nav {' '.join(attrs)}><ul>{inner}</ul></nav>" if inner else ""def _render_index_list(self, block: IndexBlock) -> str:@@ -787,7 +797,7 @@ def _wrap_visual_body(kind: str,) -> str:"""为视觉主体添加不参与 CSS 类型推断的精确机器容器。"""- attrs = [f'class="mineru-visual-body mineru-visual-body--{kind}"', *_wire_block_attributes(block)]+ attrs = [f'class="{WIRE_VISUAL_BODY_CLASS} {WIRE_VISUAL_BODY_CLASS}--{kind}"', *_wire_block_attributes(block)]return f"<div {' '.join(attrs)}>{content}</div>"diff --git a/tests/unittest/test_flash_html.py b/tests/unittest/test_flash_html.pyindex c75036a2..9267a167 100644--- a/tests/unittest/test_flash_html.py+++ b/tests/unittest/test_flash_html.py@@ -27,6 +27,7 @@ from mineru.model.flash.html import document as html_document_modulefrom mineru.model.flash.html import resources as html_resources_modulefrom mineru.model.flash.html import selector as html_selector_modulefrom mineru.model.flash.html.resources import HtmlResourceContext+from mineru.model.flash.html.wire import decode_mineru_html_wirefrom mineru.parser import ParseResult, parse, parse_asyncfrom mineru.parser import api_serverfrom mineru.parser.api_server import CreateJobRequest, FileStore@@ -271,6 +272,23 @@ def test_html_charsetless_utf8_preserves_non_ascii_text() -> None:assert "中文内容 café" in markdown+ "inert_markup",+ [+ '<!-- <meta charset="windows-1252"> -->',+ '<script>const marker = `<meta charset="windows-1252">`;</script>',+ ],+ ids=["comment", "script"],+)+def test_html_charsetless_utf8_ignores_inert_encoding_declarations(inert_markup: str) -> None:+ """验证注释和脚本中的伪编码声明不会绕过无 charset UTF-8 回退。"""+ payload = f"{inert_markup}<html><body><p>中文内容 café</p></body></html>".encode()++ markdown = render_markdown(doc_analyze(payload, file_suffix="html")[0])++ assert "中文内容 café" in markdown++def test_html_declared_legacy_charset_remains_supported() -> None:"""验证显式声明的旧编码仍交由 lxml 按声明解码。"""payload = '<html><head><meta charset="windows-1252"></head><body><p>café</p></body></html>'.encode("windows-1252")@@ -1306,6 +1324,7 @@ def test_html_versioned_wire_roundtrips_all_semantic_types() -> None:source = _wire_contract_middle()default_html = render_html(source, standalone=False)full_html = render_html(source, mode=RenderMode.FULL, standalone=False)+ standalone_html = render_html(source, standalone=True)default_root = BeautifulSoup(default_html, "html.parser").select_one(".mineru-document")full_root = BeautifulSoup(full_html, "html.parser").select_one(".mineru-document")@@ -1319,6 +1338,7 @@ def test_html_versioned_wire_roundtrips_all_semantic_types() -> None:default_middle = doc_analyze(default_html.encode(), file_suffix="html")[0]full_middle = doc_analyze(full_html.encode(), file_suffix="html")[0]+ standalone_middle = doc_analyze(standalone_html.encode(), file_suffix="html")[0]auxiliary_types = {BlockType.HEADER, BlockType.FOOTER, BlockType.PAGE_NUMBER, BlockType.ASIDE_TEXT}expected_default = [_semantic_block_signature(block) for block in source.pages[0].blocks if block.type not in auxiliary_types@@ -1326,6 +1346,7 @@ def test_html_versioned_wire_roundtrips_all_semantic_types() -> None:expected_full = [_semantic_block_signature(block) for block in source.pages[0].blocks]assert [_semantic_block_signature(block) for block in default_middle.pages[0].blocks] == expected_default+ assert [_semantic_block_signature(block) for block in standalone_middle.pages[0].blocks] == expected_defaultassert [_semantic_block_signature(block) for block in full_middle.pages[0].blocks] == expected_fullassert len(full_middle.pages) == 1 and full_middle.pages[0].page_idx == 0assert next(block for block in full_middle.pages[0].blocks if block.type == BlockType.EQUATION).content == "y^2\\tag{1}" # type: ignore[union-attr]@@ -1333,6 +1354,276 @@ def test_html_versioned_wire_roundtrips_all_semantic_types() -> None:assert roundtrip_text == "Text & value < 3 <eq>x+1</eq> <eq>literal</eq>"+def test_html_wire_decode_distinguishes_absent_empty_and_noncanonical() -> None:+ """验证单一 decode 入口区分普通 HTML、合法空 wire 与非 canonical v1。"""+ source = MiddleJson.model_validate(+ {+ "pages": [{"page_idx": 0, "blocks": []}],+ "is_full_document": True,+ "file_suffix": "html",+ "effort": "flash",+ "parse_mode": "txt",+ "mineru_version": "test",+ }+ )+ ordinary = html_document_module.parse_html_document(b"<html><body><p>ordinary</p></body></html>")+ empty = html_document_module.parse_html_document(render_html(source, standalone=False).encode())+ edited_soup = BeautifulSoup(render_html(source, standalone=False), "html.parser")+ edited_soup.select_one(".mineru-document").append("EDITED")+ edited = html_document_module.parse_html_document(str(edited_soup).encode())++ ordinary_result = decode_mineru_html_wire(+ ordinary.body,+ HtmlResourceContext(ordinary.source_context),+ )+ empty_result = decode_mineru_html_wire(empty.body, HtmlResourceContext(empty.source_context))+ edited_result = decode_mineru_html_wire(edited.body, HtmlResourceContext(edited.source_context))++ assert ordinary_result.blocks is None and ordinary_result.fallback_reason is None+ assert empty_result.blocks == [] and empty_result.fallback_reason is None+ assert edited_result.blocks is None and edited_result.fallback_reason == "non_canonical_wire"++[email protected](("parent_type", "body_type"), [("image", "image_body"), ("chart", "chart_body")])[email protected]("with_main_image", [False, True])+def test_html_versioned_wire_preserves_visual_rich_content(+ parent_type: str,+ body_type: str,+ with_main_image: bool,+) -> None:+ """验证 visual 富内容及嵌套图片按语义往返且不升级为主图片载荷。"""+ body: dict[str, object] = {+ "type": body_type,+ "index": 0,+ "content": (+ '<p>Recognized <eq>x+1</eq> <a href="https://example.com/a">link</a></p>'+ '<img src="https://example.com/nested.png" alt="Nested">'+ ),+ }+ if with_main_image:+ body["image_url"] = "https://example.com/main.png"+ source = MiddleJson.model_validate(+ {+ "pages": [+ {+ "page_idx": 0,+ "blocks": [+ {+ "type": parent_type,+ "index": 0,+ "sub_type": "diagram",+ "content": [body],+ }+ ],+ }+ ],+ "is_full_document": True,+ "file_suffix": "html",+ "effort": "flash",+ "parse_mode": "txt",+ "mineru_version": "test",+ }+ )+ rendered = render_html(source, standalone=False)++ middle, model = doc_analyze(rendered.encode(), file_suffix="html")+ raw_body = model.pages[0][0]+ normalized = render_html(middle, standalone=False)+ normalized_body = BeautifulSoup(normalized, "html.parser").select_one(f'[data-block-type="{body_type}"]')+ normalized_middle = doc_analyze(normalized.encode(), file_suffix="html")[0]+ stable_body = BeautifulSoup(render_html(normalized_middle, standalone=False), "html.parser").select_one(+ f'[data-block-type="{body_type}"]'+ )++ assert '<p>Recognized <eq>x+1</eq> <a href="https://example.com/a">link</a></p>' in str(raw_body["content"])+ assert '<img alt="Nested" src="https://example.com/nested.png">' in str(raw_body["content"])+ assert raw_body.get("image_url") == ("https://example.com/main.png" if with_main_image else None)+ assert normalized_body is not None+ nested_images = [image for image in normalized_body.find_all("img") if not image.get("class")]+ assert [image.get("src") for image in nested_images] == ["https://example.com/nested.png"]+ assert str(normalized_body) == str(stable_body)+++def test_html_versioned_wire_roundtrips_canonical_visual_body_variants() -> None:+ """验证 flowchart 与 table 的固定载荷分支都通过 exact typed plan 往返。"""+ source = MiddleJson.model_validate(+ {+ "pages": [+ {+ "page_idx": 0,+ "blocks": [+ {+ "type": "image",+ "index": 0,+ "sub_type": "flowchart",+ "content": [+ {+ "type": "image_body",+ "index": 0,+ "content": "```mermaid\ngraph TD\nA-->B\n```",+ }+ ],+ },+ {+ "type": "image",+ "index": 1,+ "sub_type": "flowchart",+ "content": [+ {+ "type": "image_body",+ "index": 1,+ "content": "Plain non-Mermaid content",+ "image_url": "https://example.com/plain.png",+ }+ ],+ },+ {+ "type": "table",+ "index": 2,+ "content": [{"type": "table_body", "index": 2, "content": "A B\n1 2"}],+ },+ {+ "type": "table",+ "index": 3,+ "content": [+ {+ "type": "table_body",+ "index": 3,+ "content": "",+ "image_url": "https://example.com/table.png",+ }+ ],+ },+ {+ "type": "table",+ "index": 4,+ "content": [{"type": "table_body", "index": 4, "content": ""}],+ },+ ],+ }+ ],+ "is_full_document": True,+ "file_suffix": "html",+ "effort": "flash",+ "parse_mode": "txt",+ "mineru_version": "test",+ }+ )+ rendered = render_html(source, standalone=False)+ document = html_document_module.parse_html_document(rendered.encode())++ decode_result = decode_mineru_html_wire(document.body, HtmlResourceContext(document.source_context))+ middle, _ = doc_analyze(rendered.encode(), file_suffix="html")+ bodies = [block.content[0] for block in middle.pages[0].blocks]++ assert decode_result.blocks is not None and decode_result.fallback_reason is None+ assert bodies[0].content == "```mermaid\ngraph TD\nA-->B\n```"+ assert bodies[1].content == "Plain non-Mermaid content" and bodies[1].image_url == "https://example.com/plain.png"+ assert bodies[2].content == "A B\n1 2"+ assert bodies[3].content == "" and bodies[3].image_url == "https://example.com/table.png"+ assert bodies[4].content == "" and bodies[4].image_url is None+++def test_html_versioned_wire_distinguishes_index_carrier_from_inline_link() -> None:+ """验证未链接目录项中的普通 anchor 不会被误认为 renderer 目录外壳。"""+ source = MiddleJson.model_validate(+ {+ "pages": [+ {+ "page_idx": 0,+ "blocks": [+ {+ "type": "index",+ "index": 0,+ "content": [+ {+ "type": "text",+ "content": ("<hyperlink>External<url>https://example.com/docs</url></hyperlink>"),+ }+ ],+ }+ ],+ }+ ],+ "is_full_document": True,+ "file_suffix": "html",+ "effort": "flash",+ "parse_mode": "txt",+ "mineru_version": "test",+ }+ )+ rendered = render_html(source, standalone=False)+ document = html_document_module.parse_html_document(rendered.encode())++ decode_result = decode_mineru_html_wire(document.body, HtmlResourceContext(document.source_context))+ middle = doc_analyze(rendered.encode(), file_suffix="html")[0]++ assert decode_result.blocks is not None and decode_result.fallback_reason is None+ assert "[External](https://example.com/docs)" in render_markdown(middle)++[email protected]("edit_kind", ["index_sibling", "visual_sibling"])+def test_html_noncanonical_wire_structural_edits_use_generic_fallback(edit_kind: str) -> None:+ """验证 carrier 外结构统一触发 generic fallback,而不是增加逐 case 物化兼容。"""+ if edit_kind == "index_sibling":+ source = MiddleJson.model_validate(+ {+ "pages": [+ {+ "page_idx": 0,+ "blocks": [+ {+ "type": "paragraph_title",+ "index": 0,+ "anchor": "target",+ "level": 2,+ "content": "Target",+ },+ {+ "type": "index",+ "index": 1,+ "content": [+ {+ "type": "paragraph_title",+ "index": 2,+ "anchor": "target",+ "level": 2,+ "content": "Title",+ }+ ],+ },+ ],+ }+ ],+ "is_full_document": True,+ "file_suffix": "html",+ "effort": "flash",+ "parse_mode": "txt",+ "mineru_version": "test",+ }+ )+ soup = BeautifulSoup(render_html(source, standalone=False), "html.parser")+ target = soup.select_one('.mineru-index li[data-block-type="paragraph_title"]')+ assert target is not None+ target.append(" ADDED")+ else:+ soup = BeautifulSoup(render_html(_wire_contract_middle(), standalone=False), "html.parser")+ target = soup.select_one('[data-block-type="image_body"]')+ assert target is not None+ target.append(soup.new_tag("img", src="https://example.com/added.png", alt="Added"))+ document = html_document_module.parse_html_document(str(soup).encode())++ decode_result = decode_mineru_html_wire(document.body, HtmlResourceContext(document.source_context))+ middle, model = doc_analyze(str(soup).encode(), file_suffix="html")++ assert decode_result.blocks is None and decode_result.fallback_reason == "non_canonical_wire"+ if edit_kind == "index_sibling":+ assert "ADDED" in render_markdown(middle)+ else:+ image_urls = [str(block["image_url"]) for block in model.pages[0] if block.get("image_url")]+ assert "https://example.com/added.png" in image_urls++@pytest.mark.parametrize("outside_kind", ["text", "inline"])def test_html_versioned_list_content_outside_carrier_falls_back_without_loss(outside_kind: str) -> None:"""验证列表 carrier 外的编辑内容触发通用投影并完整保留。"""