kendrickfff's picture
Update app.py
388a67a verified
raw
history blame
4.46 kB
import os
import shutil
import subprocess
import zipfile
import time
import torch
import torch.nn as nn
import torch.optim as optim
from torchvision import datasets, transforms, models
from torch.optim import lr_scheduler
import subprocess
import zipfile
from PIL import Image
import gradio as gr
# Step 1: Setup Kaggle API
# Ensure the .kaggle directory exists
kaggle_dir = os.path.expanduser("~/.kaggle")
if not os.path.exists(kaggle_dir):
os.makedirs(kaggle_dir)
# Step 2: Copy the kaggle.json file to the ~/.kaggle directory
kaggle_json_path = "kaggle.json"
kaggle_dest_path = os.path.join(kaggle_dir, "kaggle.json")
if not os.path.exists(kaggle_dest_path):
shutil.copy(kaggle_json_path, kaggle_dest_path)
os.chmod(kaggle_dest_path, 0o600)
print("Kaggle API key copied and permissions set.")
else:
print("Kaggle API key already exists.")
# Step 3: Download the dataset from Kaggle using Kaggle CLI
dataset_name = "mostafaabla/garbage-classification"
print(f"Downloading the dataset: {dataset_name}")
download_command = f"kaggle datasets download -d {dataset_name}"
# Run the download command
subprocess.run(download_command, shell=True)
# Step 4: Unzip the downloaded dataset
dataset_zip = "garbage-classification.zip"
extracted_folder = "./garbage-classification"
# Check if the zip file exists
if os.path.exists(dataset_zip):
if not os.path.exists(extracted_folder):
with zipfile.ZipFile(dataset_zip, 'r') as zip_ref:
zip_ref.extractall(extracted_folder)
print("Dataset unzipped successfully!")
else:
print("Dataset already unzipped.")
else:
print(f"Dataset zip file '{dataset_zip}' not found.")
# Load your model
def load_model():
model = models.resnet50(weights='DEFAULT') # Using default weights for initialization
num_ftrs = model.fc.in_features
model.fc = nn.Linear(num_ftrs, 12) # Adjust to the number of classes you have
# Load the state dict without the weights_only argument
model.load_state_dict(torch.load('resnet50_garbage_classification.pth', map_location=torch.device('cpu')))
model.eval() # Set to evaluation mode
return model
model = load_model()
# Define image transformations
transform = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
])
# Class names
class_names = ['battery', 'biological', 'brown-glass', 'cardboard',
'clothes', 'green-glass', 'metal', 'paper',
'plastic', 'shoes', 'trash', 'white-glass']
# Define bin colors for each class
bin_colors = {
'battery': 'Merah (Red)', # Limbah berbahaya
'biological': 'Cokelat (Brown)', # Limbah organik
'brown-glass': 'Hijau (Green)', # Gelas berwarna coklat
'cardboard': 'Kuning (Yellow)', # Limbah daur ulang
'clothes': 'Biru (Blue)', # Pakaian dan tekstil
'green-glass': 'Hijau (Green)', # Gelas berwarna hijau
'metal': 'Kuning (Yellow)', # Limbah daur ulang
'paper': 'Kuning (Yellow)', # Limbah daur ulang
'plastic': 'Kuning (Yellow)', # Limbah daur ulang
'shoes': 'Biru (Blue)', # Pakaian dan tekstil
'trash': 'Hitam (Black)', # Limbah umum
'white-glass': 'Putih (White)' # Gelas berwarna putih
}
# Define the prediction function
def predict(image):
image = Image.fromarray(image) # Convert numpy array to PIL Image
image = transform(image) # Apply transformations
image = image.unsqueeze(0) # Add batch dimension
with torch.no_grad():
outputs = model(image)
_, predicted = torch.max(outputs, 1)
class_name = class_names[predicted.item()] # Return predicted class name
bin_color = bin_colors[class_name] # Get the corresponding bin color
return class_name, bin_color # Return both class name and bin color
# Make Gradio Interface
iface = gr.Interface(
fn=predict,
inputs=gr.Image(type="numpy", label="Unggah Gambar"),
outputs=[
gr.Textbox(label="Jenis Sampah"),
gr.Textbox(label="Tong Sampah yang Sesuai") # 2 output with label
],
title="Klasifikasi Sampah dengan ResNet50",
description="Unggah gambar sampah, dan model akan mengklasifikasikannya ke dalam salah satu dari 12 kategori bersama dengan warna tempat sampah yang sesuai."
)
iface.launch(share=True)