Skip to content

Build and run agents you can see, understand and trust.

fix(word): preserve inline tabs and breaks in Word paragraphs (#2840)

Xscaper-1f2058e46b94
diff --git a/src/agentscope/rag/_parser/_word.py b/src/agentscope/rag/_parser/_word.py
index 4222d6e31..762e76d59 100644
--- a/src/agentscope/rag/_parser/_word.py
+++ b/src/agentscope/rag/_parser/_word.py
@@ -50,7 +50,8 @@ def _extract_text_from_paragraph(para: DocxParagraph) -> str:
``mc:Fallback`` copy of a text box as a second occurrence of the same text.
Each ``mc:AlternateContent`` containing a text box uses the first branch
with readable Word text, retaining the fallback when its choices cannot
- supply any text. Other paragraph content keeps its original behavior.
+ supply any text. Run-level tabs and soft line breaks are preserved in
+ both the paragraph and its text boxes.
Args:
para (`DocxParagraph`):
@@ -64,11 +65,22 @@ def _extract_text_from_paragraph(para: DocxParagraph) -> str:
text_tag = qn("w:t")
text_box_tag = qn("w:txbxContent")
+ deleted_tag = qn("w:del")
+ run_tag = qn("w:r")
+ tab_tag = qn("w:tab")
+ carriage_return_tag = qn("w:cr")
+ separator_tags = {tab_tag, carriage_return_tag, qn("w:br")}
root = para._element
def iter_text(element: Any) -> Iterator[Any]:
- """Visit text in one readable branch of each AlternateContent."""
- if element.tag == text_tag:
+ """Visit text and inline separators in one readable branch."""
+ if element.tag == deleted_tag:
+ # Deleted runs must not contribute text or inline separators.
+ return
+ if element.tag == text_tag or (
+ element.tag in separator_tags
+ and element.getparent().tag == run_tag
+ ):
yield element
elif (
element.tag == _MC_ALTERNATE_CONTENT
@@ -77,7 +89,11 @@ def _extract_text_from_paragraph(para: DocxParagraph) -> str:
texts: list[Any] = []
for branch in element:
texts = list(iter_text(branch))
- if any(t.text and t.text.strip() for t in texts):
+ # Separators alone must not hide a readable fallback.
+ if any(
+ text.tag == text_tag and text.text and text.text.strip()
+ for text in texts
+ ):
break
yield from texts
else:
@@ -86,21 +102,34 @@ def _extract_text_from_paragraph(para: DocxParagraph) -> str:
own_parts: list[str] = []
text_boxes: dict[Any, list[str]] = {}
- for text in iter_text(root):
- if not text.text:
+ for element in iter_text(root):
+ if element.tag == text_tag:
+ value = element.text or ""
+ elif element.tag == tab_tag:
+ value = "\t"
+ elif element.tag == carriage_return_tag:
+ value = "\n"
+ elif element.get(qn("w:type"), "textWrapping") == "textWrapping":
+ value = "\n"
+ else:
+ # Page and column breaks do not contribute text.
+ value = ""
+ if not value:
continue
parts = own_parts
- for ancestor in text.iterancestors():
+ for ancestor in element.iterancestors():
if ancestor is root:
break
if ancestor.tag == text_box_tag:
parts = text_boxes.setdefault(ancestor, [])
break
- parts.append(text.text)
+ parts.append(value)
own_text = "".join(own_parts)
- if not own_text and not text_boxes:
- # python-docx also reads characters such as w:noBreakHyphen.
+ if not own_text.strip() and not any(
+ "".join(parts).strip() for parts in text_boxes.values()
+ ):
+ # Separator-only extraction must not hide w:noBreakHyphen, etc.
own_text = para.text
blocks = [own_text, *("".join(parts) for parts in text_boxes.values())]
return "\n".join(block.strip() for block in blocks if block.strip())
diff --git a/tests/rag_parser_test.py b/tests/rag_parser_test.py
index ec557f186..e787b0ea1 100644
--- a/tests/rag_parser_test.py
+++ b/tests/rag_parser_test.py
@@ -2875,6 +2875,178 @@ class WordParserTest(IsolatedAsyncioTestCase):
WordParser(table_format="csv") # type: ignore[arg-type]
+class WordParserInlineSeparatorTest(IsolatedAsyncioTestCase):
+ """Regression coverage for inline tabs and breaks in Word paragraphs."""
+
+ async def test_inline_tabs_and_soft_breaks_are_preserved(self) -> None:
+ """Tabs and consecutive soft breaks remain inside a paragraph."""
+ from docx import Document as DocxDocument
+
+ expected = "Name\tAlice\nDepartment\t\tEngineering\n\nEnd"
+ docx_bytes = _make_docx_simple([expected])
+ self.assertEqual(
+ DocxDocument(io.BytesIO(docx_bytes)).paragraphs[0].text,
+ expected,
+ )
+
+ sections = await WordParser(include_image=False).parse(
+ docx_bytes,
+ "inline.docx",
+ )
+
+ self.assertEqual([s.content.text for s in sections], [expected])
+
+ async def test_inline_separators_across_runs_keep_order(self) -> None:
+ """Separators in their own runs retain their position and count."""
+ from docx import Document as DocxDocument
+
+ doc = DocxDocument()
+ paragraph = doc.add_paragraph()
+ parts = ["First", "\t", "second", "\n\t", "third", "\n", "last"]
+ for part in parts:
+ paragraph.add_run(part)
+ buffer = io.BytesIO()
+ doc.save(buffer)
+
+ sections = await WordParser(include_image=False).parse(
+ buffer.getvalue(),
+ "runs.docx",
+ )
+
+ self.assertEqual(
+ [s.content.text for s in sections],
+ ["First\tsecond\n\tthird\nlast"],
+ )
+
+ async def test_inline_break_types(self) -> None:
+ """Text wrapping and carriage returns differ from layout breaks."""
+ from docx import Document as DocxDocument
+ from docx.oxml import parse_xml
+ from docx.oxml.ns import nsdecls
+
+ doc = DocxDocument()
+ paragraph = doc.add_paragraph()
+ run = parse_xml(
+ f'<w:r {nsdecls("w")}>'
+ "<w:t>One</w:t><w:cr/><w:t>Two</w:t>"
+ '<w:br w:type="textWrapping"/><w:t>Three</w:t>'
+ '<w:br w:type="page"/><w:t>Four</w:t>'
+ '<w:br w:type="column"/><w:t>Five</w:t></w:r>',
+ )
+ paragraph._element.append(run) # pylint: disable=protected-access
+ buffer = io.BytesIO()
+ doc.save(buffer)
+
+ sections = await WordParser(include_image=False).parse(
+ buffer.getvalue(),
+ "breaks.docx",
+ )
+
+ self.assertEqual(
+ [s.content.text for s in sections],
+ ["One\nTwo\nThreeFourFive"],
+ )
+
+ async def test_inline_separators_in_hyperlinks_and_revisions(self) -> None:
+ """Nested runs keep both their text and their inline separators."""
+ from docx import Document as DocxDocument
+ from docx.oxml import parse_xml
+ from docx.oxml.ns import nsdecls
+
+ doc = DocxDocument()
+ paragraph = doc.add_paragraph("Before ")
+ hyperlink = parse_xml(
+ f'<w:hyperlink {nsdecls("w")} w:anchor="bookmark">'
+ "<w:r><w:t>linked</w:t><w:tab/><w:t>label</w:t></w:r>"
+ "</w:hyperlink>",
+ )
+ # pylint: disable-next=protected-access
+ paragraph._element.append(hyperlink)
+ paragraph.add_run(" ")
+ revision = parse_xml(
+ f'<w:ins {nsdecls("w")} w:id="1" w:author="test">'
+ "<w:r><w:t>revised</w:t><w:br/><w:t>text</w:t></w:r></w:ins>",
+ )
+ paragraph._element.append(revision) # pylint: disable=protected-access
+ paragraph.add_run(" after")
+ buffer = io.BytesIO()
+ doc.save(buffer)
+
+ sections = await WordParser(include_image=False).parse(
+ buffer.getvalue(),
+ "nested-runs.docx",
+ )
+
+ self.assertEqual(
+ [s.content.text for s in sections],
+ ["Before linked\tlabel revised\ntext after"],
+ )
+
+ async def test_deleted_inline_separators_are_ignored(self) -> None:
+ """Deleted separators are omitted while inserted ones are kept."""
+ from docx import Document as DocxDocument
+ from docx.oxml import parse_xml
+ from docx.oxml.ns import nsdecls
+
+ for separator, expected in (("tab", "\t"), ("br", "\n"), ("cr", "\n")):
+ with self.subTest(separator=separator):
+ doc = DocxDocument()
+ paragraph = doc.add_paragraph("Before")
+ deleted = parse_xml(
+ f'<w:del {nsdecls("w")} w:id="1" w:author="test">'
+ "<w:r><w:delText>removed</w:delText>"
+ f"<w:{separator}/></w:r></w:del>",
+ )
+ # pylint: disable-next=protected-access
+ paragraph._element.append(deleted)
+ paragraph.add_run("After")
+ inserted = parse_xml(
+ f'<w:ins {nsdecls("w")} w:id="2" w:author="test">'
+ f"<w:r><w:{separator}/><w:t>Inserted</w:t></w:r>"
+ "</w:ins>",
+ )
+ # pylint: disable-next=protected-access
+ paragraph._element.append(inserted)
+ buffer = io.BytesIO()
+ doc.save(buffer)
+
+ sections = await WordParser(include_image=False).parse(
+ buffer.getvalue(),
+ "demo.docx",
+ )
+
+ self.assertEqual(
+ [section.model_dump() for section in sections],
+ _expected_word_sections(f"BeforeAfter{expected}Inserted"),
+ )
+
+ async def test_inline_separators_preserve_text_fallback(self) -> None:
+ """Separators alone do not hide non-w:t text from the fallback."""
+ from docx import Document as DocxDocument
+ from docx.oxml import parse_xml
+ from docx.oxml.ns import nsdecls
+
+ for separator in ("tab", "br"):
+ with self.subTest(separator=separator):
+ doc = DocxDocument()
+ paragraph = doc.add_paragraph()
+ run = parse_xml(
+ f'<w:r {nsdecls("w")}>'
+ f"<w:noBreakHyphen/><w:{separator}/></w:r>",
+ )
+ # pylint: disable-next=protected-access
+ paragraph._element.append(run)
+ buffer = io.BytesIO()
+ doc.save(buffer)
+
+ sections = await WordParser(include_image=False).parse(
+ buffer.getvalue(),
+ "fallback.docx",
+ )
+
+ self.assertEqual([s.content.text for s in sections], ["-"])
+
+
class WordParserParagraphTest(IsolatedAsyncioTestCase):
"""Regression coverage for paragraph and text-box extraction."""
@@ -2947,6 +3119,82 @@ class WordParserParagraphTest(IsolatedAsyncioTestCase):
_expected_word_sections("Paragraph text\nCallout\nAfter"),
)
+ async def test_inline_separators_with_text_box_branches(self) -> None:
+ """Preserve inline separators while reading each text box once."""
+ for name, template in (
+ ("modern", _DOCX_MODERN_TEXT_BOX),
+ ("with_fallback", _DOCX_TEXT_BOX_WITH_VML_FALLBACK),
+ ):
+ with self.subTest(shape=name):
+ template = template.replace(
+ "<w:t>{before}</w:t>",
+ "<w:t>Before</w:t><w:tab/><w:t>text</w:t>",
+ ).replace(
+ "<w:t>{inside}</w:t>",
+ "<w:t>Callout</w:t><w:tab/><w:t>value</w:t>"
+ "<w:br/><w:t>next</w:t>",
+ )
+ sections = await WordParser(include_image=False).parse(
+ _make_docx_with_text_box(template),
+ "demo.docx",
+ )
+ self.assertEqual(
+ [section.model_dump() for section in sections],
+ _expected_word_sections(
+ "Before\ttext\nCallout\tvalue\nnext\nAfter",
+ ),
+ )
+
+ async def test_separator_only_choice_keeps_readable_fallback(
+ self,
+ ) -> None:
+ """Inline separators alone do not make a text-box branch readable."""
+ for choice_xml in (
+ "<w:tab/>",
+ "<w:br/>",
+ "<w:cr/>",
+ "<w:tab/><w:br/><w:cr/>",
+ ):
+ with self.subTest(choice_xml=choice_xml):
+ template = _DOCX_TEXT_BOX_WITH_VML_FALLBACK.replace(
+ "<w:t>{inside}</w:t>",
+ choice_xml,
+ 1,
+ )
+ sections = await WordParser(include_image=False).parse(
+ _make_docx_with_text_box(template),
+ "demo.docx",
+ )
+ self.assertEqual(
+ [section.model_dump() for section in sections],
+ _expected_word_sections("Paragraph text\nCallout\nAfter"),
+ )
+
+ async def test_separator_only_text_box_keeps_paragraph_fallback(
+ self,
+ ) -> None:
+ """Text-box separators do not hide non-w:t paragraph characters."""
+ for name, template in (
+ ("modern", _DOCX_MODERN_TEXT_BOX),
+ ("with_fallback", _DOCX_TEXT_BOX_WITH_VML_FALLBACK),
+ ):
+ with self.subTest(shape=name):
+ template = template.replace(
+ "<w:t>{before}</w:t>",
+ "<w:noBreakHyphen/><w:tab/>",
+ ).replace(
+ "<w:t>{inside}</w:t>",
+ "<w:tab/><w:br/>",
+ )
+ sections = await WordParser(include_image=False).parse(
+ _make_docx_with_text_box(template),
+ "demo.docx",
+ )
+ self.assertEqual(
+ [section.model_dump() for section in sections],
+ _expected_word_sections("-\nAfter"),
+ )
+
async def test_text_box_fallback_is_used_without_readable_choice(
self,
) -> None: