Spaces:
Sleeping

File size: 7,066 Bytes
72de53b
 
 
 
 
 
 
 
 
 
 
6f32872
 
 
72de53b
 
6f32872
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72de53b
 
6f32872
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72de53b
 
 
6f32872
 
 
72de53b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6f32872
 
 
 
 
72de53b
 
 
 
 
 
 
6f32872
 
 
 
 
 
 
 
 
 
 
 
1035f0d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
---
title: FoodNode Card OCR
emoji: "\U0001F4C7"
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:

```json
{
  "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](../../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](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 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:
   ```bash
   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](../../onboarding/providers/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`:

```bash
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

```bash
# 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:

   ```bash
   # 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

```bash
# 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

```bash
# 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.