"""Lazy OCR support for airport signs and information boards.""" from __future__ import annotations import threading from typing import Any import numpy as np from src.config import Settings, get_settings from src.preprocessing.image_processor import ImageProcessor from src.utils.timing import elapsed_ms, now_ms try: import easyocr except ImportError: # pragma: no cover - optional dependency easyocr = None try: import torch except ImportError: # pragma: no cover - optional dependency torch = None _OCR_INFERENCE_LOCK = threading.Lock() class OCRReader: """Extract visible text without retaining uploaded image data.""" def __init__( self, settings: Settings | None = None, reader: Any | None = None, image_processor: ImageProcessor | None = None, ) -> None: self.settings = settings or get_settings() self.reader = reader self.image_processor = image_processor or ImageProcessor(self.settings) self.last_error: str | None = None def load(self) -> bool: if self.reader is not None: return True if not self.settings.ocr_enabled or easyocr is None: self.last_error = "OCR is disabled or its dependency is unavailable." return False languages = [ item.strip() for item in self.settings.ocr_languages.split(",") if item.strip() ] or ["en"] try: self.reader = easyocr.Reader(languages, gpu=False) self.last_error = None return True except Exception as exc: self.last_error = f"{type(exc).__name__}: {exc}" self.reader = None return False def extract_text(self, file_path: str | None) -> dict[str, Any]: start = now_ms() prepared = self.image_processor.prepare_image(file_path) if not prepared["valid"]: return { "success": False, "text": "", "confidence": 0.0, "items": [], "processing_time_ms": elapsed_ms(start), "error": prepared["error"] or "Invalid image.", } if not self.load(): return { "success": False, "text": "", "confidence": 0.0, "items": [], "processing_time_ms": elapsed_ms(start), "error": self.last_error or "OCR is disabled or unavailable.", } try: image_array = np.asarray(prepared["image"]) if torch is None: raw = self.reader.readtext(image_array, detail=1, paragraph=False) else: # EasyOCR hard-codes pin_memory=True in its recognition # DataLoader. ZeroGPU exposes CUDA capability to PyTorch even # outside a GPU allocation, so pinned-memory initialization can # raise "No CUDA GPUs are available" for an otherwise CPU-only # reader. Override that one constructor argument while the # synchronous OCR call runs, then restore the global factory. with _OCR_INFERENCE_LOCK: original_loader = torch.utils.data.DataLoader def cpu_loader(*args: Any, **kwargs: Any) -> Any: kwargs["pin_memory"] = False return original_loader(*args, **kwargs) torch.utils.data.DataLoader = cpu_loader try: raw = self.reader.readtext( image_array, detail=1, paragraph=False ) finally: torch.utils.data.DataLoader = original_loader items = [ {"text": str(item[1]).strip(), "confidence": float(item[2])} for item in raw if len(item) >= 3 and str(item[1]).strip() ] confidence = ( sum(item["confidence"] for item in items) / len(items) if items else 0.0 ) return { "success": bool(items), "text": " ".join(item["text"] for item in items), "confidence": confidence, "items": items, "processing_time_ms": elapsed_ms(start), "error": None if items else "No useful text detected.", } except Exception as exc: return { "success": False, "text": "", "confidence": 0.0, "items": [], "processing_time_ms": elapsed_ms(start), "error": f"{type(exc).__name__}: {exc}", }