Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
fix(rag): preserve omitted Word table columns (#2961)
SIcheng Hanac857143b2a8
diff --git a/src/agentscope/rag/_parser/_word.py b/src/agentscope/rag/_parser/_word.pyindex 89cac0c5b..44f729d3e 100644--- a/src/agentscope/rag/_parser/_word.py+++ b/src/agentscope/rag/_parser/_word.py@@ -76,7 +76,9 @@ def _extract_table_data(table: DocxTable) -> list[list[str]]:within cells.Horizontal merges (``w:gridSpan``) are expanded with empty strings so- that every row has the same number of columns. Vertically merged+ that every row has the same number of columns. Omitted leading and+ trailing cells (``w:gridBefore`` / ``w:gridAfter``) are also padded to+ preserve their grid positions. Vertically mergedcontinuation cells (``w:vMerge`` without ``val="restart"``) are keptas-is — their XML content is typically empty, which is the desiredbehaviour for downstream renderers.@@ -88,6 +90,9 @@ def _extract_table_data(table: DocxTable) -> list[list[str]]:table_data: list[list[str]] = []for tr in table._element.findall(qn("w:tr")):row_data: list[str] = []+ grid_before = tr.find(f"{qn('w:trPr')}/{qn('w:gridBefore')}")+ if grid_before is not None:+ row_data.extend([""] * int(grid_before.get(qn("w:val"), "0")))for tc in tr.findall(qn("w:tc")):paragraphs: list[str] = []# Include paragraphs of tables nested in this cell.@@ -112,6 +117,9 @@ def _extract_table_data(table: DocxTable) -> list[list[str]]:)row_data.extend([""] * (span - 1))+ grid_after = tr.find(f"{qn('w:trPr')}/{qn('w:gridAfter')}")+ if grid_after is not None:+ row_data.extend([""] * int(grid_after.get(qn("w:val"), "0")))table_data.append(row_data)return table_datadiff --git a/tests/rag_parser_test.py b/tests/rag_parser_test.pyindex 286d49292..572647914 100644--- a/tests/rag_parser_test.py+++ b/tests/rag_parser_test.py@@ -7,6 +7,7 @@ run anywhere ``agentscope[rag]`` is installed."""import base64import io+import jsonimport osimport zipfilefrom unittest.async_case import IsolatedAsyncioTestCase@@ -1703,6 +1704,71 @@ class WordParserTest(IsolatedAsyncioTestCase):],)+ async def test_omitted_table_cells_keep_column_alignment(self) -> None:+ """Omitted cells must not shift columns or truncate later rows."""+ # python-docx has no public setter for omitted grid positions.+ # pylint: disable=protected-access+ from docx import Document+ from docx.oxml import OxmlElement+ from docx.oxml.ns import qn++ doc = Document()+ table = doc.add_table(rows=4, cols=4)+ values = [+ ["unused", "B", "C", "unused"],+ ["a", "b", "c", "d"],+ ["unused", "wide", "unused", "last"],+ ["unused", "unused", "tail", "unused"],+ ]+ for row, cells in zip(table.rows, values):+ for cell, text in zip(row.cells, cells):+ cell.text = text+ table.cell(2, 1).merge(table.cell(2, 2)).text = "wide"+ for row, (before, after) in zip(+ table.rows,+ [(1, 1), (0, 0), (1, 0), (2, 1)],+ ):+ for tag, count, index in (+ ("w:gridBefore", before, 0),+ ("w:gridAfter", after, -1),+ ):+ if count:+ for _ in range(count):+ row._tr.remove(row._tr.tc_lst[index])+ omitted = OxmlElement(tag)+ omitted.set(qn("w:val"), str(count))+ row._tr.get_or_add_trPr().append(omitted)+ buffer = io.BytesIO()+ doc.save(buffer)++ for table_format in ("markdown", "json"):+ with self.subTest(table_format=table_format):+ sections = await WordParser(+ table_format=table_format,+ separate_table=True,+ ).parse(buffer.getvalue(), "omitted.docx")+ self.assertEqual(len(sections), 1)+ text = sections[0].content.text+ if table_format == "markdown":+ self.assertEqual(+ text,+ "| | B | C | |\n"+ "| --- | --- | --- | --- |\n"+ "| a | b | c | d |\n"+ "| | wide | | last |\n"+ "| | | tail | |\n",+ )+ else:+ self.assertEqual(+ json.loads(text.split("\n", 1)[1]),+ [+ ["", "B", "C", ""],+ ["a", "b", "c", "d"],+ ["", "wide", "", "last"],+ ["", "", "tail", ""],+ ],+ )+async def test_nested_table_text_is_kept(self) -> None:"""Text inside a table nested in another cell must survive parsing."""docx_bytes = _make_docx_with_nested_table()