Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,98 +1,75 @@
|
|
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 |
-
|
9 |
-
from
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
10 |
|
11 |
# Configure Logging
|
12 |
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
|
13 |
|
14 |
-
#
|
15 |
-
|
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
|
26 |
-
def
|
27 |
try:
|
28 |
-
|
29 |
-
|
30 |
-
|
|
|
31 |
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
|
|
|
|
|
|
36 |
|
37 |
-
|
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 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
|
|
|
|
49 |
|
50 |
-
|
51 |
-
|
52 |
-
|
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 |
-
|
58 |
|
59 |
-
return predicted_label, confidence.item(), treatment
|
60 |
except Exception as e:
|
61 |
logging.error(f"Prediction failed: {str(e)}")
|
62 |
-
return "
|
63 |
|
64 |
-
#
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
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()
|
|
|
1 |
import os
|
2 |
+
import json
|
3 |
import gradio as gr
|
|
|
4 |
import requests
|
5 |
import logging
|
|
|
6 |
from PIL import Image
|
7 |
+
import numpy as np
|
8 |
+
from io import BytesIO
|
9 |
+
from dotenv import load_dotenv
|
10 |
+
|
11 |
+
# Load environment variables
|
12 |
+
load_dotenv()
|
13 |
+
|
14 |
+
# Get API key from environment variables
|
15 |
+
PLANT_ID_API_KEY = os.getenv("PLANT_ID_API_KEY")
|
16 |
+
|
17 |
+
if not PLANT_ID_API_KEY:
|
18 |
+
raise ValueError("β API Key is missing! Set PLANT_ID_API_KEY in Hugging Face Secrets or .env file.")
|
19 |
|
20 |
# Configure Logging
|
21 |
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
|
22 |
|
23 |
+
# Plant.id API URL
|
24 |
+
PLANT_ID_URL = "https://api.plant.id/v2/health_assessment"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
25 |
|
26 |
+
# Function to get disease and treatment information from Plant.id
|
27 |
+
def analyze_plant_health(image):
|
28 |
try:
|
29 |
+
# Convert image to bytes
|
30 |
+
buffered = BytesIO()
|
31 |
+
image.save(buffered, format="JPEG")
|
32 |
+
img_bytes = buffered.getvalue()
|
33 |
|
34 |
+
# Send request to Plant.id API
|
35 |
+
headers = {"Content-Type": "application/json"}
|
36 |
+
payload = {
|
37 |
+
"images": [f"data:image/jpeg;base64,{img_bytes.decode()}"],
|
38 |
+
"organs": ["leaf"],
|
39 |
+
"api_key": PLANT_ID_API_KEY
|
40 |
+
}
|
41 |
|
42 |
+
response = requests.post(PLANT_ID_URL, headers=headers, json=payload)
|
|
|
|
|
|
|
|
|
|
|
43 |
|
44 |
+
if response.status_code != 200:
|
45 |
+
return f"β API Error: {response.text}"
|
46 |
+
|
47 |
+
data = response.json()
|
48 |
+
|
49 |
+
if "health_assessment" not in data:
|
50 |
+
return "β οΈ No disease detected or insufficient data."
|
51 |
|
52 |
+
assessment = data["health_assessment"]
|
53 |
+
predicted_disease = assessment.get("diseases", [{}])[0].get("name", "Unknown Disease")
|
54 |
+
treatment = assessment.get("diseases", [{}])[0].get("treatment", "No treatment suggestions available.")
|
|
|
|
|
|
|
55 |
|
56 |
+
return f"π± **Predicted Disease:** {predicted_disease}\nπ **Treatment:** {treatment}"
|
57 |
|
|
|
58 |
except Exception as e:
|
59 |
logging.error(f"Prediction failed: {str(e)}")
|
60 |
+
return f"β Error: {str(e)}"
|
61 |
|
62 |
+
# Gradio Interface
|
63 |
+
iface = gr.Interface(
|
64 |
+
fn=analyze_plant_health,
|
65 |
+
inputs=gr.Image(type="pil", label="πΈ Upload or capture a plant image"),
|
66 |
+
outputs=gr.Textbox(label="π Diagnosis & Treatment"),
|
67 |
+
title="πΏ AI-Powered Plant Disease Detector",
|
68 |
+
description="π· Upload a leaf image to detect plant diseases and get treatment suggestions from Plant.id API.",
|
69 |
+
allow_flagging="never",
|
70 |
+
theme="default",
|
71 |
+
)
|
72 |
+
|
73 |
+
# Launch Gradio App
|
74 |
+
if __name__ == "__main__":
|
75 |
+
iface.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|