File size: 1,398 Bytes
4d4d14c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
import tensorflow as tf
import numpy as np

# Load the trained model
model = tf.keras.models.load_model('model.h5')
print("Model loaded successfully!")

def preprocess_image(image):
    """Process the input image to match MNIST format"""
    # Convert to grayscale
    image = image.convert('L')
    # Resize to 28x28
    image = image.resize((28, 28))
    # Convert to numpy array and normalize
    image_array = np.array(image)
    image_array = image_array / 255.0
    # Reshape to match model input
    image_array = np.expand_dims(image_array, axis=0)
    return image_array

def predict_digit(image):
    if image is None:
        return None
    
    # Preprocess the image
    processed_image = preprocess_image(image)
    
    # Make prediction
    predictions = model.predict(processed_image)
    pred_scores = tf.nn.softmax(predictions[0]).numpy()
    pred_class = np.argmax(pred_scores)
    
    # Create result string
    result = f"Prediction: {pred_class}"
    
    return result

# Create Gradio interface
demo = gr.Interface(
    fn=predict_digit,
    inputs=gr.Image(type="pil"),
    outputs=gr.Textbox(label="Result"),
    title="MNIST Digit Recognizer",
    description="Upload a digit from 0-9 and the model will predict which digit it is.",
    examples=None,
)

if __name__ == "__main__":
    demo.launch()