Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(documents): preserve Word paragraph and table order

Rudy Celekli6e624e97d755
diff --git a/agent/src/tools/doc_reader_tool.py b/agent/src/tools/doc_reader_tool.py
index 2354b09c0..12b03beac 100644
--- a/agent/src/tools/doc_reader_tool.py
+++ b/agent/src/tools/doc_reader_tool.py
@@ -22,6 +22,7 @@ from typing import Any, Callable
from src.agent.progress import emit_progress
from src.agent.tools import BaseTool
from src.security.scanner import with_security_warnings
+from src.tools.ocr import get_ocr_engine, get_ocr_install_hint
from src.tools.path_utils import safe_document_path
_MAX_CHARS = 15000
@@ -44,7 +45,6 @@ _TEXT_EXTS = {
".dockerfile", ".makefile", ".cmake",
}
-from src.tools.ocr import get_ocr_engine, get_ocr_install_hint
_cached_ocr_engine = None
_cached_ocr_checked = False
@@ -239,16 +239,23 @@ def _read_pdf(path: Path, pages: str, min_text_per_page: int = _MIN_TEXT_PER_PAG
def _read_docx(path: Path) -> str:
try:
import docx # type: ignore
+ from docx.text.paragraph import Paragraph
except ImportError:
return _err("python-docx not installed; run: pip install python-docx")
doc = docx.Document(str(path))
- parts: list[str] = [p.text for p in doc.paragraphs if p.text.strip()]
- for t_idx, table in enumerate(doc.tables, start=1):
- parts.append(f"\n--- Table {t_idx} ---")
- for row in table.rows:
- cells = [c.text.strip().replace("\n", " ") for c in row.cells]
- parts.append(" | ".join(cells))
+ parts: list[str] = []
+ table_count = 0
+ for block in doc.iter_inner_content():
+ if isinstance(block, Paragraph):
+ if block.text.strip():
+ parts.append(block.text)
+ else:
+ table_count += 1
+ parts.append(f"\n--- Table {table_count} ---")
+ for row in block.rows:
+ cells = [c.text.strip().replace("\n", " ") for c in row.cells]
+ parts.append(" | ".join(cells))
return _envelope(path, "docx", "\n".join(parts), paragraphs=len(doc.paragraphs), tables=len(doc.tables))
diff --git a/agent/tests/test_doc_reader_docx_order.py b/agent/tests/test_doc_reader_docx_order.py
new file mode 100644
index 000000000..104897f7a
--- /dev/null
+++ b/agent/tests/test_doc_reader_docx_order.py
@@ -0,0 +1,67 @@
+"""Physical Word reports retain the association of headings and table values."""
+
+import json
+
+import pytest
+
+from src.tools.doc_reader_tool import DocReaderTool
+
+docx = pytest.importorskip("docx")
+
+
+ "nodes",
+ [
+ [
+ ("p", "FY2023 revenue"),
+ ("t", "$42m"),
+ ("p", "FY2024 revenue"),
+ ("t", "$84m"),
+ ],
+ [("t", "Opening balance"), ("p", "Closing summary")],
+ [("p", "Before"), ("t", "Between"), ("p", "After")],
+ [("p", "First\tparagraph"), ("p", "Second\nparagraph"), ("p", "")],
+ [("t", "First\ncell"), ("t", "Second cell")],
+ [],
+ ],
+ ids=[
+ "heading-values",
+ "table-first",
+ "table-between",
+ "paragraph-only",
+ "table-only",
+ "empty",
+ ],
+)
+def test_shipping_reader_keeps_document_body_order(tmp_path, monkeypatch, nodes):
+ monkeypatch.setenv("VIBE_TRADING_ALLOWED_FILE_ROOTS", str(tmp_path))
+ path = tmp_path / "report.docx"
+ document = docx.Document()
+ expected = []
+ paragraphs = tables = 0
+ for kind, text in nodes:
+ if kind == "p":
+ paragraphs += 1
+ document.add_paragraph(text)
+ if text.strip():
+ expected.append(text)
+ else:
+ tables += 1
+ document.add_table(rows=1, cols=1).cell(0, 0).text = text
+ expected.extend(
+ [f"\n--- Table {tables} ---", text.strip().replace("\n", " ")]
+ )
+ document.save(path)
+ # Direct physical XML order is independent of the extraction algorithm.
+ reopened = docx.Document(path)
+ assert [
+ child.tag.rsplit("}", 1)[-1]
+ for child in reopened.element.body
+ if child.tag.rsplit("}", 1)[-1] in {"p", "tbl"}
+ ] == ["p" if kind == "p" else "tbl" for kind, _ in nodes]
+ result = json.loads(DocReaderTool().execute(file_path=str(path)))
+ assert result["status"] == "ok", result
+ assert result["text"] == "\n".join(expected)
+ assert result["paragraphs"] == paragraphs and result["tables"] == tables
+ assert result["char_count"] == len(result["text"])
+ assert result["truncated"] is False