Spaces:
Sleeping
Sleeping
File size: 4,049 Bytes
0a131b9 f32e001 be7dd52 eec5dd1 0a131b9 eec5dd1 0a131b9 be7dd52 4bb0527 be7dd52 eec5dd1 4bb0527 eec5dd1 4bb0527 be7dd52 eec5dd1 4e5cace eec5dd1 a0d5d1b eec5dd1 be7dd52 4e5cace be7dd52 4bb0527 be7dd52 eec5dd1 be7dd52 eec5dd1 be7dd52 eec5dd1 f32e001 eec5dd1 |
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 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 |
import os
import gradio as gr
import torch
import requests
import logging
import numpy as np
from PIL import Image
from bs4 import BeautifulSoup
from transformers import AutoImageProcessor, AutoModelForImageClassification
# Configure Logging
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
# Load Model & Processor
MODEL_NAME = "linkanjarad/mobilenet_v2_1.0_224-plant-disease-identification"
try:
processor = AutoImageProcessor.from_pretrained(MODEL_NAME, use_fast=True)
model = AutoModelForImageClassification.from_pretrained(MODEL_NAME)
logging.info("β
Model and processor loaded successfully.")
except Exception as e:
logging.error(f"β Failed to load model: {str(e)}")
raise RuntimeError("Failed to load the model. Please check the logs for details.")
# Function to Fetch Treatment Suggestions from the Internet
def fetch_treatment_info(disease_name):
try:
search_url = f"https://www.bing.com/search?q=treatment+for+{disease_name.replace(' ', '+')}+in+plants"
headers = {"User-Agent": "Mozilla/5.0"}
response = requests.get(search_url, headers=headers)
if response.status_code == 200:
soup = BeautifulSoup(response.text, "html.parser")
snippets = soup.find_all("p")
treatments = [s.text for s in snippets][:3]
return "\n".join(treatments) if treatments else "No treatment suggestions found."
else:
return "Failed to fetch treatment suggestions."
except Exception as e:
logging.error(f"Error fetching treatment info: {str(e)}")
return "Error retrieving treatment details."
# Define Prediction Function
def predict(image):
try:
image = Image.fromarray(np.uint8(image)).convert("RGB")
inputs = processor(images=image, return_tensors="pt")
with torch.no_grad():
outputs = model(**inputs)
logits = outputs.logits
predicted_class_idx = logits.argmax(-1).item()
confidence = torch.nn.functional.softmax(logits, dim=-1)[0][predicted_class_idx] * 100
predicted_label = model.config.id2label[predicted_class_idx]
treatment = fetch_treatment_info(predicted_label)
return predicted_label, confidence.item(), treatment
except Exception as e:
logging.error(f"Prediction failed: {str(e)}")
return "Error", 0, "Error in prediction."
# Create a Gradio UI with Tabs & Styling
with gr.Blocks(css="body {background-color: #f7f9fc;}") as app:
gr.Markdown(
"<h1 style='text-align: center;'>πΏ AI-Powered Plant Disease Detector</h1>",
elem_id="title"
)
with gr.Tabs():
with gr.TabItem("π· Detect Disease"):
with gr.Row():
image_input = gr.Image(type="numpy", label="πΈ Upload a plant image", interactive=True)
with gr.Row():
btn_predict = gr.Button("π Analyze", variant="primary")
with gr.Row():
disease_output = gr.Textbox(label="π± Disease", interactive=False)
confidence_output = gr.Slider(minimum=0, maximum=100, interactive=False, label="π¬ Confidence (%)")
with gr.Row():
treatment_output = gr.Textbox(label="π Suggested Treatment", interactive=False)
btn_predict.click(predict, inputs=[image_input], outputs=[disease_output, confidence_output, treatment_output])
with gr.TabItem("π Prevention Guide"):
gr.Markdown("""
## πΎ How to Keep Your Plants Healthy?
- π‘ Ensure Proper Spacing to Avoid Fungal Growth
- π§ Water in the Morning to Reduce Disease Spread
- π Regularly Inspect & Remove Infected Leaves
- βοΈ Allow Good Sunlight & Ventilation for Stronger Plants
- π Use Organic Pesticides & Fungicides When Necessary
""")
app.launch()
|