skuma11 commited on
Commit
c1d1ecf
·
verified ·
1 Parent(s): 27fd7f8

Upload 3 files

Browse files
Files changed (3) hide show
  1. app.py +74 -0
  2. net.pth +3 -0
  3. requirements.txt +5 -0
app.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import gradio as gr
3
+ import torch
4
+ import torch.nn as nn
5
+ import torch.nn.functional as F
6
+ from torchvision import transforms
7
+ from PIL import Image
8
+
9
+
10
+ class LargeNet(nn.Module):
11
+ def __init__(self):
12
+ super(LargeNet, self).__init__()
13
+ self.name = "large"
14
+ self.conv1 = nn.Conv2d(3, 5, 5)
15
+ self.pool = nn.MaxPool2d(2, 2)
16
+ self.conv2 = nn.Conv2d(5, 10, 5)
17
+ self.fc1 = nn.Linear(10 * 29 * 29, 32)
18
+ self.fc2 = nn.Linear(32, 7)
19
+
20
+ def forward(self, x):
21
+ x = self.pool(F.relu(self.conv1(x)))
22
+ x = self.pool(F.relu(self.conv2(x)))
23
+ x = x.view(-1, 10 * 29 * 29)
24
+ x = F.relu(self.fc1(x))
25
+ x = self.fc2(x)
26
+ x = x.squeeze(1) # Flatten to [batch_size]
27
+ return x
28
+
29
+ ORIGINAL_LABELS = ['battery', 'biological', 'cardboard', 'glass', 'metal', 'paper', 'plastic']
30
+ NEW_LABELS = ["paper", "cardboard", "other"]
31
+
32
+ # Load best model
33
+ net = LargeNet()
34
+ net.load_state_dict(torch.load("net.pth"))
35
+ net.eval()
36
+
37
+ # Transform uploaded images
38
+ transform = transforms.Compose([
39
+ transforms.Resize((128, 128)), # Resize to 128x128
40
+ transforms.ToTensor(), # Convert to Tensor
41
+ transforms.Normalize((0.5,), (0.5,)) # Normalize to [-1, 1]
42
+ ])
43
+
44
+ # Make predictions on uploaded images
45
+ def predict(img):
46
+ img_t = transform(img).unsqueeze(0)
47
+
48
+ with torch.no_grad():
49
+ output = net(img_t)
50
+ probs = F.softmax(output[0], dim=0)
51
+
52
+ new_probs = [0.0, 0.0, 0.0]
53
+ for original_label, prob in zip(ORIGINAL_LABELS, probs):
54
+ if original_label == "paper":
55
+ new_probs[0] = prob
56
+ elif original_label == "cardboard":
57
+ new_probs[1] = prob
58
+ else:
59
+ # Accumulate probabilities if the model do not predict "paper" or "cardboard"
60
+ new_probs[2] += prob
61
+
62
+ return {label: float(prob) for label, prob in zip(NEW_LABELS, new_probs)}
63
+
64
+ # Create interface for uploading image and showing predictions
65
+ iface = gr.Interface(
66
+ fn=predict,
67
+ inputs=gr.Image(type="pil"),
68
+ outputs=gr.Label(num_top_classes=3),
69
+ title="Garbage Classifier",
70
+ description="Classify images into Paper, Cardboard, or Other."
71
+ )
72
+
73
+ if __name__ == "__main__":
74
+ iface.launch(share=True)
net.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:aa09b607b8397a1790dcd47affa2c933678da59c63d4669f0a4512220a06b81a
3
+ size 1087797
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ gradio
2
+ torch
3
+ torchvision
4
+ numpy
5
+ pillow