Spaces:
Build error
Build error
| import torch | |
| import torch.nn as nn | |
| import timm | |
| import gradio as gr | |
| from torchvision import transforms | |
| from PIL import Image | |
| # Define class labels | |
| class_names = ['Bacteria', 'Fungi', 'Healthy', 'Nematode', 'Pest', 'Phytopthora', 'Virus'] | |
| # Load model | |
| device = torch.device("cuda" if torch.cuda.is_available() else "cpu") | |
| model = timm.create_model('mobilenetv3_large_100', pretrained=False) | |
| model.classifier = nn.Sequential( | |
| nn.Linear(model.classifier.in_features, 512), | |
| nn.ReLU(), | |
| nn.Dropout(0.3), | |
| nn.Linear(512, len(class_names)) | |
| ) | |
| model.load_state_dict(torch.load('best_model.pth', map_location=device)) | |
| model.to(device) | |
| model.eval() | |
| # Transform for input image | |
| 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]) | |
| ]) | |
| # Inference function | |
| def predict(image): | |
| image = transform(image).unsqueeze(0).to(device) | |
| with torch.no_grad(): | |
| outputs = model(image) | |
| _, predicted = torch.max(outputs, 1) | |
| confidence = torch.softmax(outputs, dim=1)[0][predicted.item()].item() | |
| return {class_names[predicted.item()]: float(confidence)} | |
| # Gradio interface | |
| interface = gr.Interface( | |
| fn=predict, | |
| inputs=gr.Image(type="pil"), | |
| outputs=gr.Label(num_top_classes=3), | |
| title="Potato Leaf Disease Classification", | |
| description="Upload an image of a potato leaf to detect the disease type." | |
| ) | |
| interface.launch() | |