ranchopanda0 commited on
Commit
4895bd1
Β·
verified Β·
1 Parent(s): a51cf57

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +55 -78
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
- 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()
 
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()