Skip to content

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

fix html review edge cases

myhlolif620c2811031
diff --git a/mineru/model/flash/html/anchors.py b/mineru/model/flash/html/anchors.py
index 807aec29..09863e22 100644
--- a/mineru/model/flash/html/anchors.py
+++ b/mineru/model/flash/html/anchors.py
@@ -83,23 +83,50 @@ def _copy_note_with_source_visibility(
note: etree._Element,
stylesheet: MarkupStylesheet,
) -> etree._Element | None:
- """按原始祖先链复制 note;整树隐藏时丢弃,继承 visibility 隐藏时保留状态。"""
+ """按原始祖先链复制 note;整树隐藏时丢弃,并保留继承文字样式与 visibility。"""
inherited = TextStyle()
visibility_hidden = False
chain = [ancestor for ancestor in reversed(list(note.iterancestors())) if isinstance(ancestor.tag, str)]
- chain.append(note)
for current in chain:
resolved = stylesheet.resolve(current, inherited, visibility_hidden)
if resolved.subtree_hidden:
return None
inherited = resolved.text
visibility_hidden = resolved.visibility_hidden
+ if stylesheet.resolve(note, inherited, visibility_hidden).subtree_hidden:
+ return None
copied = deepcopy(note)
+ declarations: list[str] = []
+ if inherited.bold:
+ declarations.append("font-weight:bold")
+ if inherited.italic:
+ declarations.append("font-style:italic")
+ decorations = [
+ decoration
+ for enabled, decoration in (
+ (inherited.underline, "underline"),
+ (inherited.strikethrough, "line-through"),
+ )
+ if enabled
+ ]
+ if decorations:
+ declarations.append(f"text-decoration:{' '.join(decorations)}")
+ if inherited.superscript:
+ declarations.append("vertical-align:super")
+ elif inherited.subscript:
+ declarations.append("vertical-align:sub")
if visibility_hidden:
- style = (copied.get("style") or "").strip()
- separator = "" if not style or style.endswith(";") else ";"
- copied.set("style", f"{style}{separator}visibility:hidden")
- return copied
+ declarations.append("visibility:hidden")
+ if not declarations:
+ return copied
+ wrapper = etree.Element("div")
+ wrapper.set("style", ";".join(declarations))
+ if inherited.superscript and inherited.subscript:
+ subscript_wrapper = etree.SubElement(wrapper, "sub")
+ subscript_wrapper.append(copied)
+ else:
+ wrapper.append(copied)
+ return wrapper
class HtmlAnchorRegistry:
diff --git a/mineru/model/flash/html/selector.py b/mineru/model/flash/html/selector.py
index af7d40de..d06b504b 100644
--- a/mineru/model/flash/html/selector.py
+++ b/mineru/model/flash/html/selector.py
@@ -144,9 +144,7 @@ def _copy_candidate_with_ancestors(candidate: etree._Element, body: etree._Eleme
for ancestor in candidate.iterancestors():
if not isinstance(ancestor.tag, str):
continue
- wrapper = etree.Element(ancestor.tag, nsmap=ancestor.nsmap)
- for name, value in ancestor.attrib.items():
- wrapper.set(name, value)
+ wrapper = _empty_ancestor_wrapper(ancestor)
wrapper.append(root)
root = wrapper
if ancestor is body:
@@ -154,6 +152,20 @@ def _copy_candidate_with_ancestors(candidate: etree._Element, body: etree._Eleme
return root
+def _empty_ancestor_wrapper(ancestor: etree._Element) -> etree._Element:
+ """复制祖先标签和属性;非法 HTML QName 使用安全 div,避免复制整棵兄弟子树。"""
+ try:
+ wrapper = etree.Element(ancestor.tag, nsmap=ancestor.nsmap)
+ except ValueError:
+ wrapper = etree.Element("div", nsmap=ancestor.nsmap)
+ for name, value in ancestor.attrib.items():
+ try:
+ wrapper.set(name, value)
+ except ValueError:
+ continue
+ return wrapper
+
+
def _collect_metrics(
element: etree._Element,
stylesheet: MarkupStylesheet,
diff --git a/mineru/model/flash/html/wire.py b/mineru/model/flash/html/wire.py
index e57d11f5..2ef2b3d8 100644
--- a/mineru/model/flash/html/wire.py
+++ b/mineru/model/flash/html/wire.py
@@ -345,6 +345,8 @@ def _validate_visual_content(content_root: etree._Element, wrapper: etree._Eleme
raise _WireValidationError("invalid_visual_body_shape")
if parent_index is not None and child_index != parent_index:
raise _WireValidationError("visual_body_index_mismatch")
+ if parent_type == BlockType.CODE and (wrapper.get("data-block-sub-type") or "").strip() == BlockType.CODE:
+ _validate_code_body_shape(child)
for marker in _descendant_markers(child):
if marker is child:
continue
@@ -363,6 +365,21 @@ def _validate_visual_content(content_root: etree._Element, wrapper: etree._Eleme
_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_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 f8349298..20928286 100644
--- a/tests/unittest/test_flash_html.py
+++ b/tests/unittest/test_flash_html.py
@@ -283,6 +283,17 @@ def test_html_auto_selection_preserves_ancestor_text_styles() -> None:
]
+def test_html_auto_selection_handles_colonized_candidate_ancestor() -> None:
+ """验证正文候选位于 Office 冒号标签下时可复制祖先链且不会抛出非法标签异常。"""
+ detail = "Colonized ancestor content " * 20
+ payload = f"""<html><body><o:smarttag style="font-style:italic">
+ <main><p>{detail}</p></main></o:smarttag></body></html>""".encode()
+
+ _, model = doc_analyze(payload, file_suffix="html")
+
+ assert model.pages[0] == [{"type": BlockType.TEXT, "content": f'<text style="italic">{detail}</text>'}]
+
+
def test_html_auto_selection_rejects_single_section_from_document_index() -> None:
"""验证多个同级 section 构成的文档索引会保留全部章节而非选择最长一节。"""
detail = b" useful explanatory content with enough words to qualify as an independent scored candidate" * 4
@@ -357,6 +368,19 @@ def test_html_referenced_external_footnote_preserves_inherited_visibility() -> N
assert f"](#{footnote.anchor})" in markdown # type: ignore[union-attr]
+def test_html_referenced_external_footnote_preserves_inherited_text_styles() -> None:
+ """验证正文外引用脚注复制后仍携带祖先提供的受支持文字样式。"""
+ detail = "Useful main article text " * 20
+ payload = f"""<html><body><main><p>{detail}<a href="#fn1">[1]</a></p></main>
+ <aside style="font-weight:bold;font-style:italic;text-decoration:underline line-through">
+ <div id="fn1" role="doc-footnote">Styled note</div></aside></body></html>""".encode()
+
+ _, model = doc_analyze(payload, file_suffix="html")
+ footnote = next(block for block in model.pages[0] if block["type"] == BlockType.PAGE_FOOTNOTE)
+
+ assert footnote["content"] == '<text style="bold,italic,underline,strikethrough">Styled note</text>'
+
+
@pytest.mark.parametrize(
"href",
[
@@ -1226,6 +1250,42 @@ def test_html_versioned_wire_markerless_block_child_falls_back_without_crash() -
assert "EXTRA NOTE" in markdown
+def test_html_versioned_wire_edited_code_body_falls_back_without_loss() -> None:
+ """验证普通代码 body 中新增可见节点会整体回退并保留代码与编辑内容。"""
+ source = MiddleJson.model_validate(
+ {
+ "pages": [
+ {
+ "page_idx": 0,
+ "blocks": [
+ {
+ "type": "code",
+ "index": 0,
+ "sub_type": "code",
+ "guess_lang": "python",
+ "content": [{"type": "code_body", "index": 0, "content": "print(1)"}],
+ }
+ ],
+ }
+ ],
+ "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="code_body"]').append(paragraph)
+
+ markdown = render_markdown(doc_analyze(str(soup).encode(), file_suffix="html")[0])
+
+ assert "print(1)" 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(