File size: 1,640 Bytes
696fdb6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import torch
import torch.nn as nn
from torchvision import models, transforms
from PIL import Image
import gradio as gr

DEVICE = torch.device("cpu")
NUM_CLASSES = 64
MODEL_PATH = "resnet18_animals_64.pth"
CLASS_NAMES_FILE = "classes.txt"

with open(CLASS_NAMES_FILE, "r") as f:
    class_names = [line.strip() for line in f.readlines()]

def load_model():
    model = models.resnet18(weights=None)
    num_ftrs = model.fc.in_features
    model.fc = nn.Linear(num_ftrs, NUM_CLASSES)
    
    model.load_state_dict(torch.load(MODEL_PATH, map_location=DEVICE))
    model.to(DEVICE)
    model.eval()
    return model

model = load_model()

image_transforms = transforms.Compose([
    transforms.Resize((224, 224)),
    transforms.ToTensor(),
    transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
])

def predict(image):
    img_tensor = image_transforms(image).unsqueeze(0)
    img_tensor = img_tensor.to(DEVICE)
    
    with torch.no_grad():
        outputs = model(img_tensor)
        probabilities = torch.nn.functional.softmax(outputs[0], dim=0)
    
    top3_prob, top3_catid = torch.topk(probabilities, 3)
    
    confidences = {}
    for i in range(top3_prob.size(0)):
        confidences[class_names[top3_catid[i]]] = float(top3_prob[i])
    
    return confidences

title = "Animal Classifier 🐾"
description = "Nhận diện 64 loài động vật sử dụng mô hình ResNet-18."
examples = []

interface = gr.Interface(
    fn=predict, 
    inputs=gr.Image(type="pil"), 
    outputs=gr.Label(num_top_classes=3),
    title=title,
    description=description
)

if __name__ == "__main__":
    interface.launch()