import gradio as gr from services.analyse_image import ErrorResponse, analyze_image from dotenv import load_dotenv from utils.utils import image_to_base64_data_uri load_dotenv() async def upload_and_analyse(image_path): if image_path is None: return ( gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), "❗ No image provided." ) try: data_url = image_to_base64_data_uri(image_path) response = await analyze_image(data_url) if isinstance(response, ErrorResponse): return ( gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), f"❌ API Error: {response.status_code} - {response.error}" ) obj_type = response.object_type data = response.data if obj_type == "car": return ( gr.update(value=[ ["Brand", data.brand], ["Color", data.color], ["Type", data.type], ["Other Details", getattr(data, "other_details", "")] ], visible=True), gr.update(visible=False), gr.update(visible=False), "✅ Detected object: Car" ) elif obj_type == "animal": return ( gr.update(visible=False), gr.update(value=[ ["Name", data.name], ["Color", data.color], ["Other Details", getattr(data, "other_details", "")] ], visible=True), gr.update(visible=False), "✅ Detected object: Animal" ) elif obj_type == "flower": return ( gr.update(visible=False), gr.update(visible=False), gr.update(value=[ ["Name", data.name], ["Color", data.color] ], visible=True), "✅ Detected object: Flower" ) else: return ( gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), f"⚠️ Unknown object type: {obj_type}" ) except Exception as e: return ( gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), f"❌ Exception: {str(e)}" ) with gr.Blocks() as demo: gr.Markdown("## 🧠 Upload an Image to Analyze (Car, Animal, Flower)") image_input = gr.Image(type="filepath", label="Upload Image") btn = gr.Button("Analyze") car_block = gr.Dataframe(headers=["Field", "Value"], label="🚗 Car Info", visible=False) animal_block = gr.Dataframe(headers=["Field", "Value"], label="🐾 Animal Info", visible=False) flower_block = gr.Dataframe(headers=["Field", "Value"], label="🌸 Flower Info", visible=False) status = gr.Textbox(label="Status", interactive=False) btn.click( fn=upload_and_analyse, inputs=image_input, outputs=[car_block, animal_block, flower_block, status], show_progress=True # 🛠️ Important when using async fn ) demo.launch(share=True)