"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat(ocr): pluggable OCR engine architecture with entry_points discovery
shadowinlifea45b02486e6a
diff --git a/agent/.env.example b/agent/.env.exampleindex 2718ec790..41241d9dc 100644--- a/agent/.env.example+++ b/agent/.env.example@@ -149,6 +149,16 @@ TUSHARE_TOKEN=your-tushare-token# VIBE_TRADING_SEC_UA="Your Name [email protected]" # SEC EDGAR compliant contact User-Agent (optional; a built-in default UA also works)# Optional per-source request-spacing overrides for batch jobs — VIBE_TRADING_{EASTMONEY,SINA,STOOQ,YAHOO,SEC,FINNHUB,ALPHAVANTAGE,TIINGO,FMP,FRED,IWENCAI,THS}_MIN_INTERVAL (seconds).+# OCR engine for scanned PDF pages and images (auto by default).+# auto — local engines only (privacy: never sends pages to cloud)+# rapid — force RapidOCR (local, ONNX; pip install rapidocr_onnxruntime)+# llm-vision — force LLM vision OCR (cloud; any OpenAI-compatible vision model)+# none — disable OCR entirely+# VIBE_TRADING_OCR_ENGINE=auto+# Override the model used for LLM vision OCR (defaults to LANGCHAIN_MODEL_NAME).+# Example: qwen3.7-plus, gpt-5.5, gemini-3.5-flash, claude-sonnet-4.6+# VIBE_TRADING_OCR_LLM_MODEL=+# Opt-in local market-data cache for backtest loaders (off by default).# When enabled, every data source caches settled historical bars under# ~/.vibe-trading/cache/loaders/ so repeated/long-horizon backtests skip thediff --git a/agent/src/config/env_schema.py b/agent/src/config/env_schema.pyindex d1775132a..338033239 100644--- a/agent/src/config/env_schema.py+++ b/agent/src/config/env_schema.py@@ -183,11 +183,11 @@ class DataConfig(_EnvBase):class OcrConfig(_EnvBase):"""OCR engine selection and model configuration.- Sources: ``src/tools/ocr/engine.py``, ``src/tools/ocr/qwen_vision_ocr.py``.+ Sources: ``src/tools/ocr/engine.py``, ``src/tools/ocr/llm_vision_ocr.py``."""vibe_trading_ocr_engine: str = Field(alias="VIBE_TRADING_OCR_ENGINE", default="auto")- vibe_trading_ocr_qwen_model: str = Field(alias="VIBE_TRADING_OCR_QWEN_MODEL", default="")+ vibe_trading_ocr_llm_model: str = Field(alias="VIBE_TRADING_OCR_LLM_MODEL", default="")# ---------------------------------------------------------------------------diff --git a/agent/src/skills/doc-reader/SKILL.md b/agent/src/skills/doc-reader/SKILL.mdindex 2662d22ae..3d259b88f 100644--- a/agent/src/skills/doc-reader/SKILL.md+++ b/agent/src/skills/doc-reader/SKILL.md@@ -66,7 +66,7 @@ Format-specific extra fields:| Format | Extra keys ||---|---|-| `pdf` | `total_pages`, `pages_read`, `ocr_pages` |+| `pdf` | `total_pages`, `pages_read`, `ocr_pages`, `ocr_engine`, `ocr_quality`, `skipped_pages` || `docx` | `paragraphs`, `tables` || `excel` | `sheets` (array of `{name, rows, cols}`) || `pptx` | `slides` |@@ -102,12 +102,56 @@ parameter to read slices.2. If OCR returns empty, tell the user; don't fabricate.```+## OCR Configuration++The `read_document` tool automatically uses OCR for PDF pages with insufficient extractable text.++### OCR Threshold++Use `min_text_per_page` to control when OCR is triggered (default: 50 characters):++```python+read_document("scanned_report.pdf", min_text_per_page=10) # More aggressive OCR+read_document("mixed_pdf.pdf", min_text_per_page=100) # Less aggressive OCR+```++### OCR Engine Configuration++Two OCR engines are built in — no extra packages needed beyond the engine SDK:++| Engine | Type | Requires | Install |+|--------|------|----------|---------|+| `rapid` | Local (offline) | `rapidocr_onnxruntime` | `pip install rapidocr_onnxruntime` |+| `llm-vision` | Cloud | A vision-capable LLM model + API key | No extra install — uses your existing LLM provider config |++The `llm-vision` engine works with **any OpenAI-compatible vision model** (GPT-4o, Qwen-VL, Gemini, Claude, GLM-4V, etc.). It reuses your existing `LANGCHAIN_PROVIDER` / `LANGCHAIN_MODEL_NAME` / API key configuration — no separate provider mapping needed. If you explicitly set `VIBE_TRADING_OCR_ENGINE=llm-vision`, your model choice is trusted; a real API error from the provider is clearer feedback than a heuristic guess.++To override the model used for OCR (without changing your agent's main model):+```+VIBE_TRADING_OCR_LLM_MODEL=qwen3.7-plus+```++Set `VIBE_TRADING_OCR_ENGINE` to select the engine:+- `auto` (default): use local engines only, never cloud (privacy: document pages never leave the machine)+- `rapid`: force RapidOCR (local, ONNX)+- `llm-vision`: force LLM vision OCR (cloud — pages are sent to your configured LLM provider)+- `none`: disable OCR entirely++### Response Fields++PDF responses include OCR metadata:+- `ocr_engine`: name of the OCR engine used (e.g. "rapid", "llm-vision") or `null`+- `ocr_pages`: number of pages processed via OCR+- `skipped_pages`: number of pages skipped (no OCR engine available)+- `ocr_quality`: object with `quality_flag` (`good`/`degraded`/`no_ocr_engine`/`no_ocr_needed`), `ocr_pages`, and `text_density` (chars per page)+## Notes- **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`.+- **OCR** uses the configured engine (RapidOCR for local, or LLM vision for+ cloud). If no engine is available, image/scanned files return empty `text`+ with a `note` field — tell the user to install `rapidocr-onnxruntime` or+ set `VIBE_TRADING_OCR_ENGINE=llm-vision` with a vision-capable model.- **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.diff --git a/agent/src/skills/strategy-dev-manager/SKILL.md b/agent/src/skills/strategy-dev-manager/SKILL.mdindex 9036e781b..ac5c556de 100644--- a/agent/src/skills/strategy-dev-manager/SKILL.md+++ b/agent/src/skills/strategy-dev-manager/SKILL.md@@ -70,6 +70,15 @@ Turn the parsed content into structured artifact definitions.4. **Register the artifact**: call `sdm_register(artifact_type, name, universe, ...)` to persist the extracted definition with status "extracted".+### OCR Quality Check++After ingesting a paper via `read_document`, check the `ocr_quality` field in the response:++- `quality_flag == "good"`: proceed with extraction+- `quality_flag == "degraded"`: warn user that some pages could not be OCR'd, suggest manual review+- `quality_flag == "no_ocr_engine"`: suggest installing an OCR engine — `pip install rapidocr_onnxruntime` for local, or set `VIBE_TRADING_OCR_ENGINE=llm-vision` to use a vision-capable LLM model (GPT-4o, Qwen-VL, etc.) via your existing provider config+- `text_density < 100`: flag as potentially low-quality extraction, suggest verifying formulas manually+### Phase 3: IMPLEMENTBuild the SignalEngine, run the backtest, and link results.diff --git a/agent/src/tools/doc_reader_tool.py b/agent/src/tools/doc_reader_tool.pyindex 59c9c07b0..596e1c852 100644--- a/agent/src/tools/doc_reader_tool.py+++ b/agent/src/tools/doc_reader_tool.py@@ -119,7 +119,7 @@ def _parse_pages(pages_str: str, total: int) -> list[int]:return sorted(set(out))-def _read_pdf(path: Path, pages: str) -> str:+def _read_pdf(path: Path, pages: str, min_text_per_page: int = _MIN_TEXT_PER_PAGE) -> str:"""Extract PDF text; OCR pages with too little text."""try:import pypdfium2 as pdfium # type: ignore@@ -139,7 +139,7 @@ def _read_pdf(path: Path, pages: str) -> str:continuepage = doc[i]text = page.get_textpage().get_text_range().strip()- if len(text) >= _MIN_TEXT_PER_PAGE:+ if len(text) >= min_text_per_page:chunks.append(f"--- Page {i + 1} ---\n{text}")emit_progress("reading_pdf",@@ -179,12 +179,33 @@ def _read_pdf(path: Path, pages: str) -> str:f"All {total_pages} page(s) are scanned/image pages with no "f"extractable text, and no OCR engine is available. {hint}")+ engine = _get_ocr()++ # Compute OCR quality metrics+ pages_read = len(targets)+ text_density = len(full) / max(pages_read, 1)++ if ocr_pages == 0:+ quality_flag = "no_ocr_needed" if not skipped_pages else "no_ocr_engine"+ elif skipped_pages > 0:+ quality_flag = "degraded"+ else:+ quality_flag = "good"++ ocr_quality = {+ "ocr_pages": ocr_pages,+ "text_density": round(text_density, 1),+ "quality_flag": quality_flag,+ }+return _envelope(path, "pdf", full,total_pages=total_pages,pages_read=len(targets),ocr_pages=ocr_pages,skipped_pages=skipped_pages,+ ocr_engine=engine.name if engine else None,+ ocr_quality=ocr_quality,)finally:doc.close()@@ -278,9 +299,30 @@ def _read_image(path: Path) -> str:)text = _ocr_image_array(img)+ engine = _get_ocr()if not text.strip():- return _envelope(path, "image", "", note="OCR returned no text (empty or unreadable image)")- return _envelope(path, "image", text)+ ocr_quality = {+ "ocr_pages": 0,+ "text_density": 0.0,+ "quality_flag": "degraded",+ }+ return _envelope(+ path, "image", "",+ ocr_engine=engine.name if engine else None,+ ocr_quality=ocr_quality,+ note="OCR returned no text (empty or unreadable image)",+ )+ # Image = 1 page; text_density is total chars (matches PDF chars/page).+ ocr_quality = {+ "ocr_pages": 1,+ "text_density": round(len(text) / 1, 1),+ "quality_flag": "good",+ }+ return _envelope(+ path, "image", text,+ ocr_engine=engine.name if engine else None,+ ocr_quality=ocr_quality,+ )# ---------------- Plain text ----------------@@ -308,12 +350,14 @@ _HANDLERS: dict[str, Callable[[Path], str]] = {}-def read_document(file_path: str, pages: str = "") -> str:+def read_document(file_path: str, pages: str = "", min_text_per_page: int = _MIN_TEXT_PER_PAGE) -> str:"""Read any supported document; dispatch by extension.Args:file_path: Absolute path to the file.pages: Only used for PDF — e.g. "1-10", "5", "1,3,5-8"; empty = all.+ min_text_per_page: Minimum text chars to consider a page as text-extracted+ (below this threshold triggers OCR for PDFs). Default 50.Returns:JSON envelope: status, file, format, char_count, truncated, text,@@ -331,7 +375,7 @@ def read_document(file_path: str, pages: str = "") -> str:ext = path.suffix.lower()try:if ext == ".pdf":- return _read_pdf(path, pages)+ return _read_pdf(path, pages, min_text_per_page=min_text_per_page)if ext in _HANDLERS:return _HANDLERS[ext](path)if ext in _IMAGE_EXTS:@@ -363,10 +407,19 @@ class DocReaderTool(BaseTool):"description": "PDF only: page range (e.g. '1-10', '5', '1,3,5-8'). Ignored for other formats.","default": "",},+ "min_text_per_page": {+ "type": "integer",+ "description": "PDF only: minimum text chars per page before OCR is triggered. Default 50.",+ "default": 50,+ },},"required": ["file_path"],}repeatable = Truedef execute(self, **kwargs: Any) -> str:- return read_document(kwargs["file_path"], kwargs.get("pages", ""))+ return read_document(+ kwargs["file_path"],+ kwargs.get("pages", ""),+ min_text_per_page=kwargs.get("min_text_per_page", _MIN_TEXT_PER_PAGE),+ )diff --git a/agent/src/tools/ocr/engine.py b/agent/src/tools/ocr/engine.pyindex ede9a9431..6425416b0 100644--- a/agent/src/tools/ocr/engine.py+++ b/agent/src/tools/ocr/engine.py@@ -1,19 +1,27 @@"""Pluggable OCR engine interface and factory.Allows users to swap between local OCR (RapidOCR) and cloud vision models-(Qwen-VL, etc.) via environment variable VIBE_TRADING_OCR_ENGINE.+(any OpenAI-compatible provider) via environment variable VIBE_TRADING_OCR_ENGINE.++Third-party OCR engines can be installed as pip packages and are automatically+discovered via entry_points (group: vibe_trading.ocr_engines)."""from __future__ import annotations+import importlib.metadataimport logging+from functools import lru_cachefrom typing import Protocol, runtime_checkableimport numpy as nplogger = logging.getLogger(__name__)-_VALID_ENGINES = ("auto", "rapid", "qwen-vl", "none")+_ENTRY_POINT_GROUP = "vibe_trading.ocr_engines"++# Built-in engine registry+_BUILTIN_ENGINES: dict[str, type] = {}@runtime_checkable@@ -25,6 +33,8 @@ class OcrEngine(Protocol):"""name: str+ is_cloud: bool # auto mode filters on this (privacy red line)+ install_hint: str # shown when engine is unavailabledef is_available(self) -> bool:"""Check if this engine's dependencies are satisfied."""@@ -34,6 +44,44 @@ class OcrEngine(Protocol):"""Run OCR on a numpy RGB image array. Return extracted text."""...+ def confidence(self, image: np.ndarray) -> float | None:+ """Return OCR confidence (0-1), or None if unsupported. Optional."""+ return None+++def register_builtin(name: str, engine_class: type) -> None:+ """Register a built-in OCR engine class (shipped with core)."""+ _BUILTIN_ENGINES[name] = engine_class+++@lru_cache(maxsize=1)+def _discover_plugins() -> dict[str, type]:+ """Discover OCR engines installed via pip entry_points.++ Cached per process (Dask pattern). Plugins override built-ins on+ name collision (MLflow pattern).+ """+ plugins: dict[str, type] = {}+ for ep in importlib.metadata.entry_points(group=_ENTRY_POINT_GROUP):+ try:+ engine_class = ep.load()+ plugins[ep.name] = engine_class+ except Exception as exc:+ logger.warning("Failed to load OCR plugin '%s': %s", ep.name, exc)+ return plugins+++def _reset_plugin_cache() -> None:+ """Reset the plugin discovery cache. For test isolation only."""+ _discover_plugins.cache_clear()+++def _all_engines() -> dict[str, type]:+ """Merge built-in + plugins. Plugins override built-ins on name collision."""+ engines = dict(_BUILTIN_ENGINES)+ engines.update(_discover_plugins())+ return engines+def _get_ocr_choice() -> str:"""Return the configured OCR engine choice (cached per process)."""@@ -42,78 +90,95 @@ def _get_ocr_choice() -> str:return get_env_config().ocr.vibe_trading_ocr_engine.strip().lower()+def _select_first_local(engines: dict[str, type]) -> OcrEngine | None:+ """Return the first available local (non-cloud) engine, sorted by name.++ Instantiates every registered engine to probe :meth:`is_available`, so+ engine ``__init__`` must be cheap (attribute assignment only). Expensive+ work belongs in :meth:`is_available` or :meth:`recognize` (lazy init).+ Cloud engines (``is_cloud=True``) are skipped — privacy red line.+ """+ for name, cls in sorted(engines.items()):+ try:+ engine = cls()+ if engine.is_available() and not engine.is_cloud:+ return engine+ except Exception:+ continue+ return None++def get_ocr_engine() -> OcrEngine | None:- """Return the configured OCR engine, or None if unavailable.+ """Return the configured OCR engine, or None.Engine selection via VIBE_TRADING_OCR_ENGINE:- - "auto" (default): local RapidOCR if installed, else no OCR- - "rapid": RapidOCR only (local, ONNX)- - "qwen-vl": Qwen-VL vision model (cloud, DashScope API)+ - "auto" (default): try all LOCAL (is_cloud=False) engines+ - "<name>": try that specific engine (local or cloud)- "none": disable OCR entirely- Cloud OCR is never auto-selected: document pages leave the machine, so- "qwen-vl" must be an explicit user choice.+ Cloud engines are NEVER auto-selected (privacy: pages leave the machine).+ Plugins override built-in engines on name collision."""choice = _get_ocr_choice()- if choice not in _VALID_ENGINES:- logger.warning("Unknown OCR engine '%s', falling back to 'auto'", choice)- choice = "auto"+ engines = _all_engines()if choice == "none":return None- if choice == "qwen-vl":- return _try_qwen_vl()+ if choice == "auto":+ return _select_first_local(engines)- return _try_rapid()+ # Explicit choice+ cls = engines.get(choice)+ if cls:+ try:+ engine = cls()+ if engine.is_available():+ return engine+ except Exception as exc:+ logger.warning("OCR engine '%s' failed: %s", choice, exc)--def _try_rapid() -> OcrEngine | None:- try:- from src.tools.ocr.rapid_ocr import RapidOcrEngine- engine = RapidOcrEngine()- if engine.is_available():- return engine- except ImportError:- pass- return None---def _try_qwen_vl() -> OcrEngine | None:- try:- from src.tools.ocr.qwen_vision_ocr import QwenVisionOcrEngine- engine = QwenVisionOcrEngine()- if engine.is_available():- return engine- except Exception:- pass- return None+ # Unknown engine → fallback to auto+ logger.warning("Unknown OCR engine '%s', falling back to 'auto'", choice)+ return _select_first_local(engines)def get_ocr_install_hint(engine: OcrEngine | None) -> str:- """Return an actionable install message for the missing OCR engine."""+ """Return an actionable install message for available OCR engines."""if engine is not None:return ""choice = _get_ocr_choice()-- if choice == "qwen-vl":- return (- "Qwen-VL OCR engine requires DASHSCOPE_API_KEY environment variable. "- "Get a key from https://dashscope.console.aliyun.com/ and set: "- "export DASHSCOPE_API_KEY=your_key"- )-- if choice == "rapid":- return (- "RapidOCR engine not installed. Install with: "- "pip install rapidocr_onnxruntime"- )-- return (- "No OCR engine available. Install one of:\n"- " 1. Local OCR: pip install rapidocr_onnxruntime\n"- " 2. Cloud vision (pages are sent to DashScope): set "- "VIBE_TRADING_OCR_ENGINE=qwen-vl and DASHSCOPE_API_KEY=your_key\n"- "Or set VIBE_TRADING_OCR_ENGINE=none to disable OCR."- )+ engines = _all_engines()++ # If user explicitly chose an engine but it's unavailable+ if choice != "auto" and choice in engines:+ try:+ e = engines[choice]()+ return e.install_hint+ except Exception:+ pass++ # Read engine metadata from class attributes — no instantiation — to+ # avoid triggering is_available() side effects (e.g. network calls).+ entries = []+ for name, cls in engines.items():+ tag = "[cloud]" if getattr(cls, "is_cloud", False) else "[local]"+ entries.append(f" {tag:8s} {name}")++ lines = ["OCR engines status:"]+ lines.extend(entries if entries else [" (no engines registered)"])+ lines.append("")+ lines.append("Install an OCR engine:")+ lines.append(" pip install rapidocr_onnxruntime # local, no API key")+ lines.append(" # Cloud OCR: set VIBE_TRADING_OCR_ENGINE=llm-vision")+ lines.append(" # and configure a vision-capable LLM model")+ lines.append("")+ lines.append("Or set VIBE_TRADING_OCR_ENGINE=none to disable OCR.")+ return "\n".join(lines)+++# Built-in engine self-registration — must stay after definitions above+# because each imported module calls register_builtin() at import time.+from src.tools.ocr import llm_vision_ocr as _llm_vision # noqa: E402,F401+from src.tools.ocr import rapid_ocr as _rapid # noqa: E402,F401diff --git a/agent/src/tools/ocr/llm_vision_ocr.py b/agent/src/tools/ocr/llm_vision_ocr.pynew file mode 100644index 000000000..acb7d5f04--- /dev/null+++ b/agent/src/tools/ocr/llm_vision_ocr.py@@ -0,0 +1,246 @@+"""Built-in LLM vision OCR engine — works with any OpenAI-compatible provider+that has a vision-capable model.++Provider config (base_url, api_key) is resolved via the existing+``provider_env_names()`` function in ``src/providers/capabilities.py``,+which already covers 18+ providers. No separate provider mapping is needed.++Vision capability is not gated. ``is_available()`` returns True if an API+key is configured — the model may or may not support vision, but a failed+API call is clearer feedback than silently refusing to OCR. If the user+explicitly sets ``VIBE_TRADING_OCR_LLM_MODEL``, that choice is trusted.+"""++from __future__ import annotations++import base64+import io+import logging+import os++import numpy as np++logger = logging.getLogger(__name__)++# OCR system prompt design decisions:+# - HTML tables for complex layouts (Markdown can't express merged cells)+# - LaTeX with \( \) and \[ \] delimiters (avoids $ currency conflict)+# - No Unicode math symbols (∈ → \in) — forces portable LaTeX output+# - [unclear] for partial, [illegible] for complete unreadability+# - Reading order preservation for multi-column layouts++_OCR_SYSTEM_PROMPT = """\+You are a high-fidelity document OCR engine. Extract ALL text and structured \+content from the provided image with maximum accuracy.++## Output Format++Output clean Markdown with the following rules:++1. **Reading order**: Follow natural reading order (top-to-bottom, \+left-to-right). For multi-column layouts, read each column fully before \+moving to the next.++2. **Headings and text**: Use `#`, `##`, `###` for headings matching the \+original hierarchy. Use `**bold**` and `*italic*` where the original does. \+Use `- ` or `1. ` for lists.++3. **Tables**: For simple tables, use Markdown pipe tables (`| col |`). \+For tables with merged cells (colspan/rowspan), use HTML `<table>` with \+`colspan` and `rowspan` attributes — Markdown cannot express cell merging.++4. **Mathematical formulas**: Use LaTeX with `\\(...\\)` for inline and \+`\\[...\\]` for display formulas. Do NOT use Unicode math symbols \+(e.g., write `\\in` not `∈`, `\\subset` not `⊂`). Use `\\alpha`, \+`\\beta`, `\\sum` etc. for Greek letters and operators.++5. **Figures and charts**: Insert a placeholder: \+`[FIGURE: brief description of what the figure shows]`. Do NOT attempt to \+describe or interpret figure contents beyond a one-line caption.++6. **Headers and footers**: Wrap in `[HEADER: ...]` and `[FOOTER: ...]`.++7. **Handwriting**: Transcribe in `[HANDWRITTEN: ...]`.++8. **Watermarks and stamps**: Note in `[WATERMARK: ...]` or `[STAMP: ...]`.++9. **Unclear text**: If partially unreadable, output your best guess \+followed by `[?]`. If completely illegible, output `[illegible]`. \+Never guess or hallucinate text you cannot see.++10. **No commentary**: Output ONLY extracted content. No summaries, \+explanations, or meta-comments.++11. **Empty pages**: If no readable text, output an empty string.++12. **Preserve language**: Output in the same language(s) as the original. \+Do not translate.++## Critical Constraints++- Do NOT hallucinate text not visible in the image.+- Do NOT skip any text — include small print, footnotes, and annotations.+- Do NOT merge separate text blocks into one paragraph.+- Do NOT reorder content — follow the original layout.+- Do NOT correct apparent typos in the original.+"""++_OCR_USER_PROMPT = "Extract all text and structured content from this image."++_OCR_TIMEOUT = 90 # seconds — vision models are slower than text+++def _resolve_provider_config() -> dict[str, str]:+ """Resolve base_url, api_key, model from the configured LLM provider.++ Provider credentials use dynamically-named env vars from+ :func:`provider_env_names` (DEEPSEEK_API_KEY, DASHSCOPE_BASE_URL,+ etc.). These are not part of the static ``EnvConfig`` schema, so+ reads go through ``os.getenv`` directly.+ """+ from src.config.accessor import get_env_config+ from src.providers.capabilities import provider_env_names++ env = get_env_config()+ provider = env.llm.langchain_provider.strip().lower()+ model_name = env.llm.langchain_model_name.strip()++ model_override = env.ocr.vibe_trading_ocr_llm_model++ key_env, base_env = provider_env_names(provider, model_name)++ if key_env is not None:+ api_key = os.getenv(key_env, "") or os.getenv("OPENAI_API_KEY", "") # noqa: env-gate+ else:+ api_key = os.getenv("OPENAI_API_KEY", "") or "ollama" # noqa: env-gate++ base_url = (+ (os.getenv(base_env, "") if base_env else "") # noqa: env-gate+ or os.getenv("OPENAI_BASE_URL", "") # noqa: env-gate+ or os.getenv("OPENAI_API_BASE", "") # noqa: env-gate+ )++ model = model_override or model_name or ""++ return {+ "provider": provider,+ "base_url": base_url,+ "api_key": api_key,+ "model": model,+ }+++class LlmVisionOcrEngine:+ """Cloud OCR via any OpenAI-compatible multimodal LLM.++ Provider config is resolved via the existing ``provider_env_names()``+ function (no separate provider mapping). Vision capability is not+ gated — a failed API call is clearer feedback than silent refusal.+ """++ name = "llm-vision"+ is_cloud = True+ install_hint = (+ "LLM vision OCR requires a vision-capable model. Set "+ "LANGCHAIN_MODEL_NAME to a vision model (e.g. gpt-4o, "+ "qwen3.7-plus, gemini-2.5-flash, claude-sonnet-4) and "+ "configure the corresponding API key."+ )++ def __init__(self) -> None:+ self._client = None+ self._client_config: dict[str, str] | None = None++ def is_available(self) -> bool:+ """Available if an API key is configured."""+ try:+ from openai import OpenAI # noqa: F401 — already a core dependency++ config = _resolve_provider_config()+ return bool(config["api_key"])+ except Exception:+ return False++ def _get_client(self, config: dict[str, str]):+ """Return a cached OpenAI client, recreating if config changed."""+ if self._client is not None and self._client_config == config:+ return self._client+ from openai import OpenAI++ self._client = OpenAI(+ api_key=config["api_key"],+ base_url=config["base_url"] or None,+ timeout=_OCR_TIMEOUT,+ )+ self._client_config = dict(config)+ return self._client++ def recognize(self, image: np.ndarray) -> str:+ config = _resolve_provider_config()++ client = self._get_client(config)++ b64 = self._numpy_to_base64(image)++ # 1 retry for transient network errors+ for attempt in range(2):+ try:+ response = client.chat.completions.create(+ model=config["model"],+ messages=[+ {+ "role": "system",+ "content": [{"type": "text", "text": _OCR_SYSTEM_PROMPT}],+ },+ {+ "role": "user",+ "content": [+ {+ "type": "image_url",+ "image_url": {+ "url": f"data:image/jpeg;base64,{b64}",+ },+ },+ {+ "type": "text",+ "text": _OCR_USER_PROMPT,+ },+ ],+ },+ ],+ max_tokens=8192,+ temperature=0.0,+ )+ text = response.choices[0].message.content or ""+ return text.strip()+ except Exception as exc:+ if attempt == 0:+ logger.warning("OCR attempt 1 failed, retrying: %s", exc)+ continue+ logger.error(+ "LLM vision OCR failed (%s / %s): %s",+ config["provider"],+ config["model"],+ exc,+ )+ return ""+ return ""++ def confidence(self, image: np.ndarray) -> float | None:+ return None++ @staticmethod+ def _numpy_to_base64(image: np.ndarray) -> str:+ """Convert numpy array to base64 JPEG (10x smaller than PNG for OCR)."""+ from PIL import Image++ pil_img = Image.fromarray(image)+ buffer = io.BytesIO()+ pil_img.save(buffer, format="JPEG", quality=85)+ return base64.b64encode(buffer.getvalue()).decode("utf-8")+++# Self-register to built-in engine table+from src.tools.ocr.engine import register_builtin # noqa: E402++register_builtin("llm-vision", LlmVisionOcrEngine)diff --git a/agent/src/tools/ocr/qwen_vision_ocr.py b/agent/src/tools/ocr/qwen_vision_ocr.pydeleted file mode 100644index 0ffce4611..000000000--- a/agent/src/tools/ocr/qwen_vision_ocr.py+++ /dev/null@@ -1,95 +0,0 @@-"""Qwen-VL vision model OCR engine — cloud, DashScope OpenAI-compatible API."""--from __future__ import annotations--import base64-import io-import logging--import numpy as np--logger = logging.getLogger(__name__)--_DASHSCOPE_BASE_URL = "https://dashscope.aliyuncs.com/compatible-mode/v1"-_DEFAULT_MODEL = "qwen-vl-plus"--_OCR_SYSTEM_PROMPT = (- "You are a precise OCR engine. Extract ALL text from the provided image. "- "Rules:\n"- "- Preserve the original layout: use newlines for line breaks, "- "tabs for table columns, markdown tables for structured tables.\n"- "- Preserve mathematical formulas in LaTeX notation ($...$).\n"- "- Do NOT add commentary, summaries, or explanations.\n"- "- Output ONLY the extracted text, nothing else.\n"- "- If the image contains no readable text, output an empty string."-)---class QwenVisionOcrEngine:- """Cloud OCR engine using Qwen-VL via DashScope OpenAI-compatible API."""-- name = "qwen-vl"-- def __init__(self) -> None:- self._client = None-- def is_available(self) -> bool:- from src.config.accessor import get_env_config-- api_key = get_env_config().data.dashscope_api_key- if not api_key:- return False- try:- from openai import OpenAI # type: ignore- if self._client is None:- self._client = OpenAI(- api_key=api_key,- base_url=_DASHSCOPE_BASE_URL,- )- return True- except ImportError:- return False-- def recognize(self, image: np.ndarray) -> str:- if not self.is_available():- raise RuntimeError(- "Qwen-VL OCR requires DASHSCOPE_API_KEY environment variable"- )-- b64 = self._numpy_to_base64(image)- from src.config.accessor import get_env_config-- model = get_env_config().ocr.vibe_trading_ocr_qwen_model or _DEFAULT_MODEL-- try:- response = self._client.chat.completions.create(- model=model,- messages=[- {"role": "system", "content": [{"type": "text", "text": _OCR_SYSTEM_PROMPT}]},- {- "role": "user",- "content": [- {- "type": "image_url",- "image_url": {"url": f"data:image/png;base64,{b64}"},- },- {"type": "text", "text": "Extract all text from this image."},- ],- },- ],- max_tokens=4096,- temperature=0.0,- )- text = response.choices[0].message.content or ""- return text.strip()- except Exception as exc:- logger.error("Qwen-VL OCR failed: %s", exc)- return ""-- @staticmethod- def _numpy_to_base64(image: np.ndarray) -> str:- from PIL import Image # type: ignore- pil_img = Image.fromarray(image)- buffer = io.BytesIO()- pil_img.save(buffer, format="PNG")- return base64.b64encode(buffer.getvalue()).decode("utf-8")diff --git a/agent/src/tools/ocr/rapid_ocr.py b/agent/src/tools/ocr/rapid_ocr.pyindex 11928e6d6..95f93eb8f 100644--- a/agent/src/tools/ocr/rapid_ocr.py+++ b/agent/src/tools/ocr/rapid_ocr.py@@ -9,8 +9,13 @@ class RapidOcrEngine:"""Local OCR engine using RapidOCR (PaddleOCR-derived, ONNX Runtime)."""name = "rapid"+ is_cloud = False+ install_hint = "pip install rapidocr_onnxruntime"def __init__(self) -> None:+ # Lazy init: RapidOCR() loaded inside is_available() / recognize().+ # _select_first_local() probes every registered engine, so __init__+ # must stay cheap (attribute assignment only).self._engine = Nonedef is_available(self) -> bool:@@ -29,3 +34,20 @@ class RapidOcrEngine:if not result:return ""return "\n".join(item[1] for item in result)++ def confidence(self, image: np.ndarray) -> float | None:+ """Return mean OCR confidence (0-1), or None if unavailable."""+ if not self.is_available():+ return None+ result, _ = self._engine(image)+ if not result:+ return None+ # RapidOCR returns (bbox, text, confidence) tuples+ confidences = [item[2] for item in result if len(item) > 2]+ return sum(confidences) / len(confidences) if confidences else None+++# Self-register to built-in engine table+from src.tools.ocr.engine import register_builtin # noqa: E402++register_builtin("rapid", RapidOcrEngine)diff --git a/agent/tests/test_ocr_engine.py b/agent/tests/test_ocr_engine.pyindex 38ddf0fb2..416ae5dd2 100644--- a/agent/tests/test_ocr_engine.py+++ b/agent/tests/test_ocr_engine.py@@ -1,12 +1,13 @@"""Tests for the pluggable OCR engine factory.-Cloud OCR uploads document pages to a third party, so the qwen-vl engine+Cloud OCR uploads document pages to a third party, so cloud enginesmust only ever be reachable through an explicit VIBE_TRADING_OCR_ENGINEchoice — never via "auto" fallback."""from __future__ import annotations+import numpy as npimport pytestfrom src.config.accessor import reset_env_config@@ -15,51 +16,342 @@ from src.tools.ocr import engine as ocr_engine@pytest.fixture(autouse=True)def _reset_config():- """Reset the cached EnvConfig around each test."""+ """Reset the cached EnvConfig and plugin cache around each test."""reset_env_config()+ ocr_engine._reset_plugin_cache()yieldreset_env_config()+ ocr_engine._reset_plugin_cache()-def test_auto_never_selects_cloud_engine(monkeypatch):- """auto must not fall through to Qwen-VL even with DASHSCOPE_API_KEY set."""- monkeypatch.setenv("DASHSCOPE_API_KEY", "sk-test-not-real")- monkeypatch.setenv("VIBE_TRADING_OCR_ENGINE", "auto")- reset_env_config()+# ---------------------------------------------------------------------------+# Engine selection and privacy+# ---------------------------------------------------------------------------- monkeypatch.setattr(- ocr_engine, "_try_qwen_vl",- lambda: pytest.fail("auto mode must never try the cloud engine"),- )- engine = ocr_engine.get_ocr_engine()- assert engine is None or engine.name == "rapid"+class TestEngineSelection:+ """Test get_ocr_engine() selection logic and privacy guarantees."""-def test_explicit_qwen_vl_reaches_cloud_factory(monkeypatch):- """qwen-vl is reachable, but only as an explicit choice."""- monkeypatch.setenv("VIBE_TRADING_OCR_ENGINE", "qwen-vl")- reset_env_config()+ def test_none_disables_ocr(self, monkeypatch):+ monkeypatch.setenv("VIBE_TRADING_OCR_ENGINE", "none")+ reset_env_config()+ assert ocr_engine.get_ocr_engine() is None- sentinel = object()- monkeypatch.setattr(ocr_engine, "_try_qwen_vl", lambda: sentinel)- assert ocr_engine.get_ocr_engine() is sentinel+ def test_auto_never_selects_cloud_engine(self, monkeypatch):+ """auto must not select any engine with is_cloud=True."""+ monkeypatch.setenv("VIBE_TRADING_OCR_ENGINE", "auto")+ monkeypatch.setenv("OPENAI_API_KEY", "sk-test-not-real")+ monkeypatch.setenv("LANGCHAIN_MODEL_NAME", "gpt-4o")+ reset_env_config()+ engine = ocr_engine.get_ocr_engine()+ if engine is not None:+ assert engine.is_cloud is False, (+ f"auto mode selected cloud engine '{engine.name}'"+ )-def test_none_disables_ocr(monkeypatch):- monkeypatch.setenv("VIBE_TRADING_OCR_ENGINE", "none")- reset_env_config()- assert ocr_engine.get_ocr_engine() is None+ def test_unknown_choice_falls_back_to_local(self, monkeypatch):+ """An unknown engine name degrades to auto, which stays local."""+ monkeypatch.setenv("VIBE_TRADING_OCR_ENGINE", "bogus-engine")+ reset_env_config()+ engine = ocr_engine.get_ocr_engine()+ if engine is not None:+ assert engine.is_cloud is False-def test_unknown_choice_falls_back_to_local_only(monkeypatch):- """An unknown engine name degrades to auto, which stays local."""- monkeypatch.setenv("VIBE_TRADING_OCR_ENGINE", "bogus-engine")- monkeypatch.setenv("DASHSCOPE_API_KEY", "sk-test-not-real")- reset_env_config()+ def test_llm_vision_explicit_not_auto_selected(self, monkeypatch):+ """llm-vision is available via explicit choice but not via auto."""+ monkeypatch.setenv("VIBE_TRADING_OCR_ENGINE", "auto")+ monkeypatch.setenv("OPENAI_API_KEY", "sk-test")+ monkeypatch.setenv("LANGCHAIN_MODEL_NAME", "gpt-4o")+ reset_env_config()++ # auto should NOT return the cloud llm-vision engine+ engine = ocr_engine.get_ocr_engine()+ if engine is not None:+ assert engine.name != "llm-vision"++ def test_llm_vision_available_with_api_key(self, monkeypatch):+ """llm-vision is_available returns True when API key is set.++ Vision capability is NOT gated — the call is attempted regardless+ and a failed API call gives clearer feedback than silent refusal.+ """+ monkeypatch.setenv("VIBE_TRADING_OCR_ENGINE", "llm-vision")+ monkeypatch.setenv("LANGCHAIN_PROVIDER", "openai")+ monkeypatch.setenv("LANGCHAIN_MODEL_NAME", "gpt-4o")+ monkeypatch.setenv("OPENAI_API_KEY", "sk-test")+ reset_env_config()++ engine = ocr_engine.get_ocr_engine()+ assert engine is not None+ assert engine.name == "llm-vision"+ assert engine.is_cloud is True++ def test_llm_vision_unavailable_without_api_key(self, monkeypatch):+ """llm-vision is_available returns False when no API key is set.++ When the cloud engine is unavailable, get_ocr_engine falls back+ to auto (local engines). The returned engine must NOT be llm-vision.+ """+ monkeypatch.setenv("VIBE_TRADING_OCR_ENGINE", "llm-vision")+ monkeypatch.setenv("LANGCHAIN_PROVIDER", "openai")+ monkeypatch.setenv("LANGCHAIN_MODEL_NAME", "gpt-4o")+ monkeypatch.delenv("OPENAI_API_KEY", raising=False)+ reset_env_config()++ engine = ocr_engine.get_ocr_engine()+ # Either no engine (no local OCR installed) or a local engine+ if engine is not None:+ assert engine.name != "llm-vision"+ assert engine.is_cloud is False++ def test_llm_vision_available_even_for_unknown_model(self, monkeypatch):+ """llm-vision is available even if model name is unknown.++ The vision model check is advisory (warning only), not a gate.+ A text-only model name should still let the engine be available+ — the API call will fail with a clear error if the model truly+ lacks vision support.+ """+ monkeypatch.setenv("VIBE_TRADING_OCR_ENGINE", "llm-vision")+ monkeypatch.setenv("LANGCHAIN_PROVIDER", "deepseek")+ monkeypatch.setenv("LANGCHAIN_MODEL_NAME", "deepseek-chat")+ monkeypatch.setenv("DEEPSEEK_API_KEY", "sk-test")+ reset_env_config()++ engine = ocr_engine.get_ocr_engine()+ assert engine is not None+ assert engine.name == "llm-vision"+++# ---------------------------------------------------------------------------+# Deprecated aliases+# ---------------------------------------------------------------------------+++class TestRegistry:+ """Test the built-in registry and plugin discovery."""++ def test_builtin_engines_registered(self):+ """rapid and llm-vision should be in the built-in registry."""+ engines = ocr_engine._all_engines()+ assert "rapid" in engines+ assert "llm-vision" in engines++ def test_rapid_engine_is_local(self):+ """rapid engine should have is_cloud=False."""+ engines = ocr_engine._all_engines()+ rapid_cls = engines["rapid"]+ engine = rapid_cls()+ assert engine.is_cloud is False+ assert engine.name == "rapid"++ def test_llm_vision_engine_is_cloud(self):+ """llm-vision engine should have is_cloud=True."""+ engines = ocr_engine._all_engines()+ llm_cls = engines["llm-vision"]+ engine = llm_cls()+ assert engine.is_cloud is True+ assert engine.name == "llm-vision"++ def test_reset_plugin_cache_clears_cache(self):+ """_reset_plugin_cache should clear the lru_cache."""+ # Call _discover_plugins to populate cache+ ocr_engine._discover_plugins()+ cache_info = ocr_engine._discover_plugins.cache_info()+ assert cache_info.currsize >= 0++ # Reset should clear+ ocr_engine._reset_plugin_cache()+ cache_info = ocr_engine._discover_plugins.cache_info()+ assert cache_info.currsize == 0++ def test_plugin_overrides_builtin(self, monkeypatch):+ """A plugin with the same name as a builtin should override it."""++ class FakePluginEngine:+ name = "rapid"+ is_cloud = False+ install_hint = "fake plugin"++ def is_available(self):+ return True++ def recognize(self, image):+ return "fake"++ # Mock _discover_plugins to return our fake plugin+ monkeypatch.setattr(+ ocr_engine,+ "_discover_plugins",+ lambda: {"rapid": FakePluginEngine},+ )++ engines = ocr_engine._all_engines()+ rapid_cls = engines["rapid"]+ engine = rapid_cls()+ assert engine.install_hint == "fake plugin"+++# ---------------------------------------------------------------------------+# Install hints+# ---------------------------------------------------------------------------+++class TestInstallHints:+ """Test get_ocr_install_hint() dynamic generation."""++ def test_hint_empty_when_engine_available(self):+ """No hint needed when an engine object is passed (working)."""+ hint = ocr_engine.get_ocr_install_hint(object())+ assert hint == ""++ def test_hint_generated_when_engine_none(self, monkeypatch):+ """Hint should be generated when engine is None and OCR is needed."""+ monkeypatch.setenv("VIBE_TRADING_OCR_ENGINE", "auto")+ reset_env_config()+ engine = ocr_engine.get_ocr_engine()+ hint = ocr_engine.get_ocr_install_hint(engine)+ if engine is None:+ assert "pip install" in hint+ assert "rapidocr_onnxruntime" in hint++ def test_hint_does_not_reference_deleted_plugin(self, monkeypatch):+ """Install hint must not reference the removed vibe-ocr-llm package."""+ monkeypatch.setenv("VIBE_TRADING_OCR_ENGINE", "auto")+ reset_env_config()+ engine = ocr_engine.get_ocr_engine()+ hint = ocr_engine.get_ocr_install_hint(engine)+ assert "vibe-ocr-llm" not in hint+++# ---------------------------------------------------------------------------+# Provider config resolution+# ---------------------------------------------------------------------------+++class TestProviderConfigResolution:+ """Test _resolve_provider_config() fallback paths."""++ def test_normal_path_with_provider_env(self, monkeypatch):+ """When provider-specific env vars are set, they take priority."""+ monkeypatch.setenv("LANGCHAIN_PROVIDER", "deepseek")+ monkeypatch.setenv("LANGCHAIN_MODEL_NAME", "deepseek-vl2")+ monkeypatch.setenv("DEEPSEEK_API_KEY", "sk-test-123")+ monkeypatch.setenv("DEEPSEEK_BASE_URL", "https://api.deepseek.com/v1")+ reset_env_config()++ from src.tools.ocr.llm_vision_ocr import _resolve_provider_config++ config = _resolve_provider_config()+ assert config["provider"] == "deepseek"+ assert config["api_key"] == "sk-test-123"+ assert config["model"] == "deepseek-vl2"++ def test_fallback_to_openai_api_key(self, monkeypatch):+ """When provider env is unset, fall back to OPENAI_API_KEY."""+ monkeypatch.setenv("LANGCHAIN_PROVIDER", "unknown-provider")+ monkeypatch.setenv("LANGCHAIN_MODEL_NAME", "gpt-4o")+ monkeypatch.setenv("OPENAI_API_KEY", "sk-openai-test")+ monkeypatch.delenv("OPENAI_BASE_URL", raising=False)+ monkeypatch.delenv("OPENAI_API_BASE", raising=False)+ reset_env_config()++ from src.tools.ocr.llm_vision_ocr import _resolve_provider_config++ config = _resolve_provider_config()+ assert config["api_key"] == "sk-openai-test"++ def test_ollama_fallback_when_no_key(self, monkeypatch):+ """When no API key is set at all, fall back to 'ollama'."""+ monkeypatch.setenv("LANGCHAIN_PROVIDER", "ollama")+ monkeypatch.setenv("LANGCHAIN_MODEL_NAME", "llava-1.5-7b")+ monkeypatch.delenv("OPENAI_API_KEY", raising=False)+ reset_env_config()++ from src.tools.ocr.llm_vision_ocr import _resolve_provider_config++ config = _resolve_provider_config()+ assert config["api_key"] == "ollama"++ def test_model_override_priority(self, monkeypatch):+ """VIBE_TRADING_OCR_LLM_MODEL overrides LANGCHAIN_MODEL_NAME."""+ monkeypatch.setenv("LANGCHAIN_PROVIDER", "openai")+ monkeypatch.setenv("LANGCHAIN_MODEL_NAME", "gpt-4o-mini")+ monkeypatch.setenv("OPENAI_API_KEY", "sk-test")+ monkeypatch.setenv("VIBE_TRADING_OCR_LLM_MODEL", "gpt-4o")+ reset_env_config()++ from src.tools.ocr.llm_vision_ocr import _resolve_provider_config++ config = _resolve_provider_config()+ assert config["model"] == "gpt-4o"++ def test_base_url_fallback_chain(self, monkeypatch):+ """base_url should fall back through provider env → OPENAI_BASE_URL → OPENAI_API_BASE."""+ monkeypatch.setenv("LANGCHAIN_PROVIDER", "ollama")+ monkeypatch.setenv("LANGCHAIN_MODEL_NAME", "llava-1.5-7b")+ monkeypatch.delenv("OPENAI_API_KEY", raising=False)+ monkeypatch.setenv("OPENAI_BASE_URL", "http://localhost:11434/v1")+ reset_env_config()++ from src.tools.ocr.llm_vision_ocr import _resolve_provider_config++ config = _resolve_provider_config()+ assert config["base_url"] == "http://localhost:11434/v1"+++# ---------------------------------------------------------------------------+# recognize() should never emit advisory warnings+# ---------------------------------------------------------------------------+++class TestRecognizeNoAdvisory:+ """Explicit engine choice (llm-vision) is the strongest multimodality+ signal — recognize() must not second-guess the user by emitting+ heuristic 'may not support vision' warnings. If the model truly+ lacks vision support, the provider-side API call fails with a clear+ error — better UX than heuristic warnings.+ """++ def test_no_warning_with_text_only_model_name(self, monkeypatch, caplog):+ """deepseek-chat is a text-only model name, but explicit llm-vision+ engine choice should suppress any advisory warning — the user has+ already committed to that engine.+ """+ monkeypatch.setenv("VIBE_TRADING_OCR_ENGINE", "llm-vision")+ monkeypatch.setenv("LANGCHAIN_PROVIDER", "deepseek")+ monkeypatch.setenv("LANGCHAIN_MODEL_NAME", "deepseek-chat")+ monkeypatch.setenv("DEEPSEEK_API_KEY", "sk-test")+ reset_env_config()++ from src.tools.ocr.llm_vision_ocr import LlmVisionOcrEngine++ engine = LlmVisionOcrEngine()+ monkeypatch.setattr(+ engine, "_get_client", lambda config: _FakeNoOpClient(),+ )++ with caplog.at_level("WARNING", logger="src.tools.ocr.llm_vision_ocr"):+ engine.recognize(np.zeros((10, 10, 3), dtype=np.uint8))++ assert not any(+ "may not support vision" in rec.message for rec in caplog.records+ )+++class _FakeNoOpClient:+ """Stub: chat.completions.create returns an empty message for recognize()."""- monkeypatch.setattr(- ocr_engine, "_try_qwen_vl",- lambda: pytest.fail("fallback from unknown choice must stay local"),- )- engine = ocr_engine.get_ocr_engine()- assert engine is None or engine.name == "rapid"+ def __init__(self):+ class _Chat:+ class _Completions:+ def create(self, **kwargs):+ return type("Resp", (), {+ "choices": [type("Ch", (), {+ "message": type("Msg", (), {"content": ""}),+ })],+ })()+ completions = _Completions()+ self.chat = _Chat()diff --git a/agent/tests/test_ocr_integration.py b/agent/tests/test_ocr_integration.pynew file mode 100644index 000000000..80265ec3e--- /dev/null+++ b/agent/tests/test_ocr_integration.py@@ -0,0 +1,125 @@+"""Integration tests for the OCR pipeline.++Tests the full path: synthetic scanned PDF → _read_pdf() → OCR → text output.+Requires rapidocr_onnxruntime to be installed for the OCR path.+"""++from __future__ import annotations++import json+from pathlib import Path++import pytest++from src.config.accessor import reset_env_config+++def _has_rapid_ocr() -> bool:+ """Check if RapidOCR is available for testing."""+ try:+ from rapidocr_onnxruntime import RapidOCR # noqa: F401+ return True+ except ImportError:+ return False++[email protected](autouse=True)+def _reset_config():+ """Reset the cached EnvConfig around each test."""+ reset_env_config()+ yield+ reset_env_config()+++ not _has_rapid_ocr(),+ reason="rapidocr_onnxruntime not installed",+)+class TestOcrIntegration:+ """End-to-end OCR tests requiring RapidOCR."""++ _FONT_CANDIDATES = [+ "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",+ "/usr/share/fonts/dejavu/DejaVuSans.ttf",+ "/System/Library/Fonts/Helvetica.ttc",+ "/System/Library/Fonts/Menlo.ttc",+ ]++ @classmethod+ def _find_font(cls):+ from PIL import ImageFont++ for path in cls._FONT_CANDIDATES:+ try:+ return ImageFont.truetype(path, 36)+ except (OSError, IOError):+ continue+ return ImageFont.load_default()++ def test_synthetic_scanned_pdf_end_to_end(self, tmp_path: Path):+ """Create a scanned PDF with text, run _read_pdf, verify OCR output."""+ try:+ import pypdfium2 as pdfium # noqa: F401+ from PIL import Image, ImageDraw # noqa: F401+ except ImportError:+ pytest.skip("pypdfium2 or Pillow not installed")++ # Create a synthetic "scanned" PDF: render text as image, save as PDF+ # Pillow saves images as PDF with no text layer — exactly like a scan+ img = Image.new("RGB", (800, 200), color="white")+ draw = ImageDraw.Draw(img)+ test_text = "Hello OCR Test 12345"+ font = self._find_font()+ draw.text((50, 70), test_text, fill="black", font=font)++ # Save image directly as PDF via Pillow (no text layer, simulates scan)+ pdf_path = tmp_path / "test_scanned.pdf"+ img.save(str(pdf_path), "PDF", resolution=100.0)++ # Now run _read_pdf on this synthetic scanned PDF+ from src.tools.doc_reader_tool import _read_pdf++ result_json = _read_pdf(pdf_path, "")+ result = json.loads(result_json)++ # The PDF has no text layer (it's an image), so OCR should kick in+ # With RapidOCR available, we should get text back+ assert result["status"] == "ok", f"Expected ok, got: {result}"+ # The extracted text should contain our test string (OCR may not be perfect)+ text = result.get("text", "")+ # At minimum, some text should be extracted+ assert len(text) > 0, "OCR extracted no text from scanned PDF"+++class TestOcrEngineDiscovery:+ """Test that the OCR engine registry works correctly at integration level."""++ def test_builtin_engines_discoverable(self):+ """Built-in engines should be discoverable via _all_engines()."""+ from src.tools.ocr.engine import _all_engines++ engines = _all_engines()+ assert "rapid" in engines, "rapid engine not registered"+ assert "llm-vision" in engines, "llm-vision engine not registered"++ def test_rapid_engine_availability(self):+ """RapidOCR engine availability matches installation state."""+ from src.tools.ocr.engine import _all_engines++ engines = _all_engines()+ rapid = engines["rapid"]()+ # is_available() should match whether rapidocr_onnxruntime is installed+ assert rapid.is_available() == _has_rapid_ocr()++ def test_auto_mode_returns_local_or_none(self, monkeypatch):+ """auto mode should return a local engine or None, never cloud."""+ monkeypatch.setenv("VIBE_TRADING_OCR_ENGINE", "auto")+ reset_env_config()++ from src.tools.ocr.engine import get_ocr_engine++ engine = get_ocr_engine()+ if engine is not None:+ assert engine.is_cloud is False, (+ f"auto mode returned cloud engine: {engine.name}"+ )