File size: 1,678 Bytes
49cc0f0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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()