Spaces:
Sleeping
Sleeping
Download app.py from skuma11/classify-garbage: direct link, hf CLI and curl.
- Browser
- Download file 1.86 kB
-
https://huggingface.co/spaces/skuma11/classify-garbage/resolve/main/app.py
- Command line
-
hf download hf://spaces/skuma11/classify-garbage/app.py
-
curl -L -o app.py https://huggingface.co/spaces/skuma11/classify-garbage/resolve/main/app.py
1.86 kB
| 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) | |