File size: 2,569 Bytes
f555524
0b48197
b0471d8
0b48197
 
b87a427
0b48197
b0471d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b41a5c0
 
f555524
1c7b13d
05d5fb1
1c7b13d
 
 
05d5fb1
 
59d9c25
 
05d5fb1
 
f555524
59d9c25
 
 
 
 
f2bdd93
 
 
 
59d9c25
f2bdd93
 
 
 
 
 
 
59d9c25
 
f2bdd93
f555524
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import gradio as gr
import torch
from torch import nn
from PIL import Image
from torchvision import transforms
import numpy as np


class CustomModel(nn.Module):
    def __init__(self, input_shape, num_classes):
        super(CustomModel, self).__init__()

        self.conv_layers = nn.Sequential(
            nn.Conv2d(in_channels=input_shape[0], out_channels=32, kernel_size=3, padding=1),
            nn.ReLU(),
            nn.BatchNorm2d(32),
            nn.MaxPool2d(kernel_size=2),
            nn.Conv2d(in_channels=32, out_channels=64, kernel_size=3, padding=1),
            nn.ReLU(),
            nn.BatchNorm2d(64),
            nn.MaxPool2d(kernel_size=2),
            nn.Conv2d(in_channels=64, out_channels=128, kernel_size=3, padding=1),
            nn.ReLU(),
            nn.BatchNorm2d(128),
            nn.MaxPool2d(kernel_size=2),
            nn.Conv2d(in_channels=128, out_channels=128, kernel_size=3, padding=1),
            nn.ReLU(),
            nn.BatchNorm2d(128),
            nn.MaxPool2d(kernel_size=2)
        )

        self.fc_layers = nn.Sequential(
            nn.Flatten(),
            nn.Dropout(0.5),
            nn.Linear(128 * (input_shape[1] // 16) * (input_shape[2] // 16), 512),
            nn.ReLU(),
            nn.BatchNorm1d(512),
            nn.Dropout(0.5),
            nn.Linear(512, num_classes)
        )

    def forward(self, x):
        x = self.conv_layers(x)
        x = self.fc_layers(x)
        return x

model = CustomModel(input_shape=(3,128,128), num_classes=2)
model.load_state_dict(torch.load('model.pth', map_location=torch.device('cpu')))


def predict(image):
    preprocess = transforms.Compose([
        transforms.Resize((128, 128)),
        transforms.ToTensor(),
        transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
    ])

    # Ensure the image is a PIL Image
    image = Image.fromarray(image.astype('uint8'), 'RGB')

    x = preprocess(image).unsqueeze(0)

    # Set model to evaluation mode
    model.eval()

    with torch.no_grad():  # Use no_grad context for inference to save memory and computations
        x = model(x)
        probabilities = torch.nn.functional.softmax(x, dim=1)[0]
        #class_id = probabilities.argmax(dim=1).item()
        cat_prob = probabilities[0]
        dog_prob = probabilities[1]

    return {
        'cat': cat_prob.item(),
        'dog': dog_prob.item()
    }

    #classes = ['cat', 'dog']
    #return classes[class_id]

# Update Gradio interface
demo = gr.Interface(fn=predict, inputs="image", outputs="label")
demo.launch()