Skip to content

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

fix: unify document projection semantics and enhance list handling

myhloli6eb3aeca1877
diff --git a/CLAUDE.md b/CLAUDE.md
index c4713fe6..d9ca645b 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -76,6 +76,23 @@ from mineru.render import RenderMode
## 编程原则
+### 统一文档信息投影
+
+MinerU 文档解析的目标是尽可能保留具有跨格式价值的内容和结构,并通过统一 Middle JSON 稳定导出多种格式;目标不是逐输入格式、逐排版细节地 100% 复刻源文件。
+
+- 优先保留正文、标题、列表层级、表格、图片、公式、链接、注释和脚注等具有语义价值的信息。
+- Middle JSON 是各输入格式的统一语义交集。新增信息应尽可能能被 Markdown 表达,并能稳定导出为 HTML、DOCX 和 Structured Content。
+- Markdown 是主要兼容基线,但不是纯文本上限;Markdown 原生能力不足时,可以复用现有安全 HTML、图片资源和结构化 block。
+- 不为单一输入格式增加只用于还原罕见排版、编号样式或物理分页的私有 block、私有字段或 renderer 特判。
+- 只有同时满足“常见、语义价值高、可进入统一 Middle JSON、可被多个 renderer 稳定消费”的格式私有信息,才应扩展公共契约。
+- Review 时,源格式细节未被 100% 还原不应自动视为缺陷。只有丢失统一契约支持的有价值内容、破坏结构、产生错误语义,或引入安全和资源问题时才应报告。
+- 禁止通过不断增加格式例外来追求源文件视觉级复刻;优先规范化为确定、可静态分析、跨格式一致的表示。
+
+具体投影约束:
+
+- ODT 忽略 `text:soft-page-break` 和普通 `fo:break-before/after`;只有有效 `master-page-name` 变化形成章节虚拟页。
+- 有序列表仅保证阿拉伯连续序号及单一列表级起始值;不精确还原字母、罗马数字、前后缀、倒序和 `1,5,6` 式逐项跳号,Review 不应再针对这些未支持能力提出检测。
+
### 确定性优先
agent 通过静态分析理解代码。避免运行时注册、猴子补丁、`globals()` 等动态模式,使用显式映射。
diff --git a/mineru/model/flash/epub/xhtml.py b/mineru/model/flash/epub/xhtml.py
index 1b10950a..68c4cb10 100644
--- a/mineru/model/flash/epub/xhtml.py
+++ b/mineru/model/flash/epub/xhtml.py
@@ -805,16 +805,14 @@ class EpubChapterConverter:
element: etree._Element,
style: TextStyle,
) -> tuple[dict[str, object] | None, list[dict[str, object]]]:
- """解析有序/无序列表,保留嵌套和每项最终可见标签。"""
+ """解析有序/无序列表,并投影为跨 renderer 的连续编号结构。"""
ordered = _local_name(element) == "ol"
items = [child for child in element if isinstance(child.tag, str) and _local_name(child) == "li"]
if not items:
return None, []
- numbers = self._ordered_list_numbers(element, len(items)) if ordered else [None] * len(items)
- marker_type = (element.get("type") or "1").strip()
children: list[dict[str, object]] = []
extras: list[dict[str, object]] = []
- for item, number in zip(items, numbers, strict=True):
+ for item in items:
item_style = self.stylesheet.resolve(item, style)
if item_style.hidden:
continue
@@ -851,10 +849,7 @@ class EpubChapterConverter:
content_parts.append(self._render_text(child.tail, item_style.text))
content = "".join(content_parts).strip()
if content:
- text_block: dict[str, object] = {"type": BlockType.TEXT, "content": content}
- if ordered and number is not None:
- text_block["list_label"] = self._format_list_label(number, marker_type)
- children.append(text_block)
+ children.append({"type": BlockType.TEXT, "content": content})
children.extend(nested_lists)
if not children:
return None, extras
@@ -863,79 +858,18 @@ class EpubChapterConverter:
"attribute": "ordered" if ordered else "unordered",
"content": children,
}
+ if ordered:
+ block["start"] = self._ordered_list_start(element)
return block, extras
@staticmethod
- def _ordered_list_numbers(element: etree._Element, item_count: int) -> list[int]:
- """计算 start、reversed 和 li value 共同决定的每项编号。"""
- reversed_list = element.get("reversed") is not None
+ def _ordered_list_start(element: etree._Element) -> int:
+ """读取有序列表唯一通用起始值,非法或负值统一回退为一。"""
try:
- current = int(element.get("start") or (item_count if reversed_list else 1))
+ start = int(element.get("start") or 1)
except ValueError:
- current = item_count if reversed_list else 1
- numbers: list[int] = []
- for item in [child for child in element if isinstance(child.tag, str) and _local_name(child) == "li"]:
- try:
- current = int(item.get("value")) if item.get("value") is not None else current
- except ValueError:
- pass
- numbers.append(current)
- current += -1 if reversed_list else 1
- return numbers
-
- @classmethod
- def _format_list_label(cls, number: int, marker_type: str) -> str:
- """把 HTML ordered-list marker 类型格式化为最终可见标签。"""
- if marker_type == "a":
- return f"{cls._alpha_marker(number, upper=False)}."
- if marker_type == "A":
- return f"{cls._alpha_marker(number, upper=True)}."
- if marker_type == "i":
- return f"{cls._roman_marker(number).casefold()}."
- if marker_type == "I":
- return f"{cls._roman_marker(number)}."
- return f"{number}."
-
- @staticmethod
- def _alpha_marker(number: int, *, upper: bool) -> str:
- """把正整数转换为 HTML 字母序号,非正值保留十进制。"""
- if number <= 0:
- return str(number)
- chars: list[str] = []
- current = number
- while current > 0:
- current -= 1
- chars.append(chr(ord("A" if upper else "a") + current % 26))
- current //= 26
- return "".join(reversed(chars))
-
- @staticmethod
- def _roman_marker(number: int) -> str:
- """把 1..3999 转换为罗马数字,范围外保留十进制。"""
- if number <= 0 or number >= 4000:
- return str(number)
- pairs = (
- (1000, "M"),
- (900, "CM"),
- (500, "D"),
- (400, "CD"),
- (100, "C"),
- (90, "XC"),
- (50, "L"),
- (40, "XL"),
- (10, "X"),
- (9, "IX"),
- (5, "V"),
- (4, "IV"),
- (1, "I"),
- )
- parts: list[str] = []
- current = number
- for value, symbol in pairs:
- while current >= value:
- parts.append(symbol)
- current -= value
- return "".join(parts)
+ return 1
+ return start if start >= 0 else 1
def convert_svg_spine(
diff --git a/mineru/model/flash/office/odf/converters.py b/mineru/model/flash/office/odf/converters.py
index 8988d498..ecbbfc8d 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, collect_emittable_anchor_targets, flatten_block_text
+from .text import OdfBlockParser, OdfTextExpansionBudget, 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*$")
@@ -78,22 +78,17 @@ def _flush_notes(parser: OdfBlockParser, page: list[dict[str, Any]]) -> None:
def _append_flow_items(
- items: list[dict[str, Any] | PageBreakMarker | InlineNote],
+ items: list[dict[str, Any] | InlineNote],
*,
parser: OdfBlockParser,
- pages: list[list[dict[str, Any]]],
- page_masters: list[str | None],
- current_master: str | None,
+ page: list[dict[str, Any]],
) -> None:
- """把段落结果追加到当前页,并在显式 marker 处切换逻辑页。"""
+ """把段落结果和脚注按统一流语义追加到当前章节页。"""
for item in items:
- if isinstance(item, PageBreakMarker):
- _flush_notes(parser, pages[-1])
- _new_page(pages, page_masters, current_master)
- elif isinstance(item, InlineNote):
+ if isinstance(item, InlineNote):
parser.notes.append(item.content)
else:
- pages[-1].append(item)
+ page.append(item)
def _master_auxiliary_blocks(
@@ -102,11 +97,17 @@ def _master_auxiliary_blocks(
package: OdfPackage,
styles: OdfStyles,
anchor_targets: frozenset[str],
+ text_expansion_budget: OdfTextExpansionBudget,
) -> list[dict[str, Any]]:
"""从 master-page 的 header/footer 中提取页面辅助文本。"""
if master_page is None:
return []
- parser = OdfBlockParser(package, styles, anchor_targets=anchor_targets)
+ parser = OdfBlockParser(
+ package,
+ styles,
+ anchor_targets=anchor_targets,
+ text_expansion_budget=text_expansion_budget,
+ )
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,9 +123,15 @@ def _master_auxiliary_blocks(
def _parse_odt_pages(context: _OdfContext) -> list[list[dict[str, Any]]]:
- """按显式 ODF 分页样式递归构造 ODT 逻辑页。"""
+ """仅按 master-page 章节变化递归构造 ODT 逻辑页。"""
anchor_targets = collect_emittable_anchor_targets(context.content_root, context.styles)
- parser = OdfBlockParser(context.package, context.styles, anchor_targets=anchor_targets)
+ text_expansion_budget = OdfTextExpansionBudget()
+ parser = OdfBlockParser(
+ context.package,
+ context.styles,
+ anchor_targets=anchor_targets,
+ text_expansion_budget=text_expansion_budget,
+ )
pages: list[list[dict[str, Any]]] = [[]]
page_masters: list[str | None] = [None]
current_master: str | None = None
@@ -136,29 +143,21 @@ def _parse_odt_pages(context: _OdfContext) -> list[list[dict[str, Any]]]:
if not isinstance(child.tag, str):
continue
if child.tag in {qname("text", "p"), qname("text", "h")}:
- properties = context.styles.paragraph_properties(child.get(qname("text", "style-name")))
- requested_master = properties.master_page_name
+ requested_master = context.styles.paragraph_master_page_name(child.get(qname("text", "style-name")))
master_changed = (
- requested_master is not None
- and current_master is not None
- and requested_master != current_master
+ requested_master is not None and current_master is not None and requested_master != current_master
)
- if (properties.break_before or master_changed) and pages[-1]:
+ if master_changed and pages[-1]:
_flush_notes(parser, pages[-1])
- _new_page(pages, page_masters, requested_master or current_master)
+ _new_page(pages, page_masters, requested_master)
if requested_master is not None:
current_master = requested_master
page_masters[-1] = current_master
_append_flow_items(
- parser.parse_paragraph(child, allow_page_breaks=True),
+ parser.parse_paragraph(child),
parser=parser,
- pages=pages,
- page_masters=page_masters,
- current_master=current_master,
+ page=pages[-1],
)
- if properties.break_after:
- _flush_notes(parser, pages[-1])
- _new_page(pages, page_masters, current_master)
elif child.tag in {
qname("text", "section"),
qname("text", "index-body"),
@@ -166,13 +165,7 @@ def _parse_odt_pages(context: _OdfContext) -> list[list[dict[str, Any]]]:
}:
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,
- )
+ pages[-1].extend(parser.parse_list_blocks(child))
else:
pages[-1].extend(parser.parse_element(child))
@@ -188,6 +181,7 @@ def _parse_odt_pages(context: _OdfContext) -> list[list[dict[str, Any]]]:
package=context.package,
styles=context.styles,
anchor_targets=anchor_targets,
+ text_expansion_budget=text_expansion_budget,
)
)
return pages or [[]]
@@ -290,9 +284,7 @@ def _parse_odp_pages(context: _OdfContext) -> list[list[dict[str, Any]]]:
)
document_title_emitted = True
output.extend(
- block
- for block in entry.blocks
- if block.get("type") in {BlockType.IMAGE, BlockType.TABLE, BlockType.CHART}
+ block for block in entry.blocks if block.get("type") in {BlockType.IMAGE, BlockType.TABLE, BlockType.CHART}
)
for entry in body_entries:
output.extend(entry.blocks)
diff --git a/mineru/model/flash/office/odf/models.py b/mineru/model/flash/office/odf/models.py
index 8d92ac8e..a3519477 100644
--- a/mineru/model/flash/office/odf/models.py
+++ b/mineru/model/flash/office/odf/models.py
@@ -70,32 +70,12 @@ class TextStyleDelta:
)
-@dataclass(frozen=True, slots=True)
-class ParagraphProperties:
- """保存影响逻辑分页的 ODF 段落属性。"""
-
- break_before: bool = False
- break_after: bool = False
- master_page_name: str | None = None
-
-
-@dataclass(frozen=True, slots=True)
-class ParagraphPropertiesDelta:
- """保存可区分缺省与显式 reset 的 ODF 段落分页增量。"""
-
- break_before: bool | None = None
- break_after: bool | None = None
- master_page_name: str | None = None
-
-
@dataclass(frozen=True, slots=True)
class ListLevel:
- """保存一个 ODF 列表层级的编号语义。"""
+ """保存一个 ODF 列表层级的通用编号语义。"""
ordered: bool = False
start: int = 1
- prefix: str = ""
- suffix: str = "."
@dataclass(frozen=True, slots=True)
@@ -119,14 +99,9 @@ class InlineBreak:
"""表示段内显式换行。"""
-@dataclass(frozen=True, slots=True)
-class InlinePageBreak:
- """表示 ODT 内容中的显式软分页。"""
-
-
@dataclass(frozen=True, slots=True)
class InlineNote:
- """保存应随当前行内分页分组归属的 ODF note body。"""
+ """保存应随当前行内内容归属的 ODF note body。"""
content: str
@@ -151,7 +126,6 @@ InlineAtom: TypeAlias = Union[
InlineText,
InlineMath,
InlineBreak,
- InlinePageBreak,
InlineNote,
InlineImage,
InlineBlockGroup,
@@ -195,11 +169,8 @@ __all__ = [
"InlineImage",
"InlineMath",
"InlineNote",
- "InlinePageBreak",
"InlineText",
"ListLevel",
- "ParagraphProperties",
- "ParagraphPropertiesDelta",
"TableGrid",
"TextStyle",
"TextStyleDelta",
diff --git a/mineru/model/flash/office/odf/styles.py b/mineru/model/flash/office/odf/styles.py
index 488c8628..5ace4b24 100644
--- a/mineru/model/flash/office/odf/styles.py
+++ b/mineru/model/flash/office/odf/styles.py
@@ -9,19 +9,19 @@ from loguru import logger
from lxml import etree # type: ignore[reportMissingImports]
from .constants import qname
-from .models import ListLevel, ParagraphProperties, ParagraphPropertiesDelta, TextStyle, TextStyleDelta
+from .models import ListLevel, TextStyle, TextStyleDelta
@dataclass(frozen=True, slots=True)
class _StyleDefinition:
- """保存一个命名样式的父级、文本增量和分页属性。"""
+ """保存一个命名样式的父级、文本增量和跨格式投影属性。"""
name: str
family: str
parent: str | None
display_name: str | None
text_delta: TextStyleDelta
- paragraph: ParagraphPropertiesDelta
+ master_page_name: str | None
table_display: bool | None
@@ -34,6 +34,7 @@ class OdfStyles:
self._defaults: dict[str, TextStyleDelta] = {}
self._list_styles: dict[str, dict[int, ListLevel]] = {}
self._resolved_text: dict[tuple[str, str], TextStyleDelta] = {}
+ self._resolved_table_display: dict[str, bool | None] = {}
self._master_pages: dict[str, etree._Element] = {}
for root in roots:
if root is not None:
@@ -56,7 +57,7 @@ class OdfStyles:
parent=style.get(qname("style", "parent-style-name")),
display_name=style.get(qname("style", "display-name")),
text_delta=self._text_delta(style),
- paragraph=self._paragraph_properties(style),
+ master_page_name=style.get(qname("style", "master-page-name")),
table_display=self._table_display(style),
)
for list_style in root.iter(qname("text", "list-style")):
@@ -121,18 +122,6 @@ class OdfStyles:
except ValueError:
return False
- @staticmethod
- def _paragraph_properties(style: etree._Element) -> ParagraphPropertiesDelta:
- """读取可区分缺省与显式非分页值的段落属性增量。"""
- properties = style.find(qname("style", "paragraph-properties"))
- before = properties.get(qname("fo", "break-before")) if properties is not None else None
- after = properties.get(qname("fo", "break-after")) if properties is not None else None
- return ParagraphPropertiesDelta(
- break_before=None if before is None else before.casefold() == "page",
- break_after=None if after is None else after.casefold() == "page",
- master_page_name=style.get(qname("style", "master-page-name")),
- )
-
@staticmethod
def _table_display(style: etree._Element) -> bool | None:
"""读取表格样式的 display 开关,用于过滤隐藏工作表。"""
@@ -146,7 +135,7 @@ class OdfStyles:
@staticmethod
def _parse_list_style(element: etree._Element) -> dict[int, ListLevel]:
- """解析列表样式的层级、起始值和前后缀。"""
+ """解析列表样式的层级、类型和通用起始值。"""
levels: dict[int, ListLevel] = {}
for child in element:
if not isinstance(child.tag, str):
@@ -166,8 +155,6 @@ class OdfStyles:
levels[level - 1] = ListLevel(
ordered=ordered,
start=start,
- prefix=child.get(qname("style", "num-prefix"), ""),
- suffix=child.get(qname("style", "num-suffix"), "." if ordered else ""),
)
return levels
@@ -212,30 +199,24 @@ class OdfStyles:
delta = base.merge(delta)
return delta.resolve()
- def paragraph_properties(self, style_name: str | None) -> ParagraphProperties:
- """沿段落父样式继承分页标记和 master-page 名称。"""
+ def paragraph_master_page_name(self, style_name: str | None) -> str | None:
+ """沿段落父样式查找首个有效 master-page 名称。"""
if not style_name:
- return ParagraphProperties()
- chain: list[_StyleDefinition] = []
+ return None
seen: set[str] = set()
current = style_name
- while current and current not in seen:
+ while current:
+ if current in seen:
+ logger.warning("ODF style inheritance cycle detected: family=paragraph, style={}", current)
+ break
seen.add(current)
definition = self._styles.get(("paragraph", current))
if definition is None:
break
- chain.append(definition)
+ if definition.master_page_name is not None:
+ return definition.master_page_name
current = definition.parent or ""
- before = False
- after = False
- master: str | None = None
- for definition in reversed(chain):
- if definition.paragraph.break_before is not None:
- before = definition.paragraph.break_before
- if definition.paragraph.break_after is not None:
- after = definition.paragraph.break_after
- master = definition.paragraph.master_page_name or master
- return ParagraphProperties(before, after, master)
+ return None
def is_document_title(self, style_name: str | None) -> bool:
"""根据样式名称和 display-name 判断段落是否为文档标题。"""
@@ -254,11 +235,28 @@ class OdfStyles:
return levels.get(depth, ListLevel())
def table_is_visible(self, style_name: str | None) -> bool:
- """判断工作表样式是否显式隐藏,未知样式默认可见。"""
+ """沿表格父样式解析 display,子样式显式值优先。"""
if not style_name:
return True
- definition = self._styles.get(("table", style_name))
- return definition is None or definition.table_display is not False
+ if style_name in self._resolved_table_display:
+ return self._resolved_table_display[style_name] is not False
+ seen: set[str] = set()
+ current = style_name
+ resolved: bool | None = None
+ while current:
+ if current in seen:
+ logger.warning("ODF style inheritance cycle detected: family=table, style={}", current)
+ break
+ seen.add(current)
+ definition = self._styles.get(("table", current))
+ if definition is None:
+ break
+ if definition.table_display is not None:
+ resolved = definition.table_display
+ break
+ current = definition.parent or ""
+ self._resolved_table_display[style_name] = resolved
+ return resolved is not False
def master_page(self, name: str | None) -> etree._Element | None:
"""返回指定 master-page;空名称时优先使用第一个定义。"""
diff --git a/mineru/model/flash/office/odf/text.py b/mineru/model/flash/office/odf/text.py
index ef887bfb..3f894731 100644
--- a/mineru/model/flash/office/odf/text.py
+++ b/mineru/model/flash/office/odf/text.py
@@ -19,7 +19,8 @@ from ..._shared.image import image_to_b64str
from ..image import create_text_placeholder, serialize_office_image
from ..rich_text import OfficeRichTextSegment, build_rich_text_from_segments
from .chart import parse_chart_block
-from .constants import qname
+from .constants import MAX_EXPANSION_TEXT_BYTES, qname
+from .errors import OdfResourceLimitError
from .models import (
InlineAtom,
InlineBlockGroup,
@@ -27,7 +28,6 @@ from .models import (
InlineImage,
InlineMath,
InlineNote,
- InlinePageBreak,
InlineText,
TextStyle,
)
@@ -40,13 +40,20 @@ _WHITESPACE_RE = re.compile(r"[\t\r\n ]+")
_SAFE_EXTERNAL_HYPERLINK_SCHEMES = frozenset({"http", "https", "mailto", "tel"})
-@dataclass(frozen=True, slots=True)
-class PageBreakMarker:
- """表示 ODT 流式解析中应建立新逻辑页的位置。"""
+@dataclass(slots=True)
+class OdfTextExpansionBudget:
+ """记录单个 ODF 文档显式文本膨胀的累计字节数。"""
+ used_bytes: int = 0
-PAGE_BREAK = PageBreakMarker()
-RawFlowItem = dict[str, Any] | PageBreakMarker | InlineNote
+ def charge(self, byte_count: int) -> None:
+ """在分配膨胀文本前计费,超过固定上限时立即失败。"""
+ if byte_count < 0 or self.used_bytes > MAX_EXPANSION_TEXT_BYTES - byte_count:
+ raise OdfResourceLimitError(f"ODF resource limit exceeded: max_expansion_text_bytes={MAX_EXPANSION_TEXT_BYTES}")
+ self.used_bytes += byte_count
+
+
+RawFlowItem = dict[str, Any] | InlineNote
def _clean_xml_text(value: str | None) -> str:
@@ -159,7 +166,7 @@ def render_atoms_to_html(atoms: Sequence[InlineAtom]) -> str:
parts.append(rendered)
elif isinstance(atom, InlineMath):
parts.append(f"<eq>{html.escape(atom.latex)}</eq>")
- elif isinstance(atom, (InlineBreak, InlinePageBreak)):
+ elif isinstance(atom, InlineBreak):
parts.append("<br/>")
elif isinstance(atom, InlineImage):
parts.append(f'<img src="{html.escape(atom.data_uri, quote=True)}" alt="{html.escape(atom.alt, quote=True)}"/>')
@@ -172,9 +179,23 @@ def render_atoms_to_model(atoms: Sequence[InlineAtom], *, trim_edges: bool = Fal
"""把 ODF 行内语义序列转换为现有 Office 富文本协议。"""
parts: list[str] = []
segments: list[OfficeRichTextSegment] = []
+ text_fragments: list[str] = []
+ fragment_style: tuple[str, ...] | None = None
+ fragment_hyperlink: str | None = None
+
+ def flush_text_fragments() -> None:
+ """线性合并连续同样式文本,避免逐片段重复复制前缀。"""
+ nonlocal fragment_style, fragment_hyperlink
+ if not text_fragments:
+ return
+ segments.append(OfficeRichTextSegment("".join(text_fragments), fragment_style, fragment_hyperlink))
+ text_fragments.clear()
+ fragment_style = None
+ fragment_hyperlink = None
def flush_segments() -> None:
"""把连续文本片段批量写入富文本结果。"""
+ flush_text_fragments()
if not segments:
return
parts.append(build_rich_text_from_segments(list(segments), trim_plain_edges=trim_edges and not parts))
@@ -182,18 +203,19 @@ def render_atoms_to_model(atoms: Sequence[InlineAtom], *, trim_edges: bool = Fal
for atom in atoms:
if isinstance(atom, InlineText):
- segments.append(
- OfficeRichTextSegment(
- html.escape(atom.text, quote=False),
- atom.style.names(),
- html.escape(atom.hyperlink, quote=False) if atom.hyperlink else None,
- )
- )
+ style_names = atom.style.names()
+ hyperlink = html.escape(atom.hyperlink, quote=False) if atom.hyperlink else None
+ if text_fragments and (style_names != fragment_style or hyperlink != fragment_hyperlink):
+ flush_text_fragments()
+ if not text_fragments:
+ fragment_style = style_names
+ fragment_hyperlink = hyperlink
+ text_fragments.append(html.escape(atom.text, quote=False))
continue
flush_segments()
if isinstance(atom, InlineMath):
parts.append(f"<eq>{html.escape(atom.latex, quote=False)}</eq>")
- elif isinstance(atom, (InlineBreak, InlinePageBreak)):
+ elif isinstance(atom, InlineBreak):
parts.append("\n")
elif isinstance(atom, InlineImage) and atom.alt:
parts.append(atom.alt)
@@ -203,17 +225,6 @@ def render_atoms_to_model(atoms: Sequence[InlineAtom], *, trim_edges: bool = Fal
return "".join(parts).strip() if trim_edges else "".join(parts)
-def split_atoms_on_page_break(atoms: list[InlineAtom]) -> list[list[InlineAtom]]:
- """按 InlinePageBreak 把一个段落切分为多个逻辑片段。"""
- groups: list[list[InlineAtom]] = [[]]
- for atom in atoms:
- if isinstance(atom, InlinePageBreak):
- groups.append([])
- else:
- groups[-1].append(atom)
- return groups
-
-
class OdfBlockParser:
"""在单个 ODF 包上下文中解析正文、表格和嵌入资源。"""
@@ -229,6 +240,7 @@ class OdfBlockParser:
collect_cell_visuals: bool = False,
shared_cell_visuals: list[dict[str, Any]] | None = None,
anchor_targets: frozenset[str] | None = None,
+ text_expansion_budget: OdfTextExpansionBudget | None = None,
) -> None:
"""绑定单次解析包、样式、子文档路径及可跨 parser 共享的状态。"""
self.package = package
@@ -240,6 +252,7 @@ class OdfBlockParser:
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()
+ self._text_expansion_budget = text_expansion_budget or OdfTextExpansionBudget()
def _append_text_atom(
self,
@@ -254,12 +267,7 @@ class OdfBlockParser:
text = value if preserve_whitespace else _clean_xml_text(value)
if not text:
return
- atom = InlineText(text=text, style=style, hyperlink=hyperlink)
- if atoms and isinstance(atoms[-1], InlineText) and atoms[-1].style == style and atoms[-1].hyperlink == hyperlink:
- previous = atoms[-1]
- atoms[-1] = InlineText(previous.text + text, style, hyperlink)
- else:
- atoms.append(atom)
+ atoms.append(InlineText(text=text, style=style, hyperlink=hyperlink))
def _walk_inlines(
self,
@@ -299,6 +307,7 @@ class OdfBlockParser:
)
elif child.tag == qname("text", "s"):
count = min(_positive_space_count(child.get(qname("text", "c"))), 10_000)
+ self._text_expansion_budget.charge(count)
self._append_text_atom(
atoms,
" " * count,
@@ -311,7 +320,7 @@ class OdfBlockParser:
elif child.tag == qname("text", "line-break"):
atoms.append(InlineBreak())
elif child.tag == qname("text", "soft-page-break"):
- atoms.append(InlinePageBreak())
+ pass
elif child.tag == qname("text", "note"):
self._parse_note(child, style=style, hyperlink=hyperlink, atoms=atoms)
elif child.tag == qname("draw", "frame"):
@@ -382,53 +391,45 @@ class OdfBlockParser:
)
return atoms
- def parse_paragraph(self, paragraph: etree._Element, *, allow_page_breaks: bool = False) -> list[RawFlowItem]:
- """把 text:p/text:h 转为标题、正文、公式及显式分页项。"""
+ def parse_paragraph(self, paragraph: etree._Element) -> list[RawFlowItem]:
+ """把 text:p/text:h 转为标题、正文、公式和段外内容。"""
atoms = self.parse_inline_atoms(paragraph)
- groups = (
- split_atoms_on_page_break(atoms)
- if allow_page_breaks
- else [[InlineBreak() if isinstance(atom, InlinePageBreak) else atom for atom in atoms]]
- )
results: list[RawFlowItem] = []
is_heading = paragraph.tag == qname("text", "h")
style_name = paragraph.get(qname("text", "style-name"))
- for group_index, group in enumerate(groups):
- content_atoms = [atom for atom in group if not isinstance(atom, (InlineBlockGroup, InlineNote))]
- content = render_atoms_to_model(content_atoms, trim_edges=True)
- math_atoms = [atom for atom in content_atoms if isinstance(atom, InlineMath)]
- visible_text = "".join(atom.text for atom in content_atoms if isinstance(atom, InlineText)).strip()
- if content:
- if math_atoms and not visible_text and len(math_atoms) == 1 and len(group) == 1:
- 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 := _paragraph_anchor(paragraph):
- block["anchor"] = anchor
- results.append(block)
- elif is_heading:
- try:
- outline_level = int(paragraph.get(qname("text", "outline-level"), "1"))
- except ValueError:
- outline_level = 1
- block = {
- "type": BlockType.PARAGRAPH_TITLE,
- "level": min(max(outline_level + 1, 2), 6),
- "is_numbered_style": False,
- "content": content,
- }
- if anchor := _paragraph_anchor(paragraph):
- block["anchor"] = anchor
- results.append(block)
- else:
- results.append({"type": BlockType.TEXT, "content": content})
- for atom in group:
- if isinstance(atom, InlineBlockGroup):
- results.extend(atom.blocks)
- elif isinstance(atom, InlineNote):
- results.append(atom)
- if group_index < len(groups) - 1:
- results.append(PAGE_BREAK)
+ content_atoms = [atom for atom in atoms if not isinstance(atom, (InlineBlockGroup, InlineNote))]
+ content = render_atoms_to_model(content_atoms, trim_edges=True)
+ math_atoms = [atom for atom in content_atoms if isinstance(atom, InlineMath)]
+ visible_text = "".join(atom.text for atom in content_atoms if isinstance(atom, InlineText)).strip()
+ if content:
+ if math_atoms and not visible_text and len(math_atoms) == 1 and len(content_atoms) == 1:
+ 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 := _paragraph_anchor(paragraph):
+ block["anchor"] = anchor
+ results.append(block)
+ elif is_heading:
+ try:
+ outline_level = int(paragraph.get(qname("text", "outline-level"), "1"))
+ except ValueError:
+ outline_level = 1
+ block = {
+ "type": BlockType.PARAGRAPH_TITLE,
+ "level": min(max(outline_level + 1, 2), 6),
+ "is_numbered_style": False,
+ "content": content,
+ }
+ if anchor := _paragraph_anchor(paragraph):
+ block["anchor"] = anchor
+ results.append(block)
+ else:
+ results.append({"type": BlockType.TEXT, "content": content})
+ for atom in atoms:
+ if isinstance(atom, InlineBlockGroup):
+ results.extend(atom.blocks)
+ elif isinstance(atom, InlineNote):
+ results.append(atom)
return results
def parse_list(
@@ -437,21 +438,14 @@ class OdfBlockParser:
*,
depth: int = 0,
inherited_style: str | None = None,
- allow_page_breaks: bool = False,
- ) -> list[RawFlowItem]:
+ ) -> list[dict[str, Any]]:
"""递归构造严格 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,
- allow_page_breaks=allow_page_breaks,
- )
+ return self._parse_list_items(element, items, depth=depth, inherited_style=inherited_style)
def _parse_list_items(
self,
@@ -460,8 +454,7 @@ class OdfBlockParser:
*,
depth: int,
inherited_style: str | None,
- allow_page_breaks: bool,
- ) -> list[RawFlowItem]:
+ ) -> list[dict[str, Any]]:
"""按源条目构造 LIST 分片,每个条目只保留一个文本叶子和一个 marker。"""
style_name = element.get(qname("text", "style-name")) or inherited_style
level = self.styles.list_level(style_name, depth)
@@ -472,13 +465,11 @@ 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[RawFlowItem] = []
+ results: list[dict[str, Any]] = []
content: list[dict[str, Any]] = []
- pending_notes: list[InlineNote] = []
item_count = 0
- fragment_start = start
- def flush_content() -> None:
+ def flush_content(fragment_start: int) -> None:
"""把当前合法子块冻结为一个 LIST 分片。"""
if not content:
return
@@ -493,60 +484,28 @@ class OdfBlockParser:
results.append(block)
content.clear()
- 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()
-
+ fragment_start = start
for item in items:
is_header = item.tag == qname("text", "list-header")
if not is_header:
- try:
- item_start = int(item.get(qname("text", "start-value"), str(start + item_count)))
- if item_count == 0:
+ if item_count == 0:
+ try:
+ item_start = int(item.get(qname("text", "start-value"), str(start)))
start = max(0, item_start)
- except ValueError:
- pass
+ fragment_start = start
+ except ValueError:
+ pass
+ # 统一 LIST 只支持列表级起始值,后续逐项重启按连续序号投影。
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)
+ self.notes.append(block.content)
continue
block_type = block.get("type")
block_content = block.get("content")
@@ -563,53 +522,28 @@ class OdfBlockParser:
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")}:
- consume_flow(self.parse_paragraph(child, allow_page_breaks=allow_page_breaks))
+ consume_flow(self.parse_paragraph(child))
elif child.tag == qname("text", "list"):
- consume_nested_flow(
- self.parse_list_blocks(
- child,
- depth=depth + 1,
- inherited_style=style_name,
- allow_page_breaks=allow_page_breaks,
- )
- )
+ 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)
else:
consume_flow(self.parse_container(child))
- flush_item_segment()
-
- flush_content()
- flush_pending_notes()
+ 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)
next_value = start + item_count
self._list_counters[key] = next_value
if list_id := element.get(qname("xml", "id")):
@@ -622,17 +556,11 @@ class OdfBlockParser:
*,
depth: int = 0,
inherited_style: str | None = None,
- allow_page_breaks: bool = False,
- ) -> list[RawFlowItem]:
+ ) -> list[dict[str, Any]]:
"""把含 text:h 的编号章节提升为标题,并保留其余连续列表。"""
if next(element.iter(qname("text", "h")), None) is None:
- return self.parse_list(
- element,
- depth=depth,
- inherited_style=inherited_style,
- allow_page_breaks=allow_page_breaks,
- )
- results: list[RawFlowItem] = []
+ return self.parse_list(element, depth=depth, inherited_style=inherited_style)
+ results: list[dict[str, Any]] = []
pending_items: list[etree._Element] = []
def flush_pending() -> None:
@@ -644,7 +572,6 @@ class OdfBlockParser:
list(pending_items),
depth=depth,
inherited_style=inherited_style,
- allow_page_breaks=allow_page_breaks,
)
pending_items.clear()
results.extend(blocks)
@@ -663,15 +590,9 @@ class OdfBlockParser:
if not isinstance(child.tag, str):
continue
if child.tag in {qname("text", "p"), qname("text", "h")}:
- for parsed in self.parse_paragraph(child, allow_page_breaks=allow_page_breaks):
+ for parsed in self.parse_paragraph(child):
if isinstance(parsed, InlineNote):
- if allow_page_breaks:
- results.append(parsed)
- else:
- self.notes.append(parsed.content)
- continue
- if isinstance(parsed, PageBreakMarker):
- results.append(parsed)
+ self.notes.append(parsed.content)
continue
if child.tag == qname("text", "h") and parsed.get("type") == BlockType.PARAGRAPH_TITLE:
parsed["is_numbered_style"] = True
@@ -682,7 +603,6 @@ class OdfBlockParser:
child,
depth=depth + 1,
inherited_style=element.get(qname("text", "style-name")) or inherited_style,
- allow_page_breaks=allow_page_breaks,
)
)
else:
@@ -794,6 +714,7 @@ class OdfBlockParser:
collect_cell_visuals=self._collect_cell_visuals,
shared_cell_visuals=self._cell_visuals,
anchor_targets=self._anchor_targets,
+ text_expansion_budget=self._text_expansion_budget,
)
chart = parse_chart_block(
object_root,
@@ -1002,8 +923,7 @@ def flatten_block_text(blocks: list[dict[str, Any]]) -> str:
__all__ = [
"OdfBlockParser",
- "PAGE_BREAK",
- "PageBreakMarker",
+ "OdfTextExpansionBudget",
"RawFlowItem",
"flatten_block_text",
"render_atoms_to_html",
diff --git a/tests/unittest/test_flash_epub.py b/tests/unittest/test_flash_epub.py
index abb54079..bc89edb3 100644
--- a/tests/unittest/test_flash_epub.py
+++ b/tests/unittest/test_flash_epub.py
@@ -13,6 +13,7 @@ from lxml import etree
import mineru.model.flash.epub.package as epub_package_module
from mineru.backend.analyze import aio_doc_analyze, doc_analyze
+from mineru.backend.postprocess.lists import fix_office_list_blocks
from mineru.doclib.core.file_io import extract_metadata
from mineru.doclib.core.db import DatabaseManager
from mineru.doclib.core.fts import FTSManager
@@ -156,8 +157,8 @@ def test_epub_notes_use_page_footnote_and_document_wide_anchors() -> None:
assert any(f"](#{first.anchor})" in str(block.get("content", "")) for block in structured_blocks)
-def test_epub_internal_heading_links_and_exact_list_labels_survive() -> None:
- """验证 spine 正文内部标题链接和列表标签保留,不注入 nav/NCX 目录页。"""
+def test_epub_internal_links_and_lists_use_cross_renderer_projection() -> None:
+ """验证 spine 链接保留,列表规范为连续阿拉伯序号且不注入目录页。"""
middle, _ = doc_analyze(build_epub_fixture(), file_suffix="epub")
first_page = middle.pages[0]
second_page = middle.pages[1]
@@ -171,8 +172,38 @@ def test_epub_internal_heading_links_and_exact_list_labels_survive() -> None:
assert "Landmark" not in markdown
assert f"](#{second_title.anchor})" in markdown # type: ignore[union-attr]
assert f"](#{first_title.anchor})" in markdown # type: ignore[union-attr]
- assert "C. Three" in markdown
- assert "B. Two" in markdown
+ assert "3. Three" in markdown
+ assert "4. Two" in markdown
+ list_block = next(block for block in first_page.blocks if block.type == BlockType.LIST)
+ assert [child.content for child in list_block.content] == ["3. Three", "4. Two"]
+ assert all(label in render_html(middle, standalone=False) for label in ("Three", "Two"))
+ structured = render_structured_content(middle)
+ assert any(block.get("content") == "3. Three\n4. Two" for page in structured["pages"] for block in page["blocks"])
+ assert render_docx(middle).startswith(b"PK")
+
+
+def test_epub_hidden_list_items_do_not_consume_normalized_numbers() -> None:
+ """验证隐藏条目先被过滤,统一列表后处理再为可见内容连续编号。"""
+ package = EpubPackage(build_epub_fixture())
+ chapter_path = "EPUB/text/ch1.xhtml"
+ try:
+ root = package.xml_part(chapter_path, allow_external_doctype=True)
+ ordered_list = next(element for element in root.iter() if isinstance(element.tag, str) and element.tag.endswith("}ol"))
+ ordered_list.attrib.pop("start", None)
+ ordered_list.attrib.pop("reversed", None)
+ ordered_list.attrib.pop("type", None)
+ items = [child for child in ordered_list if isinstance(child.tag, str) and child.tag.endswith("}li")]
+ items[0].set("hidden", "hidden")
+ anchors = build_anchor_registry([(chapter_path, root)], package)
+ blocks = EpubChapterConverter(package, chapter_path, root, anchors).convert()
+ list_block = next(block for block in blocks if block["type"] == BlockType.LIST)
+
+ assert list_block["start"] == 1
+ assert list_block["content"] == [{"type": BlockType.TEXT, "content": "Two"}]
+ fix_office_list_blocks([list_block])
+ assert list_block["content"] == [{"type": BlockType.TEXT, "content": "1. Two"}]
+ finally:
+ package.close()
@pytest.mark.parametrize(
diff --git a/tests/unittest/test_flash_odf.py b/tests/unittest/test_flash_odf.py
index 028bc54d..eae1a432 100644
--- a/tests/unittest/test_flash_odf.py
+++ b/tests/unittest/test_flash_odf.py
@@ -14,6 +14,7 @@ import pytest
from lxml import etree
import mineru.model.flash.office.odf.table as odf_table_module
+import mineru.model.flash.office.odf.text as odf_text_module
from mineru.backend.analyze import aio_doc_analyze, doc_analyze
from mineru.doclib.core.file_io import extract_metadata
from mineru.doclib.core.db import DatabaseManager
@@ -37,7 +38,7 @@ from _odf_test_utils import _PIXEL_PNG, build_odf_package, build_odp_fixture, bu
@pytest.mark.parametrize(
("suffix", "model_class", "payload", "page_count"),
[
- ("odt", OdtModel, build_odt_fixture(), 3),
+ ("odt", OdtModel, build_odt_fixture(), 1),
("ods", OdsModel, build_ods_fixture(), 2),
("odp", OdpModel, build_odp_fixture(), 3),
],
@@ -66,11 +67,11 @@ def test_odf_models_and_analyze_keep_flash_contract(
def test_odt_recovers_structure_and_all_renderers() -> None:
- """验证 ODT 标题、富文本、列表、合并表、分页、脚注、公式和图片。"""
+ """验证 ODT 标题、富文本、列表、合并表、连续排版、脚注、公式和图片。"""
middle, model = doc_analyze(build_odt_fixture(), file_suffix="odt")
raw_blocks = [block for page in model.pages for block in page]
raw_types = [block["type"] for block in raw_blocks]
- assert len(model.pages) == 3
+ assert len(model.pages) == 1
assert BlockType.DOC_TITLE in raw_types
assert BlockType.PARAGRAPH_TITLE in raw_types
assert BlockType.LIST in raw_types
@@ -128,6 +129,21 @@ def test_odt_preserves_explicit_space_count() -> None:
assert pages == [[{"type": BlockType.TEXT, "content": "A B"}]]
+def test_odt_explicit_space_expansion_uses_document_budget(monkeypatch: pytest.MonkeyPatch) -> None:
+ """验证多个 text:s 共享文档级预算,并在超限分配前稳定失败。"""
+ monkeypatch.setattr(odf_text_module, "MAX_EXPANSION_TEXT_BYTES", 5)
+ 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:p>A<text:s text:c="3"/>B</text:p><text:p>C<text:s text:c="3"/>D</text:p>
+ </office:text></office:body>
+</office:document-content>"""
+
+ with pytest.raises(OdfResourceLimitError, match="max_expansion_text_bytes=5"):
+ OdtModel().predict(BytesIO(build_odf_package("odt", content)))
+
+
def test_odt_list_lifts_visual_blocks_outside_strict_list() -> None:
"""验证列表段落图片保留原类型并提升为 LIST 的有序兄弟块。"""
content = """<office:document-content
@@ -154,6 +170,35 @@ def test_odt_list_lifts_visual_blocks_outside_strict_list() -> None:
assert [child.content for child in middle.pages[0].blocks[2].content] == ["4. Next item"] # type: ignore[union-attr]
+def test_odt_ordered_list_normalizes_marker_format_and_item_restarts() -> None:
+ """验证 ODF 列表只保留列表级 start,并连续输出阿拉伯序号。"""
+ 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:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0">
+ <office:automatic-styles><text:list-style style:name="L1">
+ <text:list-level-style-number text:level="1" style:num-format="A" style:num-prefix="(" style:num-suffix=")"/>
+ </text:list-style></office:automatic-styles>
+ <office:body><office:text><text:list text:style-name="L1">
+ <text:list-item text:start-value="2"><text:p>First</text:p></text:list-item>
+ <text:list-item text:start-value="9"><text:p>Second</text:p></text:list-item>
+ <text:list-item><text:p>Third</text:p></text:list-item>
+ </text:list></office:text></office:body>
+</office:document-content>"""
+ middle, _ = doc_analyze(build_odf_package("odt", content), file_suffix="odt")
+ expected = ["2. First", "3. Second", "4. Third"]
+ list_block = middle.pages[0].blocks[0]
+
+ assert [child.content for child in list_block.content] == expected # type: ignore[union-attr]
+ assert render_markdown(middle).splitlines() == expected
+ assert all(label in render_html(middle, standalone=False) for label in ("First", "Second", "Third"))
+ structured = render_structured_content(middle)
+ assert structured["pages"][0]["blocks"][0]["content"] == "\n".join(expected)
+ with ZipFile(BytesIO(render_docx(middle))) as package:
+ document_xml = package.read("word/document.xml").decode("utf-8")
+ assert all(label in document_xml for label in expected)
+
+
def test_odt_list_item_joins_multiple_paragraphs_before_markers() -> None:
"""验证一个源 list-item 的多个段落只生成一个 LIST 文本叶子和一个 marker。"""
content = """<office:document-content
@@ -192,8 +237,8 @@ def test_odt_table_cell_renders_inline_image_once() -> None:
assert pages[0][0]["content"].count("<img") == 1
-def test_odt_inline_visual_stays_before_soft_page_break() -> None:
- """验证 soft-page-break 前遇到的段内视觉块仍留在来源逻辑页。"""
+def test_odt_soft_page_break_is_ignored_with_inline_visual() -> None:
+ """验证 soft-page-break 不拆页、不换行且段内视觉块继续保留。"""
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"
@@ -206,14 +251,12 @@ def test_odt_inline_visual_stays_before_soft_page_break() -> None:
pages = OdtModel().predict(BytesIO(build_odf_package("odt", content, extra_parts={"Pictures/pixel.png": _PIXEL_PNG})))
- assert [[block["type"] for block in page] for page in pages] == [
- [BlockType.TEXT, BlockType.IMAGE],
- [BlockType.TEXT],
- ]
+ assert [[block["type"] for block in page] for page in pages] == [[BlockType.TEXT, BlockType.IMAGE]]
+ assert pages[0][0]["content"] == "BeforeAfter"
-def test_odt_list_preserves_soft_page_break_as_logical_page_boundary() -> None:
- """验证列表项内的 soft-page-break 会拆分 ODT 逻辑页且不丢前后文本。"""
+def test_odt_list_ignores_soft_page_break_and_keeps_note_on_current_page() -> None:
+ """验证列表软分页不拆页,连续文本与脚注仍保留在当前章节页。"""
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">
@@ -227,43 +270,47 @@ def test_odt_list_preserves_soft_page_break_as_logical_page_boundary() -> None:
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])
+ assert len(pages) == 1
+ assert pages[0][0]["type"] == BlockType.LIST
+ assert [child["content"] for child in pages[0][0]["content"]] == ["BeforeAfter [1]", "Next"]
+ assert pages[0][1] == {"type": BlockType.PAGE_FOOTNOTE, "content": "[1] After note"}
-def test_odt_child_style_can_reset_inherited_page_breaks() -> None:
- """验证 break-before/after=auto 显式关闭父样式的逻辑分页。"""
+def test_odt_ignores_physical_breaks_and_pages_only_on_master_change() -> None:
+ """验证普通分页样式无效,只有 master-page 章节变化形成虚拟页。"""
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:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0"
xmlns:fo="urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0">
<office:automatic-styles>
- <style:style style:name="Parent" style:family="paragraph">
+ <style:style style:name="ChapterA" style:family="paragraph" style:master-page-name="MasterA"/>
+ <style:style style:name="PhysicalBreak" style:family="paragraph" style:parent-style-name="ChapterA">
<style:paragraph-properties fo:break-before="page" fo:break-after="page"/>
</style:style>
- <style:style style:name="Inherited" style:family="paragraph" style:parent-style-name="Parent"/>
- <style:style style:name="Reset" style:family="paragraph" style:parent-style-name="Parent">
- <style:paragraph-properties fo:break-before="auto" fo:break-after="auto"/>
- </style:style>
+ <style:style style:name="ChapterB" style:family="paragraph" style:master-page-name="MasterB"/>
</office:automatic-styles>
<office:body><office:text>
- <text:p>Before</text:p><text:p text:style-name="Reset">Reset</text:p><text:p>After</text:p>
+ <text:p text:style-name="ChapterA">Before<text:soft-page-break/>Soft</text:p>
+ <text:section><text:p text:style-name="PhysicalBreak">Physical</text:p></text:section>
+ <text:p text:style-name="ChapterB">After</text:p>
</office:text></office:body>
</office:document-content>"""
- inherited_content = content.replace('text:style-name="Reset"', 'text:style-name="Inherited"')
+ styles = """<office:document-styles
+ xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"
+ xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0"
+ xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0">
+ <office:master-styles>
+ <style:master-page style:name="MasterA"><style:header><text:p>Header A</text:p></style:header></style:master-page>
+ <style:master-page style:name="MasterB"><style:header><text:p>Header B</text:p></style:header></style:master-page>
+ </office:master-styles>
+</office:document-styles>"""
- reset_pages = OdtModel().predict(BytesIO(build_odf_package("odt", content)))
- inherited_pages = OdtModel().predict(BytesIO(build_odf_package("odt", inherited_content)))
+ pages = OdtModel().predict(BytesIO(build_odf_package("odt", content, styles_xml=styles)))
- assert [[block.get("content") for block in page] for page in reset_pages] == [["Before", "Reset", "After"]]
- assert [[block.get("content") for block in page] for page in inherited_pages] == [
- ["Before"],
- ["Reset"],
- ["After"],
+ assert [[block.get("content") for block in page] for page in pages] == [
+ ["BeforeSoft", "Physical", "Header A"],
+ ["After", "Header B"],
]
@@ -293,8 +340,8 @@ def test_odf_covered_placeholder_reuses_colspan_coordinate() -> None:
assert [cell.html if cell is not None else None for cell in grid.rows[1]] == ["A", "B", "C"]
-def test_odt_note_after_soft_page_break_stays_on_new_page() -> None:
- """验证 soft-page-break 后的 note reference 和正文归属同一新页。"""
+def test_odt_note_after_soft_page_break_stays_on_current_page() -> None:
+ """验证 soft-page-break 被忽略后 note reference 和正文仍归属当前章节页。"""
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">
@@ -306,11 +353,10 @@ def test_odt_note_after_soft_page_break_stays_on_new_page() -> None:
pages = OdtModel().predict(BytesIO(build_odf_package("odt", content)))
assert pages == [
- [{"type": BlockType.TEXT, "content": "Before"}],
[
- {"type": BlockType.TEXT, "content": "After [1]"},
+ {"type": BlockType.TEXT, "content": "BeforeAfter [1]"},
{"type": BlockType.PAGE_FOOTNOTE, "content": "[1] After note"},
- ],
+ ]
]
@@ -381,6 +427,46 @@ def test_ods_skips_hidden_sheet_and_emits_tables_images_and_charts() -> None:
assert len(middle.pages) == 2
+def test_ods_resolves_inherited_table_visibility_with_child_override() -> None:
+ """验证 table display 沿父样式继承,且子样式显式显示可以覆盖隐藏。"""
+ content = """<office:document-content
+ xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"
+ xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0"
+ xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0"
+ xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0">
+ <office:automatic-styles>
+ <style:style style:name="HiddenParent" style:family="table">
+ <style:table-properties table:display="false"/>
+ </style:style>
+ <style:style style:name="InheritedHidden" style:family="table" style:parent-style-name="HiddenParent"/>
+ <style:style style:name="ExplicitVisible" style:family="table" style:parent-style-name="HiddenParent">
+ <style:table-properties table:display="true"/>
+ </style:style>
+ </office:automatic-styles>
+ <office:body><office:spreadsheet>
+ <table:table table:name="Secret" table:style-name="InheritedHidden">
+ <table:table-row><table:table-cell><text:p>secret</text:p></table:table-cell></table:table-row>
+ </table:table>
+ <table:table table:name="Override" table:style-name="ExplicitVisible">
+ <table:table-row><table:table-cell><text:p>override</text:p></table:table-cell></table:table-row>
+ </table:table>
+ <table:table table:name="DefaultVisible">
+ <table:table-row><table:table-cell><text:p>default</text:p></table:table-cell></table:table-row>
+ </table:table>
+ </office:spreadsheet></office:body>
+</office:document-content>"""
+ payload = build_odf_package("ods", content)
+
+ pages = OdsModel().predict(BytesIO(payload))
+ metadata = extract_odf_metadata(BytesIO(payload), "ods")
+
+ assert len(pages) == 2
+ assert "secret" not in str(pages)
+ assert "override" in str(pages)
+ assert "default" in str(pages)
+ assert metadata["page_count"] == 2
+
+
@pytest.mark.parametrize(
("suffix", "payload"),
[("odt", build_odt_fixture()), ("ods", build_ods_fixture()), ("odp", build_odp_fixture())],