ranchopanda0 commited on
Commit
7507f29
Β·
verified Β·
1 Parent(s): fcb731c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +3 -75
app.py CHANGED
@@ -1,84 +1,12 @@
1
  import os
2
- import json
3
- import gradio as gr
4
- import requests
5
- import logging
6
- import base64
7
- from PIL import Image
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("bW56klawyFv1jspkrbj3GBhmueOznSQIR3FQJFNawEuTjmVjeH")
 
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 analyze plant health using Plant.id API
27
- def analyze_plant_health(image):
28
- try:
29
- # Convert image to bytes & encode in Base64
30
- buffered = BytesIO()
31
- image.save(buffered, format="JPEG")
32
- img_base64 = base64.b64encode(buffered.getvalue()).decode()
33
-
34
- # Send request to Plant.id API
35
- headers = {"Content-Type": "application/json"}
36
- payload = {
37
- "images": [f"data:image/jpeg;base64,{img_base64}"],
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 or not data["health_assessment"].get("diseases"):
50
- return "βœ… No disease detected! Your plant looks healthy. 🌿"
51
-
52
- assessment = data["health_assessment"]
53
- disease_info = assessment["diseases"][0]
54
- predicted_disease = disease_info.get("name", "Unknown Disease")
55
- treatment = disease_info.get("treatment", "No treatment suggestions available.")
56
-
57
- return f"""
58
- 🌱 **Predicted Disease:** {predicted_disease}
59
- πŸ’Š **Treatment:** {treatment}
60
- """
61
-
62
- except Exception as e:
63
- logging.error(f"Prediction failed: {str(e)}")
64
- return f"❌ Error: {str(e)}"
65
-
66
- # Gradio Interface with Improved UI
67
- iface = gr.Interface(
68
- fn=analyze_plant_health,
69
- inputs=gr.Image(type="pil", label="πŸ“Έ Upload or Capture a Plant Image"),
70
- outputs=gr.Textbox(label="πŸ” Diagnosis & Treatment"),
71
- title="🌿 AI-Powered Plant Disease Detector",
72
- description="""
73
- πŸ“· Upload an image of a plant leaf to detect diseases and get treatment suggestions from Plant.id API.
74
- βœ… Supports **multiple plant species**
75
- βœ… Instant **AI-powered analysis**
76
- βœ… Get **organic & chemical treatment suggestions**
77
- """,
78
- theme="compact",
79
- allow_flagging="never",
80
- )
81
-
82
- # **Ensure this part runs correctly in Hugging Face Spaces**
83
- if __name__ == "__main__":
84
- iface.launch(server_name="0.0.0.0", server_port=7860)
 
1
  import os
 
 
 
 
 
 
 
2
  from dotenv import load_dotenv
3
 
4
  # Load environment variables
5
  load_dotenv()
6
 
7
+ # Debug: Print API key (Remove this line after testing)
8
+ PLANT_ID_API_KEY = os.getenv("PLANT_ID_API_KEY")
9
+ print(f"πŸ” Loaded API Key: {PLANT_ID_API_KEY}")
10
 
11
  if not PLANT_ID_API_KEY:
12
  raise ValueError("❌ API Key is missing! Set PLANT_ID_API_KEY in Hugging Face Secrets or .env file.")