File size: 2,083 Bytes
c28dbdc
 
e1504de
 
643a4b4
c28dbdc
 
 
 
ccf3cad
e16a334
c28dbdc
 
 
 
 
 
 
 
 
e1504de
c28dbdc
 
 
e1504de
c28dbdc
e1504de
c28dbdc
 
 
 
 
 
643a4b4
 
c28dbdc
 
c98379a
db7e04b
c28dbdc
e1504de
c28dbdc
 
 
 
 
 
 
 
 
e1504de
33b50c1
c28dbdc
 
e1504de
c28dbdc
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
55
56
#denis_mnist_cnn_model_resnet50_v1.h5")  # Ensure you upload this file to Hugging Face Spaces

import gradio as gr
import tensorflow as tf
import numpy as np
from tensorflow.keras.applications.resnet50 import preprocess_input
from tensorflow.keras.utils import load_img, img_to_array

# Load your trained model
model = tf.keras.models.load_model("denis_mnist_cnn_model_resnet50_v1.h5")  # Ensure you upload this file to Hugging Face Spaces 

# Define a function to preprocess the image
def preprocess_image(image):
    """
    Preprocesses the uploaded image for prediction.
    """
    image = image.resize((128, 128))  # Resize to match the model input size
    image = img_to_array(image)  # Convert PIL image to NumPy array
    image = preprocess_input(image)  # Normalize for ResNet50
    image = np.expand_dims(image, axis=0)  # Add batch dimension
    return image

# Define the prediction function
def predict(image):
    """
    Accepts an image, preprocesses it, and returns the predicted label.
    """
    processed_image = preprocess_image(image)
    predictions = model.predict(processed_image)
    predicted_class = np.argmax(predictions, axis=-1)[0]  # Get the class index
    confidence = np.max(predictions)  # Get confidence score
    #return f"Predicted Class: {predicted_class}, Confidence: {confidence:.2f}"
    return {"prediction": int(predicted_class)}


# Create a Gradio interface
#interface = gr.Interface(fn=predict, inputs="image", outputs="json")


# Create a Gradio interface
interface = gr.Interface(
    fn=predict,  # The prediction function
    inputs=gr.Image(type="pil", label="Upload an Image"),  # Input: Image
    outputs=gr.Textbox(label="Prediction"),  # Output: Textbox
    title="MNIST ResNet50 Classifier",
    description="Upload an image to classify it using the trained ResNet50 model.",
    examples=[
        ["example_images/example1.png"],  # Add paths to example images in your Hugging Face repository
        ["example_images/example2.png"]
    ],
)


# Launch the app
if __name__ == "__main__":
    interface.launch(share=True)