Nausad commited on
Commit
64bbe42
Β·
verified Β·
1 Parent(s): 35ffb7c

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +210 -0
  2. requirements.txt +10 -0
app.py ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import sys
12
+ from pathlib import Path
13
+
14
+ # ── Paths ──────────────────────────────────────────────────────────────────
15
+ BASE_DIR = Path(__file__).parent.resolve()
16
+
17
+ app = Flask(__name__, template_folder=str(BASE_DIR / "templates"))
18
+
19
+ # ── CIFAR-10 Classes ────────────────────────────────────────────────────────
20
+ CLASSES = ["airplane", "automobile", "bird", "cat", "deer",
21
+ "dog", "frog", "horse", "ship", "truck"]
22
+
23
+ # ── Model Definition ────────────────────────────────────────────────────────
24
+ class PatchEmbedding(nn.Module):
25
+ def __init__(self, img_size=32, patch_size=4, in_channels=3, embed_dim=256):
26
+ super().__init__()
27
+ self.proj = nn.Conv2d(in_channels, embed_dim, kernel_size=patch_size, stride=patch_size)
28
+ num_patches = (img_size // patch_size) ** 2
29
+ self.cls_token = nn.Parameter(torch.randn(1, 1, embed_dim))
30
+ self.pos_embed = nn.Parameter(torch.randn(1, 1 + num_patches, embed_dim))
31
+
32
+ def forward(self, x):
33
+ B = x.size(0)
34
+ x = self.proj(x).flatten(2).transpose(1, 2)
35
+ cls_token = self.cls_token.expand(B, -1, -1)
36
+ x = torch.cat((cls_token, x), dim=1) + self.pos_embed
37
+ return x
38
+
39
+ class MLP(nn.Module):
40
+ def __init__(self, in_features, hidden_features, drop_rate):
41
+ super().__init__()
42
+ self.fc1 = nn.Linear(in_features, hidden_features)
43
+ self.fc2 = nn.Linear(hidden_features, in_features)
44
+ self.dropout = nn.Dropout(drop_rate)
45
+
46
+ def forward(self, x):
47
+ return self.dropout(self.fc2(self.dropout(F.gelu(self.fc1(x)))))
48
+
49
+ class TransformerEncoderBlock(nn.Module):
50
+ def __init__(self, embed_dim, num_heads, mlp_dim, drop_rate):
51
+ super().__init__()
52
+ self.norm1 = nn.LayerNorm(embed_dim)
53
+ self.attn = nn.MultiheadAttention(embed_dim, num_heads, dropout=drop_rate, batch_first=True)
54
+ self.norm2 = nn.LayerNorm(embed_dim)
55
+ self.mlp = MLP(embed_dim, mlp_dim, drop_rate)
56
+
57
+ def forward(self, x):
58
+ x = x + self.attn(self.norm1(x), self.norm1(x), self.norm1(x))[0]
59
+ x = x + self.mlp(self.norm2(x))
60
+ return x
61
+
62
+ class VisionTransformer(nn.Module):
63
+ def __init__(self, img_size=32, patch_size=4, in_channels=3, num_classes=10,
64
+ embed_dim=256, depth=20, num_heads=8, mlp_dim=512, drop_rate=0.1):
65
+ super().__init__()
66
+ self.patch_embed = PatchEmbedding(img_size, patch_size, in_channels, embed_dim)
67
+ self.encoder = nn.Sequential(*[TransformerEncoderBlock(embed_dim, num_heads, mlp_dim, drop_rate) for _ in range(depth)])
68
+ self.norm = nn.LayerNorm(embed_dim)
69
+ self.head = nn.Linear(embed_dim, num_classes)
70
+
71
+ def forward(self, x):
72
+ x = self.patch_embed(x)
73
+ x = self.encoder(x)
74
+ return self.head(self.norm(x)[:, 0])
75
+
76
+ # ── Load Model ──────────────────────────────────────────────────────────────
77
+ device = torch.device("cpu")
78
+ model = VisionTransformer()
79
+
80
+ model_path = BASE_DIR / "cifar10_model.pth"
81
+ if not model_path.exists():
82
+ print(f"[ERROR] Model file not found at {model_path}", file=sys.stderr)
83
+ sys.exit(1)
84
+
85
+ try:
86
+ # weights_only=True is required in PyTorch >= 2.0 for safe loading
87
+ state_dict = torch.load(model_path, map_location=device, weights_only=True)
88
+ except Exception:
89
+ # Fallback for older checkpoints saved without safe tensors
90
+ state_dict = torch.load(model_path, map_location=device)
91
+
92
+ model.load_state_dict(state_dict)
93
+ model.eval()
94
+ print(f"[OK] Model loaded from {model_path}")
95
+ print(f" Parameters: {sum(p.numel() for p in model.parameters()):,}")
96
+
97
+ # ── Image Transform ─────────────────────────────────────────────────────────
98
+ transform = transforms.Compose([
99
+ transforms.Resize((32, 32)),
100
+ transforms.ToTensor(),
101
+ transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),
102
+ ])
103
+
104
+ # ── Flask Config ────────────────────────────────────────────────────────────
105
+ # Limit upload size to 16 MB to prevent memory issues on HF Spaces free tier
106
+ app.config["MAX_CONTENT_LENGTH"] = 16 * 1024 * 1024
107
+
108
+ # ── Routes ───��──────────────────────────────────────────────────────────────
109
+ @app.route("/")
110
+ def index():
111
+ return render_template("index.html")
112
+
113
+ @app.route("/predict", methods=["POST"])
114
+ def predict():
115
+ if "file" not in request.files:
116
+ return jsonify({"error": "No file uploaded"}), 400
117
+
118
+ file = request.files["file"]
119
+ if file.filename == "":
120
+ return jsonify({"error": "Empty filename"}), 400
121
+
122
+ try:
123
+ # ── Step 1: Read raw bytes robustly ─────────────────────────────────
124
+ # Reset the stream pointer β€” gunicorn/Werkzeug may have consumed it
125
+ # during multipart parsing. Try both the Werkzeug FileStorage seek
126
+ # and the underlying stream directly.
127
+ try:
128
+ file.seek(0)
129
+ except Exception:
130
+ pass
131
+ try:
132
+ file.stream.seek(0)
133
+ except Exception:
134
+ pass
135
+
136
+ img_bytes = file.read()
137
+
138
+ # Debug: log what we actually received
139
+ byte_count = len(img_bytes)
140
+ magic = img_bytes[:8].hex() if img_bytes else "empty"
141
+ print(f"[PREDICT] filename={file.filename!r} bytes={byte_count} magic={magic}")
142
+
143
+ if byte_count == 0:
144
+ return jsonify({
145
+ "error": "Server received 0 bytes. The upload stream was empty. "
146
+ "Try a smaller image (< 5 MB) or a different format."
147
+ }), 400
148
+
149
+ # ── Step 2: Open with PIL ─────────────────────────────────────────────
150
+ try:
151
+ img = Image.open(io.BytesIO(img_bytes))
152
+ img.load() # force eager decode while BytesIO is still alive
153
+ img = img.convert("RGB")
154
+ except Exception as pil_err:
155
+ return jsonify({
156
+ "error": f"Cannot read image ({pil_err}). "
157
+ "Please upload a valid JPEG, PNG, WEBP, or BMP file."
158
+ }), 400
159
+
160
+ # ── Step 3: Inference ────────────────────────────────────────────────
161
+ tensor = transform(img).unsqueeze(0).to(device)
162
+
163
+ t0 = time.time()
164
+ with torch.no_grad():
165
+ logits = model(tensor)
166
+ probs = F.softmax(logits, dim=1).squeeze(0)
167
+ ms = round((time.time() - t0) * 1000, 2)
168
+
169
+ results = sorted(
170
+ [{"class": CLASSES[i], "probability": float(probs[i])} for i in range(10)],
171
+ key=lambda x: x["probability"], reverse=True
172
+ )
173
+ return jsonify({
174
+ "top_class": results[0]["class"],
175
+ "top_probability": results[0]["probability"],
176
+ "all_predictions": results,
177
+ "inference_ms": ms
178
+ })
179
+
180
+ except Exception as e:
181
+ import traceback
182
+ traceback.print_exc()
183
+ return jsonify({"error": str(e)}), 500
184
+
185
+ @app.errorhandler(413)
186
+ def too_large(e):
187
+ return jsonify({"error": "File too large. Maximum size is 16 MB."}), 413
188
+
189
+ @app.route("/model-info")
190
+ def model_info():
191
+ return jsonify({
192
+ "architecture": "Vision Transformer (ViT)",
193
+ "parameters": sum(p.numel() for p in model.parameters()),
194
+ "depth": 20,
195
+ "embed_dim": 256,
196
+ "num_heads": 8,
197
+ "patch_size": "4Γ—4",
198
+ "input_size": "32Γ—32",
199
+ "classes": CLASSES,
200
+ "train_accuracy": "72.59%",
201
+ "test_accuracy": "70.51%",
202
+ "epochs": 25,
203
+ })
204
+
205
+ # ── Run ──────────────────────────────────────────────────────────────────────
206
+ if __name__ == "__main__":
207
+ port = int(os.environ.get("PORT", 5000))
208
+ host = "0.0.0.0" # bind to all interfaces (required for Docker / HF Spaces)
209
+ debug = os.environ.get("FLASK_DEBUG", "0") == "1"
210
+ app.run(debug=debug, host=host, port=port)
requirements.txt ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ # CPU-only PyTorch β€” install with the HF-friendly CPU wheels index
2
+ # (Dockerfile passes --extra-index-url https://download.pytorch.org/whl/cpu)
3
+ torch==2.1.2+cpu
4
+ torchvision==0.16.2+cpu
5
+ flask==3.1.3
6
+ Pillow==10.4.0
7
+ gunicorn==21.2.0
8
+ # torch 2.1.x was compiled against NumPy 1.x β€” pin to <2 to avoid
9
+ # "Failed to initialize NumPy: _ARRAY_API not found" crash at startup
10
+ numpy<2