Spaces:
Sleeping
Sleeping
| 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() | |