Spaces:
Runtime error
Runtime error
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("bW56klawyFv1jspkrbj3GBhmueOznSQIR3FQJFNawEuTjmVjeH") | |
if not PLANT_ID_API_KEY: | |
raise ValueError("β API Key is missing! Set PLANT_ID_API_KEY in Hugging Face Secrets or .env file.") | |
# 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)}" | |
# Gradio Interface with Improved UI | |
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 from Plant.id API. | |
β Supports **multiple plant species** | |
β Instant **AI-powered analysis** | |
β Get **organic & chemical treatment suggestions** | |
""", | |
theme="compact", | |
allow_flagging="never", | |
) | |
# **Ensure this part runs correctly in Hugging Face Spaces** | |
if __name__ == "__main__": | |
iface.launch(server_name="0.0.0.0", server_port=7860) | |