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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +22 -28
app.py CHANGED
@@ -1,17 +1,12 @@
1
  import os
 
2
  import gradio as gr
3
  from transformers import AutoImageProcessor, AutoModelForImageClassification
4
  from PIL import Image
5
  import torch
6
  import numpy as np
7
- import requests
8
  import logging
9
 
10
- # Load Hugging Face API Key from Secrets
11
- HUGGINGFACE_API_KEY = os.getenv("HUGGINGFACE_API_KEY")
12
- if not HUGGINGFACE_API_KEY:
13
- raise ValueError("❌ Missing Hugging Face API Key. Please set it in Hugging Face Secrets.")
14
-
15
  # Configure Logging
16
  logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
17
 
@@ -25,24 +20,23 @@ except Exception as e:
25
  logging.error(f"❌ Failed to load model: {str(e)}")
26
  raise RuntimeError("Failed to load the model. Please check the logs for details.")
27
 
28
- # Function to Get AI-Powered Treatment Suggestions
29
- def get_treatment_suggestions(disease_name):
30
- url = "https://api-inference.huggingface.co/models/OpenAGI/agriculture-gpt"
31
- headers = {"Authorization": f"Bearer {HUGGINGFACE_API_KEY}"}
32
- data = {"inputs": f"What are the treatment options for {disease_name} in plants?"}
33
-
34
  try:
35
- response = requests.post(url, headers=headers, json=data)
36
- response_data = response.json()
 
 
 
 
 
 
 
37
 
38
- if response.status_code == 200 and isinstance(response_data, list):
39
- return response_data[0].get("generated_text", "No treatment information found.")
40
- else:
41
- logging.error(f"API Error {response.status_code}: {response_data}")
42
- return f"API Error {response.status_code}: {response_data.get('error', 'Unknown error')}"
43
- except Exception as e:
44
- logging.error(f"Error fetching treatment suggestions: {str(e)}")
45
- return "❌ Error retrieving treatment details."
46
 
47
  # Define Prediction Function
48
  def predict(image):
@@ -54,14 +48,14 @@ def predict(image):
54
  logits = outputs.logits
55
  predicted_class_idx = logits.argmax(-1).item()
56
  predicted_label = model.config.id2label[predicted_class_idx]
57
-
58
- # Get AI-generated treatment suggestions
59
  treatment = get_treatment_suggestions(predicted_label)
60
-
61
  return f"🌱 **Predicted Disease:** {predicted_label}\nπŸ’Š **Treatment:** {treatment}"
62
  except Exception as e:
63
- logging.error(f"Prediction failed: {str(e)}")
64
- return f"❌ Prediction failed: {str(e)}"
65
 
66
  # Gradio Interface
67
  iface = gr.Interface(
@@ -69,7 +63,7 @@ iface = gr.Interface(
69
  inputs=gr.Image(type="numpy", label="Upload or capture plant image"),
70
  outputs=gr.Textbox(label="Result"),
71
  title="🌿 AI-Powered Plant Disease Detector",
72
- description="πŸ“· Upload a plant leaf image to detect diseases and get AI-powered treatment suggestions.",
73
  allow_flagging="never",
74
  )
75
 
 
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
 
 
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):
 
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(
 
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