Nausad commited on
Commit
3929191
·
verified ·
1 Parent(s): 9da2544

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -172
app.py DELETED
@@ -1,172 +0,0 @@
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
- img = Image.open(io.BytesIO(file.read())).convert("RGB")
124
- tensor = transform(img).unsqueeze(0).to(device)
125
-
126
- t0 = time.time()
127
- with torch.no_grad():
128
- logits = model(tensor)
129
- probs = F.softmax(logits, dim=1).squeeze(0)
130
- ms = round((time.time() - t0) * 1000, 2)
131
-
132
- results = sorted(
133
- [{"class": CLASSES[i], "probability": float(probs[i])} for i in range(10)],
134
- key=lambda x: x["probability"], reverse=True
135
- )
136
- return jsonify({
137
- "top_class": results[0]["class"],
138
- "top_probability": results[0]["probability"],
139
- "all_predictions": results,
140
- "inference_ms": ms
141
- })
142
- except Exception as e:
143
- import traceback
144
- traceback.print_exc()
145
- return jsonify({"error": str(e)}), 500
146
-
147
- @app.errorhandler(413)
148
- def too_large(e):
149
- return jsonify({"error": "File too large. Maximum size is 16 MB."}), 413
150
-
151
- @app.route("/model-info")
152
- def model_info():
153
- return jsonify({
154
- "architecture": "Vision Transformer (ViT)",
155
- "parameters": sum(p.numel() for p in model.parameters()),
156
- "depth": 20,
157
- "embed_dim": 256,
158
- "num_heads": 8,
159
- "patch_size": "4×4",
160
- "input_size": "32×32",
161
- "classes": CLASSES,
162
- "train_accuracy": "72.59%",
163
- "test_accuracy": "70.51%",
164
- "epochs": 25,
165
- })
166
-
167
- # ── Run ──────────────────────────────────────────────────────────────────────
168
- if __name__ == "__main__":
169
- port = int(os.environ.get("PORT", 5000))
170
- host = "0.0.0.0" # bind to all interfaces (required for Docker / HF Spaces)
171
- debug = os.environ.get("FLASK_DEBUG", "0") == "1"
172
- app.run(debug=debug, host=host, port=port)