Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat: universal file reader — pdf/docx/xlsx/pptx/images/text

warren61801996fff7c27
diff --git a/agent/api_server.py b/agent/api_server.py
index 97b028a1f..6c7fa3329 100644
--- a/agent/api_server.py
+++ b/agent/api_server.py
@@ -814,11 +814,31 @@ async def session_events(
# File Upload
# ============================================================================
+_BLOCKED_UPLOAD_EXT = {
+ # binaries / executables we should never accept
+ ".exe", ".msi", ".bat", ".cmd", ".com", ".scr", ".app", ".dmg",
+ ".so", ".dll", ".dylib",
+ # archives — don't auto-extract; user can unpack locally
+ ".zip", ".rar", ".7z", ".tar", ".gz", ".tgz", ".bz2", ".xz",
+}
+
+
@app.post("/upload", dependencies=[Depends(require_auth)])
async def upload_file(file: UploadFile):
- """Upload a PDF; stored under uploads/ with a UUID name (max 50MB)."""
- if not file.filename or not file.filename.lower().endswith(".pdf"):
- raise HTTPException(status_code=400, detail="Only PDF files are allowed")
+ """Upload any document or data file (max 50MB).
+
+ Accepts most common formats: PDF, Word, Excel, PowerPoint, images,
+ CSV/TSV, plain text, JSON/YAML/TOML, source code. Executables and
+ archives are rejected — unpack locally before uploading.
+ """
+ if not file.filename:
+ raise HTTPException(status_code=400, detail="Missing filename")
+ ext = Path(file.filename).suffix.lower()
+ if ext in _BLOCKED_UPLOAD_EXT:
+ raise HTTPException(
+ status_code=400,
+ detail=f"File type {ext} is not allowed (executables/archives blocked).",
+ )
content = await file.read()
if len(content) > MAX_UPLOAD_SIZE:
@@ -829,7 +849,7 @@ async def upload_file(file: UploadFile):
UPLOADS_DIR.mkdir(parents=True, exist_ok=True)
- safe_name = f"{uuid.uuid4().hex}.pdf"
+ safe_name = f"{uuid.uuid4().hex}{ext}"
dest = UPLOADS_DIR / safe_name
dest.write_bytes(content)
diff --git a/agent/src/skills/doc-reader/SKILL.md b/agent/src/skills/doc-reader/SKILL.md
index ee4b2dd64..2662d22ae 100644
--- a/agent/src/skills/doc-reader/SKILL.md
+++ b/agent/src/skills/doc-reader/SKILL.md
@@ -1,75 +1,114 @@
---
name: doc-reader
-description: Read PDF documents (papers, annual reports, research reports), automatically extracting text pages and applying OCR to image/scanned pages. Use the `read_document` tool.
+description: Read any common document/data file — PDF, Word (.docx), Excel (.xlsx/.xls), PowerPoint (.pptx), images (OCR), CSV/TSV, plain text, JSON/YAML/TOML, HTML/XML, and most source-code files. Use the `read_document` tool.
category: tool
---
-# PDF Document Reading
+# Universal Document Reader
## Purpose
-Read the full text of PDF documents and automatically handle two page types:
-- **Text pages** (most papers and digital reports) → extracted directly in milliseconds
-- **Image / scanned pages** (annual report charts, scanned research reports) → OCR recognition with Chinese and English support
-
-Applicable to PDF documents such as papers, annual reports, research reports, announcements, and contracts.
+Return extracted text from any supported file in a single unified JSON
+envelope. The tool dispatches by file extension — you always call the same
+tool regardless of format.
+
+### Supported formats
+
+| Category | Extensions | Notes |
+|---|---|---|
+| PDF | `.pdf` | Text pages extracted in ms; scanned/image pages fall back to OCR |
+| Word | `.docx` | Paragraphs + table cells |
+| Excel | `.xlsx`, `.xls` | All sheets, first 100 rows per sheet as preview |
+| PowerPoint | `.pptx` | Slide text content |
+| Images | `.png/.jpg/.jpeg/.gif/.bmp/.webp/.tiff` | OCR only |
+| CSV / TSV | `.csv`, `.tsv` | Raw text with encoding fallback |
+| Plain text | `.txt/.md/.log/.rst` | Encoding fallback |
+| Config | `.json/.yaml/.yml/.toml/.ini/.cfg/.env` | Raw text |
+| Markup | `.html/.htm/.xml` | Raw text (no HTML stripping) |
+| Source code | `.py/.js/.ts/.tsx/.go/.rs/.java/.cpp/.c/.sql/.sh/...` | Raw text |
+| Unknown extension | anything else | Best-effort read as UTF-8/GBK text |
+
+**Blocked** (rejected at `/upload`): executables (`.exe/.dll/.so/...`) and
+archives (`.zip/.tar/...`). Ask the user to unpack archives locally first.
## Usage
-**Call the `read_document` tool directly (do not use bash to write a Python script):**
+**Always call the tool directly — do not run Python from bash.**
```
read_document(file_path="uploads/paper.pdf")
read_document(file_path="uploads/annual_report.pdf", pages="1-10")
-read_document(file_path="uploads/research.pdf", pages="1,3,15-20")
+read_document(file_path="uploads/contract.docx")
+read_document(file_path="uploads/sales.xlsx")
+read_document(file_path="uploads/deck.pptx")
+read_document(file_path="uploads/chart.png") # image → OCR
+read_document(file_path="uploads/config.yaml")
+read_document(file_path="uploads/notes.md")
```
-**Forbidden**: do not run a Python script from bash to read PDFs. Call the tool directly.
+The `pages` parameter only applies to PDF; other formats ignore it.
+
+## Return envelope
-## Return Format
+All formats share this shape:
```json
{
"status": "ok",
"file": "paper.pdf",
- "total_pages": 45,
- "pages_read": 45,
- "ocr_pages": 3,
+ "format": "pdf",
"char_count": 52000,
"truncated": true,
- "text": "--- Page 1 ---\n...\n--- Page 5 [OCR] ---\n..."
+ "text": "..."
}
```
-- `ocr_pages`: number of pages recognized via OCR (image / scanned pages)
-- `truncated`: content is truncated when it exceeds 15000 characters
-- `[OCR]` indicates that the page content was obtained via image recognition
+Format-specific extra fields:
+
+| Format | Extra keys |
+|---|---|
+| `pdf` | `total_pages`, `pages_read`, `ocr_pages` |
+| `docx` | `paragraphs`, `tables` |
+| `excel` | `sheets` (array of `{name, rows, cols}`) |
+| `pptx` | `slides` |
+| `text` | `encoding`, `size` |
+
+Content longer than 15000 chars is truncated; for PDFs use the `pages`
+parameter to read slices.
-## Typical Workflows
+## Workflows
+
+### Paper / report summary
+```
+1. read_document(file_path="paper.pdf") → full text
+2. Extract abstract, methodology, conclusion → summarize
+```
-### Paper Summary
+### Contract review
```
-1. read_document(file_path="paper.pdf") → get the full text
-2. Analyze the text and extract the abstract, methodology, and conclusion
-3. Output the summary
+1. read_document(file_path="contract.docx") → paragraphs + tables
+2. Flag key clauses (termination, liability, payment, IP)
```
-### Annual Report Analysis
+### Spreadsheet quick-look
```
-1. read_document(file_path="annual_report.pdf", pages="1-5") → read the summary first
-2. Determine the key sections from the summary
-3. read_document(file_path="...", pages="15-25") → read the financial-data section
-4. Extract key metrics
+1. read_document(file_path="sales.xlsx") → all sheet previews
+2. If user wants trade journal analysis specifically, pivot to
+ `analyze_trade_journal` tool instead (see trade-journal skill).
```
-### Research Report Review
+### Chart / screenshot / scanned PDF
```
-1. read_document(file_path="research.pdf") → full text
-2. Extract the core thesis, target price, and risk factors
+1. read_document(file_path="scan.png") → OCR text
+2. If OCR returns empty, tell the user; don't fabricate.
```
## Notes
-- Content longer than 15000 characters will be truncated. For long documents, read them in chunks with the `pages` parameter
-- OCR pages are slower (about 1-3 seconds per page), while pure text pages are processed in milliseconds
-- OCR for charts and tables inside images may be imperfect, so complex tables should be checked manually
-- Only PDF format is supported
+- **Encoding fallback** order for text: utf-8 → utf-8-sig → gbk → gb2312 → big5 → latin-1.
+- **OCR** uses RapidOCR; if the package is missing, image/scanned files
+ return empty `text` with a `note` field — tell the user to install
+ `rapidocr-onnxruntime`.
+- **Excel previews** are limited to 100 rows per sheet to stay in budget.
+ If the user needs full data (e.g. trade journals), call
+ `analyze_trade_journal` instead.
+- **Source-code files** are returned raw; do not re-format or re-indent.
diff --git a/agent/src/tools/doc_reader_tool.py b/agent/src/tools/doc_reader_tool.py
index a7cfdbd5e..b0d8ae7e5 100644
--- a/agent/src/tools/doc_reader_tool.py
+++ b/agent/src/tools/doc_reader_tool.py
@@ -1,156 +1,317 @@
-"""Document reader tool: full PDF text extraction with OCR fallback for image/scanned pages."""
+"""Universal document reader: dispatches by file extension.
+
+Supported formats:
+ - PDF (.pdf) — pypdfium2 + OCR fallback for image pages
+ - Word (.docx) — python-docx (paragraphs + table cells)
+ - Excel (.xlsx/.xls) — pandas preview, all sheets
+ - PowerPoint (.pptx) — python-pptx (slide text)
+ - Images (.png/.jpg/.jpeg/.gif/.bmp/.webp/.tiff) — OCR
+ - Plain text (.txt/.md/.log/.json/.yaml/.yml/.toml/.ini/.cfg/.csv/.tsv/
+ .html/.xml/.rst/.sql/.sh and common source-code extensions)
+
+All handlers return the same JSON envelope: status, file, format, char_count,
+truncated, text. PDF/Excel add format-specific metadata (pages, sheets, ...).
+"""
from __future__ import annotations
import json
from pathlib import Path
-from typing import List, Optional, Tuple
+from typing import Any, Callable
from src.agent.tools import BaseTool
-_MAX_CHARS = 15000 # truncation threshold
-_MIN_TEXT_PER_PAGE = 50 # pages with fewer chars are treated as image pages and fall back to OCR
+_MAX_CHARS = 15000
+_MIN_TEXT_PER_PAGE = 50
+_ENCODING_FALLBACK = ("utf-8", "utf-8-sig", "gbk", "gb2312", "big5", "latin-1")
+
+_IMAGE_EXTS = {".png", ".jpg", ".jpeg", ".gif", ".bmp", ".webp", ".tiff", ".tif"}
+_TEXT_EXTS = {
+ # docs / structured
+ ".txt", ".md", ".log", ".rst",
+ ".json", ".yaml", ".yml", ".toml", ".ini", ".cfg", ".conf", ".env",
+ ".csv", ".tsv", ".html", ".htm", ".xml",
+ # source code (best-effort, LLM can read raw)
+ ".py", ".pyi", ".js", ".jsx", ".ts", ".tsx",
+ ".go", ".rs", ".java", ".kt", ".swift",
+ ".c", ".h", ".cpp", ".hpp", ".cc",
+ ".rb", ".php", ".pl", ".lua",
+ ".sh", ".bash", ".zsh", ".ps1", ".bat",
+ ".sql", ".r", ".m",
+ ".dockerfile", ".makefile", ".cmake",
+}
+
_ocr_engine = None
+# ---------------- shared helpers ----------------
+
+def _err(msg: str) -> str:
+ return json.dumps({"status": "error", "error": msg}, ensure_ascii=False)
+
+
+def _truncate(text: str) -> tuple[str, bool]:
+ """Clip to _MAX_CHARS, return (text, was_truncated)."""
+ if len(text) <= _MAX_CHARS:
+ return text, False
+ return text[:_MAX_CHARS] + f"\n\n... (truncated, total {len(text)} chars)", True
+
+
+def _envelope(path: Path, fmt: str, text: str, **extra: Any) -> str:
+ """Build the standard JSON response."""
+ body, truncated = _truncate(text)
+ payload: dict[str, Any] = {
+ "status": "ok",
+ "file": path.name,
+ "format": fmt,
+ "char_count": len(text),
+ "truncated": truncated,
+ "text": body,
+ }
+ payload.update(extra)
+ return json.dumps(payload, ensure_ascii=False)
+
+
def _get_ocr():
- """Lazily load the RapidOCR engine (first call takes ~1-2s)."""
+ """Lazily load RapidOCR. Raises ImportError if not installed."""
global _ocr_engine
if _ocr_engine is None:
- from rapidocr_onnxruntime import RapidOCR
+ from rapidocr_onnxruntime import RapidOCR # type: ignore
_ocr_engine = RapidOCR()
return _ocr_engine
-def _ocr_page(doc, page_idx: int) -> str:
- """Render a PDF page to an image and run OCR on it.
-
- Args:
- doc: pypdfium2 PdfDocument object.
- page_idx: Zero-based page index.
-
- Returns:
- OCR-extracted text for the page.
- """
- import numpy as np
-
- page = doc[page_idx]
- bitmap = page.render(scale=300 / 72)
- img = bitmap.to_numpy()
-
- ocr = _get_ocr()
+def _ocr_image_array(img) -> str:
+ """Run OCR on a numpy image; return joined lines or empty string."""
+ try:
+ ocr = _get_ocr()
+ except ImportError:
+ return ""
result, _ = ocr(img)
if not result:
return ""
- # result is list of [bbox, text, confidence]
- lines = [item[1] for item in result]
- return "\n".join(lines)
+ return "\n".join(item[1] for item in result)
-def read_document(file_path: str, pages: str = "") -> str:
- """Extract text from a PDF document, falling back to OCR for image pages.
+# ---------------- PDF ----------------
- Args:
- file_path: Absolute path to the PDF file.
- pages: Page range (e.g. "1-10", "5", "1,3,5-8"); empty means all pages.
+def _parse_pages(pages_str: str, total: int) -> list[int]:
+ """Parse '1-10' / '5' / '1,3,5-8' into zero-based indices."""
+ out: list[int] = []
+ for part in pages_str.split(","):
+ part = part.strip()
+ if not part:
+ continue
+ if "-" in part:
+ start, end = part.split("-", 1)
+ s = max(int(start.strip()) - 1, 0)
+ e = min(int(end.strip()), total)
+ out.extend(range(s, e))
+ elif part.isdigit():
+ out.append(int(part) - 1)
+ return sorted(set(out))
- Returns:
- JSON-formatted result.
- """
- path = Path(file_path)
- if not path.exists():
- return json.dumps({"status": "error", "error": f"File not found: {file_path}"}, ensure_ascii=False)
- if path.suffix.lower() != ".pdf":
- return json.dumps({"status": "error", "error": f"Only PDF supported, got: {path.suffix}"}, ensure_ascii=False)
+def _read_pdf(path: Path, pages: str) -> str:
+ """Extract PDF text; OCR pages with too little text."""
try:
- import pypdfium2 as pdfium
+ import pypdfium2 as pdfium # type: ignore
+ except ImportError:
+ return _err("pypdfium2 not installed; cannot read PDF")
- doc = pdfium.PdfDocument(str(path))
+ doc = pdfium.PdfDocument(str(path))
+ try:
total_pages = len(doc)
- target_pages = _parse_pages(pages, total_pages) if pages.strip() else list(range(total_pages))
-
- texts = []
+ targets = _parse_pages(pages, total_pages) if pages.strip() else list(range(total_pages))
+ chunks: list[str] = []
ocr_pages = 0
- for i in target_pages:
- if 0 <= i < total_pages:
- page = doc[i]
- text = page.get_textpage().get_text_range().strip()
-
- if len(text) >= _MIN_TEXT_PER_PAGE:
- texts.append(f"--- Page {i + 1} ---\n{text}")
- else:
- # Too little text — fall back to OCR
- ocr_text = _ocr_page(doc, i)
- if ocr_text.strip():
- texts.append(f"--- Page {i + 1} [OCR] ---\n{ocr_text}")
- ocr_pages += 1
- elif text:
- # OCR also found nothing; use whatever text exists
- texts.append(f"--- Page {i + 1} ---\n{text}")
-
+ for i in targets:
+ if not 0 <= i < total_pages:
+ continue
+ page = doc[i]
+ text = page.get_textpage().get_text_range().strip()
+ if len(text) >= _MIN_TEXT_PER_PAGE:
+ chunks.append(f"--- Page {i + 1} ---\n{text}")
+ continue
+ # OCR fallback for image pages
+ bitmap = page.render(scale=300 / 72)
+ img = bitmap.to_numpy()
+ ocr_text = _ocr_image_array(img)
+ if ocr_text.strip():
+ chunks.append(f"--- Page {i + 1} [OCR] ---\n{ocr_text}")
+ ocr_pages += 1
+ elif text:
+ chunks.append(f"--- Page {i + 1} ---\n{text}")
+ full = "\n\n".join(chunks)
+ return _envelope(
+ path, "pdf", full,
+ total_pages=total_pages,
+ pages_read=len(targets),
+ ocr_pages=ocr_pages,
+ )
+ finally:
doc.close()
- full_text = "\n\n".join(texts)
- char_count = len(full_text)
-
- truncated = False
- if char_count > _MAX_CHARS:
- full_text = full_text[:_MAX_CHARS] + f"\n\n... (truncated, total {char_count} chars, {total_pages} pages)"
- truncated = True
-
- return json.dumps({
- "status": "ok",
- "file": path.name,
- "total_pages": total_pages,
- "pages_read": len(target_pages),
- "ocr_pages": ocr_pages,
- "char_count": char_count,
- "truncated": truncated,
- "text": full_text,
- }, ensure_ascii=False)
+
+# ---------------- DOCX ----------------
+
+def _read_docx(path: Path) -> str:
+ try:
+ import docx # type: ignore
+ 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))
+ return _envelope(path, "docx", "\n".join(parts), paragraphs=len(doc.paragraphs), tables=len(doc.tables))
+
+
+# ---------------- Excel ----------------
+
+def _read_excel(path: Path) -> str:
+ try:
+ import pandas as pd # type: ignore
+ except ImportError:
+ return _err("pandas not installed; cannot read Excel")
+
+ xls = pd.ExcelFile(path)
+ parts: list[str] = []
+ sheet_info: list[dict[str, Any]] = []
+ for name in xls.sheet_names:
+ df = xls.parse(name, dtype=str)
+ preview = df.head(100).to_string(index=False)
+ parts.append(f"--- Sheet: {name} ({len(df)} rows × {len(df.columns)} cols) ---\n{preview}")
+ sheet_info.append({"name": name, "rows": len(df), "cols": len(df.columns)})
+ return _envelope(path, "excel", "\n\n".join(parts), sheets=sheet_info)
+
+
+# ---------------- PPTX ----------------
+
+def _read_pptx(path: Path) -> str:
+ try:
+ from pptx import Presentation # type: ignore
+ except ImportError:
+ return _err("python-pptx not installed; run: pip install python-pptx")
+
+ prs = Presentation(str(path))
+ parts: list[str] = []
+ for idx, slide in enumerate(prs.slides, start=1):
+ parts.append(f"--- Slide {idx} ---")
+ for shape in slide.shapes:
+ if shape.has_text_frame:
+ for para in shape.text_frame.paragraphs:
+ line = "".join(run.text for run in para.runs).strip()
+ if line:
+ parts.append(line)
+ return _envelope(path, "pptx", "\n".join(parts), slides=len(prs.slides))
+
+
+# ---------------- Image OCR ----------------
+
+def _read_image(path: Path) -> str:
+ try:
+ import numpy as np # type: ignore
+ from PIL import Image # type: ignore
+ except ImportError:
+ return _err("Pillow + numpy required for image OCR")
+
+ try:
+ img = np.array(Image.open(path).convert("RGB"))
except Exception as exc:
- return json.dumps({"status": "error", "error": str(exc)}, ensure_ascii=False)
+ return _err(f"Failed to open image: {exc}")
+
+ text = _ocr_image_array(img)
+ if not text.strip():
+ return _envelope(path, "image", "", note="OCR returned no text (engine missing or empty image)")
+ return _envelope(path, "image", text)
+
+# ---------------- Plain text ----------------
-def _parse_pages(pages_str: str, total: int) -> list:
- """Parse a page-range string into a list of zero-based page indices.
+def _read_text(path: Path) -> str:
+ """Read a text-like file with encoding fallback."""
+ data = path.read_bytes()
+ last_err: Exception | None = None
+ for enc in _ENCODING_FALLBACK:
+ try:
+ decoded = data.decode(enc)
+ return _envelope(path, "text", decoded, encoding=enc, size=len(data))
+ except UnicodeDecodeError as exc:
+ last_err = exc
+ return _err(f"Failed to decode file with any of {_ENCODING_FALLBACK}: {last_err}")
+
+
+# ---------------- Dispatcher ----------------
+
+_HANDLERS: dict[str, Callable[[Path], str]] = {
+ ".docx": _read_docx,
+ ".xlsx": _read_excel,
+ ".xls": _read_excel,
+ ".pptx": _read_pptx,
+}
+
+
+def read_document(file_path: str, pages: str = "") -> str:
+ """Read any supported document; dispatch by extension.
Args:
- pages_str: e.g. "1-10", "5", "1,3,5-8".
- total: Total number of pages in the document.
+ file_path: Absolute path to the file.
+ pages: Only used for PDF — e.g. "1-10", "5", "1,3,5-8"; empty = all.
Returns:
- Sorted list of zero-based page indices.
+ JSON envelope: status, file, format, char_count, truncated, text,
+ plus format-specific metadata (total_pages, sheets, etc.).
"""
- result = []
- for part in pages_str.split(","):
- part = part.strip()
- if "-" in part:
- start, end = part.split("-", 1)
- s = max(int(start.strip()) - 1, 0)
- e = min(int(end.strip()), total)
- result.extend(range(s, e))
- elif part.isdigit():
- result.append(int(part) - 1)
- return sorted(set(result))
+ path = Path(file_path)
+ if not path.exists():
+ return _err(f"File not found: {file_path}")
+ if not path.is_file():
+ return _err(f"Not a file: {file_path}")
+
+ ext = path.suffix.lower()
+ try:
+ if ext == ".pdf":
+ return _read_pdf(path, pages)
+ if ext in _HANDLERS:
+ return _HANDLERS[ext](path)
+ if ext in _IMAGE_EXTS:
+ return _read_image(path)
+ if ext in _TEXT_EXTS or ext == "":
+ return _read_text(path)
+ # Unknown extension: best-effort text read
+ return _read_text(path)
+ except Exception as exc:
+ return _err(f"{type(exc).__name__}: {exc}")
class DocReaderTool(BaseTool):
- """PDF document reader tool."""
+ """Universal document reader — PDF/Word/Excel/PowerPoint/images/text."""
name = "read_document"
- description = "Read a PDF document: extract text pages + OCR for image/scanned pages. Supports research papers, financial reports, etc. Accepts optional page ranges."
+ description = (
+ "Read a document of any common format: PDF, Word (.docx), Excel "
+ "(.xlsx/.xls), PowerPoint (.pptx), images (OCR), or plain text "
+ "(txt/md/json/yaml/csv/html/code files). Returns extracted text in "
+ "a unified JSON envelope. For PDFs, accepts an optional `pages` range."
+ )
parameters = {
"type": "object",
"properties": {
- "file_path": {"type": "string", "description": "Absolute path to the PDF file"},
- "pages": {"type": "string", "description": "Page range (e.g. '1-10', '5', '1,3,5-8'); leave empty for all pages", "default": ""},
+ "file_path": {"type": "string", "description": "Absolute path to the file."},
+ "pages": {
+ "type": "string",
+ "description": "PDF only: page range (e.g. '1-10', '5', '1,3,5-8'). Ignored for other formats.",
+ "default": "",
+ },
},
"required": ["file_path"],
}
repeatable = True
- def execute(self, **kwargs) -> str:
- """Read PDF document."""
+ def execute(self, **kwargs: Any) -> str:
return read_document(kwargs["file_path"], kwargs.get("pages", ""))
diff --git a/agent/tests/test_doc_reader.py b/agent/tests/test_doc_reader.py
new file mode 100644
index 000000000..eb7d82c95
--- /dev/null
+++ b/agent/tests/test_doc_reader.py
@@ -0,0 +1,166 @@
+"""Tests for the universal read_document tool (multi-format dispatch)."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pandas as pd
+import pytest
+
+from src.tools.doc_reader_tool import read_document
+
+FIXTURES = Path(__file__).parent / "fixtures" / "trade_journal"
+
+
+def _call(path: Path, pages: str = "") -> dict:
+ return json.loads(read_document(str(path), pages))
+
+
+# ---------------- Plain text variants ----------------
+
[email protected]("ext", [".txt", ".md", ".log", ".rst"])
+def test_plain_text(tmp_path: Path, ext: str) -> None:
+ p = tmp_path / f"note{ext}"
+ p.write_text("hello world\nline 2", encoding="utf-8")
+ result = _call(p)
+ assert result["status"] == "ok"
+ assert result["format"] == "text"
+ assert result["encoding"] == "utf-8"
+ assert "hello world" in result["text"]
+
+
[email protected]("ext", [".json", ".yaml", ".yml", ".toml", ".ini", ".env"])
+def test_config_formats(tmp_path: Path, ext: str) -> None:
+ p = tmp_path / f"conf{ext}"
+ p.write_text("key=value\n", encoding="utf-8")
+ result = _call(p)
+ assert result["status"] == "ok"
+ assert result["format"] == "text"
+
+
[email protected]("ext", [".py", ".js", ".ts", ".go", ".rs", ".sql", ".sh"])
+def test_source_code(tmp_path: Path, ext: str) -> None:
+ p = tmp_path / f"code{ext}"
+ p.write_text("print(1)", encoding="utf-8")
+ result = _call(p)
+ assert result["status"] == "ok"
+ assert result["format"] == "text"
+ assert "print(1)" in result["text"]
+
+
+def test_gbk_fallback(tmp_path: Path) -> None:
+ """GBK-encoded Chinese text (common from A-share brokers)."""
+ p = tmp_path / "gbk.txt"
+ p.write_bytes("中文内容".encode("gbk"))
+ result = _call(p)
+ assert result["status"] == "ok"
+ assert result["encoding"] == "gbk"
+ assert "中文" in result["text"]
+
+
+def test_unknown_extension_treated_as_text(tmp_path: Path) -> None:
+ p = tmp_path / "weird.xyzfmt"
+ p.write_text("abc", encoding="utf-8")
+ result = _call(p)
+ assert result["status"] == "ok"
+ assert result["format"] == "text"
+ assert result["text"] == "abc"
+
+
+def test_csv_read_as_text() -> None:
+ result = _call(FIXTURES / "futu_hk_us.csv")
+ assert result["status"] == "ok"
+ assert result["format"] == "text"
+ assert result["char_count"] > 0
+
+
+# ---------------- DOCX ----------------
+
+def test_docx_paragraphs_and_tables(tmp_path: Path) -> None:
+ import docx # type: ignore
+
+ p = tmp_path / "doc.docx"
+ d = docx.Document()
+ d.add_paragraph("First paragraph")
+ d.add_paragraph("Second paragraph")
+ table = d.add_table(rows=2, cols=2)
+ table.rows[0].cells[0].text = "A"
+ table.rows[0].cells[1].text = "B"
+ table.rows[1].cells[0].text = "1"
+ table.rows[1].cells[1].text = "2"
+ d.save(p)
+
+ result = _call(p)
+ assert result["status"] == "ok"
+ assert result["format"] == "docx"
+ assert result["paragraphs"] >= 2
+ assert result["tables"] == 1
+ assert "First paragraph" in result["text"]
+ assert "A | B" in result["text"]
+
+
+# ---------------- Excel ----------------
+
+def test_xlsx_multiple_sheets(tmp_path: Path) -> None:
+ p = tmp_path / "book.xlsx"
+ with pd.ExcelWriter(p) as w:
+ pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}).to_excel(w, sheet_name="first", index=False)
+ pd.DataFrame({"x": ["u", "v"]}).to_excel(w, sheet_name="second", index=False)
+
+ result = _call(p)
+ assert result["status"] == "ok"
+ assert result["format"] == "excel"
+ names = [s["name"] for s in result["sheets"]]
+ assert names == ["first", "second"]
+ assert "first" in result["text"]
+
+
+# ---------------- PPTX ----------------
+
+def test_pptx_slides(tmp_path: Path) -> None:
+ from pptx import Presentation # type: ignore
+
+ p = tmp_path / "deck.pptx"
+ prs = Presentation()
+ slide = prs.slides.add_slide(prs.slide_layouts[0])
+ slide.shapes.title.text = "Alpha Title"
+ prs.save(p)
+
+ result = _call(p)
+ assert result["status"] == "ok"
+ assert result["format"] == "pptx"
+ assert result["slides"] == 1
+ assert "Alpha Title" in result["text"]
+
+
+# ---------------- Error handling ----------------
+
+def test_missing_file() -> None:
+ result = _call(Path("/definitely/not/a/real/file.pdf"))
+ assert result["status"] == "error"
+ assert "not found" in result["error"].lower()
+
+
+def test_directory_rejected(tmp_path: Path) -> None:
+ result = _call(tmp_path)
+ assert result["status"] == "error"
+ assert "not a file" in result["error"].lower()
+
+
+def test_envelope_shape(tmp_path: Path) -> None:
+ """Every ok response must include the unified envelope keys."""
+ p = tmp_path / "x.txt"
+ p.write_text("hello", encoding="utf-8")
+ result = _call(p)
+ for key in ("status", "file", "format", "char_count", "truncated", "text"):
+ assert key in result
+
+
+def test_truncation(tmp_path: Path) -> None:
+ p = tmp_path / "big.txt"
+ p.write_text("x" * 20000, encoding="utf-8")
+ result = _call(p)
+ assert result["truncated"] is True
+ assert result["char_count"] == 20000
+ assert len(result["text"]) < 20000
diff --git a/frontend/src/pages/Agent.tsx b/frontend/src/pages/Agent.tsx
index 7a073605d..deb8ef338 100644
--- a/frontend/src/pages/Agent.tsx
+++ b/frontend/src/pages/Agent.tsx
@@ -587,8 +587,14 @@ export function Agent() {
const file = e.target.files?.[0];
if (!file) return;
e.target.value = "";
- if (!file.name.toLowerCase().endsWith(".pdf")) {
- toast.error("Only PDF files are supported");
+ const blockedExts = [
+ ".exe", ".msi", ".bat", ".cmd", ".com", ".scr", ".app", ".dmg",
+ ".so", ".dll", ".dylib",
+ ".zip", ".rar", ".7z", ".tar", ".gz", ".tgz", ".bz2", ".xz",
+ ];
+ const lowered = file.name.toLowerCase();
+ if (blockedExts.some((ext) => lowered.endsWith(ext))) {
+ toast.error("Executables and archives are not allowed");
return;
}
if (file.size > 50 * 1024 * 1024) {
@@ -785,7 +791,7 @@ export function Agent() {
<input
ref={fileInputRef}
type="file"
- accept=".pdf"
+ accept=".pdf,.docx,.xlsx,.xls,.pptx,.csv,.tsv,.txt,.md,.log,.json,.yaml,.yml,.toml,.html,.xml,.rst,.png,.jpg,.jpeg,.gif,.bmp,.webp,.tiff"
onChange={handleFileSelect}
className="hidden"
/>
diff --git a/pyproject.toml b/pyproject.toml
index 32d13c29d..93a14d60d 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -26,6 +26,11 @@ dependencies = [
"langgraph-checkpoint>=2.0.0",
"python-dotenv>=1.0.0",
"pandas>=2.0.0",
+ "openpyxl>=3.1.0",
+ "python-docx>=1.1.0",
+ "python-pptx>=0.6.23",
+ "pypdfium2>=4.0.0",
+ "Pillow>=10.0.0",
"numpy>=1.24.0",
"scipy>=1.10.0",
"duckdb>=1.2.0",