CoolFace
Apppublic

Corrrvo/AnimalClassificationCNN

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
gradio_deployment.py56 linesDownload Raw Back to root
1 2# Animal Classification - An exploration of CNN models3 4import gradio as gr5from keras.saving import load_model6import numpy as np7 8 9 10"""# Load the dataset11For this exercise we imported the dataset and applyed a python script to translate the name of the subfolders from italian (original language of the dataset) to english12"""13 14# Load the model once (outside the function to avoid reloading every time)15try:16    model = load_model("Alpha_6.keras", safe_mode=False)17    print("✅ Model loaded successfully!")18    print(model.summary())19except Exception as e:20    print("❌ Error loading model:", str(e))21 22from keras.preprocessing import image23from keras.applications.vgg16 import preprocess_input24from keras.models import load_model25from keras.preprocessing import image26 27# Class names28 29labels = {0: 'butterfly', 1: 'cat', 2: 'chicken', 3: 'cow', 4: 'dog',30          5: 'elephant', 6: 'horse', 7: 'sheep', 8: 'spider', 9: 'squirrel'}31 32# Function to preprocess and predict33def predict(img):34    img = img.resize((128, 128))35    img_array = image.img_to_array(img)36    img_array = np.expand_dims(img_array, axis=0)37 38    img_array = img_array / 255.039 40    prediction = model.predict(img_array)  # Make prediction41    predicted_class = np.argmax(prediction)  # Get the class index42    confidence = np.max(prediction)  # Get confidence score43 44    return f"Prediction: {labels[predicted_class]} (Confidence: {confidence:.2%})"45 46# Create Gradio interface47interface = gr.Interface(48    fn=predict,49    inputs=gr.Image(type="pil"),  # Accepts image input50    outputs=gr.Textbox(),  # Displays text output51    title="CNN Animal Classifier",52    description="Upload an image to classify it into one of 10 animal categories. Animals: butterfly, cat, chicken, cow, dog, elephant, horse, sheep, spider, squirrel"53)54 55# Launch the Gradio app56interface.launch()