Nausad commited on
Commit
152d77a
Β·
verified Β·
1 Parent(s): 6336ad8

Upload 5 files

Browse files
app.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Flask, request, jsonify, render_template
2
+ import torch
3
+ import torch.nn as nn
4
+ import torch.nn.functional as F
5
+ from torchvision import transforms
6
+ from PIL import Image
7
+ import io
8
+ import json
9
+ import time
10
+ import os
11
+ from pathlib import Path
12
+
13
+ # ── Paths ──────────────────────────────────────────────────────────────────
14
+ BASE_DIR = Path(__file__).parent.resolve()
15
+
16
+ app = Flask(__name__, template_folder=str(BASE_DIR / "templates"))
17
+
18
+ # ── CIFAR-10 Classes ────────────────────────────────────────────────────────
19
+ CLASSES = ["airplane", "automobile", "bird", "cat", "deer",
20
+ "dog", "frog", "horse", "ship", "truck"]
21
+
22
+ # ── Model Definition ────────────────────────────────────────────────────────
23
+ class PatchEmbedding(nn.Module):
24
+ def __init__(self, img_size=32, patch_size=4, in_channels=3, embed_dim=256):
25
+ super().__init__()
26
+ self.proj = nn.Conv2d(in_channels, embed_dim, kernel_size=patch_size, stride=patch_size)
27
+ num_patches = (img_size // patch_size) ** 2
28
+ self.cls_token = nn.Parameter(torch.randn(1, 1, embed_dim))
29
+ self.pos_embed = nn.Parameter(torch.randn(1, 1 + num_patches, embed_dim))
30
+
31
+ def forward(self, x):
32
+ B = x.size(0)
33
+ x = self.proj(x).flatten(2).transpose(1, 2)
34
+ cls_token = self.cls_token.expand(B, -1, -1)
35
+ x = torch.cat((cls_token, x), dim=1) + self.pos_embed
36
+ return x
37
+
38
+ class MLP(nn.Module):
39
+ def __init__(self, in_features, hidden_features, drop_rate):
40
+ super().__init__()
41
+ self.fc1 = nn.Linear(in_features, hidden_features)
42
+ self.fc2 = nn.Linear(hidden_features, in_features)
43
+ self.dropout = nn.Dropout(drop_rate)
44
+
45
+ def forward(self, x):
46
+ return self.dropout(self.fc2(self.dropout(F.gelu(self.fc1(x)))))
47
+
48
+ class TransformerEncoderBlock(nn.Module):
49
+ def __init__(self, embed_dim, num_heads, mlp_dim, drop_rate):
50
+ super().__init__()
51
+ self.norm1 = nn.LayerNorm(embed_dim)
52
+ self.attn = nn.MultiheadAttention(embed_dim, num_heads, dropout=drop_rate, batch_first=True)
53
+ self.norm2 = nn.LayerNorm(embed_dim)
54
+ self.mlp = MLP(embed_dim, mlp_dim, drop_rate)
55
+
56
+ def forward(self, x):
57
+ x = x + self.attn(self.norm1(x), self.norm1(x), self.norm1(x))[0]
58
+ x = x + self.mlp(self.norm2(x))
59
+ return x
60
+
61
+ class VisionTransformer(nn.Module):
62
+ def __init__(self, img_size=32, patch_size=4, in_channels=3, num_classes=10,
63
+ embed_dim=256, depth=20, num_heads=8, mlp_dim=512, drop_rate=0.1):
64
+ super().__init__()
65
+ self.patch_embed = PatchEmbedding(img_size, patch_size, in_channels, embed_dim)
66
+ self.encoder = nn.Sequential(*[TransformerEncoderBlock(embed_dim, num_heads, mlp_dim, drop_rate) for _ in range(depth)])
67
+ self.norm = nn.LayerNorm(embed_dim)
68
+ self.head = nn.Linear(embed_dim, num_classes)
69
+
70
+ def forward(self, x):
71
+ x = self.patch_embed(x)
72
+ x = self.encoder(x)
73
+ return self.head(self.norm(x)[:, 0])
74
+
75
+ # ── Load Model ──────────────────────────────────────────────────────────────
76
+ device = torch.device("cpu")
77
+ model = VisionTransformer()
78
+
79
+ model_path = BASE_DIR / "cifar10_model.pth"
80
+ model.load_state_dict(torch.load(model_path, map_location=device))
81
+ model.eval()
82
+ print(f"[OK] Model loaded from {model_path}")
83
+ print(f" Parameters: {sum(p.numel() for p in model.parameters()):,}")
84
+
85
+ # ── Image Transform ─────────────────────────────────────────────────────────
86
+ transform = transforms.Compose([
87
+ transforms.Resize((32, 32)),
88
+ transforms.ToTensor(),
89
+ transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),
90
+ ])
91
+
92
+ # ── Routes ──────────────────────────────────────────────────────────────────
93
+ @app.route("/")
94
+ def index():
95
+ return render_template("index.html")
96
+
97
+ @app.route("/predict", methods=["POST"])
98
+ def predict():
99
+ if "file" not in request.files:
100
+ return jsonify({"error": "No file uploaded"}), 400
101
+
102
+ file = request.files["file"]
103
+ if file.filename == "":
104
+ return jsonify({"error": "Empty filename"}), 400
105
+
106
+ try:
107
+ img = Image.open(io.BytesIO(file.read())).convert("RGB")
108
+ tensor = transform(img).unsqueeze(0).to(device)
109
+
110
+ t0 = time.time()
111
+ with torch.no_grad():
112
+ logits = model(tensor)
113
+ probs = F.softmax(logits, dim=1).squeeze(0)
114
+ ms = round((time.time() - t0) * 1000, 2)
115
+
116
+ results = sorted(
117
+ [{"class": CLASSES[i], "probability": float(probs[i])} for i in range(10)],
118
+ key=lambda x: x["probability"], reverse=True
119
+ )
120
+ return jsonify({
121
+ "top_class": results[0]["class"],
122
+ "top_probability": results[0]["probability"],
123
+ "all_predictions": results,
124
+ "inference_ms": ms
125
+ })
126
+ except Exception as e:
127
+ return jsonify({"error": str(e)}), 500
128
+
129
+ @app.route("/model-info")
130
+ def model_info():
131
+ return jsonify({
132
+ "architecture": "Vision Transformer (ViT)",
133
+ "parameters": sum(p.numel() for p in model.parameters()),
134
+ "depth": 20,
135
+ "embed_dim": 256,
136
+ "num_heads": 8,
137
+ "patch_size": "4Γ—4",
138
+ "input_size": "32Γ—32",
139
+ "classes": CLASSES,
140
+ "train_accuracy": "72.59%",
141
+ "test_accuracy": "70.51%",
142
+ "epochs": 25,
143
+ })
144
+
145
+ # ── Run ──────────────────────────────────────────────────────────────────────
146
+ if __name__ == "__main__":
147
+ port = int(os.environ.get("PORT", 5000))
148
+ host = "0.0.0.0" # bind to all interfaces (required for Docker / HF Spaces)
149
+ debug = os.environ.get("FLASK_DEBUG", "0") == "1"
150
+ app.run(debug=debug, host=host, port=port)
classes.json ADDED
@@ -0,0 +1 @@
 
 
1
+ ["airplane", "automobile", "bird", "cat", "deer", "dog", "frog", "horse", "ship", "truck"]
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ torch==2.1.2
2
+ torchvision==0.16.2
3
+ flask==3.1.3
4
+ Pillow==10.4.0
5
+ gunicorn==21.2.0
templates/index.html ADDED
@@ -0,0 +1,846 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+
4
+ <head>
5
+ <meta charset="UTF-8" />
6
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
7
+ <title>CIFAR-10 Vision Transformer Classifier</title>
8
+ <link
9
+ href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=Outfit:wght@400;600;700;800;900&display=swap"
10
+ rel="stylesheet" />
11
+ <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css" />
12
+ <style>
13
+ /* ─── Reset & Variables ─────────────────────────────────────── */
14
+ *,
15
+ *::before,
16
+ *::after {
17
+ box-sizing: border-box;
18
+ margin: 0;
19
+ padding: 0;
20
+ }
21
+
22
+ :root {
23
+ --bg: #f5ede0;
24
+ --surface: rgba(255, 248, 237, 0.75);
25
+ --border: rgba(160, 120, 75, .18);
26
+ --glow-v: #b85c2c;
27
+ --glow-c: #3a7d8c;
28
+ --text: #2c1e0f;
29
+ --muted: #8a7460;
30
+ --font-ui: 'Inter', sans-serif;
31
+ --font-h: 'Outfit', sans-serif;
32
+ }
33
+
34
+ body {
35
+ background: var(--bg);
36
+ background-image:
37
+ url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='200' height='200'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.75' numOctaves='4' stitchTiles='stitch'/%3E%3CfeColorMatrix type='saturate' values='0'/%3E%3C/filter%3E%3Crect width='200' height='200' filter='url(%23n)' opacity='0.03'/%3E%3C/svg%3E");
38
+ color: var(--text);
39
+ font-family: var(--font-ui);
40
+ min-height: 100vh;
41
+ overflow-x: hidden;
42
+ }
43
+
44
+ /* ─── Animated BG ───────────────────────────────────────────── */
45
+ body::before {
46
+ content: '';
47
+ position: fixed;
48
+ inset: 0;
49
+ z-index: -1;
50
+ background:
51
+ radial-gradient(ellipse 80% 60% at 10% 15%, rgba(184, 92, 44, .13) 0%, transparent 55%),
52
+ radial-gradient(ellipse 60% 50% at 88% 80%, rgba(58, 125, 140, .10) 0%, transparent 55%),
53
+ radial-gradient(ellipse 50% 40% at 50% 50%, rgba(220, 180, 130, .08) 0%, transparent 70%);
54
+ }
55
+
56
+ /* ─── Layout ─────────────────────────────────────────────────── */
57
+ .page {
58
+ max-width: 1200px;
59
+ margin: 0 auto;
60
+ padding: 2.5rem 1.5rem 4rem;
61
+ }
62
+
63
+ /* ─── Header ─────────────────────────────────────────────────── */
64
+ header {
65
+ text-align: center;
66
+ margin-bottom: 3rem;
67
+ }
68
+
69
+ .badge {
70
+ display: inline-flex;
71
+ align-items: center;
72
+ gap: .5rem;
73
+ padding: .4rem 1.1rem;
74
+ background: rgba(184, 92, 44, .1);
75
+ border: 1px solid rgba(184, 92, 44, .28);
76
+ border-radius: 50px;
77
+ font-family: var(--font-h);
78
+ font-size: .8rem;
79
+ font-weight: 700;
80
+ letter-spacing: 1.5px;
81
+ text-transform: uppercase;
82
+ color: var(--glow-v);
83
+ margin-bottom: 1.2rem;
84
+ }
85
+
86
+ .badge i {
87
+ color: var(--glow-c);
88
+ }
89
+
90
+ h1 {
91
+ font-family: var(--font-h);
92
+ font-size: clamp(2rem, 5vw, 3.2rem);
93
+ font-weight: 900;
94
+ line-height: 1.1;
95
+ margin-bottom: .9rem;
96
+ background: linear-gradient(135deg, #3d2910 0%, #a0522d 45%, var(--glow-v) 100%);
97
+ -webkit-background-clip: text;
98
+ -webkit-text-fill-color: transparent;
99
+ }
100
+
101
+ .subtitle {
102
+ color: var(--muted);
103
+ font-size: 1.05rem;
104
+ max-width: 620px;
105
+ margin: 0 auto;
106
+ line-height: 1.7;
107
+ }
108
+
109
+ /* ─── Stats Bar ──────────────────────────────────────────────── */
110
+ .stats-bar {
111
+ display: flex;
112
+ flex-wrap: wrap;
113
+ justify-content: center;
114
+ gap: 1rem;
115
+ margin-bottom: 2.5rem;
116
+ }
117
+
118
+ .stat-pill {
119
+ display: flex;
120
+ align-items: center;
121
+ gap: .6rem;
122
+ padding: .55rem 1.2rem;
123
+ background: var(--surface);
124
+ border: 1px solid var(--border);
125
+ border-radius: 50px;
126
+ font-size: .85rem;
127
+ font-weight: 500;
128
+ backdrop-filter: blur(10px);
129
+ transition: border-color .2s;
130
+ }
131
+
132
+ .stat-pill:hover {
133
+ border-color: rgba(184, 92, 44, .4);
134
+ }
135
+
136
+ .stat-pill i {
137
+ color: var(--glow-v);
138
+ }
139
+
140
+ .stat-pill .val {
141
+ color: var(--glow-c);
142
+ font-weight: 700;
143
+ }
144
+
145
+ /* ─── Main Grid ──────────────────────────────────────────────── */
146
+ .main-grid {
147
+ display: grid;
148
+ grid-template-columns: 1fr 1fr;
149
+ gap: 1.5rem;
150
+ }
151
+
152
+ @media (max-width: 800px) {
153
+ .main-grid {
154
+ grid-template-columns: 1fr;
155
+ }
156
+ }
157
+
158
+ /* ──��� Card ───────────────────────────────────────────────────── */
159
+ .card {
160
+ background: rgba(255, 250, 242, 0.82);
161
+ border: 1px solid var(--border);
162
+ border-radius: 18px;
163
+ backdrop-filter: blur(14px);
164
+ -webkit-backdrop-filter: blur(14px);
165
+ overflow: hidden;
166
+ transition: border-color .3s, box-shadow .3s;
167
+ box-shadow: 0 2px 16px rgba(140, 100, 60, .07);
168
+ }
169
+
170
+ .card:hover {
171
+ border-color: rgba(184, 92, 44, .3);
172
+ box-shadow: 0 12px 40px -10px rgba(184, 92, 44, .12);
173
+ }
174
+
175
+ .card-header {
176
+ padding: 1.2rem 1.5rem;
177
+ border-bottom: 1px solid var(--border);
178
+ display: flex;
179
+ align-items: center;
180
+ gap: .7rem;
181
+ }
182
+
183
+ .card-header i {
184
+ color: var(--glow-v);
185
+ font-size: 1.1rem;
186
+ }
187
+
188
+ .card-header h2 {
189
+ font-family: var(--font-h);
190
+ font-size: 1.1rem;
191
+ font-weight: 700;
192
+ }
193
+
194
+ /* ─── Upload Zone ────────────────────────────────────────────── */
195
+ .upload-zone {
196
+ margin: 1.5rem;
197
+ border: 2px dashed rgba(184, 92, 44, .28);
198
+ border-radius: 14px;
199
+ padding: 2.5rem 1.5rem;
200
+ text-align: center;
201
+ cursor: pointer;
202
+ transition: all .25s;
203
+ background: rgba(245, 230, 200, .45);
204
+ position: relative;
205
+ }
206
+
207
+ .upload-zone.drag-over {
208
+ border-color: var(--glow-c);
209
+ background: rgba(58, 125, 140, .07);
210
+ }
211
+
212
+ #file-input {
213
+ display: none;
214
+ }
215
+
216
+ .upload-icon-wrap {
217
+ width: 64px;
218
+ height: 64px;
219
+ margin: 0 auto 1rem;
220
+ background: rgba(184, 92, 44, .1);
221
+ border: 1px solid rgba(184, 92, 44, .28);
222
+ border-radius: 16px;
223
+ display: flex;
224
+ align-items: center;
225
+ justify-content: center;
226
+ font-size: 1.6rem;
227
+ color: var(--glow-v);
228
+ transition: transform .2s;
229
+ }
230
+
231
+ .upload-zone:hover .upload-icon-wrap {
232
+ transform: translateY(-3px);
233
+ }
234
+
235
+ .upload-zone h3 {
236
+ font-family: var(--font-h);
237
+ font-size: 1.1rem;
238
+ margin-bottom: .5rem;
239
+ }
240
+
241
+ .upload-zone p {
242
+ color: var(--muted);
243
+ font-size: .85rem;
244
+ margin-bottom: 1.2rem;
245
+ }
246
+
247
+ .btn {
248
+ display: inline-flex;
249
+ align-items: center;
250
+ gap: .5rem;
251
+ padding: .65rem 1.4rem;
252
+ border: none;
253
+ border-radius: 10px;
254
+ font-family: var(--font-ui);
255
+ font-size: .9rem;
256
+ font-weight: 600;
257
+ cursor: pointer;
258
+ transition: all .2s;
259
+ }
260
+
261
+ .btn-primary {
262
+ background: linear-gradient(135deg, var(--glow-v) 0%, #8b3a1a 100%);
263
+ color: #fff;
264
+ box-shadow: 0 4px 18px rgba(184, 92, 44, .28);
265
+ }
266
+
267
+ .btn-primary:hover {
268
+ transform: translateY(-2px);
269
+ box-shadow: 0 6px 24px rgba(184, 92, 44, .38);
270
+ }
271
+
272
+ /* ─── Preview Area ───────────────────────────────────────────── */
273
+ .preview-section {
274
+ padding: 1.5rem;
275
+ border-top: 1px solid var(--border);
276
+ }
277
+
278
+ .preview-grid {
279
+ display: grid;
280
+ grid-template-columns: 1fr 1fr;
281
+ gap: 1rem;
282
+ }
283
+
284
+ .preview-box {
285
+ background: rgba(210, 185, 150, .25);
286
+ border: 1px solid var(--border);
287
+ border-radius: 12px;
288
+ overflow: hidden;
289
+ aspect-ratio: 1;
290
+ display: flex;
291
+ flex-direction: column;
292
+ }
293
+
294
+ .preview-label {
295
+ padding: .5rem .8rem;
296
+ font-size: .7rem;
297
+ font-weight: 600;
298
+ text-transform: uppercase;
299
+ letter-spacing: .8px;
300
+ color: var(--muted);
301
+ border-bottom: 1px solid var(--border);
302
+ }
303
+
304
+ .preview-inner {
305
+ flex: 1;
306
+ display: flex;
307
+ align-items: center;
308
+ justify-content: center;
309
+ padding: .5rem;
310
+ }
311
+
312
+ .preview-inner img {
313
+ max-width: 100%;
314
+ max-height: 100%;
315
+ object-fit: contain;
316
+ border-radius: 6px;
317
+ }
318
+
319
+ .preview-inner canvas {
320
+ max-width: 100%;
321
+ max-height: 100%;
322
+ image-rendering: pixelated;
323
+ image-rendering: crisp-edges;
324
+ }
325
+
326
+ .preview-placeholder {
327
+ color: rgba(140, 100, 60, .3);
328
+ font-size: 2rem;
329
+ display: flex;
330
+ align-items: center;
331
+ justify-content: center;
332
+ height: 100%;
333
+ }
334
+
335
+ /* ─── Results Card ───────────────────────────────────────────── */
336
+ .results-body {
337
+ padding: 1.5rem;
338
+ }
339
+
340
+ /* empty state */
341
+ .empty-state {
342
+ padding: 3rem 1rem;
343
+ text-align: center;
344
+ color: var(--muted);
345
+ line-height: 1.8;
346
+ }
347
+
348
+ .empty-state i {
349
+ font-size: 3rem;
350
+ color: rgba(184, 92, 44, .3);
351
+ display: block;
352
+ margin-bottom: 1rem;
353
+ }
354
+
355
+ /* top prediction */
356
+ .top-pred {
357
+ display: flex;
358
+ align-items: center;
359
+ justify-content: space-between;
360
+ background: linear-gradient(120deg, rgba(184, 92, 44, .1), rgba(58, 125, 140, .07));
361
+ border: 1px solid rgba(184, 92, 44, .2);
362
+ border-radius: 14px;
363
+ padding: 1.1rem 1.4rem;
364
+ margin-bottom: 1.2rem;
365
+ animation: fadeUp .4s ease;
366
+ }
367
+
368
+ .top-left {
369
+ display: flex;
370
+ align-items: center;
371
+ gap: .9rem;
372
+ }
373
+
374
+ .class-icon {
375
+ width: 46px;
376
+ height: 46px;
377
+ border-radius: 12px;
378
+ background: rgba(184, 92, 44, .15);
379
+ border: 1px solid rgba(184, 92, 44, .35);
380
+ display: flex;
381
+ align-items: center;
382
+ justify-content: center;
383
+ font-size: 1.35rem;
384
+ color: var(--glow-v);
385
+ }
386
+
387
+ .class-label {
388
+ font-size: .7rem;
389
+ font-weight: 700;
390
+ text-transform: uppercase;
391
+ letter-spacing: 1px;
392
+ color: var(--glow-v);
393
+ }
394
+
395
+ .class-name {
396
+ font-family: var(--font-h);
397
+ font-size: 1.5rem;
398
+ font-weight: 800;
399
+ text-transform: capitalize;
400
+ }
401
+
402
+ .conf-score {
403
+ font-family: var(--font-h);
404
+ font-size: 2rem;
405
+ font-weight: 900;
406
+ color: var(--glow-c);
407
+ text-shadow: 0 0 20px rgba(58, 125, 140, .4);
408
+ }
409
+
410
+ /* meta strip */
411
+ .meta-strip {
412
+ display: flex;
413
+ gap: 1.5rem;
414
+ flex-wrap: wrap;
415
+ margin-bottom: 1.2rem;
416
+ padding-bottom: 1rem;
417
+ border-bottom: 1px solid var(--border);
418
+ }
419
+
420
+ .meta-item {
421
+ font-size: .82rem;
422
+ color: var(--muted);
423
+ }
424
+
425
+ .meta-item strong {
426
+ color: var(--text);
427
+ }
428
+
429
+ /* bars */
430
+ .bars-title {
431
+ font-family: var(--font-h);
432
+ font-size: .95rem;
433
+ font-weight: 700;
434
+ margin-bottom: .9rem;
435
+ }
436
+
437
+ .bar-row {
438
+ display: grid;
439
+ grid-template-columns: 90px 1fr 52px;
440
+ align-items: center;
441
+ gap: .9rem;
442
+ margin-bottom: .65rem;
443
+ }
444
+
445
+ .bar-name {
446
+ font-size: .82rem;
447
+ text-transform: capitalize;
448
+ color: var(--muted);
449
+ font-weight: 500;
450
+ }
451
+
452
+ .bar-track {
453
+ height: 7px;
454
+ background: rgba(160, 120, 75, .12);
455
+ border-radius: 4px;
456
+ overflow: hidden;
457
+ }
458
+
459
+ .bar-fill {
460
+ height: 100%;
461
+ width: 0;
462
+ border-radius: 4px;
463
+ background: linear-gradient(90deg, var(--glow-v), var(--glow-c));
464
+ transition: width .85s cubic-bezier(.1, .76, .55, .94);
465
+ box-shadow: 0 0 8px rgba(58, 125, 140, .2);
466
+ }
467
+
468
+ .bar-val {
469
+ font-size: .78rem;
470
+ font-weight: 700;
471
+ color: var(--muted);
472
+ text-align: right;
473
+ }
474
+
475
+ .bar-row.is-top .bar-name {
476
+ color: var(--text);
477
+ font-weight: 700;
478
+ }
479
+
480
+ .bar-row.is-top .bar-val {
481
+ color: var(--glow-c);
482
+ }
483
+
484
+ /* spinner */
485
+ .spinner-wrap {
486
+ padding: 3rem 1rem;
487
+ text-align: center;
488
+ color: var(--muted);
489
+ }
490
+
491
+ .spinner {
492
+ width: 40px;
493
+ height: 40px;
494
+ border-radius: 50%;
495
+ border: 3px solid rgba(184, 92, 44, .18);
496
+ border-top-color: var(--glow-v);
497
+ animation: spin .8s linear infinite;
498
+ margin: 0 auto 1rem;
499
+ }
500
+
501
+ /* ─── Info Footer ────────────────────────────────────────────── */
502
+ .info-footer {
503
+ margin-top: 2rem;
504
+ display: grid;
505
+ grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
506
+ gap: 1rem;
507
+ }
508
+
509
+ .info-card {
510
+ background: var(--surface);
511
+ border: 1px solid var(--border);
512
+ border-radius: 14px;
513
+ padding: 1rem 1.2rem;
514
+ transition: border-color .2s;
515
+ }
516
+
517
+ .info-card:hover {
518
+ border-color: rgba(184, 92, 44, .3);
519
+ }
520
+
521
+ .info-card .lbl {
522
+ font-size: .72rem;
523
+ text-transform: uppercase;
524
+ letter-spacing: .7px;
525
+ color: var(--muted);
526
+ font-weight: 600;
527
+ margin-bottom: .35rem;
528
+ }
529
+
530
+ .info-card .val {
531
+ font-family: var(--font-h);
532
+ font-size: 1.1rem;
533
+ font-weight: 700;
534
+ }
535
+
536
+ .info-card .val.cyan {
537
+ color: var(--glow-c);
538
+ }
539
+
540
+ /* ─── Keyframes ──────────────────────────────────────────────── */
541
+ @keyframes fadeUp {
542
+ from {
543
+ opacity: 0;
544
+ transform: translateY(12px);
545
+ }
546
+
547
+ to {
548
+ opacity: 1;
549
+ transform: none;
550
+ }
551
+ }
552
+
553
+ @keyframes spin {
554
+ to {
555
+ transform: rotate(360deg);
556
+ }
557
+ }
558
+
559
+ /* ─── Footer text ────────────────────────────────────────────── */
560
+ .page-footer {
561
+ text-align: center;
562
+ color: var(--muted);
563
+ font-size: .8rem;
564
+ margin-top: 2.5rem;
565
+ }
566
+ </style>
567
+ </head>
568
+
569
+ <body>
570
+ <div class="page">
571
+
572
+ <!-- ── Header ────────────────────��─────────────────────────────── -->
573
+ <header>
574
+ <div class="badge"><i class="fa-solid fa-microchip"></i> Vision Transformer Β· CIFAR-10</div>
575
+ <h1>Image Classification<br>with ViT</h1>
576
+ <p class="subtitle">Upload any image and let a custom-trained Vision Transformer model classify it into one of 10
577
+ CIFAR-10 categories in real time.</p>
578
+ </header>
579
+
580
+ <!-- ── Stats Bar ───────────────────────────────────────────────── -->
581
+ <div class="stats-bar">
582
+ <div class="stat-pill"><i class="fa-solid fa-layer-group"></i> Depth: <span class="val">20 Layers</span></div>
583
+ <div class="stat-pill"><i class="fa-solid fa-eye"></i> Heads: <span class="val">8</span></div>
584
+ <div class="stat-pill"><i class="fa-solid fa-vector-square"></i> Embed Dim: <span class="val">256</span></div>
585
+ <div class="stat-pill"><i class="fa-solid fa-database"></i> Params: <span class="val"
586
+ id="stat-params">10.6M</span></div>
587
+ <div class="stat-pill"><i class="fa-solid fa-bullseye"></i> Test Acc: <span class="val"
588
+ id="stat-acc">70.51%</span></div>
589
+ </div>
590
+
591
+ <!-- ── Main Grid ────────────────────────────────────────────────── -->
592
+ <div class="main-grid">
593
+
594
+ <!-- Left: Upload -->
595
+ <div class="card">
596
+ <div class="card-header">
597
+ <i class="fa-solid fa-cloud-arrow-up"></i>
598
+ <h2>Upload Image</h2>
599
+ </div>
600
+
601
+ <!-- Drop zone -->
602
+ <div class="upload-zone" id="drop-zone">
603
+ <input type="file" id="file-input" accept="image/*" />
604
+ <div class="upload-icon-wrap"><i class="fa-solid fa-image"></i></div>
605
+ <h3>Drag & Drop an Image</h3>
606
+ <p>Supports JPEG, PNG, WEBP, BMP β€” auto‑resized to 32Γ—32</p>
607
+ <button class="btn btn-primary" onclick="document.getElementById('file-input').click()">
608
+ <i class="fa-solid fa-folder-open"></i> Browse File
609
+ </button>
610
+ </div>
611
+
612
+ <!-- Preview -->
613
+ <div class="preview-section">
614
+ <div class="preview-grid">
615
+ <div class="preview-box">
616
+ <div class="preview-label">Original Image</div>
617
+ <div class="preview-inner" id="orig-wrap">
618
+ <div class="preview-placeholder"><i class="fa-regular fa-image"></i></div>
619
+ </div>
620
+ </div>
621
+ <div class="preview-box">
622
+ <div class="preview-label">Model Input (32Γ—32)</div>
623
+ <div class="preview-inner" id="pixel-wrap">
624
+ <div class="preview-placeholder"><i class="fa-solid fa-grid-2"></i></div>
625
+ </div>
626
+ </div>
627
+ </div>
628
+ </div>
629
+ </div>
630
+
631
+ <!-- Right: Results -->
632
+ <div class="card">
633
+ <div class="card-header">
634
+ <i class="fa-solid fa-chart-bar"></i>
635
+ <h2>Classification Results</h2>
636
+ </div>
637
+
638
+ <div class="results-body" id="results-body">
639
+ <div class="empty-state" id="empty-state">
640
+ <i class="fa-solid fa-brain"></i>
641
+ Upload an image to run the Vision Transformer inference and see probability scores for all 10 CIFAR‑10
642
+ classes.
643
+ </div>
644
+ </div>
645
+ </div>
646
+ </div><!-- /main-grid -->
647
+
648
+ <!-- ── Model Info Footer ────────────────────────────────────────── -->
649
+ <div class="info-footer" id="info-footer">
650
+ <div class="info-card">
651
+ <div class="lbl">Architecture</div>
652
+ <div class="val">Vision Transformer</div>
653
+ </div>
654
+ <div class="info-card">
655
+ <div class="lbl">Input Size</div>
656
+ <div class="val">32 Γ— 32</div>
657
+ </div>
658
+ <div class="info-card">
659
+ <div class="lbl">Patch Size</div>
660
+ <div class="val">4 Γ— 4</div>
661
+ </div>
662
+ <div class="info-card">
663
+ <div class="lbl">Training Epochs</div>
664
+ <div class="val">25</div>
665
+ </div>
666
+ <div class="info-card">
667
+ <div class="lbl">Train Accuracy</div>
668
+ <div class="val">72.59%</div>
669
+ </div>
670
+ <div class="info-card">
671
+ <div class="lbl">Test Accuracy</div>
672
+ <div class="val cyan" id="footer-acc">70.51%</div>
673
+ </div>
674
+ </div>
675
+
676
+ <div class="page-footer">Built with ❀️ and a Cup of Coffee by Nausad Ali</div>
677
+ </div><!-- /page -->
678
+
679
+ <!-- ── Icons map ─────────────────────────────────────────────────── -->
680
+ <script>
681
+ const ICONS = {
682
+ airplane: "fa-plane",
683
+ automobile: "fa-car",
684
+ bird: "fa-dove",
685
+ cat: "fa-cat",
686
+ deer: "fa-leaf",
687
+ dog: "fa-dog",
688
+ frog: "fa-frog",
689
+ horse: "fa-horse",
690
+ ship: "fa-ship",
691
+ truck: "fa-truck",
692
+ };
693
+
694
+ // ── DOM refs ────────────────────────────────────────────────────────
695
+ const dropZone = document.getElementById("drop-zone");
696
+ const fileInput = document.getElementById("file-input");
697
+ const origWrap = document.getElementById("orig-wrap");
698
+ const pixelWrap = document.getElementById("pixel-wrap");
699
+ const resultsBody = document.getElementById("results-body");
700
+ const emptyState = document.getElementById("empty-state");
701
+
702
+ // ── Drag & Drop ─────────────────────────────────────────────────────
703
+ dropZone.addEventListener("dragover", e => { e.preventDefault(); dropZone.classList.add("drag-over"); });
704
+ dropZone.addEventListener("dragleave", () => dropZone.classList.remove("drag-over"));
705
+ dropZone.addEventListener("drop", e => {
706
+ e.preventDefault(); dropZone.classList.remove("drag-over");
707
+ if (e.dataTransfer.files[0]) handleFile(e.dataTransfer.files[0]);
708
+ });
709
+ dropZone.addEventListener("click", e => {
710
+ if (e.target === dropZone || e.target.closest(".upload-icon-wrap") || e.target.tagName === "H3" || e.target.tagName === "P")
711
+ fileInput.click();
712
+ });
713
+ fileInput.addEventListener("change", e => { if (e.target.files[0]) handleFile(e.target.files[0]); });
714
+
715
+ // ── Handle File ──────────────────────────────────────────────────────
716
+ function handleFile(file) {
717
+ if (!file.type.startsWith("image/")) return;
718
+
719
+ const reader = new FileReader();
720
+ reader.onload = evt => {
721
+ // Show original preview
722
+ origWrap.innerHTML = `<img src="${evt.target.result}" alt="preview"/>`;
723
+
724
+ // Draw pixelated 32x32
725
+ const img = new Image();
726
+ img.onload = () => drawPixel(img);
727
+ img.src = evt.target.result;
728
+ };
729
+ reader.readAsDataURL(file);
730
+
731
+ // Send to Flask
732
+ uploadToFlask(file);
733
+ }
734
+
735
+ // ── Draw 32Γ—32 pixel grid ────────────────────────────────────────────
736
+ function drawPixel(img) {
737
+ const SZ = 32, DISPLAY = 192;
738
+ const tmp = document.createElement("canvas");
739
+ tmp.width = tmp.height = SZ;
740
+ const tc = tmp.getContext("2d");
741
+ const min = Math.min(img.width, img.height);
742
+ tc.drawImage(img, (img.width - min) / 2, (img.height - min) / 2, min, min, 0, 0, SZ, SZ);
743
+
744
+ const cv = document.createElement("canvas");
745
+ cv.width = cv.height = DISPLAY;
746
+ const cx = cv.getContext("2d");
747
+ cx.imageSmoothingEnabled = false;
748
+ cx.drawImage(tmp, 0, 0, SZ, SZ, 0, 0, DISPLAY, DISPLAY);
749
+
750
+ // grid lines
751
+ cx.strokeStyle = "rgba(255,255,255,.06)";
752
+ cx.lineWidth = 0.5;
753
+ const sc = DISPLAY / SZ;
754
+ for (let i = 0; i <= SZ; i++) {
755
+ cx.beginPath(); cx.moveTo(i * sc, 0); cx.lineTo(i * sc, DISPLAY); cx.stroke();
756
+ cx.beginPath(); cx.moveTo(0, i * sc); cx.lineTo(DISPLAY, i * sc); cx.stroke();
757
+ }
758
+ pixelWrap.innerHTML = "";
759
+ pixelWrap.appendChild(cv);
760
+ }
761
+
762
+ // ── Upload to Flask ──────────────────────────────────────────────────
763
+ function uploadToFlask(file) {
764
+ // Show spinner
765
+ resultsBody.innerHTML = `
766
+ <div class="spinner-wrap">
767
+ <div class="spinner"></div>
768
+ Running transformer inference…
769
+ </div>`;
770
+
771
+ const fd = new FormData();
772
+ fd.append("file", file);
773
+
774
+ fetch("/predict", { method: "POST", body: fd })
775
+ .then(r => r.json())
776
+ .then(renderResults)
777
+ .catch(err => {
778
+ resultsBody.innerHTML = `
779
+ <div class="empty-state">
780
+ <i class="fa-solid fa-circle-exclamation" style="color:#ff4d6d"></i>
781
+ Error: ${err.message}
782
+ </div>`;
783
+ });
784
+ }
785
+
786
+ // ── Render Results ───────────────────────────────────────────────────
787
+ function renderResults(data) {
788
+ if (data.error) {
789
+ resultsBody.innerHTML = `<div class="empty-state"><i class="fa-solid fa-triangle-exclamation" style="color:#ff9f43"></i>${data.error}</div>`;
790
+ return;
791
+ }
792
+
793
+ const icon = ICONS[data.top_class] || "fa-question";
794
+ const conf = (data.top_probability * 100).toFixed(1);
795
+
796
+ let barsHTML = "";
797
+ data.all_predictions.forEach(p => {
798
+ const isTop = p.class === data.top_class;
799
+ barsHTML += `
800
+ <div class="bar-row ${isTop ? "is-top" : ""}">
801
+ <span class="bar-name">${p.class}</span>
802
+ <div class="bar-track"><div class="bar-fill" data-pct="${(p.probability * 100).toFixed(1)}"></div></div>
803
+ <span class="bar-val">${(p.probability * 100).toFixed(1)}%</span>
804
+ </div>`;
805
+ });
806
+
807
+ resultsBody.innerHTML = `
808
+ <div class="top-pred">
809
+ <div class="top-left">
810
+ <div class="class-icon"><i class="fa-solid ${icon}"></i></div>
811
+ <div>
812
+ <div class="class-label">Top Prediction</div>
813
+ <div class="class-name">${data.top_class}</div>
814
+ </div>
815
+ </div>
816
+ <div class="conf-score">${conf}%</div>
817
+ </div>
818
+
819
+ <div class="meta-strip">
820
+ <div class="meta-item"><i class="fa-solid fa-gauge-high"></i> Inference: <strong>${data.inference_ms} ms</strong></div>
821
+ <div class="meta-item"><i class="fa-solid fa-microchip"></i> Device: <strong>CPU</strong></div>
822
+ <div class="meta-item"><i class="fa-solid fa-network-wired"></i> Model: <strong>ViT Β· 20 Layers</strong></div>
823
+ </div>
824
+
825
+ <div class="bars-title">All Class Probabilities</div>
826
+ ${barsHTML}`;
827
+
828
+ // Animate bars after render
829
+ requestAnimationFrame(() => {
830
+ document.querySelectorAll(".bar-fill").forEach(el => {
831
+ el.style.width = el.dataset.pct + "%";
832
+ });
833
+ });
834
+ }
835
+
836
+ // ── Fetch & populate model info ──────────────────────────────────────
837
+ fetch("/model-info").then(r => r.json()).then(d => {
838
+ document.getElementById("stat-params").textContent =
839
+ (d.parameters / 1e6).toFixed(2) + "M";
840
+ document.getElementById("stat-acc").textContent = d.test_accuracy;
841
+ document.getElementById("footer-acc").textContent = d.test_accuracy;
842
+ }).catch(() => { });
843
+ </script>
844
+ </body>
845
+
846
+ </html>
transformerbased-image-classification-model-cfr10.ipynb ADDED
The diff for this file is too large to render. See raw diff