Spaces:
Sleeping
Sleeping
File size: 2,525 Bytes
188b4e1 3c8acf4 4895bd1 3c8acf4 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 |
import os
import json
import gradio as gr
import requests
import logging
import base64
from PIL import Image
from io import BytesIO
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
# Get API key from environment variables
PLANT_ID_API_KEY = os.getenv("PLANT_ID_API_KEY")
if not PLANT_ID_API_KEY:
raise ValueError("β API Key is missing! Set PLANT_ID_API_KEY in Hugging Face Secrets.")
# Configure Logging
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
# Plant.id API URL
PLANT_ID_URL = "https://api.plant.id/v2/health_assessment"
# Function to analyze plant health using Plant.id API
def analyze_plant_health(image):
try:
# Convert image to bytes & encode in Base64
buffered = BytesIO()
image.save(buffered, format="JPEG")
img_base64 = base64.b64encode(buffered.getvalue()).decode()
# Send request to Plant.id API
headers = {"Content-Type": "application/json"}
payload = {
"images": [f"data:image/jpeg;base64,{img_base64}"],
"organs": ["leaf"],
"api_key": PLANT_ID_API_KEY
}
response = requests.post(PLANT_ID_URL, headers=headers, json=payload)
if response.status_code != 200:
return f"β API Error: {response.text}"
data = response.json()
if "health_assessment" not in data or not data["health_assessment"].get("diseases"):
return "β
No disease detected! Your plant looks healthy. πΏ"
assessment = data["health_assessment"]
disease_info = assessment["diseases"][0]
predicted_disease = disease_info.get("name", "Unknown Disease")
treatment = disease_info.get("treatment", "No treatment suggestions available.")
return f"""
π± **Predicted Disease:** {predicted_disease}
π **Treatment:** {treatment}
"""
except Exception as e:
logging.error(f"Prediction failed: {str(e)}")
return f"β Error: {str(e)}"
# Launch Gradio App
if __name__ == "__main__":
iface = gr.Interface(
fn=analyze_plant_health,
inputs=gr.Image(type="pil", label="πΈ Upload or Capture a Plant Image"),
outputs=gr.Textbox(label="π Diagnosis & Treatment"),
title="πΏ AI-Powered Plant Disease Detector",
description="π· Upload an image of a plant leaf to detect diseases and get treatment suggestions.",
allow_flagging="never"
)
iface.launch()
|