Skip to content

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

fix(rag): normalize Word and Excel parser errors (#2881)

DiegoCluv7a351c6860eac
diff --git a/src/agentscope/rag/_parser/_excel.py b/src/agentscope/rag/_parser/_excel.py
index 3288ffb71..5c4643db9 100644
--- a/src/agentscope/rag/_parser/_excel.py
+++ b/src/agentscope/rag/_parser/_excel.py
@@ -250,9 +250,15 @@ class ExcelParser(ParserBase):
) from e
if isinstance(file, str):
- excel_file = pd.ExcelFile(file)
- else:
+ with open(file, "rb") as fp:
+ file = fp.read()
+
+ try:
excel_file = pd.ExcelFile(io.BytesIO(file))
+ except Exception as e: # pylint: disable=broad-except
+ raise ValueError(
+ f"Failed to parse {filename!r} as Excel: {e}",
+ ) from e
workbook = None
try:
diff --git a/src/agentscope/rag/_parser/_word.py b/src/agentscope/rag/_parser/_word.py
index 33bbece37..89cac0c5b 100644
--- a/src/agentscope/rag/_parser/_word.py
+++ b/src/agentscope/rag/_parser/_word.py
@@ -273,9 +273,15 @@ class WordParser(ParserBase):
) from e
if isinstance(file, str):
- doc = DocxDocument(file)
- else:
+ with open(file, "rb") as fp:
+ file = fp.read()
+
+ try:
doc = DocxDocument(io.BytesIO(file))
+ except Exception as e: # pylint: disable=broad-except
+ raise ValueError(
+ f"Failed to parse {filename!r} as DOCX: {e}",
+ ) from e
sections: list[Section] = []
text_buffer: list[str] = []
diff --git a/tests/rag_parser_test.py b/tests/rag_parser_test.py
index 4684e0cb2..b304b9cc6 100644
--- a/tests/rag_parser_test.py
+++ b/tests/rag_parser_test.py
@@ -8,6 +8,7 @@ run anywhere ``agentscope[rag]`` is installed.
import base64
import io
import os
+import zipfile
from unittest.async_case import IsolatedAsyncioTestCase
from utils import AnyString
@@ -1047,6 +1048,22 @@ class PPTParserTest(IsolatedAsyncioTestCase):
class ExcelParserTest(IsolatedAsyncioTestCase):
"""Behavioural coverage for :class:`ExcelParser`."""
+ async def test_invalid_input_errors(self) -> None:
+ """Missing paths and invalid workbooks use documented errors."""
+ parser = ExcelParser()
+ with self.assertRaises(FileNotFoundError):
+ await parser.parse("/no/such/report.xlsx", "report.xlsx")
+
+ workbook = _make_xlsx_simple({"Data": [["value"]]})
+ with self.assertRaises(ValueError):
+ await parser.parse(workbook[: len(workbook) // 2], "bad.xlsx")
+
+ buffer = io.BytesIO()
+ with zipfile.ZipFile(buffer, "w") as archive:
+ archive.writestr("notes.txt", "not a workbook")
+ with self.assertRaises(ValueError):
+ await parser.parse(buffer.getvalue(), "bad.xlsx")
+
async def test_header_only_sheet(self) -> None:
"""A sheet with only a header row is kept as a table."""
xlsx_bytes = _make_xlsx_simple({"Data": [["Revenue", "Year"]]})
@@ -1423,6 +1440,21 @@ class ExcelParserTest(IsolatedAsyncioTestCase):
class WordParserTest(IsolatedAsyncioTestCase):
"""Behavioural coverage for :class:`WordParser`."""
+ async def test_invalid_input_errors(self) -> None:
+ """Missing paths and invalid documents use documented errors."""
+ parser = WordParser()
+ with self.assertRaises(FileNotFoundError):
+ await parser.parse("/no/such/report.docx", "report.docx")
+
+ with self.assertRaises(ValueError):
+ await parser.parse(b"not a docx", "bad.docx")
+
+ buffer = io.BytesIO()
+ with zipfile.ZipFile(buffer, "w") as archive:
+ archive.writestr("notes.txt", "not a document")
+ with self.assertRaises(ValueError):
+ await parser.parse(buffer.getvalue(), "bad.docx")
+
async def test_simple_paragraphs(self) -> None:
"""Plain paragraphs are merged into a single text Section."""
docx_bytes = _make_docx_simple(["Hello", "World"])