Spaces:
Sleeping
Sleeping
import os | |
import requests | |
from io import BytesIO | |
import base64 | |
from PIL import Image | |
import gradio as gr # β Import Gradio | |
from dotenv import load_dotenv | |
# Load API key safely | |
load_dotenv() | |
API_KEY = os.getenv("PLANT_ID_API_KEY") # Make sure .env contains the API key | |
def analyze_plant(image): | |
try: | |
# Convert image to base64 | |
buffered = BytesIO() | |
image.save(buffered, format="JPEG") | |
img_b64 = base64.b64encode(buffered.getvalue()).decode() | |
# API Request | |
response = requests.post( | |
"https://api.plant.id/v2/health_assessment", | |
headers={"Content-Type": "application/json"}, | |
json={ | |
"images": [f"data:image/jpeg;base64,{img_b64}"], | |
"organs": ["leaf"], | |
"api_key": API_KEY # Injected securely | |
} | |
) | |
# Process response | |
if response.status_code == 200: | |
data = response.json() | |
if data["health_assessment"]["diseases"]: | |
disease = data["health_assessment"]["diseases"][0] | |
return f""" | |
π **Disease:** {disease['name']} | |
β οΈ **Probability:** {disease['probability']:.0%} | |
π **Treatment:** {disease['treatment']['details']} | |
""" | |
return "β Healthy plant detected!" | |
return f"β API Error: {response.text}" | |
except Exception as e: | |
return f"π₯ Error: {str(e)}" | |
# Launch Gradio App | |
gr.Interface( | |
fn=analyze_plant, | |
inputs=gr.Image(type="pil", label="πΌοΈ Upload Leaf"), | |
outputs=gr.Markdown(), | |
title="πΏ Plant Disease Detector" | |
).launch() | |