mayura25 commited on
Commit
bdb79ae
1 Parent(s): d96981c

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +68 -0
app.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import tensorflow as tf
3
+ from tensorflow import keras
4
+ import matplotlib.pyplot as plt
5
+ from PIL import Image
6
+
7
+
8
+ (X_train, y_train) , (X_test, y_test) = keras.datasets.mnist.load_data()
9
+
10
+ # Scaling array values so we get values form 0 to 1
11
+ X_train = X_train / 255
12
+ X_test = X_test / 255
13
+
14
+ # Define a simple feedforward neural network
15
+ model2 = keras.Sequential([
16
+ keras.layers.Flatten(input_shape=(28, 28)), # Flatten the 28x28 images
17
+ keras.layers.Dense(128, activation='relu'),
18
+ keras.layers.Dense(64, activation='relu'),
19
+ keras.layers.Dense(10, activation='softmax')
20
+ ])
21
+
22
+ # Compile the model
23
+ model2.compile(optimizer='adam',
24
+ loss='sparse_categorical_crossentropy', # Corrected the loss function
25
+ metrics=['accuracy'])
26
+
27
+ # Train the model
28
+ model2.fit(X_train, y_train, epochs=5) # Assuming X_train and y_train are properly loaded
29
+
30
+
31
+ # Function to preprocess the uploaded image
32
+ def preprocess_image(input_image_path): # Accept file path as input
33
+ # Load the image using PIL
34
+ image = Image.open(input_image_path)
35
+ # Resize and convert the image to grayscale
36
+ image = image.resize((28, 28)).convert('L')
37
+ # Convert the image to a NumPy array
38
+ image_array = np.array(image)
39
+ # Normalize the pixel values
40
+ image_array = image_array / 255.0
41
+ return image_array
42
+
43
+
44
+ # Function to make predictions
45
+ def predict_digit(input_image_path):
46
+ # Preprocess the image
47
+ image_array = preprocess_image(input_image_path)
48
+ # Reshape the image_array
49
+ image_array = image_array.reshape(1, 28, 28)
50
+
51
+ prediction = model2.predict(image_array)
52
+ predicted_digit = np.argmax(prediction)
53
+ otpt = f"Predicted digit: {predicted_digit}"
54
+
55
+ return str(otpt)
56
+
57
+
58
+ import gradio as gr
59
+
60
+ iface = gr.Interface(
61
+ fn=predict_digit,
62
+ inputs=gr.Image(type="filepath", label="Upload Image"),
63
+ outputs=gr.Textbox(text="Predicted Digit"),
64
+ )
65
+
66
+ iface.launch()
67
+
68
+