anand_plant2 / app.py
ranchopanda0's picture
Update app.py
188b4e1 verified
raw
history blame
2.53 kB
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()