Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import torch
|
| 3 |
+
from torchvision import models, transforms
|
| 4 |
+
from PIL import Image
|
| 5 |
+
import json
|
| 6 |
+
import os
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 10 |
+
model_path = "plant_disease_model/model.pth"
|
| 11 |
+
class_names_path = "plant_disease_model/class_names.json"
|
| 12 |
+
|
| 13 |
+
model_disease = models.mobilenet_v3_small(pretrained=False)
|
| 14 |
+
model_disease.classifier[3] = torch.nn.Linear(model_disease.classifier[3].in_features, 38)
|
| 15 |
+
model_disease.load_state_dict(torch.load(model_path, map_location=device))
|
| 16 |
+
model_disease.to(device)
|
| 17 |
+
model_disease.eval()
|
| 18 |
+
|
| 19 |
+
with open(class_names_path, 'r') as f:
|
| 20 |
+
class_names = json.load(f)
|
| 21 |
+
|
| 22 |
+
transform = transforms.Compose([
|
| 23 |
+
transforms.Resize((224, 224)),
|
| 24 |
+
transforms.ToTensor()
|
| 25 |
+
])
|
| 26 |
+
|
| 27 |
+
def predict_disease(image_path):
|
| 28 |
+
image = Image.open(image_path).convert("RGB")
|
| 29 |
+
img_tensor = transform(image).unsqueeze(0).to(device)
|
| 30 |
+
with torch.no_grad():
|
| 31 |
+
outputs = model_disease(img_tensor)
|
| 32 |
+
_, predicted = torch.max(outputs, 1)
|
| 33 |
+
return f"🌿 Predicted Disease: *{class_names[str(predicted.item())]}*"
|
| 34 |
+
|
| 35 |
+
with gr.Blocks() as demo:
|
| 36 |
+
gr.Markdown("# 🌱 AgroVision: Smart Assistant for Farmers")
|
| 37 |
+
with gr.TabItem("🦠 Plant Disease Detection"):
|
| 38 |
+
gr.Markdown("### Upload a crop leaf image to detect disease")
|
| 39 |
+
image_input = gr.Image(type="filepath")
|
| 40 |
+
disease_btn = gr.Button("Detect Disease")
|
| 41 |
+
disease_output = gr.Markdown()
|
| 42 |
+
disease_btn.click(fn=predict_disease, inputs=image_input, outputs=disease_output)
|
| 43 |
+
|
| 44 |
+
demo.launch()
|