Spaces:
Sleeping

card-ocr / README.md
sagardeswal's picture
Claude Opus 4.7 (1M context)
docs(card-ocr): operator runbook for the Hugging Face Space deploy
1035f0d
|
Raw History Blame Contribute Delete
7.07 kB
metadata
title: FoodNode Card OCR
emoji: πŸ“‡
colorFrom: blue
colorTo: green
sdk: docker
app_port: 7860
pinned: false
short_description: Internal PaddleOCR sidecar for FoodNode onboarding.

card-ocr sidecar

PaddleOCR FastAPI service that fronts the onboarding card-OCR pipeline. Deployed as a Hugging Face Space (Docker SDK); the frontmatter at the top of this file is the canonical Space config.

Surface

GET  /health              # liveness
POST /extract             # multipart: front_image, back_image
                          # header:    X-Internal-API-Key

/extract returns:

{
  "front_text": "Aanya Patel\nFounder\nSunrise Organics",
  "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}]
  }
}

blocks is the per-line OCR output that the Django side (backend/onboarding/providers/real_card_ocr.py) uses to attribute Haiku's structured fields back to a specific OCR line β€” that's how per-field confidence works.

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 key returns 401. Empty OCR_INTERNAL_API_KEY returns 503 (refuse to run unauthenticated even in dev).
  • HF Spaces are publicly reachable by URL, so the X-Internal-API-Key gate is the single boundary keeping arbitrary callers out β€” never leak the key. Treat it like a database password.
  • Image bytes are processed in-memory; nothing is persisted by the sidecar.

Deploying to Hugging Face Spaces

  1. Create a Space at 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 it the 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:
    git 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 needs no code change β€” it already POSTs to ${OCR_SERVICE_URL}/extract.

Hardware tier: free cpu-basic works for development. For production the cold-start (~10 s for PaddleOCR model load) plus the free tier's sleep-after-inactivity policy will surface as a 30–60 s first-call latency; upgrade to a paid CPU tier to keep the Space warm.

Local development

The full stack still runs via docker compose up β€” the sidecar is built from this directory and exposed at http://card-ocr:8001 inside the Docker network (intentionally not published to the host). Compose sets PORT=8001 to override the HF default of 7860 so the existing in-network URL stays stable.

Apple Silicon dev machines: the PaddlePaddle wheel is linux/amd64 only, so build the image via docker buildx:

docker buildx build --platform linux/amd64 -t card-ocr ./backend/services/card_ocr

Or just docker compose up --build, which builds inside Linux containers regardless of host arch.

Image size

The image is ~1.5 GB. The bulk is PaddleOCR weights, pre-baked at build time so the first request after a deploy isn't a ~10 s download.

Tests

# Fast unit tests with the OCR singleton stubbed (no PaddleOCR required):
cd backend/services/card_ocr
pip install -r requirements.txt fastapi[testclient]
pytest -v

# Real PaddleOCR integration (downloads models, takes ~30s):
CARD_OCR_INTEGRATION=1 pytest -v

Operator runbook

End-to-end deploy of this sidecar to the FoodNode Hugging Face Space (https://huggingface.co/spaces/foodnode/card-ocr). The Dockerfile, README frontmatter, and hf git remote are already in place -- these are the manual steps that the repo can't automate for you.

One-time setup

  1. Create the Space at https://huggingface.co/new-space with owner foodnode, name card-ocr, SDK: Docker, hardware CPU basic (free). (If the Space already exists, skip.)

  2. Set the shared secret in the Space's Settings β†’ Repository secrets:

    OCR_INTERNAL_API_KEY = <openssl rand -hex 32>
    

    The same value goes into Django's env (OCR_INTERNAL_API_KEY Fly secret). Without it the sidecar refuses every request with 503 ocr-key-not-configured.

  3. Authenticate the local hf git remote. Anonymous fetches against an HF Space repo error with fatal: expected 'acknowledgments' -- that is HF rejecting the unauthenticated git protocol. Two options:

    # Option A: huggingface_hub CLI (preferred -- one login lasts
    # across every HF command)
    pip install huggingface_hub
    huggingface-cli login   # paste a write-scoped token from
                            # https://huggingface.co/settings/tokens
    
    # Option B: bake the token into the remote URL
    git remote set-url hf https://USER:HF_TOKEN@huggingface.co/spaces/foodnode/card-ocr
    

Every deploy

# Push only this subdirectory as the root of the HF Space repo
git subtree push --prefix=backend/services/card_ocr hf main

The first push triggers a ~5–10 min HF build (downloads PaddleOCR weights into the image). Subsequent pushes are layered, so only the files that actually changed re-upload.

Smoke tests

# Liveness (always cheap, no auth)
curl https://foodnode-card-ocr.hf.space/health
# β†’ {"ok": true}

# Auth check (no body needed)
curl -i -H "X-Internal-API-Key: $OCR_INTERNAL_API_KEY" \
  https://foodnode-card-ocr.hf.space/health

# End-to-end extract -- replace the JPGs with real card photos
curl -H "X-Internal-API-Key: $OCR_INTERNAL_API_KEY" \
  -F front_image=@samples/card_front.jpg \
  -F back_image=@samples/card_back.jpg \
  https://foodnode-card-ocr.hf.space/extract

The first call after the Space has been idle for a while will take 30–60 s to return -- that's PaddleOCR loading its model into a cold container. Bump Django's OCR_REQUEST_TIMEOUT_SECONDS to β‰₯ 30 on the free tier so the /api/onboarding/sessions/<id>/extract-card/ endpoint doesn't time out before the sidecar wakes.

Wire Django to the Space

Set on the Django host (Fly secrets, etc.):

OCR_SERVICE_URL=https://foodnode-card-ocr.hf.space
OCR_INTERNAL_API_KEY=<same value as the HF Space secret>
OCR_REQUEST_TIMEOUT_SECONDS=30
CARD_OCR_ENABLED=true

No code change is needed -- backend/onboarding/providers/real_card_ocr.py already POSTs to ${OCR_SERVICE_URL}/extract with the X-Internal-API-Key header.