Skip to content

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

fix: keep document note and anchor targets valid

myhloli5a66b85f8728
diff --git a/mineru/model/flash/epub/xhtml.py b/mineru/model/flash/epub/xhtml.py
index 1f40c79a..636d03ab 100644
--- a/mineru/model/flash/epub/xhtml.py
+++ b/mineru/model/flash/epub/xhtml.py
@@ -267,7 +267,10 @@ class EpubAnchorRegistry:
notes = [
element
for element in chapter.root.iter()
- if isinstance(element.tag, str) and _is_individual_note(element) and _note_has_text_block(element)
+ if isinstance(element.tag, str)
+ and _is_individual_note(element)
+ and _note_has_text_block(element)
+ and not _element_is_hidden(element, stylesheet)
]
for ordinal, note in enumerate(notes):
source_id = _element_id(note)
diff --git a/mineru/model/flash/office/odf/converters.py b/mineru/model/flash/office/odf/converters.py
index 13513679..a9bdb81c 100644
--- a/mineru/model/flash/office/odf/converters.py
+++ b/mineru/model/flash/office/odf/converters.py
@@ -15,7 +15,7 @@ from .models import InlineNote
from .package import OdfPackage
from .styles import OdfStyles
from .table import parse_table_grid, split_table_regions, table_grid_to_html
-from .text import OdfBlockParser, PageBreakMarker, flatten_block_text
+from .text import OdfBlockParser, PageBreakMarker, collect_emittable_anchor_targets, flatten_block_text
_LENGTH_RE = re.compile(r"^\s*(?P<value>[+-]?(?:\d+(?:\.\d*)?|\.\d+))(?P<unit>cm|mm|in|pt|pc|px)?\s*$")
@@ -101,11 +101,12 @@ def _master_auxiliary_blocks(
*,
package: OdfPackage,
styles: OdfStyles,
+ anchor_targets: frozenset[str],
) -> list[dict[str, Any]]:
"""从 master-page 的 header/footer 中提取页面辅助文本。"""
if master_page is None:
return []
- parser = OdfBlockParser(package, styles)
+ parser = OdfBlockParser(package, styles, anchor_targets=anchor_targets)
result: list[dict[str, Any]] = []
for tag_name, block_type in (("header", BlockType.HEADER), ("footer", BlockType.FOOTER)):
element = master_page.find(qname("style", tag_name))
@@ -122,7 +123,8 @@ def _master_auxiliary_blocks(
def _parse_odt_pages(context: _OdfContext) -> list[list[dict[str, Any]]]:
"""按显式 ODF 分页样式递归构造 ODT 逻辑页。"""
- parser = OdfBlockParser(context.package, context.styles)
+ anchor_targets = collect_emittable_anchor_targets(context.content_root, context.styles)
+ parser = OdfBlockParser(context.package, context.styles, anchor_targets=anchor_targets)
pages: list[list[dict[str, Any]]] = [[]]
page_masters: list[str | None] = [None]
current_master: str | None = None
@@ -177,6 +179,7 @@ def _parse_odt_pages(context: _OdfContext) -> list[list[dict[str, Any]]]:
context.styles.master_page(master_name),
package=context.package,
styles=context.styles,
+ anchor_targets=anchor_targets,
)
)
return pages or [[]]
@@ -285,7 +288,9 @@ def _parse_odp_pages(context: _OdfContext) -> list[list[dict[str, Any]]]:
)
for entry in body_entries:
output.extend(entry.blocks)
+ _flush_notes(parser, output)
output.extend(_notes_blocks(page, parser))
+ _flush_notes(parser, output)
pages.append(output)
return pages or [[]]
diff --git a/mineru/model/flash/office/odf/text.py b/mineru/model/flash/office/odf/text.py
index 54aab858..f4ee63fd 100644
--- a/mineru/model/flash/office/odf/text.py
+++ b/mineru/model/flash/office/odf/text.py
@@ -90,6 +90,29 @@ def _safe_hyperlink(value: str | None) -> str | None:
return normalized
+def _paragraph_anchor(paragraph: etree._Element) -> str | None:
+ """返回段落最终能够挂载到输出 block 的首个 bookmark 名称。"""
+ for tag in (qname("text", "bookmark"), qname("text", "bookmark-start")):
+ bookmark = next(paragraph.iter(tag), None)
+ if bookmark is not None and (name := bookmark.get(qname("text", "name"))):
+ return name
+ return None
+
+
+def collect_emittable_anchor_targets(root: etree._Element, styles: OdfStyles) -> frozenset[str]:
+ """收集 ODT 标题类 block 实际能够公开的 bookmark target。"""
+ targets: set[str] = set()
+ for paragraph in root.iter():
+ if paragraph.tag not in {qname("text", "p"), qname("text", "h")}:
+ continue
+ style_name = paragraph.get(qname("text", "style-name"))
+ if paragraph.tag != qname("text", "h") and not styles.is_document_title(style_name):
+ continue
+ if anchor := _paragraph_anchor(paragraph):
+ targets.add(anchor)
+ return frozenset(targets)
+
+
def _style_html(text: str, style: TextStyle) -> str:
"""按稳定顺序把已转义文本包裹为 HTML 行内样式。"""
rendered = text
@@ -205,6 +228,7 @@ class OdfBlockParser:
list_ids: dict[str, int] | None = None,
collect_cell_visuals: bool = False,
shared_cell_visuals: list[dict[str, Any]] | None = None,
+ anchor_targets: frozenset[str] | None = None,
) -> None:
"""绑定单次解析包、样式、子文档路径及可跨 parser 共享的状态。"""
self.package = package
@@ -215,6 +239,7 @@ class OdfBlockParser:
self._list_ids = list_ids if list_ids is not None else {}
self._collect_cell_visuals = collect_cell_visuals
self._cell_visuals = shared_cell_visuals if shared_cell_visuals is not None else []
+ self._anchor_targets = anchor_targets or frozenset()
def _append_text_atom(
self,
@@ -262,11 +287,13 @@ class OdfBlockParser:
atoms=atoms,
)
elif child.tag == qname("text", "a"):
- target = _safe_hyperlink(child.get(qname("xlink", "href"))) or hyperlink
+ target = _safe_hyperlink(child.get(qname("xlink", "href")))
+ if target is not None and target.startswith("#") and target[1:] not in self._anchor_targets:
+ target = None
self._walk_inlines(
child,
style=style,
- hyperlink=target,
+ hyperlink=target or hyperlink,
atoms=atoms,
)
elif child.tag == qname("text", "s"):
@@ -348,15 +375,6 @@ class OdfBlockParser:
)
return atoms
- @staticmethod
- def _paragraph_anchor(paragraph: etree._Element) -> str | None:
- """返回段落内首个 bookmark 名称。"""
- for tag in (qname("text", "bookmark"), qname("text", "bookmark-start")):
- bookmark = next(paragraph.iter(tag), None)
- if bookmark is not None and (name := bookmark.get(qname("text", "name"))):
- return name
- return None
-
def parse_paragraph(self, paragraph: etree._Element, *, allow_page_breaks: bool = False) -> list[RawFlowItem]:
"""把 text:p/text:h 转为标题、正文、公式及显式分页项。"""
atoms = self.parse_inline_atoms(paragraph)
@@ -378,7 +396,7 @@ class OdfBlockParser:
results.append({"type": BlockType.EQUATION, "content": math_atoms[0].latex})
elif self.styles.is_document_title(style_name):
block: dict[str, Any] = {"type": BlockType.DOC_TITLE, "level": 1, "content": content}
- if anchor := self._paragraph_anchor(paragraph):
+ if anchor := _paragraph_anchor(paragraph):
block["anchor"] = anchor
results.append(block)
elif is_heading:
@@ -392,7 +410,7 @@ class OdfBlockParser:
"is_numbered_style": False,
"content": content,
}
- if anchor := self._paragraph_anchor(paragraph):
+ if anchor := _paragraph_anchor(paragraph):
block["anchor"] = anchor
results.append(block)
else:
@@ -697,6 +715,7 @@ class OdfBlockParser:
list_ids=self._list_ids,
collect_cell_visuals=self._collect_cell_visuals,
shared_cell_visuals=self._cell_visuals,
+ anchor_targets=self._anchor_targets,
)
chart = parse_chart_block(
object_root,
diff --git a/tests/unittest/test_flash_epub.py b/tests/unittest/test_flash_epub.py
index 2dcc18b5..086ef7f2 100644
--- a/tests/unittest/test_flash_epub.py
+++ b/tests/unittest/test_flash_epub.py
@@ -210,6 +210,53 @@ def test_epub_anchor_registry_excludes_hidden_headings(attribute: str, value: st
package.close()
+ ("attribute", "value"),
+ [
+ ("hidden", "hidden"),
+ ("aria-hidden", "true"),
+ ("style", "display: none"),
+ ("class", "hidden"),
+ ],
+)
+def test_epub_anchor_registry_excludes_hidden_notes(attribute: str, value: str) -> None:
+ """验证隐藏 note 不生成 converter 无法兑现的 fragment target。"""
+ package = EpubPackage(build_epub_notes_fixture())
+ try:
+ chapters: list[tuple[str, etree._Element]] = []
+ note_path = ""
+ hidden_note: etree._Element | None = None
+ for item in package.spine:
+ if not item.path or not item.media_type or "xhtml" not in item.media_type:
+ continue
+ root = package.xml_part(item.path, allow_external_doctype=True)
+ chapters.append((item.path, root))
+ for element in root.iter():
+ if element.get("id") == "fn-one":
+ hidden_note = element
+ note_path = item.path
+ assert hidden_note is not None
+ hidden_note.set(attribute, value)
+ if attribute == "class":
+ namespace = etree.QName(hidden_note.getroottree().getroot()).namespace
+ style = etree.SubElement(hidden_note.getroottree().getroot(), f"{{{namespace}}}style")
+ style.text = ".hidden { display: none; }"
+
+ anchors = build_anchor_registry(chapters, package)
+ blocks = [
+ block
+ for chapter_path, root in chapters
+ for block in EpubChapterConverter(package, chapter_path, root, anchors).convert()
+ ]
+
+ assert anchors.resolve_link("#fn-one", base_part=note_path) is None
+ assert "First footnote paragraph" not in str(blocks)
+ assert "Same-page [1]" in str(blocks)
+ assert "<hyperlink>[1]" not in str(blocks)
+ finally:
+ package.close()
+
+
def test_epub_table_contents_resolve_title_marker_and_expand_only_exact_single_target_rows() -> None:
"""验证标题内部 marker 可跳转,且目录表格只扩展严格匹配的单目标行。"""
middle, model = doc_analyze(build_epub_table_toc_fixture(), file_suffix="epub")
diff --git a/tests/unittest/test_flash_odf.py b/tests/unittest/test_flash_odf.py
index cbf1d5b8..5e0180af 100644
--- a/tests/unittest/test_flash_odf.py
+++ b/tests/unittest/test_flash_odf.py
@@ -296,6 +296,28 @@ def test_ods_cell_note_emits_page_footnote() -> None:
assert pages[0][1]["content"] == "[1] Cell note"
+def test_odp_slide_inline_note_emits_page_footnote() -> None:
+ """验证 ODP slide 正文中的 note body 不会被 presentation notes 路径遗漏。"""
+ content = """<office:document-content
+ xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"
+ xmlns:presentation="urn:oasis:names:tc:opendocument:xmlns:presentation:1.0"
+ xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0"
+ xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0">
+ <office:body><office:presentation><draw:page draw:name="Slide1"><draw:frame><draw:text-box><text:p>Slide
+ <text:note><text:note-citation>1</text:note-citation><text:note-body><text:p>Inline note</text:p></text:note-body></text:note>
+ </text:p></draw:text-box></draw:frame></draw:page></office:presentation></office:body>
+</office:document-content>"""
+
+ pages = OdpModel().predict(BytesIO(build_odf_package("odp", content)))
+
+ assert pages == [
+ [
+ {"type": BlockType.TEXT, "content": "Slide [1]"},
+ {"type": BlockType.PAGE_FOOTNOTE, "content": "[1] Inline note"},
+ ]
+ ]
+
+
def test_odp_preserves_empty_slide_chart_preview_and_notes() -> None:
"""验证 ODP 空 slide 不丢失,图表同时保留数据和预览,备注归属原页。"""
middle, model = doc_analyze(build_odp_fixture(), file_suffix="odp")
@@ -469,7 +491,6 @@ def test_odf_rejects_unsafe_hyperlinks_before_shared_renderers(target: str) -> N
"https://example.com/path",
"tel:+123456",
- "#section-one",
"chapter.odt#section-one",
],
)
@@ -493,6 +514,27 @@ def test_odf_preserves_allowed_external_and_relative_hyperlinks(target: str) ->
]
+def test_odf_preserves_title_fragment_and_drops_unemittable_text_fragment() -> None:
+ """验证本地 fragment 仅链接到标题类 block 实际公开的 bookmark。"""
+ content = """<office:document-content
+ xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"
+ xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"
+ xmlns:xlink="http://www.w3.org/1999/xlink">
+ <office:body><office:text>
+ <text:p><text:a xlink:href="#title-target">Title jump</text:a> / <text:a xlink:href="#text-target">Text jump</text:a></text:p>
+ <text:h text:outline-level="1"><text:bookmark-start text:name="title-target"/>Heading</text:h>
+ <text:p><text:bookmark text:name="text-target"/>Ordinary target</text:p>
+ </office:text></office:body>
+</office:document-content>"""
+
+ pages = OdtModel().predict(BytesIO(build_odf_package("odt", content)))
+
+ assert pages[0][0]["content"] == ("<hyperlink><text>Title jump</text><url>#title-target</url></hyperlink> / Text jump")
+ assert pages[0][1]["type"] == BlockType.PARAGRAPH_TITLE
+ assert pages[0][1]["anchor"] == "title-target"
+ assert pages[0][2] == {"type": BlockType.TEXT, "content": "Ordinary target"}
+
+
def test_odf_corrupt_optional_styles_and_external_image_degrade_locally() -> None:
"""验证可选样式损坏和外部图片不会阻断正文或触发网络读取。"""
content = """<office:document-content