"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
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.pyindex 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, Callablefrom src.agent.progress import emit_progressfrom src.agent.tools import BaseToolfrom src.security.scanner import with_security_warnings+from src.tools.ocr import get_ocr_engine, get_ocr_install_hintfrom 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_PAGocr_pages = 0ocr_attempted_pages = 0 # pages where OCR ran but returned emptyskipped_pages = 0+ native_text_without_ocr = Falsefor 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)continueif 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 += 1emit_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)"+ ),)continuebitmap = page.render(scale=300 / 72)@@ -206,7 +217,7 @@ def _read_pdf(path: Path, pages: str, min_text_per_page: int = _MIN_TEXT_PER_PAGif ocr_attempted_pages > 0:# OCR was attempted but returned no usable textquality_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.pynew file mode 100644index 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"]