Sun commited on
Commit ·
7065d8d
0
Parent(s):
chore: consolidate plans, add explicit permissions, and update onboarding flow
Browse filesFiles changed (4)
- DockerfileAdded+39
- main.pyAdded+124
- requirements.txtAdded+6
- test_main.pyAdded+102
123456789101112131415161718192021222324252627282930313233343536373839# PaddleOCR sidecar for the FoodNode onboarding pipeline.## Internal-only service. Listens on :8001 inside the Docker network.# Auths every request via the X-Internal-API-Key header.## PaddlePaddle is heavy (~800MB resident set, ~2GB image). Python 3.12# slim base + system libs needed for libGL / OpenCV.FROM python:3.12-slim
ENV PYTHONUNBUFFERED=1 \ PYTHONDONTWRITEBYTECODE=1 \ PIP_NO_CACHE_DIR=1 \ HOME=/root
# System deps for PaddlePaddle + OpenCV (libgomp, libGL, libglib).RUN apt-get update \ && apt-get install -y --no-install-recommends \ ca-certificates curl \ libgomp1 libglib2.0-0 libsm6 libxext6 libxrender1 libgl1 \ && rm -rf /var/lib/apt/lists/*
WORKDIR /app
COPY requirements.txt .RUN pip install --upgrade pip \ && pip install -r requirements.txt
# Pre-download the English PaddleOCR detection + recognition models so the# first request after a deploy isn't a 10s download. Bake into the image.RUN python -c "from paddleocr import PaddleOCR; PaddleOCR(use_angle_cls=True, lang='en', show_log=False)" \ || echo "model preload failed; will pull on first request"
COPY main.py .
EXPOSE 8001
# Single worker -- PaddleOCR holds GPU/CPU model state per-process and we# expect single-digit cards/day, so concurrency isn't worth the RAM.CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8001", "--workers", "1"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124"""PaddleOCR sidecar for FoodNode onboarding.
Single endpoint -- ``POST /extract`` -- that takes a front + back cardimage pair and returns the OCR'd text per side. Auth is a sharedsecret in the ``X-Internal-API-Key`` header; mismatched / missing keysget a 401. The Docker network is the only thing that should be ableto 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 ioimport loggingimport osfrom typing import Optional
from fastapi import FastAPI, File, Header, HTTPException, UploadFilefrom fastapi.responses import JSONResponsefrom 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]: """Run PaddleOCR on a single image. Returns (joined_text, mean_confidence).""" 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] = [] 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 text: lines.append(text) try: confidences.append(float(conf)) except (TypeError, ValueError): pass
joined = "\n".join(lines) mean_conf = sum(confidences) / len(confidences) if confidences else 0.0 return joined, round(mean_conf, 4)
@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 = _ocr_one(front_bytes) back_text, back_conf = _ocr_one(back_bytes)
return { "front_text": front_text, "back_text": back_text, "confidence": {"front": front_conf, "back": back_conf}, }123456fastapi==0.115.6uvicorn[standard]==0.34.0python-multipart==0.0.20paddlepaddle==2.6.2paddleocr==2.10.0Pillow==11.0.0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102"""Smoke tests for the PaddleOCR sidecar.
Avoid invoking the real PaddleOCR singleton in CI -- monkeypatch``_get_ocr`` so the unit tests run in a few hundred ms withoutloading a 800MB model. Integration coverage with real PaddleOCRlives behind the ``CARD_OCR_INTEGRATION=1`` env var so the developercan run it locally on demand."""from __future__ import annotations
import ioimport os
import pytestfrom fastapi.testclient import TestClientfrom PIL import Image
@pytest.fixturedef client(monkeypatch): # Ensure auth check passes without needing the real key in CI. monkeypatch.setenv("OCR_INTERNAL_API_KEY", "test-key")
# Reload main so it picks up the env var. import importlib import main as ocr_main importlib.reload(ocr_main)
# Stub the OCR singleton so tests don't need PaddlePaddle installed. class _FakeOCR: def ocr(self, _arr, cls=True): # noqa: ARG002 return [[ [[[0, 0], [0, 0], [0, 0], [0, 0]], ("Aanya Patel", 0.97)], [[[0, 0], [0, 0], [0, 0], [0, 0]], ("aanya@sunrise.example", 0.92)], ]]
monkeypatch.setattr(ocr_main, "_ocr_singleton", _FakeOCR()) return TestClient(ocr_main.app)
def _png_bytes() -> bytes: img = Image.new("RGB", (50, 30), (255, 255, 255)) buf = io.BytesIO() img.save(buf, format="PNG") return buf.getvalue()
def test_health_200(client): res = client.get("/health") assert res.status_code == 200 assert res.json() == {"ok": True}
def test_extract_requires_internal_key(client): res = client.post( "/extract", files={"front_image": ("f.png", _png_bytes(), "image/png")}, ) assert res.status_code == 401
def test_extract_rejects_wrong_key(client): res = client.post( "/extract", files={"front_image": ("f.png", _png_bytes(), "image/png")}, headers={"X-Internal-API-Key": "wrong"}, ) assert res.status_code == 401
def test_extract_returns_text_and_confidence(client): res = client.post( "/extract", files={ "front_image": ("f.png", _png_bytes(), "image/png"), "back_image": ("b.png", _png_bytes(), "image/png"), }, headers={"X-Internal-API-Key": "test-key"}, ) assert res.status_code == 200, res.text body = res.json() assert "Aanya Patel" in body["front_text"] assert "aanya@sunrise.example" in body["front_text"] assert body["confidence"]["front"] > 0
def test_extract_rejects_empty_request(client): res = client.post( "/extract", headers={"X-Internal-API-Key": "test-key"}, ) # FastAPI may return 400 (no-images-provided) or 422 (validation). assert res.status_code in (400, 422)
def test_extract_rejects_invalid_image(client): res = client.post( "/extract", files={"front_image": ("f.png", b"not-an-image", "image/png")}, headers={"X-Internal-API-Key": "test-key"}, ) assert res.status_code == 400DockerfileAdded+39
main.pyAdded+124
requirements.txtAdded+6
test_main.pyAdded+102