rezaenayati's picture
Update app.py
050405b verified
raw
history blame
1.26 kB
import gradio as gr
import numpy as np
from PIL import Image, ImageOps
import tensorflow as tf
#Load the model
model = tf.keras.models.load_model("cnn_model.h5")
def predict(image_array):
try:
print("Function called!")
# Check for blank or None input
if image_array is None or np.sum(image_array) == 0:
return "Please draw a digit."
# Convert to PIL image and process
image = Image.fromarray(image_array.astype("uint8"), mode="L")
image = ImageOps.invert(image).resize((28, 28))
# Normalize and reshape for model input
image_array = np.array(image).astype("float32") / 255.0
image_array = image_array.reshape(1, 28, 28, 1)
# Predict
logits = model.predict(image_array)
prediction = int(np.argmax(logits))
confidence = float(tf.nn.softmax(logits)[0][prediction])
return f"Digit: {prediction} (confidence: {confidence:.2%})"
except Exception as err:
return f"πŸ’₯ Runtime error: {str(err)}"
gr.Sketchpad(image_mode="L", canvas_size=(200, 200), type="numpy")
gr.Interface(
fn=predict,
inputs=gr.Sketchpad(image_mode="L", canvas_size=(200, 200)),
outputs="text",
title="Digit Classifier",
).launch()