File size: 5,361 Bytes
7065d8d 6f32872 7065d8d 6f32872 7065d8d 6f32872 7065d8d 6f32872 7065d8d 6f32872 7065d8d 85aa55f 7065d8d 6f32872 7065d8d 6f32872 7065d8d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 | """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},
}
|