ranchopanda0 commited on
Commit
eec5dd1
Β·
verified Β·
1 Parent(s): b1a2d84

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +68 -41
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 numpy as np
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
- model_name = "linkanjarad/mobilenet_v2_1.0_224-plant-disease-identification"
 
15
  try:
16
- processor = AutoImageProcessor.from_pretrained(model_name, use_fast=True)
17
- model = AutoModelForImageClassification.from_pretrained(model_name)
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
- # Load Treatment Data
24
- treatment_file = os.path.join(os.getcwd(), "treatments.json")
25
- if os.path.exists(treatment_file):
26
  try:
27
- with open(treatment_file, "r", encoding="utf-8") as f:
28
- treatment_data = json.load(f)
29
- logging.info("βœ… Treatment data loaded successfully.")
30
- except json.JSONDecodeError:
31
- logging.error("❌ Invalid JSON format in treatments.json.")
32
- treatment_data = {}
33
- else:
34
- logging.warning("⚠️ treatments.json not found. Using empty treatment data.")
35
- treatment_data = {}
36
 
37
- # Function to Get Treatment Suggestions
38
- def get_treatment_suggestions(disease_name):
39
- return treatment_data.get(disease_name, "⚠️ No treatment suggestions available for this disease.")
 
 
 
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
- # Gradio Interface
61
- iface = gr.Interface(
62
- fn=predict,
63
- inputs=gr.Image(type="numpy", label="Upload or capture plant image"),
64
- outputs=gr.Textbox(label="Result"),
65
- title="🌿 AI-Powered Plant Disease Detector",
66
- description="πŸ“Έ Upload a plant leaf image to detect diseases and receive treatment suggestions.",
67
- allow_flagging="never",
68
- )
69
 
70
- # Launch Gradio App
71
- iface.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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()