"""PaddleOCR sidecar for FoodNode onboarding. Single endpoint -- ``POST /extract`` -- that takes a front + back card image pair and returns the OCR'd text per side. Auth is a shared secret in the ``X-Internal-API-Key`` header; mismatched / missing keys get a 401. The Docker network is the only thing that should be able to reach this; do not map the host port. The Django side calls this from ``onboarding/providers/real_card_ocr.py``. """ from __future__ import annotations import io import logging import os from typing import Optional from fastapi import FastAPI, File, Header, HTTPException, UploadFile from fastapi.responses import JSONResponse from PIL import Image logger = logging.getLogger("card-ocr") logging.basicConfig(level=logging.INFO) app = FastAPI(title="FoodNode card-ocr sidecar", docs_url=None, redoc_url=None) OCR_INTERNAL_API_KEY = os.environ.get("OCR_INTERNAL_API_KEY", "") MAX_BYTES = int(os.environ.get("CARD_OCR_MAX_BYTES", str(8 * 1024 * 1024))) # Lazy-init PaddleOCR -- module import time would block uvicorn startup # for ~10s while the first model loads. Defer until first request and # cache the singleton. _ocr_singleton = None def _get_ocr(): global _ocr_singleton if _ocr_singleton is None: from paddleocr import PaddleOCR # local import keeps app startup fast _ocr_singleton = PaddleOCR(use_angle_cls=True, lang="en", show_log=False) return _ocr_singleton def _check_auth(x_internal_api_key: Optional[str]) -> None: if not OCR_INTERNAL_API_KEY: # Refuse to run unauthenticated even in dev -- the sidecar is # internal-only and forgetting to set the key in production # would silently expose it. raise HTTPException(status_code=503, detail="ocr-key-not-configured") if not x_internal_api_key or x_internal_api_key != OCR_INTERNAL_API_KEY: raise HTTPException(status_code=401, detail="invalid-internal-key") def _ocr_one(image_bytes: bytes) -> tuple[str, float, list[dict]]: """Run PaddleOCR on a single image. Returns ``(joined_text, mean_confidence, blocks)`` where blocks is a list of ``{"text": ..., "confidence": ...}`` per detected line so the Django side can attribute Haiku's structured output back to a specific OCR block (used for per-field confidence aggregation). """ if not image_bytes: return "", 0.0, [] if len(image_bytes) > MAX_BYTES: raise HTTPException(status_code=413, detail="image-too-large") try: img = Image.open(io.BytesIO(image_bytes)) img.load() # raise on truncated bytes early except Exception as exc: # noqa: BLE001 logger.warning("invalid-image-bytes: %s", exc) raise HTTPException(status_code=400, detail="invalid-image") import numpy as np arr = np.array(img.convert("RGB")) ocr = _get_ocr() # PaddleOCR returns a list of "page" results; we feed one image so we # take the first page. Each line is [bbox, (text, confidence)]. pages = ocr.ocr(arr, cls=True) lines: list[str] = [] confidences: list[float] = [] blocks: list[dict] = [] for page in pages or []: for entry in page or []: try: _bbox, (text, conf) = entry except Exception: # noqa: BLE001 -- shape may vary across versions continue text = (text or "").strip() if not text: continue lines.append(text) try: conf_f = float(conf) except (TypeError, ValueError): conf_f = 0.0 confidences.append(conf_f) blocks.append({"text": text, "confidence": round(conf_f, 4)}) joined = "\n".join(lines) mean_conf = sum(confidences) / len(confidences) if confidences else 0.0 return joined, round(mean_conf, 4), blocks @app.get("/") def root() -> JSONResponse: """HF Spaces' edge healthcheck pings GET / to decide if the Space is 'running'. Without a handler here the Space gets a 404 and HF marks it unhealthy, then kills the container after 30 min. Return the same shape as /health so anything probing either gets a 200.""" return JSONResponse({"ok": True, "service": "card-ocr"}) @app.get("/health") def health() -> JSONResponse: """Liveness probe. Returns 200 once the process is up; the OCR singleton lazy-loads on first /extract call so /health is cheap.""" return JSONResponse({"ok": True}) @app.post("/extract") async def extract( front_image: Optional[UploadFile] = File(default=None), back_image: Optional[UploadFile] = File(default=None), x_internal_api_key: Optional[str] = Header(default=None, alias="X-Internal-API-Key"), ): _check_auth(x_internal_api_key) front_bytes = await front_image.read() if front_image else b"" back_bytes = await back_image.read() if back_image else b"" if not front_bytes and not back_bytes: raise HTTPException(status_code=400, detail="no-images-provided") front_text, front_conf, front_blocks = _ocr_one(front_bytes) back_text, back_conf, back_blocks = _ocr_one(back_bytes) return { "front_text": front_text, "back_text": back_text, "confidence": {"front": front_conf, "back": back_conf}, "blocks": {"front": front_blocks, "back": back_blocks}, }