Spaces:
Running
Running
import gradio as gr | |
import tensorflow as tf | |
import numpy as np | |
from PIL import Image | |
model_path = 'model' | |
model = tf.saved_model.load(model_path) | |
labels = ['butterfly', 'cats', 'cow', 'dogs', 'elephant', | |
'horse', 'monkey', 'sheep', 'spider', 'squirrel'] | |
def predict_image(image): | |
image_resized = image.resize((224, 224)) | |
image_array = np.array(image_resized).astype(np.float32) / 255.0 | |
image_array = np.expand_dims(image_array, axis=0) | |
predictions = model.signatures['serving_default'](tf.convert_to_tensor(image_array, dtype=tf.float32))['output_0'] | |
# Top 3 classes | |
top_3_indices = np.argsort(predictions.numpy(), axis=1)[0][-3:][::-1] | |
top_3_labels = [labels[i] for i in top_3_indices] | |
top_3_probabilities = [predictions.numpy()[0][i] * 100 for i in top_3_indices] | |
output_string = "\n".join([f"{label}: {probability:.2f}%" for label, probability in zip(top_3_labels, top_3_probabilities)]) | |
return image_resized, output_string | |
# Gradio Interface | |
interface = gr.Interface( | |
fn=predict_image, | |
inputs=gr.Image(type="pil"), | |
outputs=[gr.Image(type="pil", label="Image Output"), gr.Textbox(label="Prediction")], | |
title="Animals Classifier", | |
description="Upload an image of an animal, and the model will predict it.\n\n**Disclaimer:** This model is trained only on specific animal classes (butterfly, cats, cow, dogs, elephant, horse, monkey, sheep, spider, squirrel) and may not accurately predict animals outside these classes." | |
) | |
interface.launch(share=True) | |