Skip to content

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

fix: buffer RTF text and preserve ODF spaces

myhlolie3faeff6506f
diff --git a/mineru/model/flash/office/odf/text.py b/mineru/model/flash/office/odf/text.py
index f4ee63fd..51741980 100644
--- a/mineru/model/flash/office/odf/text.py
+++ b/mineru/model/flash/office/odf/text.py
@@ -248,9 +248,10 @@ class OdfBlockParser:
*,
style: TextStyle,
hyperlink: str | None,
+ preserve_whitespace: bool = False,
) -> None:
- """清理并追加一个文本节点,同时合并相邻同样式片段。"""
- text = _clean_xml_text(value)
+ """清理并追加文本节点;显式 ODF 空格可跳过普通 XML 空白折叠。"""
+ text = value if preserve_whitespace else _clean_xml_text(value)
if not text:
return
atom = InlineText(text=text, style=style, hyperlink=hyperlink)
@@ -298,7 +299,13 @@ class OdfBlockParser:
)
elif child.tag == qname("text", "s"):
count = min(_positive_space_count(child.get(qname("text", "c"))), 10_000)
- self._append_text_atom(atoms, " " * count, style=style, hyperlink=hyperlink)
+ self._append_text_atom(
+ atoms,
+ " " * count,
+ style=style,
+ hyperlink=hyperlink,
+ preserve_whitespace=True,
+ )
elif child.tag == qname("text", "tab"):
self._append_text_atom(atoms, " ", style=style, hyperlink=hyperlink)
elif child.tag == qname("text", "line-break"):
diff --git a/mineru/model/flash/office/rtf/parser.py b/mineru/model/flash/office/rtf/parser.py
index 2a142ec6..e2e14b72 100644
--- a/mineru/model/flash/office/rtf/parser.py
+++ b/mineru/model/flash/office/rtf/parser.py
@@ -362,6 +362,8 @@ class _OutputContext:
blocks: list[RtfBlock] = field(default_factory=list)
inlines: list[RtfInline] = field(default_factory=list)
+ text_fragments: list[str] = field(default_factory=list)
+ text_style: RtfTextStyle | None = None
pending_list_label: str | None = None
tables: dict[int, _TableBuilder] = field(default_factory=dict)
@@ -903,6 +905,7 @@ class RtfParser:
self.state.destination = "suppressed"
return True
if name == "field":
+ self._flush_text_run()
frame.destination = "field"
frame.inline_start = len(self.context.inlines)
return True
@@ -996,10 +999,11 @@ class RtfParser:
elif destination == "bookmark":
name = "".join(frame.capture_text).strip()
if name:
- self.context.inlines.append(RtfAnchor(name))
+ self._append_inline(RtfAnchor(name))
def _finish_field(self, frame: _GroupFrame) -> None:
"""把安全 HYPERLINK field result 包装回行内 run。"""
+ self._flush_text_run()
instruction = "".join(frame.instruction).strip()
match = _HYPERLINK_RE.search(instruction)
if match is None:
@@ -1024,7 +1028,7 @@ class RtfParser:
return
note_id = f"rtf{len(self.document.notes)}"
self.document.notes.append(RtfNote(note_id, frame.note_kind, note_context.blocks))
- self.context.inlines.append(RtfNoteReference(note_id))
+ self._append_inline(RtfNoteReference(note_id))
def _finish_auxiliary(self, frame: _GroupFrame, destination: str) -> None:
"""结束页眉页脚隔离 context,并恢复父正文。"""
@@ -1041,7 +1045,7 @@ class RtfParser:
return
image = self._materialize_picture(capture)
if image is not None:
- self.context.inlines.append(image)
+ self._append_inline(image)
def _materialize_picture(self, capture: _PictCapture) -> RtfImage | None:
"""把已捕获 pict 转成有界图片载荷,并累计文档素材预算。"""
@@ -1084,7 +1088,7 @@ class RtfParser:
continue
image = self._materialize_picture(capture)
if image is not None:
- self.context.inlines.append(image)
+ self._append_inline(image)
break
return
if display:
@@ -1092,7 +1096,8 @@ class RtfParser:
self._flush_tables()
self.context.blocks.extend(RtfDisplayEquation(formula) for formula in formulas)
else:
- self.context.inlines.extend(RtfInlineEquation(formula) for formula in formulas)
+ for formula in formulas:
+ self._append_inline(RtfInlineEquation(formula))
def _control_symbol(self, token: RtfControlSymbol) -> None:
"""处理 ignorable marker、转义结构字符和特殊空白。"""
@@ -1374,15 +1379,23 @@ class RtfParser:
return
if self.state.destination != "body":
return
- self._append_inline(RtfTextRun(text=text, style=self.state.style))
+ if self.context.text_fragments and self.context.text_style != self.state.style:
+ self._flush_text_run()
+ self.context.text_style = self.state.style
+ self.context.text_fragments.append(text)
+
+ def _flush_text_run(self) -> None:
+ """把当前 context 的相邻文本片段一次性合并为 typed run。"""
+ if not self.context.text_fragments:
+ return
+ style = self.context.text_style if self.context.text_style is not None else RtfTextStyle()
+ self.context.inlines.append(RtfTextRun(text="".join(self.context.text_fragments), style=style))
+ self.context.text_fragments.clear()
+ self.context.text_style = None
def _append_inline(self, inline: RtfInline) -> None:
- """追加行内节点,并合并样式和链接完全相同的相邻文本 run。"""
- if isinstance(inline, RtfTextRun) and self.context.inlines:
- previous = self.context.inlines[-1]
- if isinstance(previous, RtfTextRun) and previous.style == inline.style and previous.hyperlink == inline.hyperlink:
- self.context.inlines[-1] = replace(previous, text=f"{previous.text}{inline.text}")
- return
+ """先冻结累计文本,再追加公式、图片、锚点等结构行内节点。"""
+ self._flush_text_run()
self.context.inlines.append(inline)
def _resolve_list_info(self) -> RtfListInfo | None:
@@ -1425,6 +1438,7 @@ class RtfParser:
if self._pending_high_surrogate is not None:
self._append_text("\ufffd")
self._pending_high_surrogate = None
+ self._flush_text_run()
inlines = self.context.inlines
self.context.inlines = []
list_info = self._resolve_list_info()
diff --git a/tests/unittest/test_flash_odf.py b/tests/unittest/test_flash_odf.py
index 08699c08..0558d8e5 100644
--- a/tests/unittest/test_flash_odf.py
+++ b/tests/unittest/test_flash_odf.py
@@ -115,6 +115,19 @@ def test_odt_promotes_numbered_heading_inside_list() -> None:
assert middle.pages[0].blocks[0].content == "1 Chapter" # type: ignore[union-attr]
+def test_odt_preserves_explicit_space_count() -> None:
+ """验证 text:s 的显式重复空格不会被普通 XML 空白规则折叠。"""
+ 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="4"/>B</text:p></office:text></office:body>
+</office:document-content>"""
+
+ pages = OdtModel().predict(BytesIO(build_odf_package("odt", content)))
+
+ assert pages == [[{"type": BlockType.TEXT, "content": "A B"}]]
+
+
def test_odt_list_lifts_visual_blocks_outside_strict_list() -> None:
"""验证列表段落图片保留原类型并提升为 LIST 的有序兄弟块。"""
content = """<office:document-content
diff --git a/tests/unittest/test_flash_rtf.py b/tests/unittest/test_flash_rtf.py
index b02d3302..a9273be2 100644
--- a/tests/unittest/test_flash_rtf.py
+++ b/tests/unittest/test_flash_rtf.py
@@ -6,6 +6,7 @@ import subprocess
import sys
import tracemalloc
from pathlib import Path
+from unittest.mock import patch
import pytest
@@ -77,6 +78,23 @@ def test_rtf_font_codepages_and_unicode_surrogates_are_exact() -> None:
assert pages == [[{"type": BlockType.TEXT, "content": "Привет こんにちは 😀"}]]
+def test_rtf_unicode_controls_buffer_adjacent_text_without_repeated_run_copy() -> None:
+ """验证逐字符 Unicode control 只在边界处物化文本 run。"""
+ count = 5_000
+ source = b"{\\rtf1\\ansi\\uc1 " + b"\\u20013?" * count + b"\\par}"
+
+ with patch.object(parser_module, "replace", wraps=parser_module.replace) as replace_mock:
+ pages = RtfModel().predict(BytesIO(source))
+
+ text_replacements = [
+ call
+ for call in replace_mock.call_args_list
+ if isinstance(call.args[0], parser_module.RtfTextRun) and "text" in call.kwargs
+ ]
+ assert pages == [[{"type": BlockType.TEXT, "content": "中" * count}]]
+ assert text_replacements == []
+
+
def test_rtf_inherited_style_honors_explicit_formatting_resets() -> None:
"""验证 derived stylesheet 的 b0/i0/ul0/strike0 覆盖基样式开启值。"""
source = (