File size: 1,864 Bytes
c1d1ecf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8ac53ea
c1d1ecf
 
 
8d17e1e
c1d1ecf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8ac53ea
c1d1ecf
 
 
 
 
8ac53ea
c1d1ecf
8ac53ea
c1d1ecf
 
 
 
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
import numpy as np
import gradio as gr
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision import transforms
from PIL import Image


class LargeNet(nn.Module):
    def __init__(self):
        super(LargeNet, self).__init__()
        self.name = "large"
        self.conv1 = nn.Conv2d(3, 5, 5)
        self.pool = nn.MaxPool2d(2, 2)
        self.conv2 = nn.Conv2d(5, 10, 5)
        self.fc1 = nn.Linear(10 * 29 * 29, 32)
        self.fc2 = nn.Linear(32, 7)

    def forward(self, x):
        x = self.pool(F.relu(self.conv1(x)))
        x = self.pool(F.relu(self.conv2(x)))
        x = x.view(-1, 10 * 29 * 29)
        x = F.relu(self.fc1(x))
        x = self.fc2(x)
        x = x.squeeze(1) # Flatten to [batch_size]
        return x

LABELS = ['battery', 'biological', 'cardboard', 'glass', 'metal', 'paper', 'plastic']

# Load best model
net = LargeNet()
net.load_state_dict(torch.load("net.pth", map_location=torch.device('cpu')))
net.eval()

# Transform uploaded images
transform = transforms.Compose([
    transforms.Resize((128, 128)),  # Resize to 128x128
    transforms.ToTensor(),         # Convert to Tensor
    transforms.Normalize((0.5,), (0.5,))  # Normalize to [-1, 1]
])

# Make predictions on uploaded images
def predict(img):
    img_t = transform(img).unsqueeze(0)

    with torch.no_grad():
        output = net(img_t)
        probs = F.softmax(output[0], dim=0)

    return {label: float(prob) for label, prob in zip(LABELS, probs)}

# Create interface for uploading image and showing predictions
iface = gr.Interface(
    fn=predict,
    inputs=gr.Image(type="pil"),
    outputs=gr.Label(num_top_classes=7),
    title="Garbage Classifier",
    description="Classify garbage images into Battery, Biological, Cardboard, Glass', Metal, Paper, or Plastic"
)

if __name__ == "__main__":
    iface.launch(share=True)