LaelaZ commited on
Commit
c2c1e02
Β·
verified Β·
1 Parent(s): 43a2563

Add Space card front-matter

Browse files
Files changed (1) hide show
  1. README.md +183 -5
README.md CHANGED
@@ -1,10 +1,188 @@
1
  ---
2
- title: Distilbert Emotion Api
3
- emoji: πŸ“š
4
- colorFrom: blue
5
  colorTo: purple
6
  sdk: docker
7
- pinned: false
 
 
8
  ---
9
 
10
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: Emotion Spectrum API
3
+ emoji: "🎭"
4
+ colorFrom: pink
5
  colorTo: purple
6
  sdk: docker
7
+ app_port: 8000
8
+ pinned: true
9
+ short_description: DistilBERT emotion classifier β€” live demo + API
10
  ---
11
 
12
+ # distilbert-emotion-api
13
+
14
+ A batched, observable, deploy-ready FastAPI inference service that serves the fine-tuned [`LaelaZ/distilbert-emotion`](https://huggingface.co/LaelaZ/distilbert-emotion) classifier β€” and runs **fully offline** for development, CI, and load testing.
15
+
16
+ ## The problem
17
+
18
+ Training a model is the easy half. The half that actually ships is everything around it: a typed HTTP contract, input validation, health probes, metrics a dashboard can read, request batching so throughput doesn't fall over under load, a container, and a deploy story. And none of that should require downloading 270 MB of weights (or a GPU, or network access) just to run the tests or demo the API.
19
+
20
+ This repo is that production layer for an emotion classifier β€” six emotions (sadness, joy, love, anger, fear, surprise) with full per-class probabilities β€” built so the entire service, its demo UI, its test suite, and its load test run with **zero downloads** by swapping the model for a deterministic stub when `OFFLINE=1`. Flip `OFFLINE=0` and the same code path loads the real DistilBERT from the Hub.
21
+
22
+ ## What it does
23
+
24
+ - **`POST /predict`** β€” single (`{"text": ...}`) or batch (`{"texts": [...]}`), pydantic-validated, returns the top label plus the full probability distribution.
25
+ - **`GET /healthz`** β€” readiness/liveness; 503 until the model is loaded and the batcher is running.
26
+ - **`GET /metrics`** β€” Prometheus exposition: request count, latency histogram, in-flight gauge, error count, plus model-level inference latency and batch-size histograms.
27
+ - **Dynamic micro-batching** β€” concurrent single requests are coalesced into one forward pass for throughput, with a latency cap you control.
28
+ - **Offline stub** β€” a deterministic, lexicon-driven classifier so the API behaves (and tests pass) with no weights.
29
+ - **Built-in demo UI** at `/demo` that calls the live API.
30
+
31
+ ```mermaid
32
+ flowchart LR
33
+ U[Client / Demo UI] -->|POST /predict| API[FastAPI app]
34
+ API --> V[pydantic validation]
35
+ V --> B[Micro-batcher<br/>coalesce + flush]
36
+ B --> M{Model loader}
37
+ M -->|OFFLINE=1| S[Stub classifier<br/>deterministic, no downloads]
38
+ M -->|OFFLINE=0| H[DistilBERT pipeline<br/>LaelaZ/distilbert-emotion]
39
+ S --> R[label + probabilities]
40
+ H --> R
41
+ R --> U
42
+ API -.->|/metrics| P[(Prometheus)]
43
+ P --> G[Grafana dashboard]
44
+ API -.->|/healthz| K[Orchestrator probes]
45
+ ```
46
+
47
+ ## Results / impact
48
+
49
+ Latency and throughput measured by the included load test (`scripts/loadtest.py`) hitting `POST /predict` against the **offline stub**, single uvicorn worker, on an Apple-silicon laptop. Numbers are reproducible from a clean checkout with no downloads:
50
+
51
+ ```bash
52
+ make bench # human-readable summary
53
+ make bench-table # the markdown row below
54
+ ```
55
+
56
+ | concurrency | throughput (req/s) | p50 (ms) | p95 (ms) | p99 (ms) |
57
+ |---|---|---|---|---|
58
+ | 1 | 118 | 8.27 | 8.87 | 13.12 |
59
+ | 8 | 595 | 13.35 | 16.49 | 19.97 |
60
+ | 16 | 604 | 19.03 | 67.49 | 107.39 |
61
+
62
+ Throughput scales ~5x from serial to 8 concurrent requests as the micro-batcher coalesces forward passes, while p50 stays in the low-teens of milliseconds; all runs completed with **0 errors**. (These reflect the stub plus full HTTP/validation/batching overhead β€” the real model adds per-call inference cost on top, but the service shape, batching wins, and tail-latency behavior are what's being measured here.)
63
+
64
+ ## Quickstart
65
+
66
+ No model download, no GPU, no network β€” `OFFLINE=1` is the default.
67
+
68
+ ```bash
69
+ python -m venv .venv && source .venv/bin/activate
70
+ pip install -r requirements-dev.txt
71
+
72
+ make test # full suite, offline, < 1s
73
+ make demo # serve API + UI at http://localhost:8000/demo
74
+ ```
75
+
76
+ Call it:
77
+
78
+ ```bash
79
+ curl -s -X POST http://localhost:8000/predict \
80
+ -H 'Content-Type: application/json' \
81
+ -d '{"text": "i can'\''t stop smiling, today went better than i ever hoped"}'
82
+ # {"label":"joy","score":0.74,"probabilities":{"sadness":...,"joy":0.74,...}}
83
+
84
+ curl -s -X POST http://localhost:8000/predict \
85
+ -H 'Content-Type: application/json' \
86
+ -d '{"texts": ["i am so scared right now", "how dare they"]}'
87
+ # {"predictions":[{"label":"fear",...},{"label":"anger",...}]}
88
+ ```
89
+
90
+ Run the **real** model instead of the stub:
91
+
92
+ ```bash
93
+ pip install -r requirements-ml.txt # adds torch + transformers
94
+ OFFLINE=0 make serve # loads LaelaZ/distilbert-emotion from the Hub
95
+ ```
96
+
97
+ ## Tech stack
98
+
99
+ - **API:** FastAPI + Uvicorn, pydantic v2 validation
100
+ - **Model:** Hugging Face `transformers` pipeline over the fine-tuned DistilBERT (`LaelaZ/distilbert-emotion`); deterministic lexicon stub for the offline path
101
+ - **Throughput:** custom async micro-batcher (asyncio queue + threaded forward pass)
102
+ - **Observability:** `prometheus-client`, Prometheus, Grafana (provisioned dashboard)
103
+ - **Packaging/CI:** multi-stage slim Docker image (non-root), GitHub Actions
104
+ - **IaC:** Fly.io (`fly.toml`), Render (`render.yaml`), Terraform stub (`deploy/terraform/`)
105
+ - **Load test:** asyncio + httpx benchmark script
106
+
107
+ ## Deploy
108
+
109
+ The image runs in offline mode by default, so every target below comes up with no external dependencies. For the real model, build from `requirements-ml.txt`, set `OFFLINE=0`, and give the machine more memory (>= 2 GB for torch + weights).
110
+
111
+ **Docker (local):**
112
+ ```bash
113
+ make docker-run # build the slim image and run it on :8000
114
+ ```
115
+
116
+ **Full stack with monitoring:**
117
+ ```bash
118
+ make compose-up # API :8000, Prometheus :9090, Grafana :3000
119
+ ```
120
+
121
+ **Fly.io:**
122
+ ```bash
123
+ fly launch --no-deploy # reads fly.toml
124
+ fly deploy
125
+ ```
126
+
127
+ **Render:** connect the repo; it picks up `render.yaml` automatically.
128
+
129
+ **Terraform (Fly provider):**
130
+ ```bash
131
+ cd deploy/terraform
132
+ export FLY_API_TOKEN=$(fly auth token)
133
+ terraform init
134
+ terraform apply -var="image=ghcr.io/laelazorana/distilbert-emotion-api:latest"
135
+ ```
136
+
137
+ CI (`.github/workflows/ci.yml`) runs the offline tests, builds the image, and smoke-tests it. The GHCR push step is present but **guarded off** (`if: false`) so CI never publishes β€” flip the guard to enable a real release.
138
+
139
+ ## Monitoring
140
+
141
+ `docker compose up` brings up Prometheus (scraping `/metrics` every 5s) and Grafana with a pre-provisioned **Service Overview** dashboard (`observability/grafana/dashboards/emotion-api.json`):
142
+
143
+ - Request rate, error rate (5xx %), in-flight requests, p95 latency (stat tiles)
144
+ - HTTP latency percentiles (p50/p95/p99) over time
145
+ - Request rate by status code
146
+ - **Model inference latency** (separated from HTTP overhead, so "model is slow" vs "framework is slow" is visible)
147
+ - Average inference batch size (shows the batcher working under load)
148
+
149
+ Open Grafana at `http://localhost:3000` (anonymous viewer; `admin`/`admin` to edit). Generate traffic with `make bench` and watch the panels move.
150
+
151
+ Exported metrics: `emotion_api_requests_total`, `emotion_api_request_latency_seconds`, `emotion_api_errors_total`, `emotion_api_requests_in_progress`, `emotion_api_inference_latency_seconds`, `emotion_api_inference_batch_size`.
152
+
153
+ ## Screenshots
154
+
155
+ > _Placeholder._ Add screenshots of the demo UI (`/demo`), the Swagger docs (`/docs`), and the Grafana dashboard here.
156
+ >
157
+ > - `docs/demo-ui.png` β€” the emotion demo page
158
+ > - `docs/grafana.png` β€” the Service Overview dashboard under load
159
+
160
+ ## Project layout
161
+
162
+ ```
163
+ distilbert-emotion-api/
164
+ β”œβ”€β”€ app/
165
+ β”‚ β”œβ”€β”€ __init__.py # labels + version
166
+ β”‚ β”œβ”€β”€ config.py # env-driven settings
167
+ β”‚ β”œβ”€β”€ classifier.py # model abstraction: stub + real transformers backend
168
+ β”‚ β”œβ”€β”€ batching.py # async micro-batcher
169
+ β”‚ β”œβ”€β”€ schemas.py # pydantic request/response models
170
+ β”‚ β”œβ”€β”€ metrics.py # Prometheus collectors + middleware
171
+ β”‚ └── main.py # FastAPI app, routes, lifespan
172
+ β”œβ”€β”€ demo/index.html # zero-dependency demo UI that calls /predict
173
+ β”œβ”€β”€ scripts/loadtest.py # asyncio/httpx latency + throughput benchmark
174
+ β”œβ”€β”€ tests/ # /predict, validation, stub, batcher, health, metrics
175
+ β”œβ”€β”€ observability/ # Prometheus + Grafana provisioning + dashboard
176
+ β”œβ”€β”€ deploy/terraform/ # Terraform stub (Fly provider)
177
+ β”œβ”€β”€ Dockerfile # multi-stage slim image (non-root)
178
+ β”œβ”€β”€ docker-compose.yml # API + Prometheus + Grafana
179
+ β”œβ”€β”€ fly.toml Β· render.yaml # IaC for managed platforms
180
+ β”œβ”€β”€ .github/workflows/ci.yml
181
+ └── Makefile
182
+ ```
183
+
184
+ ## License
185
+
186
+ MIT β€” Copyright (c) 2026 Laela Zorana. See [LICENSE](LICENSE).
187
+
188
+ **Links:** [GitHub](https://github.com/LaelaZorana) Β· [Model on the Hub](https://huggingface.co/LaelaZ/distilbert-emotion) Β· [HuggingFace](https://huggingface.co/LaelaZ)