Spaces:
Runtime error
Runtime error
| import gradio as gr | |
| import requests | |
| import base64 | |
| import json | |
| API_KEY = "GCT8F6KhPYNUvBvh7X617OzRF9zXUNhwvWu4NyWxhklqU75S8d" | |
| API_URL = "https://plant.id/api/v3/identification" | |
| # Tracks the last prediction to detect repetition | |
| last_prediction = {"name": None} | |
| def identify_plant(image): | |
| global last_prediction | |
| try: | |
| with open(image, "rb") as img_file: | |
| img_data = base64.b64encode(img_file.read()).decode("utf-8") | |
| payload = { | |
| "images": [img_data], | |
| "similar_images": True | |
| } | |
| headers = { | |
| "Content-Type": "application/json", | |
| "Api-Key": API_KEY | |
| } | |
| response = requests.post(API_URL, headers=headers, data=json.dumps(payload)) | |
| if response.status_code != 200: | |
| return f"⚠️ Error {response.status_code}: {response.text}" | |
| result = response.json() | |
| suggestions = result.get("result", {}).get("classification", {}).get("suggestions", []) | |
| if not suggestions: | |
| return "❌ No plant match found." | |
| top = suggestions[0] | |
| name = top.get("name", "Unknown") | |
| prob = top.get("probability", 0.0) | |
| desc = top.get("details", {}).get("description", {}).get("value", "No description available.") | |
| warning = "" | |
| if last_prediction["name"] == name: | |
| warning = "\n⚠️ Same result as last time. This may indicate repetition. Try a different photo or angle." | |
| last_prediction["name"] = name | |
| result = response.json() | |
| suggestions = result.get("result", {}).get("classification", {}).get("suggestions", []) | |
| if not suggestions: | |
| return "❌ No plant match found." | |
| top = suggestions[0] | |
| name = top.get("name", "Unknown") | |
| prob = top.get("probability", 0.0) | |
| return f""" | |
| 🌿 **Plant:** {name} | |
| 📊 **Confidence:** {prob * 100:.2f}% | |
| """ | |
| iface = gr.Interface( | |
| fn=identify_plant, | |
| inputs=gr.Image(type="filepath", label="Upload UAE Plant Image"), | |
| outputs="text", | |
| title="🌿 UAE Plant Identifier", | |
| description="Upload a photo of a UAE plant (leaf preferred). We'll identify it using the Plant.id API.", | |
| ) | |
| if __name__ == "__main__": | |
| iface.launch() | |