| 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 = (180, 180) |
| 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): |
| |
|
|
| |
| try: |
| |
| if input_img_pil is None: |
| |
| return {"Please upload an image first.": 1.0} |
|
|
| if model is None: |
| |
| return {"MODEL NOT FOUND": 1.0, "Please check if cat-vs-dog.keras exists.": 0.0} |
|
|
| |
| print(f"Original image size: {input_img_pil.size}") |
| img_resized = input_img_pil.resize(IMAGE_SIZE) |
| img_array = keras.preprocessing.image.img_to_array(img_resized) |
| |
| |
| img_array = img_array / 255.0 |
| img_array = np.expand_dims(img_array, axis=0) |
|
|
| |
| print(f"Array shape for model input: {img_array.shape}") |
| predictions = model.predict(img_array) |
| print(f"Raw model predictions: {predictions}") |
|
|
| |
| |
| |
| return {"dog":predictions[0][0],"cat":1-predictions[0][0]} |
| |
| except Exception as e: |
| |
| error_message = f"CRITICAL RUNTIME ERROR: {str(e)}" |
| detailed_trace = traceback.format_exc() |
| |
| print("\n--- DETAILED RUNTIME ERROR LOG ---") |
| print(error_message) |
| print(detailed_trace) |
| print("------------------------------------\n") |
| |
| |
| return {f"💥 {error_message}": 1.0} |
|
|
|
|
|
|
| |
|
|
| |
| 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() |
|
|