Skip to content

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

harden html decoding and flowchart wires

myhloli703ab7b22102
diff --git a/mineru/model/flash/html/document.py b/mineru/model/flash/html/document.py
index 275f8bc9..32fe44df 100644
--- a/mineru/model/flash/html/document.py
+++ b/mineru/model/flash/html/document.py
@@ -42,6 +42,8 @@ _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*=)")
+_UNICODE_BOMS = (b"\x00\x00\xfe\xff", b"\xff\xfe\x00\x00", b"\xef\xbb\xbf", b"\xfe\xff", b"\xff\xfe")
@dataclass(frozen=True, slots=True)
@@ -83,7 +85,7 @@ def parse_html_document(file_bytes: bytes, source_context: HtmlSourceContext | N
huge_tree=False,
)
try:
- root = lxml_html.document_fromstring(file_bytes, parser=parser)
+ root = lxml_html.document_fromstring(_html_parser_input(file_bytes), parser=parser)
except (etree.ParserError, etree.XMLSyntaxError, UnicodeError, ValueError) as exc:
raise HtmlParseError(f"Malformed HTML document: {exc}") from exc
_validate_dom_shape(root)
@@ -140,6 +142,16 @@ def parse_html_document(file_bytes: bytes, source_context: HtmlSourceContext | N
)
+def _html_parser_input(file_bytes: bytes) -> bytes | str:
+ """无显式编码且符合 UTF-8 时先解码,避免 lxml 按单字节旧编码解释正文。"""
+ if file_bytes.startswith(_UNICODE_BOMS) or _HTML_ENCODING_DECLARATION_RE.search(file_bytes[:4096]):
+ return file_bytes
+ try:
+ return file_bytes.decode("utf-8")
+ except UnicodeDecodeError:
+ return file_bytes
+
+
def _validate_dom_shape(root: etree._Element) -> None:
"""迭代校验 DOM 节点数和最大深度,避免深层递归继续传播。"""
node_count = 0
diff --git a/mineru/model/flash/html/wire.py b/mineru/model/flash/html/wire.py
index 760ce992..8de0b68c 100644
--- a/mineru/model/flash/html/wire.py
+++ b/mineru/model/flash/html/wire.py
@@ -349,6 +349,8 @@ def _validate_visual_content(content_root: etree._Element, wrapper: etree._Eleme
_validate_code_body_shape(child)
elif parent_type == BlockType.TABLE:
_validate_table_body_shape(child)
+ elif parent_type == BlockType.IMAGE and (wrapper.get("data-block-sub-type") or "").strip() == "flowchart":
+ _validate_flowchart_body_shape(child)
for marker in _descendant_markers(child):
if marker is child:
continue
@@ -403,6 +405,48 @@ def _validate_table_body_shape(body: etree._Element) -> None:
raise _WireValidationError("invalid_table_body_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:
diff --git a/tests/unittest/test_flash_html.py b/tests/unittest/test_flash_html.py
index 3d73fa3e..09fd76ee 100644
--- a/tests/unittest/test_flash_html.py
+++ b/tests/unittest/test_flash_html.py
@@ -256,6 +256,24 @@ def test_html_doc_analyze_projects_static_semantics_and_renderers() -> None:
assert "https://cdn.example.com/a.png" in relationships
+def test_html_charsetless_utf8_preserves_non_ascii_text() -> None:
+ """验证无 charset 的 UTF-8 字节不会被 lxml 按单字节旧编码解释。"""
+ payload = "<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")
+
+ markdown = render_markdown(doc_analyze(payload, file_suffix="html")[0])
+
+ assert "café" in markdown
+
+
def test_html_auto_selection_preserves_all_repeated_forum_posts() -> None:
"""验证重复 article 场景不会只保留论坛中的首个帖子。"""
payload = b"""<html><body><header>Forum</header><main>
@@ -1386,6 +1404,47 @@ def test_html_versioned_wire_edited_table_body_falls_back_without_loss() -> None
assert "NEW NOTE" in markdown
+def test_html_versioned_wire_edited_flowchart_body_falls_back_without_loss() -> None:
+ """验证流程图 body 中新增可见节点会整体回退并保留源码与编辑内容。"""
+ 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```",
+ }
+ ],
+ }
+ ],
+ }
+ ],
+ "is_full_document": True,
+ "file_suffix": "html",
+ "effort": "flash",
+ "parse_mode": "txt",
+ "mineru_version": "test",
+ }
+ )
+ soup = BeautifulSoup(render_html(source, standalone=False), "html.parser")
+ paragraph = soup.new_tag("p")
+ paragraph.string = "NEW NOTE"
+ soup.select_one('[data-block-type="image_body"]').append(paragraph)
+
+ markdown = render_markdown(doc_analyze(str(soup).encode(), file_suffix="html")[0])
+
+ assert "graph TD" in markdown
+ assert "NEW NOTE" in markdown
+
+
def test_html_marker_fallback_does_not_double_resolve_images(monkeypatch: pytest.MonkeyPatch) -> None:
"""验证结构校验先于资源物化,非法 marker 回退只解析一次图片。"""
source = MiddleJson.model_validate(