Ni3SinghR's picture
Upload 4 files
d4e1911 verified
# app.py
import gradio as gr
import requests
from PIL import Image
import io
# --- Configuration ---
BACKEND_URL = "http://127.0.0.1:8000/predict"
# --- Interface Logic ---
def predict_gender(image):
"""
Sends an image to the FastAPI backend and returns the prediction.
'image' is a NumPy array from the Gradio Image component.
"""
if image is None:
raise gr.Error("Please upload an image first.")
try:
# Convert numpy array to bytes
pil_image = Image.fromarray(image.astype('uint8'), 'RGB')
img_byte_arr = io.BytesIO()
pil_image.save(img_byte_arr, format='PNG')
img_byte_arr.seek(0) # Move cursor to the beginning of the buffer
# Prepare the file for the POST request
files = {'file': ('image.png', img_byte_arr, 'image/png')}
# Send request to the backend
response = requests.post(BACKEND_URL, files=files, timeout=30)
# Process the response
if response.status_code == 200:
return response.json()
else:
# Display error from the backend as a Gradio error
error_detail = response.json().get('detail', 'An unknown error occurred.')
raise gr.Error(f"API Error: {error_detail}")
except requests.exceptions.RequestException as e:
raise gr.Error(f"Could not connect to the backend. Please ensure the backend is running. Details: {e}")
except Exception as e:
raise gr.Error(f"An unexpected error occurred: {e}")
# --- Gradio Interface Definition ---
iface = gr.Interface(
fn=predict_gender,
inputs=gr.Image(label="Upload a Photo", type="numpy"),
outputs=gr.Label(label="Gender Prediction", num_top_classes=2),
title="📸 Gender Prediction with CLIP",
description=(
"Upload a clear, front-facing photo of a single person to predict their gender. "
"The app uses a backend API powered by OpenAI's CLIP model."
),
examples=[
["examples/male_example.jpg"],
["examples/female_example.jpg"],
],
allow_flagging="never",
css=".gradio-container {max-width: 780px !important; margin: auto;}"
)
# --- Launch the App ---
if __name__ == "__main__":
# Create an 'examples' directory for Gradio examples if it doesn't exist
import os
if not os.path.exists("examples"):
os.makedirs("examples")
print("Created 'examples' directory. Please add 'male_example.jpg' and 'female_example.jpg' for the demo.")
iface.launch()