| import gradio as gr |
| import tensorflow as tf |
| from tensorflow import keras |
| import numpy as np |
| from PIL import Image |
|
|
| |
| MODEL_PATH = "cats-vs-dogs-finetuned.keras" |
| IMAGE_SIZE = (150, 150) |
| CLASS_LABELS = ['Cat', 'Dog'] |
|
|
| |
| |
| |
| try: |
| model = keras.models.load_model(MODEL_PATH) |
| print(f"Model loaded successfully from {MODEL_PATH}") |
| except Exception as e: |
| |
| |
| print(f"Error loading model: {e}. Using a placeholder function.") |
| model = None |
|
|
| |
| def predict_image(input_img_pil): |
| """ |
| Predicts the class (Cat or Dog) given a PIL Image object. |
| |
| Args: |
| input_img_pil: A PIL Image object received from Gradio's Image input. |
| |
| Returns: |
| A dictionary of class labels and their probabilities (for Gradio's Label output). |
| """ |
| if model is None: |
| |
| return {"Error": 1.0} |
|
|
| |
| img_resized = input_img_pil.resize(IMAGE_SIZE) |
| print("image resized") |
| img_array = keras.preprocessing.image.img_to_array(img_resized) |
| print(" image converted to array") |
| |
| |
| |
| |
| |
| img_array = img_array / 255.0 |
| img_array = np.expand_dims(img_array, axis=0) |
|
|
| |
| predictions = model.predict(img_array)[0] |
|
|
| |
| |
| |
| |
| output_dict = { |
| CLASS_LABELS[0]: float(predictions[0]), |
| CLASS_LABELS[1]: float(predictions[1]) |
| } |
| |
| return output_dict |
|
|
|
|
| |
|
|
| |
| image_input = gr.Image(type="pil", label="Upload a Cat or Dog Image") |
| label_output = gr.Label(num_top_classes=2, label="Prediction") |
|
|
| |
| examples = [ |
| |
| |
| |
| ] |
|
|
| |
| demo = gr.Interface( |
| fn=predict_image, |
| inputs=image_input, |
| outputs=label_output, |
| title="Keras Cat vs Dog Classifier", |
| description="Upload an image of a cat or dog to see the model's prediction. The model is loaded from cat-vs-dog.keras.", |
| theme=gr.themes.Soft(), |
| |
| |
| ) |
|
|
| |
| if __name__ == "__main__": |
| demo.launch() |
|
|