Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(documents): retain sparse native PDF text without OCR

Rudy Celeklifaf7d4a6ebb3
diff --git a/agent/src/tools/doc_reader_tool.py b/agent/src/tools/doc_reader_tool.py
index 2354b09c0..d84a38661 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
@@ -146,6 +146,7 @@ def _read_pdf(path: Path, pages: str, min_text_per_page: int = _MIN_TEXT_PER_PAG
ocr_pages = 0
ocr_attempted_pages = 0 # pages where OCR ran but returned empty
skipped_pages = 0
+ native_text_without_ocr = False
for idx, i in enumerate(targets, start=1):
if not 0 <= i < total_pages:
continue
@@ -161,12 +162,22 @@ def _read_pdf(path: Path, pages: str, min_text_per_page: int = _MIN_TEXT_PER_PAG
)
continue
if not _ocr_available():
- skipped_pages += 1
+ if text:
+ # The threshold requests OCR; it does not invalidate the
+ # native text already extracted from a sparse text page.
+ chunks.append(f"--- Page {i + 1} ---\n{text}")
+ native_text_without_ocr = True
+ else:
+ skipped_pages += 1
emit_progress(
"reading_pdf",
current=idx,
total=total_targets,
- message=f"page {i + 1}/{total_pages} (skipped: no OCR)",
+ message=(
+ f"page {i + 1}/{total_pages} (native text only: no OCR)"
+ if text
+ else f"page {i + 1}/{total_pages} (skipped: no OCR)"
+ ),
)
continue
bitmap = page.render(scale=300 / 72)
@@ -206,7 +217,7 @@ def _read_pdf(path: Path, pages: str, min_text_per_page: int = _MIN_TEXT_PER_PAG
if ocr_attempted_pages > 0:
# OCR was attempted but returned no usable text
quality_flag = "degraded"
- elif skipped_pages:
+ elif skipped_pages or native_text_without_ocr:
quality_flag = "no_ocr_engine"
else:
quality_flag = "no_ocr_needed"
diff --git a/agent/tests/test_doc_reader_native_fallback.py b/agent/tests/test_doc_reader_native_fallback.py
new file mode 100644
index 000000000..cae7d77c1
--- /dev/null
+++ b/agent/tests/test_doc_reader_native_fallback.py
@@ -0,0 +1,101 @@
+"""Physical PDF text survives missing OCR without hiding extraction limitations."""
+
+import json
+
+import pytest
+
+from src.config.accessor import reset_env_config
+from src.tools import doc_reader_tool
+
+pdfium = pytest.importorskip("pypdfium2")
+canvas = pytest.importorskip("reportlab.pdfgen.canvas")
+
+
[email protected](autouse=True)
+def disable_ocr(monkeypatch, tmp_path):
+ monkeypatch.setenv("VIBE_TRADING_OCR_ENGINE", "none")
+ monkeypatch.setenv("VIBE_TRADING_ALLOWED_FILE_ROOTS", str(tmp_path))
+ monkeypatch.setattr(doc_reader_tool, "_cached_ocr_checked", False)
+ monkeypatch.setattr(doc_reader_tool, "_cached_ocr_engine", None)
+ reset_env_config()
+ yield
+ reset_env_config()
+
+
+def read_pdf(tmp_path, texts, **kwargs):
+ path = tmp_path / "report.pdf"
+ writer = canvas.Canvas(str(path))
+ for text in texts:
+ if text:
+ writer.drawString(50, 750, text)
+ writer.showPage()
+ writer.save()
+ # Independent native extractor verifies these are real text pages, rather
+ # than OCR mocks or fixtures that accidentally contain only raster images.
+ document = pdfium.PdfDocument(str(path))
+ try:
+ assert [
+ document[i].get_textpage().get_text_range().strip()
+ for i in range(len(document))
+ ] == texts
+ finally:
+ document.close()
+ return json.loads(
+ doc_reader_tool.DocReaderTool().execute(file_path=str(path), **kwargs)
+ )
+
+
+ "texts,pages,threshold,expected,skipped",
+ [
+ (["Revenue: $42m"], "", 50, ["Revenue: $42m"], 0),
+ (
+ ["A native summary longer than fifty characters is ordinarily readable."],
+ "",
+ 200,
+ ["A native summary longer than fifty characters is ordinarily readable."],
+ 0,
+ ),
+ (
+ [
+ "Revenue: $42m",
+ "A native summary longer than fifty characters is ordinarily readable.",
+ ],
+ "",
+ 50,
+ [
+ "Revenue: $42m",
+ "A native summary longer than fifty characters is ordinarily readable.",
+ ],
+ 0,
+ ),
+ (["Revenue: $42m", "Another short note"], "2", 50, ["Another short note"], 0),
+ (["", "Revenue: $42m"], "", 50, ["Revenue: $42m"], 1),
+ ],
+)
+def test_shipping_reader_retains_short_native_text(
+ tmp_path, texts, pages, threshold, expected, skipped
+):
+ result = read_pdf(tmp_path, texts, pages=pages, min_text_per_page=threshold)
+ assert result["status"] == "ok", result
+ for text in expected:
+ assert text in result["text"]
+ assert result["skipped_pages"] == skipped
+ assert result["ocr_pages"] == 0 and result["ocr_engine"] is None
+ assert result["ocr_quality"]["quality_flag"] == "no_ocr_engine"
+ if pages == "2":
+ assert "Revenue: $42m" not in result["text"]
+
+
+def test_long_native_page_keeps_no_ocr_needed_control(tmp_path):
+ text = "A native summary longer than fifty characters is ordinarily readable."
+ result = read_pdf(tmp_path, [text])
+ assert result["status"] == "ok" and text in result["text"]
+ assert result["skipped_pages"] == 0
+ assert result["ocr_quality"]["quality_flag"] == "no_ocr_needed"
+
+
+def test_blank_pdf_still_requires_ocr(tmp_path):
+ result = read_pdf(tmp_path, [""])
+ assert result["status"] == "error"
+ assert "no extractable text" in result["error"]