File size: 1,927 Bytes
bdb79ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84b1aa3
bdb79ae
 
471fd31
bdb79ae
 
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
57
58
59
60
61
62
63
64
65
66
67
68
69
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)