Skip to content

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

fix: bound EPUB tables and preserve ODF list pages

myhloli5f15f5c1cfc7
diff --git a/mineru/model/flash/epub/xhtml.py b/mineru/model/flash/epub/xhtml.py
index 636d03ab..8e2bf2e3 100644
--- a/mineru/model/flash/epub/xhtml.py
+++ b/mineru/model/flash/epub/xhtml.py
@@ -99,6 +99,7 @@ _NOTE_NON_TEXT_SUBTREES = frozenset(
_WHITESPACE_RE = re.compile(r"[\t\r\n\f ]+")
_XML_ID = "{http://www.w3.org/XML/1998/namespace}id"
_XLINK_HREF = "{http://www.w3.org/1999/xlink}href"
+MAX_EPUB_TABLE_SPAN = 1_000
def _local_name(element: etree._Element) -> str:
@@ -113,6 +114,17 @@ def _clean_text_node(value: str | None) -> str:
return _WHITESPACE_RE.sub(" ", value)
+def _bounded_table_span(value: str) -> str | None:
+ """规范化 EPUB 表格跨度,并在整数转换前拒绝超长或越界值。"""
+ if not value.isdigit():
+ return None
+ normalized = value.lstrip("0")
+ if not normalized or len(normalized) > len(str(MAX_EPUB_TABLE_SPAN)):
+ return None
+ span = int(normalized)
+ return str(span) if span <= MAX_EPUB_TABLE_SPAN else None
+
+
def _visible_text(element: etree._Element) -> str:
"""提取元素折叠空白后的可见纯文本。"""
return _WHITESPACE_RE.sub(" ", html.unescape("".join(element.itertext()))).strip()
@@ -592,7 +604,9 @@ class EpubChapterConverter:
continue
name = _local_name(child)
if name in {"img", "image"}:
- blocks.extend(self._image_blocks(child, caption=caption))
+ child_style = self.stylesheet.resolve(child, style)
+ if not child_style.hidden:
+ blocks.extend(self._image_blocks(child, caption=caption))
elif name != "figcaption":
child_blocks = (
self._parse_block(child, style) if name in _BLOCK_TAGS else self._render_inline_element(child, style)[1]
@@ -692,12 +706,14 @@ class EpubChapterConverter:
if name in {"td", "th"}:
for attribute in ("colspan", "rowspan", "scope"):
value = (element.get(attribute) or "").strip()
- if value and (attribute == "scope" or value.isdigit()):
+ if attribute == "scope" and value:
attributes.append(f'{attribute}="{html.escape(value, quote=True)}"')
+ elif span := _bounded_table_span(value):
+ attributes.append(f'{attribute}="{span}"')
elif name in {"col", "colgroup"}:
value = (element.get("span") or "").strip()
- if value.isdigit():
- attributes.append(f'span="{value}"')
+ if span := _bounded_table_span(value):
+ attributes.append(f'span="{span}"')
if name == "a":
target = self.anchors.resolve_link(element.get("href") or "", base_part=self.chapter_path)
if target:
diff --git a/mineru/model/flash/office/odf/converters.py b/mineru/model/flash/office/odf/converters.py
index a9bdb81c..8988d498 100644
--- a/mineru/model/flash/office/odf/converters.py
+++ b/mineru/model/flash/office/odf/converters.py
@@ -165,6 +165,14 @@ def _parse_odt_pages(context: _OdfContext) -> list[list[dict[str, Any]]]:
qname("text", "index-title"),
}:
walk(child)
+ elif child.tag == qname("text", "list"):
+ _append_flow_items(
+ parser.parse_list_blocks(child, allow_page_breaks=True),
+ parser=parser,
+ pages=pages,
+ page_masters=page_masters,
+ current_master=current_master,
+ )
else:
pages[-1].extend(parser.parse_element(child))
diff --git a/mineru/model/flash/office/odf/text.py b/mineru/model/flash/office/odf/text.py
index 51741980..34f301e8 100644
--- a/mineru/model/flash/office/odf/text.py
+++ b/mineru/model/flash/office/odf/text.py
@@ -437,14 +437,21 @@ class OdfBlockParser:
*,
depth: int = 0,
inherited_style: str | None = None,
- ) -> list[dict[str, Any]]:
+ allow_page_breaks: bool = False,
+ ) -> list[RawFlowItem]:
"""递归构造严格 LIST 分片,并把不允许嵌套的 block 提升为有序兄弟。"""
items = [
item
for item in element
if isinstance(item.tag, str) and item.tag in {qname("text", "list-item"), qname("text", "list-header")}
]
- return self._parse_list_items(element, items, depth=depth, inherited_style=inherited_style)
+ return self._parse_list_items(
+ element,
+ items,
+ depth=depth,
+ inherited_style=inherited_style,
+ allow_page_breaks=allow_page_breaks,
+ )
def _parse_list_items(
self,
@@ -453,7 +460,8 @@ class OdfBlockParser:
*,
depth: int,
inherited_style: str | None,
- ) -> list[dict[str, Any]]:
+ allow_page_breaks: bool,
+ ) -> list[RawFlowItem]:
"""按源条目构造 LIST 分片,每个条目只保留一个文本叶子和一个 marker。"""
style_name = element.get(qname("text", "style-name")) or inherited_style
level = self.styles.list_level(style_name, depth)
@@ -464,11 +472,13 @@ class OdfBlockParser:
start = self._list_ids[continue_list]
elif element.get(qname("text", "continue-numbering")) == "true" and key in self._list_counters:
start = self._list_counters[key]
- results: list[dict[str, Any]] = []
+ results: list[RawFlowItem] = []
content: list[dict[str, Any]] = []
+ pending_notes: list[InlineNote] = []
item_count = 0
+ fragment_start = start
- def flush_content(fragment_start: int) -> None:
+ def flush_content() -> None:
"""把当前合法子块冻结为一个 LIST 分片。"""
if not content:
return
@@ -483,7 +493,18 @@ class OdfBlockParser:
results.append(block)
content.clear()
- fragment_start = start
+ def queue_note(note: InlineNote) -> None:
+ """分页模式保留 note 的流位置,其余调用维持既有共享队列行为。"""
+ if allow_page_breaks:
+ pending_notes.append(note)
+ else:
+ self.notes.append(note.content)
+
+ def flush_pending_notes() -> None:
+ """在分页 marker 前或列表结尾输出按来源顺序累计的 note。"""
+ results.extend(pending_notes)
+ pending_notes.clear()
+
for item in items:
is_header = item.tag == qname("text", "list-header")
if not is_header:
@@ -491,66 +512,104 @@ class OdfBlockParser:
item_start = int(item.get(qname("text", "start-value"), str(start + item_count)))
if item_count == 0:
start = max(0, item_start)
- fragment_start = start
except ValueError:
pass
item_count += 1
+ item_number = start + max(item_count - 1, 0)
text_parts: list[str] = []
nested_blocks: list[dict[str, Any]] = []
lifted_blocks: list[dict[str, Any]] = []
+
+ def flush_item_segment() -> None:
+ """把当前列表项在分页边界前后的一个连续片段写入结果。"""
+ nonlocal fragment_start
+ if text_parts or nested_blocks:
+ if not content:
+ fragment_start = item_number
+ if text_parts:
+ content.append({"type": BlockType.TEXT, "content": "\n".join(text_parts)})
+ content.extend(nested_blocks)
+ if lifted_blocks:
+ flush_content()
+ results.extend(lifted_blocks)
+ text_parts.clear()
+ nested_blocks.clear()
+ lifted_blocks.clear()
+
+ def consume_flow(flow: Sequence[RawFlowItem]) -> None:
+ """分类列表项子流,并在显式分页 marker 处冻结当前 LIST 分片。"""
+ for block in flow:
+ if isinstance(block, PageBreakMarker):
+ flush_item_segment()
+ flush_content()
+ flush_pending_notes()
+ results.append(PAGE_BREAK)
+ continue
+ if isinstance(block, InlineNote):
+ queue_note(block)
+ continue
+ block_type = block.get("type")
+ block_content = block.get("content")
+ if block_type in {
+ BlockType.TEXT,
+ BlockType.REF_TEXT,
+ BlockType.DOC_TITLE,
+ BlockType.PARAGRAPH_TITLE,
+ } and isinstance(block_content, str):
+ if block_content:
+ text_parts.append(block_content)
+ elif block_type == BlockType.LIST:
+ nested_blocks.append(block)
+ else:
+ lifted_blocks.append(block)
+
+ def consume_nested_flow(flow: Sequence[RawFlowItem]) -> None:
+ """按分页分段处理嵌套列表,并保留原有整体提升判定。"""
+ segment: list[dict[str, Any]] = []
+
+ def flush_nested_segment() -> None:
+ """把纯 LIST 片段嵌套,其余混合结构整体提升。"""
+ if not segment:
+ return
+ if all(block.get("type") == BlockType.LIST for block in segment):
+ nested_blocks.extend(segment)
+ else:
+ lifted_blocks.extend(segment)
+ segment.clear()
+
+ for block in flow:
+ if isinstance(block, PageBreakMarker):
+ flush_nested_segment()
+ flush_item_segment()
+ flush_content()
+ flush_pending_notes()
+ results.append(PAGE_BREAK)
+ elif isinstance(block, InlineNote):
+ queue_note(block)
+ else:
+ segment.append(block)
+ flush_nested_segment()
+
for child in item:
if not isinstance(child.tag, str):
continue
if child.tag in {qname("text", "p"), qname("text", "h")}:
- for block in self.parse_paragraph(child):
- if isinstance(block, InlineNote):
- self.notes.append(block.content)
- continue
- if not isinstance(block, dict):
- continue
- block_type = block.get("type")
- block_content = block.get("content")
- if block_type in {
- BlockType.TEXT,
- BlockType.REF_TEXT,
- BlockType.DOC_TITLE,
- BlockType.PARAGRAPH_TITLE,
- } and isinstance(block_content, str):
- if block_content:
- text_parts.append(block_content)
- else:
- lifted_blocks.append(block)
+ consume_flow(self.parse_paragraph(child, allow_page_breaks=allow_page_breaks))
elif child.tag == qname("text", "list"):
- nested_flow = self.parse_list_blocks(child, depth=depth + 1, inherited_style=style_name)
- if all(block.get("type") == BlockType.LIST for block in nested_flow):
- nested_blocks.extend(nested_flow)
- else:
- lifted_blocks.extend(nested_flow)
+ consume_nested_flow(
+ self.parse_list_blocks(
+ child,
+ depth=depth + 1,
+ inherited_style=style_name,
+ allow_page_breaks=allow_page_breaks,
+ )
+ )
else:
- for block in self.parse_container(child):
- block_type = block.get("type")
- block_content = block.get("content")
- if block_type in {
- BlockType.TEXT,
- BlockType.REF_TEXT,
- BlockType.DOC_TITLE,
- BlockType.PARAGRAPH_TITLE,
- } and isinstance(block_content, str):
- if block_content:
- text_parts.append(block_content)
- elif block_type == BlockType.LIST:
- nested_blocks.append(block)
- else:
- lifted_blocks.append(block)
- if text_parts:
- content.append({"type": BlockType.TEXT, "content": "\n".join(text_parts)})
- content.extend(nested_blocks)
- if lifted_blocks:
- flush_content(fragment_start)
- results.extend(lifted_blocks)
- fragment_start = start + item_count
-
- flush_content(fragment_start)
+ consume_flow(self.parse_container(child))
+ flush_item_segment()
+
+ flush_content()
+ flush_pending_notes()
next_value = start + item_count
self._list_counters[key] = next_value
if list_id := element.get(qname("xml", "id")):
@@ -563,11 +622,17 @@ class OdfBlockParser:
*,
depth: int = 0,
inherited_style: str | None = None,
- ) -> list[dict[str, Any]]:
+ allow_page_breaks: bool = False,
+ ) -> list[RawFlowItem]:
"""把含 text:h 的编号章节提升为标题,并保留其余连续列表。"""
if next(element.iter(qname("text", "h")), None) is None:
- return self.parse_list(element, depth=depth, inherited_style=inherited_style)
- results: list[dict[str, Any]] = []
+ return self.parse_list(
+ element,
+ depth=depth,
+ inherited_style=inherited_style,
+ allow_page_breaks=allow_page_breaks,
+ )
+ results: list[RawFlowItem] = []
pending_items: list[etree._Element] = []
def flush_pending() -> None:
@@ -579,6 +644,7 @@ class OdfBlockParser:
list(pending_items),
depth=depth,
inherited_style=inherited_style,
+ allow_page_breaks=allow_page_breaks,
)
pending_items.clear()
results.extend(blocks)
@@ -596,14 +662,18 @@ class OdfBlockParser:
for child in item:
if not isinstance(child.tag, str):
continue
- if child.tag == qname("text", "h"):
- for parsed in self.parse_paragraph(child):
+ if child.tag in {qname("text", "p"), qname("text", "h")}:
+ for parsed in self.parse_paragraph(child, allow_page_breaks=allow_page_breaks):
if isinstance(parsed, InlineNote):
- self.notes.append(parsed.content)
+ if allow_page_breaks:
+ results.append(parsed)
+ else:
+ self.notes.append(parsed.content)
continue
- if not isinstance(parsed, dict):
+ if isinstance(parsed, PageBreakMarker):
+ results.append(parsed)
continue
- if parsed.get("type") == BlockType.PARAGRAPH_TITLE:
+ if child.tag == qname("text", "h") and parsed.get("type") == BlockType.PARAGRAPH_TITLE:
parsed["is_numbered_style"] = True
results.append(parsed)
elif child.tag == qname("text", "list"):
@@ -612,6 +682,7 @@ class OdfBlockParser:
child,
depth=depth + 1,
inherited_style=element.get(qname("text", "style-name")) or inherited_style,
+ allow_page_breaks=allow_page_breaks,
)
)
else:
@@ -764,7 +835,7 @@ class OdfBlockParser:
self.notes.append(item.content)
return blocks
if element.tag == qname("text", "list"):
- return self.parse_list_blocks(element)
+ return [item for item in self.parse_list_blocks(element) if isinstance(item, dict)]
if element.tag == qname("table", "table"):
table_block = self.parse_table(element)
return [table_block] if table_block is not None else []
diff --git a/tests/unittest/test_flash_epub.py b/tests/unittest/test_flash_epub.py
index 086ef7f2..52c33e9e 100644
--- a/tests/unittest/test_flash_epub.py
+++ b/tests/unittest/test_flash_epub.py
@@ -282,6 +282,55 @@ def test_epub_table_contents_resolve_title_marker_and_expand_only_exact_single_t
assert chapter_link["href"] == f"#{chapter_title['id']}"
+def test_epub_table_spans_are_bounded_before_downstream_grid_parsing() -> None:
+ """验证超大 EPUB colspan 在进入 DOCX 占位网格前被移除。"""
+ package = EpubPackage(build_epub_fixture())
+ chapter_path = "EPUB/text/ch2.xhtml"
+ try:
+ root = package.xml_part(chapter_path, allow_external_doctype=True)
+ cell = next(element for element in root.iter() if isinstance(element.tag, str) and element.tag.endswith("}td"))
+ cell.set("colspan", "100000000")
+
+ anchors = build_anchor_registry([(chapter_path, root)], package)
+ blocks = EpubChapterConverter(package, chapter_path, root, anchors).convert()
+ table = next(block for block in blocks if block["type"] == BlockType.TABLE)
+ parsed_cell = BeautifulSoup(str(table["content"]), "html.parser").find("td", string="1")
+
+ assert parsed_cell is not None
+ assert parsed_cell["rowspan"] == "2"
+ assert not parsed_cell.has_attr("colspan")
+ finally:
+ package.close()
+
+
+ ("attribute", "value"),
+ [
+ ("hidden", "hidden"),
+ ("aria-hidden", "true"),
+ ("style", "display: none"),
+ ("class", "hidden"),
+ ],
+)
+def test_epub_figure_skips_hidden_direct_images(attribute: str, value: str) -> None:
+ """验证 figure 的直接图片同样遵守元素属性、内联样式和 CSS 隐藏规则。"""
+ package = EpubPackage(build_epub_fixture())
+ chapter_path = "EPUB/text/ch1.xhtml"
+ try:
+ root = package.xml_part(chapter_path, allow_external_doctype=True)
+ figure = next(element for element in root.iter() if isinstance(element.tag, str) and element.tag.endswith("}figure"))
+ image = next(child for child in figure if isinstance(child.tag, str) and child.tag.endswith("}img"))
+ image.set(attribute, value)
+
+ anchors = build_anchor_registry([(chapter_path, root)], package)
+ blocks = EpubChapterConverter(package, chapter_path, root, anchors).convert()
+
+ assert all(block["type"] != BlockType.IMAGE for block in blocks)
+ assert "Dot caption" in str(blocks)
+ finally:
+ package.close()
+
+
def test_public_parser_rejects_epub_page_range(tmp_path: Path) -> None:
"""验证 EPUB 公共 Parser 只接受整本解析。"""
source = tmp_path / "book.epub"
diff --git a/tests/unittest/test_flash_odf.py b/tests/unittest/test_flash_odf.py
index 0558d8e5..a2ea6e27 100644
--- a/tests/unittest/test_flash_odf.py
+++ b/tests/unittest/test_flash_odf.py
@@ -212,6 +212,28 @@ def test_odt_inline_visual_stays_before_soft_page_break() -> None:
]
+def test_odt_list_preserves_soft_page_break_as_logical_page_boundary() -> None:
+ """验证列表项内的 soft-page-break 会拆分 ODT 逻辑页且不丢前后文本。"""
+ 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">
+ <office:body><office:text><text:list>
+ <text:list-item><text:p>Before<text:soft-page-break/>After
+ <text:note><text:note-citation>1</text:note-citation><text:note-body><text:p>After note</text:p></text:note-body></text:note>
+ </text:p></text:list-item>
+ <text:list-item><text:p>Next</text:p></text:list-item>
+ </text:list></office:text></office:body>
+</office:document-content>"""
+
+ pages = OdtModel().predict(BytesIO(build_odf_package("odt", content)))
+
+ assert len(pages) == 2
+ assert "Before" in str(pages[0]) and "After" not in str(pages[0])
+ assert "After" in str(pages[1]) and "Next" in str(pages[1])
+ assert all(block["type"] != BlockType.PAGE_FOOTNOTE for block in pages[0])
+ assert any(block["type"] == BlockType.PAGE_FOOTNOTE and "After note" in block["content"] for block in pages[1])
+
+
def test_odt_child_style_can_reset_inherited_page_breaks() -> None:
"""验证 break-before/after=auto 显式关闭父样式的逻辑分页。"""
content = """<office:document-content