Sagar Deswal Claude Opus 4.7 (1M context) commited on
Commit Β·
72de53b
1
Parent(s): 6f32872
chore(card-ocr): migrate sidecar deployment from Railway to Hugging Face Space
Browse filesFiles changed (3)
- Dockerfile+29-23
- README.md+59-18
- railway.jsonDeleted-12
1234567891 unmodified line11121314151617182 unmodified lines21222324252627282930313 unmodified lines3536373839404142434445464748495051525354555657# 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). Pin to# Python 3.11 -- paddlepaddle 2.6.2's pre-built wheel is built against# CPython 3.10/3.11 and segfaults on import under 3.12. Slim base +# system libs needed for libGL / OpenCV.1 unmodified lineENV PYTHONUNBUFFERED=1 \PYTHONDONTWRITEBYTECODE=1 \PIP_NO_CACHE_DIR=1 \HOME=/root# System deps for PaddlePaddle + OpenCV (libgomp, libGL, libglib).RUN apt-get update \2 unmodified lineslibgomp1 libglib2.0-0 libsm6 libxext6 libxrender1 libgl1 \&& rm -rf /var/lib/apt/lists/*WORKDIR /appCOPY requirements.txt .RUN pip install --upgrade pip \&& pip install -r requirements.txt \# paddleocr pulls in BOTH opencv-python and opencv-contrib-python as# transitive deps, on top of the opencv-python-headless we want for# server-side use. All three install side-by-side and ship overlapping3 unmodified lines&& pip uninstall -y opencv-python opencv-contrib-python# 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.## `--host ::` binds dual-stack (IPv6 + IPv4 on Linux) so Railway's private# network can route to the container. The local docker-compose stack still# reaches it via IPv4 because Linux dual-stack accepts both families.## `--port ${PORT:-8001}` lets Railway's healthcheck infrastructure (which# expects the app to bind to whatever PORT env var Railway injects) find# the service. Local docker-compose doesn't set PORT, so the fallback# keeps the existing 8001 binding for dev.CMD ["sh", "-c", "exec uvicorn main:app --host :: --port ${PORT:-8001} --workers 1"]123456789101 unmodified line121314151617182 unmodified lines2122232425262728293031323334353637383 unmodified lines42434445464748495051525354555657585960616263# PaddleOCR sidecar for the FoodNode onboarding pipeline.## Deployed as a Hugging Face Space (Docker SDK -- see README.md frontmatter).# Auths every request via the X-Internal-API-Key header, since HF Spaces# are publicly reachable by URL.## PaddlePaddle is heavy (~800MB resident set, ~1.5GB image). Pin to# Python 3.11 -- paddlepaddle 2.6.2's pre-built wheel is built against# CPython 3.10/3.11 and segfaults on import under 3.12. Slim base +# system libs needed for libGL / OpenCV.1 unmodified lineENV PYTHONUNBUFFERED=1 \PYTHONDONTWRITEBYTECODE=1 \PIP_NO_CACHE_DIR=1# System deps for PaddlePaddle + OpenCV (libgomp, libGL, libglib).RUN apt-get update \2 unmodified lineslibgomp1 libglib2.0-0 libsm6 libxext6 libxrender1 libgl1 \&& rm -rf /var/lib/apt/lists/*# Hugging Face Spaces runs containers as uid 1000 -- files baked at# build time must be owned by that uid or the runtime can't read them.RUN useradd -m -u 1000 userUSER userENV HOME=/home/user \PATH=/home/user/.local/bin:$PATHWORKDIR $HOME/appCOPY --chown=user:user requirements.txt .RUN pip install --user --upgrade pip \&& pip install --user -r requirements.txt \# paddleocr pulls in BOTH opencv-python and opencv-contrib-python as# transitive deps, on top of the opencv-python-headless we want for# server-side use. All three install side-by-side and ship overlapping3 unmodified lines&& pip uninstall -y opencv-python opencv-contrib-python# Pre-download the English PaddleOCR detection + recognition models so the# first request after a deploy isn't a ~10s download. Cache lands in# $HOME/.paddleocr/, owned by uid 1000 and writable on subsequent boots.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 --chown=user:user main.py .# HF Spaces convention: routes incoming HTTP to the port declared in# README.md frontmatter (`app_port: 7860`). Local docker-compose sets# PORT=8001 explicitly so the existing in-network URL `http://card-ocr:8001`# continues to resolve without compose-side rewires.EXPOSE 7860# Single worker -- PaddleOCR holds model state per-process and we expect# single-digit cards/day, so concurrency isn't worth the RAM.## `--host ::` binds dual-stack (IPv6 + IPv4 on Linux) so HF's edge / the# local docker network can route to the container.CMD ["sh", "-c", "exec uvicorn main:app --host :: --port ${PORT:-7860} --workers 1"]
12345611 unmodified lines18192021222324255 unmodified lines31323334353637383940414243444546474849505152535455565758596061626364# card-ocr sidecarPaddleOCR FastAPI service that fronts the onboarding card-OCR pipeline.## Surface11 unmodified lines"back_text": "+91 99 1234 5678\naanya@sunrise.example","confidence": {"front": 0.94, "back": 0.91},"blocks": {"front": [{"text": "Aanya Patel", "confidence": 0.97}, ...],"back": [{"text": "+91 99 1234 5678", "confidence": 0.92}, ...]}}```5 unmodified lines## Security model- The service binds to port `8001` inside the Docker network and isintentionally **not** mapped to the host. Only the `backend` servicecan reach it.- Every request must carry `X-Internal-API-Key: <OCR_INTERNAL_API_KEY>`matching the env var the sidecar started with. Missing or wrong keyreturns `401`. Empty `OCR_INTERNAL_API_KEY` returns `503` (refuse torun unauthenticated even in dev).- Image bytes are processed in-memory; nothing is persisted by thesidecar.## Image sizeThe image is large (~1.5 GB). The bulk is PaddleOCR weights, which arepre-baked at build time so the first request after a deploy isn't a~10 s download. The healthcheck has a 30 s `start_period` to covercontainer start.## Local build (Apple Silicon)The PaddlePaddle wheel is `linux/amd64` only. On Apple Silicon devmachines, build the image with buildx:```bashdocker buildx build --platform linux/amd64 -t card-ocr ./backend/services/card_ocr```Or just run the full stack via `docker compose up --build`, whichbuilds the sidecar inside Linux containers regardless of host arch.## Tests1234567891011121314151617181911 unmodified lines31323334353637385 unmodified lines4445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105---title: FoodNode Card OCRemoji: "\U0001F4C7"colorFrom: bluecolorTo: greensdk: dockerapp_port: 7860pinned: falseshort_description: Internal PaddleOCR sidecar for FoodNode onboarding.---# card-ocr sidecarPaddleOCR FastAPI service that fronts the onboarding card-OCR pipeline.Deployed as a Hugging Face Space (Docker SDK); the frontmatter at thetop of this file is the canonical Space config.## Surface11 unmodified lines"back_text": "+91 99 1234 5678\naanya@sunrise.example","confidence": {"front": 0.94, "back": 0.91},"blocks": {"front": [{"text": "Aanya Patel", "confidence": 0.97}],"back": [{"text": "+91 99 1234 5678", "confidence": 0.92}]}}```5 unmodified lines## Security model- Every request must carry `X-Internal-API-Key: <OCR_INTERNAL_API_KEY>`matching the env var the sidecar started with. Missing or wrong keyreturns `401`. Empty `OCR_INTERNAL_API_KEY` returns `503` (refuse torun unauthenticated even in dev).- HF Spaces are publicly reachable by URL, so the X-Internal-API-Keygate is the single boundary keeping arbitrary callers out β neverleak the key. Treat it like a database password.- Image bytes are processed in-memory; nothing is persisted by thesidecar.## Deploying to Hugging Face Spaces1. Create a Space at [huggingface.co/new-space](https://huggingface.co/new-space)with **SDK: Docker**.2. In the Space's **Settings β Repository secrets**, add`OCR_INTERNAL_API_KEY` (same shared secret Django uses). Without itthe sidecar refuses every request with `503 ocr-key-not-configured`.Optionally also add `CARD_OCR_MAX_BYTES` to override the 8 MB cap.3. Push this directory to the Space's git remote:```bashgit remote add hf https://huggingface.co/spaces/<user>/<space>git subtree push --prefix=backend/services/card_ocr hf main```(Or use `huggingface_hub`'s `HfApi().upload_folder` from a script.)4. Set Django's `OCR_SERVICE_URL` env to `https://<user>-<space>.hf.space`and `OCR_INTERNAL_API_KEY` to the same secret. The provider in[real_card_ocr.py](../../onboarding/providers/real_card_ocr.py) needsno code change β it already POSTs to `${OCR_SERVICE_URL}/extract`.Hardware tier: free `cpu-basic` works for development. For productionthe cold-start (~10 s for PaddleOCR model load) plus the free tier'ssleep-after-inactivity policy will surface as a 30β60 s first-calllatency; upgrade to a paid CPU tier to keep the Space warm.## Local developmentThe full stack still runs via `docker compose up` β the sidecar isbuilt from this directory and exposed at `http://card-ocr:8001` insidethe Docker network (intentionally not published to the host). Composesets `PORT=8001` to override the HF default of 7860 so the existingin-network URL stays stable.Apple Silicon dev machines: the PaddlePaddle wheel is `linux/amd64`only, so build the image via `docker buildx`:```bashdocker buildx build --platform linux/amd64 -t card-ocr ./backend/services/card_ocr```Or just `docker compose up --build`, which builds inside Linux containersregardless of host arch.## Image sizeThe image is ~1.5 GB. The bulk is PaddleOCR weights, pre-baked at buildtime so the first request after a deploy isn't a ~10 s download.## Tests
123456789101112{ "$schema": "https://railway.app/railway.schema.json", "build": { "builder": "DOCKERFILE", "dockerfilePath": "Dockerfile" }, "deploy": { "startCommand": "sh -c 'exec uvicorn main:app --host :: --port ${PORT:-8001} --workers 1'", "restartPolicyType": "ON_FAILURE", "restartPolicyMaxRetries": 3 }}Dockerfile+29-23
README.md+59-18
railway.jsonDeleted-12