File size: 1,647 Bytes
e96b839
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a1f6062
 
e96b839
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import gradio as gr
import tensorflow as tf
import numpy as np
from PIL import Image

# 1. Load the model
# Ensure 'my_cifar_model.keras' is uploaded to the same Space directory
model = tf.keras.models.load_model('my_cifar_model.keras')

# 2. Define the class labels (Matches CIFAR-10 order)
labels = [
    'airplane', 'automobile', 'bird', 'cat', 'deer',
    'dog', 'frog', 'horse', 'ship', 'truck'
]

def predict(img):
    """
    Takes an input image, processes it, and returns 
    the top classification probabilities.
    """
    if img is None:
        return None

    # Preprocessing:
    # Convert to PIL Image if it's a numpy array, then resize to 32x32
    img = Image.fromarray(img).resize((32, 32))
    
    # Convert to array and normalize (0 to 1)
    img_array = np.array(img).astype('float32') / 255.0
    
    # Add batch dimension: (32, 32, 3) -> (1, 32, 32, 3)
    img_array = np.expand_dims(img_array, axis=0)

    # Perform prediction
    predictions = model.predict(img_array).flatten()

    # Apply Softmax to get probabilities (if not already in the model output)
    score = tf.nn.softmax(predictions).numpy()

    # Create a dictionary of {Label: Probability}
    return {labels[i]: float(score[i]) for i in range(10)}

# 3. Create the Gradio Interface
demo = gr.Interface(
    fn=predict,
    inputs=gr.Image(),
    outputs=gr.Label(num_top_classes=3),
    title="CIFAR-10 Image Classifier",
    description="Upload an image and the model will predict its category among 10 classes."
    # REMOVED: examples=["airplane_example.jpg", "cat_example.jpg"]
)
# 4. Launch the app
if __name__ == "__main__":
    demo.launch()