Kimmilkbreab commited on
Commit
89cdf7f
·
verified ·
1 Parent(s): bed4465

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +42 -0
app.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from torchvision import models, transforms
4
+ from PIL import Image
5
+ import gradio as gr
6
+
7
+ # Load trained model
8
+ num_classes = 200 # CUB-200 dataset
9
+ model = models.resnet18(weights=None)
10
+ model.fc = nn.Linear(model.fc.in_features, num_classes)
11
+
12
+ checkpoint = torch.load("resnet18_finetune_best.pth", map_location="cpu")
13
+ model.load_state_dict(checkpoint["model_state"])
14
+ model.eval()
15
+
16
+ # Image preprocessing
17
+ transform = transforms.Compose([
18
+ transforms.Resize((224,224)),
19
+ transforms.ToTensor(),
20
+ transforms.Normalize(mean=[0.485, 0.456, 0.406],
21
+ std=[0.229, 0.224, 0.225])
22
+ ])
23
+
24
+ # Predict function
25
+ def predict(img):
26
+ img = transform(img).unsqueeze(0)
27
+ with torch.no_grad():
28
+ outputs = model(img)
29
+ probs = torch.softmax(outputs, dim=1)[0]
30
+ top5_prob, top5_catid = torch.topk(probs, 5)
31
+ return {f"Class {i.item()}": float(top5_prob[j]) for j, i in enumerate(top5_catid)}
32
+
33
+ # Gradio interface
34
+ demo = gr.Interface(
35
+ fn=predict,
36
+ inputs=gr.Image(type="pil", label="Upload Bird Image"),
37
+ outputs=gr.Label(num_top_classes=5),
38
+ title="Bird Species Classifier (ResNet18)",
39
+ description="Upload an image of a bird to predict its species using a fine-tuned ResNet18 model."
40
+ )
41
+
42
+ demo.launch()