ranchopanda0 commited on
Commit
188b4e1
ยท
verified ยท
1 Parent(s): 3c8acf4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +65 -2
app.py CHANGED
@@ -1,7 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  # Launch Gradio App
2
  if __name__ == "__main__":
3
- import gradio as gr
4
-
5
  iface = gr.Interface(
6
  fn=analyze_plant_health,
7
  inputs=gr.Image(type="pil", label="๐Ÿ“ธ Upload or Capture a Plant Image"),
 
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("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.")
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
  # Launch Gradio App
67
  if __name__ == "__main__":
 
 
68
  iface = gr.Interface(
69
  fn=analyze_plant_health,
70
  inputs=gr.Image(type="pil", label="๐Ÿ“ธ Upload or Capture a Plant Image"),