File size: 9,101 Bytes
3c4611e
 
 
 
 
 
 
 
b4f279b
3c4611e
 
 
 
20e328b
 
 
 
 
3c4611e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
---
title: AI Image Classifier
emoji: πŸ–ΌοΈ
colorFrom: indigo
colorTo: blue
sdk: docker
app_port: 8000
pinned: false
license: mit
---

# πŸ–ΌοΈ Advanced Image Classification Pipeline

[![Live Demo](https://img.shields.io/badge/%F0%9F%A4%97%20Live%20Demo-Hugging%20Face-yellow)](https://jitendra25-image-classification-pipeline.hf.space)
[![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)

**πŸš€ Live Demo:** **https://jitendra25-image-classification-pipeline.hf.space**

A **production-ready PyTorch image classifier** with a modern FastAPI backend, a
beautiful drag-and-drop web UI (Tailwind CSS), a polished CLI, and a fully
optimized multi-stage Docker build ready for free / cheap cloud hosting.

> Uses **MobileNet_V3_Large** (default) or **EfficientNet_B0** β€” both more modern,
> faster and more accurate than the classic ResNet-18, pretrained on ImageNet (1000 classes).

---

## ✨ Features

- ⚑ **FastAPI** backend with async upload handling
- 🧠 Modern CNN with **singleton model caching** (loads weights only once)
- πŸ“Š `/predict` returns **top-k classes, confidence scores & inference time (ms)**
- 🎨 **Drag-and-drop web UI** with live results, confidence bars & loading spinner
- πŸ–₯️ **CLI tool** (`predict.py`) with a clean ASCII results table
- πŸ“ Structured **request + timing logging**
- 🐳 **Multi-stage Dockerfile** (CPU-only torch wheels, slim final image, non-root user)
- 🩺 `/health` endpoint for cloud readiness probes

---

## πŸ“ Directory Structure

```
Image-Classification-Pipeline/
β”œβ”€β”€ app/
β”‚   β”œβ”€β”€ __init__.py
β”‚   └── main.py            # FastAPI backend + Tailwind single-page UI
β”œβ”€β”€ predict.py             # Advanced argparse CLI classifier
β”œβ”€β”€ requirements.txt       # Pinned dependencies
β”œβ”€β”€ Dockerfile             # Optimized multi-stage build (python:3.10-slim)
β”œβ”€β”€ .dockerignore
β”œβ”€β”€ .gitignore
└── README.md              # You are here
```

---

## πŸš€ Local Setup (Windows)

> Requires **Python 3.10+**. Commands shown for **PowerShell**.

### 1. Clone / open the project

```powershell
cd D:\Image-Classification-Pipeline
```

### 2. Create & activate a virtual environment

```powershell
python -m venv .venv
.\.venv\Scripts\Activate.ps1
```

> If activation is blocked by execution policy, run once:
> `Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy RemoteSigned`

### 3. Install dependencies

```powershell
python -m pip install --upgrade pip
pip install -r requirements.txt
```

> πŸ’‘ For a **smaller, CPU-only** PyTorch install (recommended for laptops/servers
> without a GPU):
> ```powershell
> pip install -r requirements.txt --extra-index-url https://download.pytorch.org/whl/cpu
> ```

### 4. Run the web server

```powershell
uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload
```

Now open **http://localhost:8000** in your browser and drag in an image. πŸŽ‰

---

## πŸ–₯️ CLI Usage

Classify any image directly from the terminal:

```powershell
python predict.py path\to\cat.jpg
python predict.py path\to\cat.jpg --top_k 10
python predict.py path\to\cat.jpg --model efficientnet_b0
```

### Sample output

```
  Model : mobilenet_v3_large
  Image : path\to\cat.jpg

+------+------------------------------+------------+------------------------+
| #    | Class                        | Conf.      | Confidence             |
+------+------------------------------+------------+------------------------+
| 1    | tabby                        |  74.18%    | ################...... |
| 2    | tiger cat                    |  18.55%    | ####.................. |
| 3    | Egyptian cat                 |   4.92%    | #..................... |
| 4    | lynx                         |   0.81%    | ...................... |
| 5    | tiger                        |   0.22%    | ...................... |
+------+------------------------------+------------+------------------------+

  Top prediction : tabby (74.18%)
  Inference time : 41.3 ms
```

---

## πŸ”Œ API Usage

### `POST /predict`

```powershell
curl -X POST "http://localhost:8000/predict?top_k=5" -F "file=@cat.jpg"
```

```json
{
  "filename": "cat.jpg",
  "model": "mobilenet_v3_large",
  "device": "cpu",
  "inference_time_ms": 41.3,
  "total_time_ms": 58.7,
  "predictions": [
    { "rank": 1, "label": "tabby", "confidence": 0.7418, "confidence_pct": 74.18 },
    { "rank": 2, "label": "tiger cat", "confidence": 0.1855, "confidence_pct": 18.55 }
  ]
}
```

### `GET /health`

```json
{ "status": "ok", "model": "mobilenet_v3_large", "device": "cpu" }
```

### Interactive docs

FastAPI auto-generates Swagger UI at **http://localhost:8000/docs**.

---

## 🐳 Docker

Build and run locally:

```powershell
docker build -t image-classifier .
docker run -p 8000:8000 image-classifier
```

Then visit **http://localhost:8000**.

> The build uses a **multi-stage** approach: dependencies are compiled in a
> builder stage, and only the slim virtualenv + app are copied into the final
> `python:3.10-slim` runtime. CPU-only torch wheels keep the image small and
> free-tier friendly.

---

## ☁️ Production Deployment Guides

### a) Hugging Face Spaces (Docker Space)

1. Create a new Space β†’ **SDK: Docker** β†’ **Blank** template.
2. Push this repo to the Space (it ships with a `Dockerfile`).
   ```powershell
   git remote add space https://huggingface.co/spaces/<your-username>/<space-name>
   git push space main
   ```
3. **Important:** HF Spaces routes traffic to **port 7860** by default. Either:
   - Add this line to your `Dockerfile` and update the `CMD` port:
     ```dockerfile
     ENV PORT=7860
     CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "7860"]
     ```
   - **or** add `app_port: 8000` to the Space's `README.md` YAML front-matter:
     ```yaml
     ---
     title: AI Image Classifier
     sdk: docker
     app_port: 8000
     ---
     ```
4. The Space builds automatically and serves your UI publicly. βœ…

---

### b) Render.com (Web Service via GitHub)

1. Push your repo to GitHub (see Git section below).
2. On [render.com](https://render.com): **New β†’ Web Service β†’ Connect your repo**.
3. Settings:
   - **Environment:** `Docker`
   - **Region:** closest to you
   - **Instance type:** `Free`
   - Render auto-detects the `Dockerfile` β€” no build/start command needed.
4. Render injects a `$PORT` env var. Make uvicorn respect it by changing the
   `CMD` in your `Dockerfile`:
   ```dockerfile
   CMD ["sh", "-c", "uvicorn app.main:app --host 0.0.0.0 --port ${PORT:-8000}"]
   ```
5. Click **Create Web Service**. Render builds & deploys on every `git push`. βœ…

---

### c) Koyeb / Railway (modern alternatives)

#### Koyeb
1. [app.koyeb.com](https://app.koyeb.com) β†’ **Create App β†’ GitHub** (or Docker image).
2. Builder: **Dockerfile**. Koyeb provides `$PORT` (default `8000`).
3. Set the exposed port to **8000** in the *Ports* section, health check path `/health`.
4. Deploy β€” Koyeb gives you a public `*.koyeb.app` URL on the free tier. βœ…

#### Railway
1. [railway.app](https://railway.app) β†’ **New Project β†’ Deploy from GitHub repo**.
2. Railway detects the `Dockerfile` automatically.
3. Add a public domain under **Settings β†’ Networking β†’ Generate Domain**.
4. Railway sets `$PORT` β€” use the same `${PORT:-8000}` `CMD` shown for Render. βœ…

> πŸ”‘ **General cloud tip:** Most PaaS providers inject a `$PORT` environment
> variable. The portable production command is:
> ```dockerfile
> CMD ["sh", "-c", "uvicorn app.main:app --host 0.0.0.0 --port ${PORT:-8000}"]
> ```

---

## πŸ”— Git: Initialize & Push to GitHub

```powershell
# 1. Initialize the repository
git init
git add .
git commit -m "Initial commit: advanced PyTorch image classification pipeline"

# 2. Rename default branch to main
git branch -M main

# 3. Create a new EMPTY repo on github.com, then link it:
git remote add origin https://github.com/<your-username>/image-classification-pipeline.git

# 4. Push
git push -u origin main
```

### Subsequent updates

```powershell
git add .
git commit -m "Describe your change"
git push
```

> πŸ’‘ Prefer the GitHub CLI? After `gh auth login`:
> ```powershell
> gh repo create image-classification-pipeline --public --source=. --remote=origin --push
> ```

---

## βš™οΈ Configuration (Environment Variables)

| Variable          | Default               | Description                                   |
|-------------------|-----------------------|-----------------------------------------------|
| `MODEL_NAME`      | `mobilenet_v3_large`  | `mobilenet_v3_large` or `efficientnet_b0`     |
| `MAX_UPLOAD_BYTES`| `10485760` (10 MB)    | Max accepted upload size                       |
| `PORT`            | `8000`                | Port to bind (when using the portable `CMD`)  |

---

## πŸ§ͺ Quick Smoke Test

```powershell
# Terminal 1 β€” start the server
uvicorn app.main:app --reload

# Terminal 2 β€” hit the health endpoint
curl http://localhost:8000/health
```

---

## πŸ“œ License

MIT β€” free to use, modify and deploy. Happy classifying! πŸš€