rohithkumars's picture
Update app.py
e9a07e8 verified
import gradio as gr
import requests
import io
# API endpoint (local FastAPI server)
API_URL = "http://127.0.0.1:8000/predict_image"
# Function to send image and process response
def classify_trash(img):
try:
# Convert PIL image to in-memory file
img_bytes = io.BytesIO()
img.save(img_bytes, format="PNG") # format-agnostic
img_bytes.seek(0)
files = {"file": ("uploaded.png", img_bytes, "image/png")}
response = requests.post(API_URL, files=files)
if response.status_code == 200:
data = response.json()
result = f"🧠 **Predicted Class**: `{data['predicted_class']}`\n"
result += f"πŸ“Š **Confidence**: `{data['confidence']*100:.2f}%`\n\n"
result += "πŸ“‹ **Class Probabilities:**\n"
for item in data["all_probabilities"]:
result += f"- {item['class']}: `{float(item['confidence'])*100:.2f}%`\n"
return result
else:
return f"❌ Error: {response.status_code} - {response.text}"
except Exception as e:
return f"❌ Exception occurred: {str(e)}"
# Gradio UI definition
def launch_ui():
gr.Interface(
fn=classify_trash,
inputs=gr.Image(type="pil", label="πŸ“€ Upload a Trash Image"),
outputs=gr.Markdown(label="🧠 Classification Result"),
title="EcoVision - Trash Classifier",
description="Upload an image to detect the type of trash (e.g., cardboard, metal, plastic, etc.).",
allow_flagging="never",
).launch()
# Run the UI only when executed directly
if __name__ == "__main__":
print("πŸš€ Launching Gradio UI...")
launch_ui()