Phoenix3238 commited on
Commit
40c9211
·
verified ·
1 Parent(s): 4b0cfc9

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +85 -0
app.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import time
4
+ import glob
5
+ import torch
6
+ import torch.nn as nn
7
+ from torchvision import models, transforms
8
+ from PIL import Image
9
+ import gradio as gr
10
+ import spaces
11
+
12
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
13
+
14
+ with open("class_names.json", "r") as f:
15
+ class_names = json.load(f)
16
+
17
+ def load_model():
18
+ model = models.convnext_tiny(weights=None)
19
+ in_features = model.classifier[2].in_features
20
+ model.classifier[2] = nn.Linear(in_features, len(class_names))
21
+
22
+ state_dict = torch.load("convnext_caltech101.pth", map_location=device)
23
+ model.load_state_dict(state_dict)
24
+
25
+ model.to(device)
26
+ model.eval()
27
+ return model
28
+
29
+ model = load_model()
30
+
31
+ transform = transforms.Compose([
32
+ transforms.Resize((224, 224)),
33
+ transforms.ToTensor(),
34
+ transforms.Normalize(
35
+ mean=[0.485, 0.456, 0.406],
36
+ std=[0.229, 0.224, 0.225]
37
+ )
38
+ ])
39
+
40
+ # Adding the ZeroGPU decorator to the inference function
41
+ @spaces.GPU
42
+ def predict(image):
43
+ if image is None:
44
+ return None, 0.0
45
+
46
+ start_time = time.perf_counter()
47
+ img_tensor = transform(image).unsqueeze(0).to(device)
48
+
49
+ with torch.inference_mode():
50
+ logits = model(img_tensor)
51
+ probs = torch.softmax(logits, dim=1).squeeze()
52
+
53
+ # Ensure accurate timing on GPU
54
+ if device.type == "cuda":
55
+ torch.cuda.synchronize()
56
+
57
+ latency = time.perf_counter() - start_time
58
+
59
+ confidences = {
60
+ class_names[i]: float(probs[i])
61
+ for i in range(len(class_names))
62
+ }
63
+
64
+ return confidences, round(latency, 4)
65
+
66
+ # Building the UI
67
+ example_images = glob.glob("demo_images/*.jpg")
68
+
69
+ demo = gr.Interface(
70
+ fn=predict,
71
+ inputs=gr.Image(type="pil", label="Upload Input Image"),
72
+ outputs=[
73
+ gr.Label(num_top_classes=5, label="Top 5 Predictions"),
74
+ gr.Number(label="Inference Latency (seconds)")
75
+ ],
76
+ title="CalTech-101 Image Classifier",
77
+ description="Upload an image to see how the fine-tuned ConvNeXt model classifies it.",
78
+ examples=example_images if example_images else None,
79
+ flagging_mode="never",
80
+ live=True,
81
+ theme=gr.themes.Soft()
82
+ )
83
+
84
+ if __name__ == "__main__":
85
+ demo.launch()