hb-setosys's picture
Update app.py
9ca4f01 verified
raw
history blame
1.71 kB
import gradio as gr
import tensorflow as tf
import numpy as np
from tensorflow.keras.preprocessing import image
from PIL import Image
# Load the trained model
MODEL_PATH = "setosys_dogs_model.h5"
model = tf.keras.models.load_model(MODEL_PATH)
# Image preprocessing function
def preprocess_image(img: Image.Image) -> np.ndarray:
"""Preprocess the image to match the model's input requirements."""
img = img.resize((224, 224)) # Resize image to model input size
img_array = image.img_to_array(img)
img_array = np.expand_dims(img_array, axis=0) # Add batch dimension
img_array /= 255.0 # Normalize pixel values
return img_array
# Prediction function
def predict_dog_breed(img: Image.Image) -> dict:
"""Predict the breed of the dog in the uploaded image."""
img_array = preprocess_image(img)
predictions = model.predict(img_array)
class_idx = np.argmax(predictions) # Index of the highest prediction probability
confidence = float(np.max(predictions)) # Confidence score
# Get class labels from the model
class_labels = model.classes_ if hasattr(model, 'classes_') else None
# If class labels are available, return the predicted breed with confidence score
if class_labels is not None:
predicted_breed = class_labels[class_idx]
else:
predicted_breed = "Unknown"
return {predicted_breed: confidence}
# Create Gradio interface
interface = gr.Interface(
fn=predict_dog_breed,
inputs=gr.Image(type="pil"),
outputs=gr.Label(),
title="Dog Breed Classifier",
description="Upload an image of a dog to predict its breed."
)
# Launch the Gradio app
if __name__ == "__main__":
interface.launch()