ma4389 commited on
Commit
11cfb1b
Β·
verified Β·
1 Parent(s): cc65e2c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +65 -76
app.py CHANGED
@@ -1,76 +1,65 @@
1
- import gradio as gr
2
- import torch
3
- import torch.nn as nn
4
- from torchvision import transforms, models
5
- from PIL import Image
6
-
7
- # ===============================
8
- # πŸ“Œ Classes (same order as ImageFolder during training)
9
- # Replace with trainers.classes if available
10
- # ===============================
11
- class_names = [
12
- "Acura", "Alfa Romeo", "Aston Martin", "Audi", "Bentley",
13
- "BMW", "Bugatti", "Buick", "Cadillac", "Chevrolet",
14
- "Chrysler", "Citroen", "Dodge", "Ferrari", "Fiat",
15
- "Ford", "Genesis", "GMC", "Honda", "Hyundai",
16
- "Infiniti", "Jaguar", "Jeep", "Kia", "Lamborghini",
17
- "Land Rover", "Lexus", "Lincoln", "Maserati", "Mazda",
18
- "McLaren", "Mercedes", "Mini", "Mitsubishi", "Nissan",
19
- "Pagani", "Peugeot", "Porsche", "Ram", "Renault",
20
- "Rolls Royce", "Saab", "Subaru", "Suzuki", "Tesla",
21
- "Toyota", "Volkswagen", "Volvo", "Others1", "Others2"
22
- ]
23
-
24
- # ===============================
25
- # πŸ“Œ Inference Transform (NO augmentation)
26
- # ===============================
27
- transform = transforms.Compose([
28
- transforms.Lambda(lambda x: x.convert("RGB")),
29
- transforms.Resize((224,224)),
30
- transforms.ToTensor(),
31
- transforms.Normalize([0.5]*3, [0.5]*3)
32
- ])
33
-
34
- device = "cuda" if torch.cuda.is_available() else "cpu"
35
-
36
- # ===============================
37
- # πŸ“Œ Load Model
38
- # ===============================
39
- def load_model(weights_path="best_model.pth"):
40
- base_model = models.resnet50(weights=models.ResNet50_Weights.DEFAULT)
41
- in_features = base_model.fc.in_features
42
- base_model.fc = nn.Sequential(
43
- nn.Linear(in_features, 512),
44
- nn.ReLU(),
45
- nn.Dropout(0.5),
46
- nn.Linear(512, len(class_names))
47
- )
48
- base_model.load_state_dict(torch.load(weights_path, map_location=device))
49
- return base_model.to(device).eval()
50
-
51
- model = load_model()
52
-
53
- # ===============================
54
- # πŸ“Œ Prediction Function
55
- # ===============================
56
- def predict(image):
57
- img = transform(image).unsqueeze(0).to(device)
58
- with torch.no_grad():
59
- outputs = model(img)
60
- probs = torch.softmax(outputs, dim=1)[0]
61
- top5_probs, top5_idx = torch.topk(probs, 5)
62
- return {class_names[idx]: float(prob) for idx, prob in zip(top5_idx, top5_probs)}
63
-
64
- # ===============================
65
- # πŸ“Œ Gradio Interface
66
- # ===============================
67
- demo = gr.Interface(
68
- fn=predict,
69
- inputs=gr.Image(type="pil"),
70
- outputs=gr.Label(num_top_classes=5),
71
- title="πŸš— Car Brand Classifier",
72
- description="Upload a car image and the model predicts the brand (Top-5)."
73
- )
74
-
75
- if __name__ == "__main__":
76
- demo.launch()
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torchvision.transforms as transforms
4
+ from PIL import Image
5
+ import gradio as gr
6
+
7
+ # -----------------------------
8
+ # 1. Load your model
9
+ # -----------------------------
10
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
11
+ model = torch.load("best_model.pth", map_location=device) # update filename if needed
12
+ model.eval()
13
+
14
+ # -----------------------------
15
+ # 2. Class mapping (from training)
16
+ # -----------------------------
17
+ class_to_idx = {
18
+ 'Acura': 0, 'Alfa Romeo': 1, 'Aston Martin': 2, 'Audi': 3, 'BMW': 4, 'Bentley': 5, 'Bugatti': 6,
19
+ 'Buick': 7, 'Cadillac': 8, 'Chevrolet': 9, 'Chrysler': 10, 'Citroen': 11, 'Daewoo': 12,
20
+ 'Dodge': 13, 'Ferrari': 14, 'Fiat': 15, 'Ford': 16, 'GMC': 17, 'Genesis': 18, 'Honda': 19,
21
+ 'Hudson': 20, 'Hyundai': 21, 'Infiniti': 22, 'Jaguar': 23, 'Jeep': 24, 'Kia': 25, 'Land Rover': 26,
22
+ 'Lexus': 27, 'Lincoln': 28, 'MG': 29, 'Maserati': 30, 'Mazda': 31, 'Mercedes-Benz': 32, 'Mini': 33,
23
+ 'Mitsubishi': 34, 'Nissan': 35, 'Oldsmobile': 36, 'Peugeot': 37, 'Pontiac': 38, 'Porsche': 39,
24
+ 'Ram Trucks': 40, 'Renault': 41, 'Saab': 42, 'Studebaker': 43, 'Subaru': 44, 'Suzuki': 45,
25
+ 'Tesla': 46, 'Toyota': 47, 'Volkswagen': 48, 'Volvo': 49
26
+ }
27
+ idx_to_class = {v: k for k, v in class_to_idx.items()}
28
+
29
+ # -----------------------------
30
+ # 3. Transform (inference version: no randomness)
31
+ # -----------------------------
32
+ transform = transforms.Compose([
33
+ transforms.Lambda(lambda x: x.convert("RGB")),
34
+ transforms.Resize((224,224)),
35
+ transforms.ToTensor(),
36
+ transforms.Normalize([0.5]*3, [0.5]*3)
37
+ ])
38
+
39
+ # -----------------------------
40
+ # 4. Prediction function
41
+ # -----------------------------
42
+ def predict(img):
43
+ img = transform(img).unsqueeze(0).to(device)
44
+
45
+ with torch.no_grad():
46
+ outputs = model(img)
47
+ probs = torch.softmax(outputs, dim=1)[0]
48
+
49
+ top5_probs, top5_idx = torch.topk(probs, 5)
50
+ results = {idx_to_class[idx.item()]: float(top5_probs[i]) for i, idx in enumerate(top5_idx)}
51
+ return results
52
+
53
+ # -----------------------------
54
+ # 5. Gradio UI
55
+ # -----------------------------
56
+ demo = gr.Interface(
57
+ fn=predict,
58
+ inputs=gr.Image(type="pil"),
59
+ outputs=gr.Label(num_top_classes=5),
60
+ title="Car Brand Classifier",
61
+ description="Upload a car image to classify its brand"
62
+ )
63
+
64
+ if __name__ == "__main__":
65
+ demo.launch()