Skip to content

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

fix: preserve ODF grids and EPUB anchor targets

myhloli9f134a2c614a
diff --git a/mineru/model/flash/epub/xhtml.py b/mineru/model/flash/epub/xhtml.py
index 5c012d56..1f40c79a 100644
--- a/mineru/model/flash/epub/xhtml.py
+++ b/mineru/model/flash/epub/xhtml.py
@@ -203,6 +203,41 @@ class _ChapterTree:
root: etree._Element
+def _load_chapter_stylesheet(package: EpubPackage, chapter_path: str, root: etree._Element) -> EpubStylesheet:
+ """按章节 head 顺序加载包内 CSS 与内联 style。"""
+ stylesheet = EpubStylesheet()
+ for element in root.iter():
+ if not isinstance(element.tag, str):
+ continue
+ name = _local_name(element)
+ if name == "link" and "stylesheet" in (element.get("rel") or "").casefold().split():
+ target = package.resolve_reference(element.get("href") or "", base_part=chapter_path)
+ if target is None:
+ continue
+ data = package.read_part(target.path)
+ if data is not None:
+ stylesheet.add(data.decode("utf-8-sig", errors="replace"))
+ elif name == "style":
+ stylesheet.add("".join(element.itertext()))
+ return stylesheet
+
+
+def _element_is_hidden(element: etree._Element, stylesheet: EpubStylesheet) -> bool:
+ """按 converter 的祖先到自身样式解析顺序判断元素是否不会输出。"""
+ inherited = TextStyle()
+ chain = [ancestor for ancestor in reversed(list(element.iterancestors())) if isinstance(ancestor.tag, str)]
+ body_index = next((index for index, ancestor in enumerate(chain) if _local_name(ancestor) == "body"), None)
+ if body_index is not None:
+ chain = chain[body_index:]
+ chain.append(element)
+ for current in chain:
+ resolved = stylesheet.resolve(current, inherited)
+ if resolved.hidden:
+ return True
+ inherited = resolved.text
+ return False
+
+
class EpubAnchorRegistry:
"""建立章节路径、标题与 note fragment 到实际 canonical anchor 的别名表。"""
@@ -214,12 +249,14 @@ class EpubAnchorRegistry:
self._targets: dict[tuple[str, str | None], str] = {}
self._heading_labels: dict[str, str] = {}
for chapter in chapters:
+ stylesheet = _load_chapter_stylesheet(package, chapter.path, chapter.root)
headings = [
element
for element in chapter.root.iter()
if isinstance(element.tag, str)
and _local_name(element) in {"h1", "h2", "h3", "h4", "h5", "h6"}
and _visible_text(element)
+ and not _element_is_hidden(element, stylesheet)
]
for ordinal, heading in enumerate(headings):
source_id = _element_id(heading)
@@ -342,21 +379,7 @@ class EpubChapterConverter:
def _load_stylesheet(self) -> EpubStylesheet:
"""按 head 文档顺序加载包内 CSS 和内联 style 元素。"""
- stylesheet = EpubStylesheet()
- for element in self.root.iter():
- if not isinstance(element.tag, str):
- continue
- name = _local_name(element)
- if name == "link" and "stylesheet" in (element.get("rel") or "").casefold().split():
- target = self.package.resolve_reference(element.get("href") or "", base_part=self.chapter_path)
- if target is None:
- continue
- data = self.package.read_part(target.path)
- if data is not None:
- stylesheet.add(data.decode("utf-8-sig", errors="replace"))
- elif name == "style":
- stylesheet.add("".join(element.itertext()))
- return stylesheet
+ return _load_chapter_stylesheet(self.package, self.chapter_path, self.root)
def convert(self) -> list[dict[str, object]]:
"""解析 XHTML body 并返回按 DOM 顺序排列的 raw blocks。"""
diff --git a/mineru/model/flash/office/odf/table.py b/mineru/model/flash/office/odf/table.py
index c3c8e20f..ceef5de9 100644
--- a/mineru/model/flash/office/odf/table.py
+++ b/mineru/model/flash/office/odf/table.py
@@ -175,12 +175,13 @@ def parse_table_grid(table: etree._Element, render_cell: CellRenderer) -> TableG
col_index += pending_empty_columns
_ensure_row(grid, row_index, col_index)
pending_empty_columns = 0
- _validate_grid_extent(row_index + 1, max(grid.width, col_index + repeat))
+ if not is_covered:
+ _validate_grid_extent(row_index + 1, max(grid.width, col_index + repeat))
for _ in range(repeat):
if is_covered:
- _ensure_row(grid, row_index, col_index + 1)
- grid.covered.add((row_index, col_index))
- col_index += 1
+ if (row_index, col_index) in grid.covered:
+ _ensure_row(grid, row_index, col_index + 1)
+ col_index += 1
continue
while (row_index, col_index) in grid.covered:
col_index += 1
diff --git a/tests/unittest/test_flash_epub.py b/tests/unittest/test_flash_epub.py
index 46c75014..2dcc18b5 100644
--- a/tests/unittest/test_flash_epub.py
+++ b/tests/unittest/test_flash_epub.py
@@ -9,6 +9,7 @@ from pathlib import Path
import pytest
from bs4 import BeautifulSoup
+from lxml import etree
import mineru.model.flash.epub.package as epub_package_module
from mineru.backend.analyze import aio_doc_analyze, doc_analyze
@@ -19,6 +20,7 @@ from mineru.doclib.services.parse_svc import ParseService
from mineru.errors import InvalidRequestError
from mineru.model.flash import EpubModel
from mineru.model.flash.epub import EpubEncryptedError, EpubPackage, EpubParseError, EpubResourceLimitError, detect_epub
+from mineru.model.flash.epub.xhtml import EpubChapterConverter, build_anchor_registry
from mineru.parser import MinerUParser, parse, parse_async
from mineru.parser import api_server
from mineru.parser.api_server import CreateJobRequest, FileStore
@@ -173,6 +175,41 @@ def test_epub_internal_heading_links_and_exact_list_labels_survive() -> None:
assert "B. Two" in markdown
+ ("attribute", "value"),
+ [
+ ("hidden", "hidden"),
+ ("aria-hidden", "true"),
+ ("style", "display: none"),
+ ("class", "hidden"),
+ ],
+)
+def test_epub_anchor_registry_excludes_hidden_headings(attribute: str, value: str) -> None:
+ """验证 registry 不为 converter 会丢弃的隐藏标题生成悬空 anchor。"""
+ package = EpubPackage(build_epub_fixture())
+ chapter_path = "EPUB/text/ch1.xhtml"
+ try:
+ root = package.xml_part(chapter_path, allow_external_doctype=True)
+ heading = next(element for element in root.iter() if isinstance(element.tag, str) and element.tag.endswith("}h1"))
+ heading.set(attribute, value)
+ heading.text = "Hidden target"
+ body = next(element for element in root.iter() if isinstance(element.tag, str) and element.tag.endswith("}body"))
+ namespace = etree.QName(body).namespace
+ paragraph = etree.SubElement(body, f"{{{namespace}}}p")
+ link = etree.SubElement(paragraph, f"{{{namespace}}}a", href="#chapter-one")
+ link.text = "Hidden link"
+
+ anchors = build_anchor_registry([(chapter_path, root)], package)
+ blocks = EpubChapterConverter(package, chapter_path, root, anchors).convert()
+
+ assert anchors.resolve_link("#chapter-one", base_part=chapter_path) is None
+ assert "Hidden target" not in str(blocks)
+ assert "Hidden link" in str(blocks)
+ assert "<hyperlink>Hidden link" 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 d73e83bf..64e3bfd5 100644
--- a/tests/unittest/test_flash_odf.py
+++ b/tests/unittest/test_flash_odf.py
@@ -231,6 +231,32 @@ def test_odt_child_style_can_reset_inherited_page_breaks() -> None:
]
+def test_odf_covered_placeholder_reuses_colspan_coordinate() -> None:
+ """验证 colspan 后的 covered placeholder 不会额外扩宽表格。"""
+ table = etree.fromstring(
+ """<table:table xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0"
+ xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0">
+ <table:table-row>
+ <table:table-cell table:number-columns-spanned="2"><text:p>Merged</text:p></table:table-cell>
+ <table:covered-table-cell/><table:table-cell><text:p>Tail</text:p></table:table-cell>
+ </table:table-row>
+ <table:table-row>
+ <table:table-cell><text:p>A</text:p></table:table-cell>
+ <table:table-cell><text:p>B</text:p></table:table-cell>
+ <table:table-cell><text:p>C</text:p></table:table-cell>
+ </table:table-row>
+</table:table>""".encode()
+ )
+
+ grid = odf_table_module.parse_table_grid(table, lambda cell: "".join(cell.itertext()).strip())
+
+ assert grid.width == 3
+ assert grid.covered == {(0, 1)}
+ assert grid.rows[0][0] is not None and grid.rows[0][0].col_span == 2
+ assert grid.rows[0][2] is not None and grid.rows[0][2].html == "Tail"
+ assert [cell.html if cell is not None else None for cell in grid.rows[1]] == ["A", "B", "C"]
+
+
def test_odp_preserves_empty_slide_chart_preview_and_notes() -> None:
"""验证 ODP 空 slide 不丢失,图表同时保留数据和预览,备注归属原页。"""
middle, model = doc_analyze(build_odp_fixture(), file_suffix="odp")