Download app.py from Nausad/Vision_Transformer_Based_Image_Classification_Model: direct link, hf CLI and curl.
- Browser
- Download file 7.62 kB
-
https://huggingface.co/spaces/Nausad/Vision_Transformer_Based_Image_Classification_Model/resolve/e6a047715fc3f645d66c059e5e292abe85abc772/app.py
- Command line
-
hf download hf://spaces/Nausad/Vision_Transformer_Based_Image_Classification_Model@e6a047715fc3f645d66c059e5e292abe85abc772/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Nausad/Vision_Transformer_Based_Image_Classification_Model/resolve/e6a047715fc3f645d66c059e5e292abe85abc772/app.py
7.62 kB
| from flask import Flask, request, jsonify, render_template | |
| import torch | |
| import torch.nn as nn | |
| import torch.nn.functional as F | |
| from torchvision import transforms | |
| import pillow_avif | |
| from PIL import Image | |
| import io | |
| import json | |
| import time | |
| import os | |
| from pathlib import Path | |
| # ββ Paths ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| BASE_DIR = Path(__file__).parent.resolve() | |
| app = Flask(__name__, template_folder=str(BASE_DIR / "templates")) | |
| # ββ CIFAR-10 Classes ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| CLASSES = ["airplane", "automobile", "bird", "cat", "deer", | |
| "dog", "frog", "horse", "ship", "truck"] | |
| # ββ Model Definition ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| class PatchEmbedding(nn.Module): | |
| def __init__(self, img_size=32, patch_size=4, in_channels=3, embed_dim=256): | |
| super().__init__() | |
| self.proj = nn.Conv2d(in_channels, embed_dim, kernel_size=patch_size, stride=patch_size) | |
| num_patches = (img_size // patch_size) ** 2 | |
| self.cls_token = nn.Parameter(torch.randn(1, 1, embed_dim)) | |
| self.pos_embed = nn.Parameter(torch.randn(1, 1 + num_patches, embed_dim)) | |
| def forward(self, x): | |
| B = x.size(0) | |
| x = self.proj(x).flatten(2).transpose(1, 2) | |
| cls_token = self.cls_token.expand(B, -1, -1) | |
| x = torch.cat((cls_token, x), dim=1) + self.pos_embed | |
| return x | |
| class MLP(nn.Module): | |
| def __init__(self, in_features, hidden_features, drop_rate): | |
| super().__init__() | |
| self.fc1 = nn.Linear(in_features, hidden_features) | |
| self.fc2 = nn.Linear(hidden_features, in_features) | |
| self.dropout = nn.Dropout(drop_rate) | |
| def forward(self, x): | |
| return self.dropout(self.fc2(self.dropout(F.gelu(self.fc1(x))))) | |
| class TransformerEncoderBlock(nn.Module): | |
| def __init__(self, embed_dim, num_heads, mlp_dim, drop_rate): | |
| super().__init__() | |
| self.norm1 = nn.LayerNorm(embed_dim) | |
| self.attn = nn.MultiheadAttention(embed_dim, num_heads, dropout=drop_rate, batch_first=True) | |
| self.norm2 = nn.LayerNorm(embed_dim) | |
| self.mlp = MLP(embed_dim, mlp_dim, drop_rate) | |
| def forward(self, x): | |
| x = x + self.attn(self.norm1(x), self.norm1(x), self.norm1(x))[0] | |
| x = x + self.mlp(self.norm2(x)) | |
| return x | |
| class VisionTransformer(nn.Module): | |
| def __init__(self, img_size=32, patch_size=4, in_channels=3, num_classes=10, | |
| embed_dim=256, depth=20, num_heads=8, mlp_dim=512, drop_rate=0.1): | |
| super().__init__() | |
| self.patch_embed = PatchEmbedding(img_size, patch_size, in_channels, embed_dim) | |
| self.encoder = nn.Sequential(*[TransformerEncoderBlock(embed_dim, num_heads, mlp_dim, drop_rate) for _ in range(depth)]) | |
| self.norm = nn.LayerNorm(embed_dim) | |
| self.head = nn.Linear(embed_dim, num_classes) | |
| def forward(self, x): | |
| x = self.patch_embed(x) | |
| x = self.encoder(x) | |
| return self.head(self.norm(x)[:, 0]) | |
| # ββ Load Model ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| device = torch.device("cpu") | |
| model = VisionTransformer() | |
| model_path = BASE_DIR / "cifar10_model.pth" | |
| model.load_state_dict(torch.load(model_path, map_location=device)) | |
| model.eval() | |
| print(f"[OK] Model loaded from {model_path}") | |
| print(f" Parameters: {sum(p.numel() for p in model.parameters()):,}") | |
| # ββ Image Transform βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| transform = transforms.Compose([ | |
| transforms.Resize((32, 32)), | |
| transforms.ToTensor(), | |
| transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)), | |
| ]) | |
| # ββ Routes ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def index(): | |
| return render_template("index.html") | |
| def predict(): | |
| if "file" not in request.files: | |
| return jsonify({"error": "No file uploaded"}), 400 | |
| ``` | |
| file = request.files["file"] | |
| if file.filename == "": | |
| return jsonify({"error": "Empty filename"}), 400 | |
| try: | |
| data = file.read() | |
| print("=" * 60) | |
| print("Filename:", file.filename) | |
| print("Content-Type:", file.content_type) | |
| print("Bytes length:", len(data)) | |
| img = Image.open(io.BytesIO(data)) | |
| print("Format:", img.format) | |
| print("Size:", img.size) | |
| img = img.convert("RGB") | |
| print("Step 1: RGB conversion done") | |
| tensor = transform(img).unsqueeze(0).to(device) | |
| print("Step 2: Transform done") | |
| print("Tensor shape:", tensor.shape) | |
| print("Tensor dtype:", tensor.dtype) | |
| t0 = time.time() | |
| with torch.no_grad(): | |
| print("Step 3: Starting inference") | |
| logits = model(tensor) | |
| print("Step 4: Inference complete") | |
| probs = F.softmax(logits, dim=1).squeeze(0) | |
| print("Step 5: Softmax complete") | |
| ms = round((time.time() - t0) * 1000, 2) | |
| results = sorted( | |
| [ | |
| { | |
| "class": CLASSES[i], | |
| "probability": float(probs[i]) | |
| } | |
| for i in range(10) | |
| ], | |
| key=lambda x: x["probability"], | |
| reverse=True | |
| ) | |
| print("Step 6: Results generated") | |
| print("Top class:", results[0]["class"]) | |
| print("Top probability:", results[0]["probability"]) | |
| return jsonify({ | |
| "top_class": results[0]["class"], | |
| "top_probability": results[0]["probability"], | |
| "all_predictions": results, | |
| "inference_ms": ms | |
| }) | |
| except Exception as e: | |
| import traceback | |
| print("ERROR OCCURRED:") | |
| traceback.print_exc() | |
| return jsonify({ | |
| "error": str(e) | |
| }), 500 | |
| ``` | |
| def model_info(): | |
| return jsonify({ | |
| "architecture": "Vision Transformer (ViT)", | |
| "parameters": sum(p.numel() for p in model.parameters()), | |
| "depth": 20, | |
| "embed_dim": 256, | |
| "num_heads": 8, | |
| "patch_size": "4Γ4", | |
| "input_size": "32Γ32", | |
| "classes": CLASSES, | |
| "train_accuracy": "72.59%", | |
| "test_accuracy": "70.51%", | |
| "epochs": 25, | |
| }) | |
| # ββ Run ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| if __name__ == "__main__": | |
| port = int(os.environ.get("PORT", 5000)) | |
| host = "0.0.0.0" # bind to all interfaces (required for Docker / HF Spaces) | |
| debug = os.environ.get("FLASK_DEBUG", "0") == "1" | |
| app.run(debug=debug, host=host, port=port) | |