Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(ocr): pluggable OCR engine interface with RapidOCR and Qwen-VL backends

shadowinlife65fb112c5f49
diff --git a/agent/src/tools/doc_reader_tool.py b/agent/src/tools/doc_reader_tool.py
index 9cfed30da..0112ce2ed 100644
--- a/agent/src/tools/doc_reader_tool.py
+++ b/agent/src/tools/doc_reader_tool.py
@@ -44,26 +44,31 @@ _TEXT_EXTS = {
".dockerfile", ".makefile", ".cmake",
}
-_ocr_engine = None
-_ocr_checked = False
+from src.tools.ocr import get_ocr_engine, get_ocr_install_hint
-_OCR_INSTALL_MSG = (
- "OCR engine not available. This document contains scanned/image-based pages "
- "that require OCR to extract text. "
- "Install the OCR dependency: pip install rapidocr_onnxruntime"
-)
+_cached_ocr_engine = None
+_cached_ocr_checked = False
+
+
+def _get_ocr():
+ """Return the configured OCR engine (cached), or None."""
+ global _cached_ocr_engine, _cached_ocr_checked
+ if not _cached_ocr_checked:
+ _cached_ocr_engine = get_ocr_engine()
+ _cached_ocr_checked = True
+ return _cached_ocr_engine
def _ocr_available() -> bool:
- """Check if RapidOCR is importable (cached after first call)."""
- global _ocr_checked
- if not _ocr_checked:
- try:
- import rapidocr_onnxruntime # noqa: F401 # type: ignore
- _ocr_checked = True
- except ImportError:
- _ocr_checked = False
- return _ocr_checked
+ return _get_ocr() is not None
+
+
+def _ocr_image_array(img) -> str:
+ """Run OCR on a numpy image via the pluggable engine."""
+ engine = _get_ocr()
+ if engine is None:
+ return ""
+ return engine.recognize(img)
# ---------------- shared helpers ----------------
@@ -95,27 +100,6 @@ def _envelope(path: Path, fmt: str, text: str, **extra: Any) -> str:
return json.dumps(payload, ensure_ascii=False)
-def _get_ocr():
- """Lazily load RapidOCR. Raises ImportError if not installed."""
- global _ocr_engine
- if _ocr_engine is None:
- from rapidocr_onnxruntime import RapidOCR # type: ignore
- _ocr_engine = RapidOCR()
- return _ocr_engine
-
-
-def _ocr_image_array(img) -> str:
- """Run OCR on a numpy image; return joined lines or empty string.
-
- Raises ImportError if RapidOCR is not installed.
- """
- ocr = _get_ocr()
- result, _ = ocr(img)
- if not result:
- return ""
- return "\n".join(item[1] for item in result)
-
-
# ---------------- PDF ----------------
def _parse_pages(pages_str: str, total: int) -> list[int]:
@@ -165,10 +149,11 @@ def _read_pdf(path: Path, pages: str) -> str:
continue
# Scanned/image page detected — OCR required
if not _ocr_available():
+ engine = _get_ocr()
+ hint = get_ocr_install_hint(engine)
return _err(
f"Page {i + 1}/{total_pages} is a scanned/image page with no "
- f"extractable text, but the OCR engine is not installed. "
- f"{_OCR_INSTALL_MSG}"
+ f"extractable text, but no OCR engine is available. {hint}"
)
bitmap = page.render(scale=300 / 72)
img = bitmap.to_numpy()
@@ -275,7 +260,12 @@ def _read_image(path: Path) -> str:
return _err(f"Failed to open image: {exc}")
if not _ocr_available():
- return _err(_OCR_INSTALL_MSG)
+ engine = _get_ocr()
+ hint = get_ocr_install_hint(engine)
+ return _err(
+ f"This image requires OCR to extract text, but no OCR engine is "
+ f"available. {hint}"
+ )
text = _ocr_image_array(img)
if not text.strip():
diff --git a/agent/src/tools/ocr/__init__.py b/agent/src/tools/ocr/__init__.py
new file mode 100644
index 000000000..f19607a5e
--- /dev/null
+++ b/agent/src/tools/ocr/__init__.py
@@ -0,0 +1,5 @@
+"""OCR engine package."""
+
+from src.tools.ocr.engine import OcrEngine, get_ocr_engine, get_ocr_install_hint
+
+__all__ = ["OcrEngine", "get_ocr_engine", "get_ocr_install_hint"]
diff --git a/agent/src/tools/ocr/engine.py b/agent/src/tools/ocr/engine.py
new file mode 100644
index 000000000..cd58bb93c
--- /dev/null
+++ b/agent/src/tools/ocr/engine.py
@@ -0,0 +1,123 @@
+"""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.
+"""
+
+from __future__ import annotations
+
+import logging
+import os
+from typing import Protocol, runtime_checkable
+
+import numpy as np
+
+logger = logging.getLogger(__name__)
+
+_OCR_ENGINE_ENV = "VIBE_TRADING_OCR_ENGINE"
+_VALID_ENGINES = ("auto", "rapid", "qwen-vl", "none")
+
+
+@runtime_checkable
+class OcrEngine(Protocol):
+ """Abstract OCR engine interface.
+
+ All implementations must accept a numpy RGB image array and return
+ extracted text (empty string if no text found).
+ """
+
+ name: str
+
+ def is_available(self) -> bool:
+ """Check if this engine's dependencies are satisfied."""
+ ...
+
+ def recognize(self, image: np.ndarray) -> str:
+ """Run OCR on a numpy RGB image array. Return extracted text."""
+ ...
+
+
+def get_ocr_engine() -> OcrEngine | None:
+ """Return the configured OCR engine, or None if unavailable.
+
+ Engine selection via VIBE_TRADING_OCR_ENGINE:
+ - "auto" (default): try rapid first, then qwen-vl
+ - "rapid": RapidOCR only (local, ONNX)
+ - "qwen-vl": Qwen-VL vision model (cloud, DashScope API)
+ - "none": disable OCR entirely
+ """
+ choice = os.getenv(_OCR_ENGINE_ENV, "auto").strip().lower()
+ if choice not in _VALID_ENGINES:
+ logger.warning("Unknown OCR engine '%s', falling back to 'auto'", choice)
+ choice = "auto"
+
+ if choice == "none":
+ return None
+
+ if choice == "rapid":
+ return _try_rapid()
+
+ if choice == "qwen-vl":
+ return _try_qwen_vl()
+
+ engines_to_try = [(_try_rapid, "rapid"), (_try_qwen_vl, "qwen-vl")]
+ for factory, name in engines_to_try:
+ try:
+ engine = factory()
+ if engine is not None and engine.is_available():
+ logger.info("OCR engine selected: %s", name)
+ return engine
+ except Exception:
+ logger.debug("OCR engine '%s' not available", name, exc_info=True)
+
+ return None
+
+
+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
+
+
+def get_ocr_install_hint(engine: OcrEngine | None) -> str:
+ """Return an actionable install message for the missing OCR engine."""
+ if engine is not None:
+ return ""
+
+ choice = os.getenv(_OCR_ENGINE_ENV, "auto").strip().lower()
+
+ 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: export DASHSCOPE_API_KEY=your_key (uses Qwen-VL)\n"
+ "Or set VIBE_TRADING_OCR_ENGINE=none to disable OCR."
+ )
diff --git a/agent/src/tools/ocr/qwen_vision_ocr.py b/agent/src/tools/ocr/qwen_vision_ocr.py
new file mode 100644
index 000000000..a85f91175
--- /dev/null
+++ b/agent/src/tools/ocr/qwen_vision_ocr.py
@@ -0,0 +1,94 @@
+"""Qwen-VL vision model OCR engine — cloud, DashScope OpenAI-compatible API."""
+
+from __future__ import annotations
+
+import base64
+import io
+import logging
+import os
+
+import numpy as np
+
+logger = logging.getLogger(__name__)
+
+_DASHSCOPE_API_KEY_ENV = "DASHSCOPE_API_KEY"
+_DASHSCOPE_BASE_URL = "https://dashscope.aliyuncs.com/compatible-mode/v1"
+_DEFAULT_MODEL = "qwen-vl-plus"
+_MODEL_ENV = "VIBE_TRADING_OCR_QWEN_MODEL"
+
+_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:
+ api_key = os.getenv(_DASHSCOPE_API_KEY_ENV)
+ 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(
+ f"Qwen-VL OCR requires {_DASHSCOPE_API_KEY_ENV} environment variable"
+ )
+
+ b64 = self._numpy_to_base64(image)
+ model = os.getenv(_MODEL_ENV, _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.py
new file mode 100644
index 000000000..11928e6d6
--- /dev/null
+++ b/agent/src/tools/ocr/rapid_ocr.py
@@ -0,0 +1,31 @@
+"""RapidOCR engine — local, ONNX Runtime based, no API key needed."""
+
+from __future__ import annotations
+
+import numpy as np
+
+
+class RapidOcrEngine:
+ """Local OCR engine using RapidOCR (PaddleOCR-derived, ONNX Runtime)."""
+
+ name = "rapid"
+
+ def __init__(self) -> None:
+ self._engine = None
+
+ def is_available(self) -> bool:
+ try:
+ from rapidocr_onnxruntime import RapidOCR # type: ignore
+ if self._engine is None:
+ self._engine = RapidOCR()
+ return True
+ except ImportError:
+ return False
+
+ def recognize(self, image: np.ndarray) -> str:
+ if not self.is_available():
+ raise RuntimeError("RapidOCR not installed: pip install rapidocr_onnxruntime")
+ result, _ = self._engine(image)
+ if not result:
+ return ""
+ return "\n".join(item[1] for item in result)