Spaces:
Runtime error
Runtime error
import numpy as np | |
import tensorflow as tf | |
from tensorflow import keras | |
import matplotlib.pyplot as plt | |
from PIL import Image | |
(X_train, y_train) , (X_test, y_test) = keras.datasets.mnist.load_data() | |
# Scaling array values so we get values form 0 to 1 | |
X_train = X_train / 255 | |
X_test = X_test / 255 | |
# Define a simple feedforward neural network | |
model2 = keras.Sequential([ | |
keras.layers.Flatten(input_shape=(28, 28)), # Flatten the 28x28 images | |
keras.layers.Dense(128, activation='relu'), | |
keras.layers.Dense(64, activation='relu'), | |
keras.layers.Dense(10, activation='softmax') | |
]) | |
# Compile the model | |
model2.compile(optimizer='adam', | |
loss='sparse_categorical_crossentropy', # Corrected the loss function | |
metrics=['accuracy']) | |
# Train the model | |
model2.fit(X_train, y_train, epochs=5) # Assuming X_train and y_train are properly loaded | |
# Function to preprocess the uploaded image | |
def preprocess_image(input_image_path): # Accept file path as input | |
# Load the image using PIL | |
image = Image.open(input_image_path) | |
# Resize and convert the image to grayscale | |
image = image.resize((28, 28)).convert('L') | |
# Convert the image to a NumPy array | |
image_array = np.array(image) | |
# Normalize the pixel values | |
image_array = image_array / 255.0 | |
return image_array | |
# Function to make predictions | |
def predict_digit(input_image_path): | |
# Preprocess the image | |
image_array = preprocess_image(input_image_path) | |
# Reshape the image_array | |
image_array = image_array.reshape(1, 28, 28) | |
prediction = model2.predict(image_array) | |
predicted_digit = np.argmax(prediction) | |
otpt = f"Predicted digit: {predicted_digit}" | |
return str(otpt) | |
import gradio as gr | |
iface = gr.Interface( | |
fn=predict_digit, | |
inputs=gr.Image(type="filepath", label="Upload Image"), | |
outputs=gr.Textbox("Predicted Digit"), | |
) | |
iface.launch(share=True) | |