Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,71 +1,98 @@
|
|
1 |
import os
|
2 |
-
import json
|
3 |
import gradio as gr
|
4 |
-
from transformers import AutoImageProcessor, AutoModelForImageClassification
|
5 |
-
from PIL import Image
|
6 |
import torch
|
7 |
-
import
|
8 |
import logging
|
|
|
|
|
|
|
|
|
9 |
|
10 |
# Configure Logging
|
11 |
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
|
12 |
|
13 |
# Load Model & Processor
|
14 |
-
|
|
|
15 |
try:
|
16 |
-
processor = AutoImageProcessor.from_pretrained(
|
17 |
-
model = AutoModelForImageClassification.from_pretrained(
|
18 |
logging.info("β
Model and processor loaded successfully.")
|
19 |
except Exception as e:
|
20 |
logging.error(f"β Failed to load model: {str(e)}")
|
21 |
raise RuntimeError("Failed to load the model. Please check the logs for details.")
|
22 |
|
23 |
-
#
|
24 |
-
|
25 |
-
if os.path.exists(treatment_file):
|
26 |
try:
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
treatment_data = {}
|
36 |
|
37 |
-
|
38 |
-
|
39 |
-
|
|
|
|
|
|
|
40 |
|
41 |
# Define Prediction Function
|
42 |
def predict(image):
|
43 |
try:
|
44 |
image = Image.fromarray(np.uint8(image)).convert("RGB")
|
45 |
inputs = processor(images=image, return_tensors="pt")
|
|
|
46 |
with torch.no_grad():
|
47 |
outputs = model(**inputs)
|
48 |
logits = outputs.logits
|
49 |
predicted_class_idx = logits.argmax(-1).item()
|
|
|
50 |
predicted_label = model.config.id2label[predicted_class_idx]
|
51 |
-
|
52 |
-
# Get treatment suggestions
|
53 |
-
treatment = get_treatment_suggestions(predicted_label)
|
54 |
-
|
55 |
-
return f"π± **Predicted Disease:** {predicted_label}\nπ **Treatment:** {treatment}"
|
56 |
-
except Exception as e:
|
57 |
-
logging.error(f"β Prediction failed: {str(e)}")
|
58 |
-
return f"β **Error:** Unable to process image. Please try again."
|
59 |
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
description="πΈ Upload a plant leaf image to detect diseases and receive treatment suggestions.",
|
67 |
-
allow_flagging="never",
|
68 |
-
)
|
69 |
|
70 |
-
#
|
71 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import os
|
|
|
2 |
import gradio as gr
|
|
|
|
|
3 |
import torch
|
4 |
+
import requests
|
5 |
import logging
|
6 |
+
import numpy as np
|
7 |
+
from PIL import Image
|
8 |
+
from bs4 import BeautifulSoup
|
9 |
+
from transformers import AutoImageProcessor, AutoModelForImageClassification
|
10 |
|
11 |
# Configure Logging
|
12 |
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
|
13 |
|
14 |
# Load Model & Processor
|
15 |
+
MODEL_NAME = "linkanjarad/mobilenet_v2_1.0_224-plant-disease-identification"
|
16 |
+
|
17 |
try:
|
18 |
+
processor = AutoImageProcessor.from_pretrained(MODEL_NAME, use_fast=True)
|
19 |
+
model = AutoModelForImageClassification.from_pretrained(MODEL_NAME)
|
20 |
logging.info("β
Model and processor loaded successfully.")
|
21 |
except Exception as e:
|
22 |
logging.error(f"β Failed to load model: {str(e)}")
|
23 |
raise RuntimeError("Failed to load the model. Please check the logs for details.")
|
24 |
|
25 |
+
# Function to Fetch Treatment Suggestions from the Internet
|
26 |
+
def fetch_treatment_info(disease_name):
|
|
|
27 |
try:
|
28 |
+
search_url = f"https://www.bing.com/search?q=treatment+for+{disease_name.replace(' ', '+')}+in+plants"
|
29 |
+
headers = {"User-Agent": "Mozilla/5.0"}
|
30 |
+
response = requests.get(search_url, headers=headers)
|
31 |
+
|
32 |
+
if response.status_code == 200:
|
33 |
+
soup = BeautifulSoup(response.text, "html.parser")
|
34 |
+
snippets = soup.find_all("p")
|
35 |
+
treatments = [s.text for s in snippets][:3]
|
|
|
36 |
|
37 |
+
return "\n".join(treatments) if treatments else "No treatment suggestions found."
|
38 |
+
else:
|
39 |
+
return "Failed to fetch treatment suggestions."
|
40 |
+
except Exception as e:
|
41 |
+
logging.error(f"Error fetching treatment info: {str(e)}")
|
42 |
+
return "Error retrieving treatment details."
|
43 |
|
44 |
# Define Prediction Function
|
45 |
def predict(image):
|
46 |
try:
|
47 |
image = Image.fromarray(np.uint8(image)).convert("RGB")
|
48 |
inputs = processor(images=image, return_tensors="pt")
|
49 |
+
|
50 |
with torch.no_grad():
|
51 |
outputs = model(**inputs)
|
52 |
logits = outputs.logits
|
53 |
predicted_class_idx = logits.argmax(-1).item()
|
54 |
+
confidence = torch.nn.functional.softmax(logits, dim=-1)[0][predicted_class_idx] * 100
|
55 |
predicted_label = model.config.id2label[predicted_class_idx]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
56 |
|
57 |
+
treatment = fetch_treatment_info(predicted_label)
|
58 |
+
|
59 |
+
return predicted_label, confidence.item(), treatment
|
60 |
+
except Exception as e:
|
61 |
+
logging.error(f"Prediction failed: {str(e)}")
|
62 |
+
return "Error", 0, "Error in prediction."
|
|
|
|
|
|
|
63 |
|
64 |
+
# Create a Gradio UI with Tabs & Styling
|
65 |
+
with gr.Blocks(css="body {background-color: #f7f9fc;}") as app:
|
66 |
+
gr.Markdown(
|
67 |
+
"<h1 style='text-align: center;'>πΏ AI-Powered Plant Disease Detector</h1>",
|
68 |
+
elem_id="title"
|
69 |
+
)
|
70 |
+
|
71 |
+
with gr.Tabs():
|
72 |
+
with gr.TabItem("π· Detect Disease"):
|
73 |
+
with gr.Row():
|
74 |
+
image_input = gr.Image(type="numpy", label="πΈ Upload a plant image", interactive=True)
|
75 |
+
|
76 |
+
with gr.Row():
|
77 |
+
btn_predict = gr.Button("π Analyze", variant="primary")
|
78 |
+
|
79 |
+
with gr.Row():
|
80 |
+
disease_output = gr.Textbox(label="π± Disease", interactive=False)
|
81 |
+
confidence_output = gr.Slider(minimum=0, maximum=100, interactive=False, label="π¬ Confidence (%)")
|
82 |
+
|
83 |
+
with gr.Row():
|
84 |
+
treatment_output = gr.Textbox(label="π Suggested Treatment", interactive=False)
|
85 |
+
|
86 |
+
btn_predict.click(predict, inputs=[image_input], outputs=[disease_output, confidence_output, treatment_output])
|
87 |
+
|
88 |
+
with gr.TabItem("π Prevention Guide"):
|
89 |
+
gr.Markdown("""
|
90 |
+
## πΎ How to Keep Your Plants Healthy?
|
91 |
+
- π‘ Ensure Proper Spacing to Avoid Fungal Growth
|
92 |
+
- π§ Water in the Morning to Reduce Disease Spread
|
93 |
+
- π Regularly Inspect & Remove Infected Leaves
|
94 |
+
- βοΈ Allow Good Sunlight & Ventilation for Stronger Plants
|
95 |
+
- π Use Organic Pesticides & Fungicides When Necessary
|
96 |
+
""")
|
97 |
+
|
98 |
+
app.launch()
|