File size: 1,524 Bytes
727d2ea
 
 
ebf1ca5
 
 
727d2ea
ebf1ca5
 
727d2ea
ebf1ca5
727d2ea
ebf1ca5
727d2ea
ebf1ca5
727d2ea
 
ebf1ca5
727d2ea
ebf1ca5
727d2ea
ebf1ca5
727d2ea
ebf1ca5
 
 
 
 
 
 
 
727d2ea
ebf1ca5
 
 
727d2ea
ebf1ca5
 
 
 
 
 
 
 
 
 
 
 
 
727d2ea
ebf1ca5
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
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()