anand_plant2 / app.py
ranchopanda0's picture
Update app.py
49cc0f0 verified
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()