Josephus67 commited on
Commit
2d08276
·
verified ·
1 Parent(s): 349e566

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +47 -0
  2. requirements.txt +4 -0
app.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import tensorflow as tf
3
+ import numpy as np
4
+ from PIL import Image, ImageOps
5
+
6
+ # Load the model directly
7
+ # reliable for Spaces where you upload the model file alongside the app
8
+ model = tf.keras.models.load_model("mnist_model.keras")
9
+
10
+ def predict_digit(image):
11
+ if image is None:
12
+ return None
13
+
14
+ # 1. Convert to grayscale
15
+ image = image.convert('L')
16
+
17
+ # 2. Resize to 28x28 to match training data
18
+ image = image.resize((28, 28))
19
+
20
+ # 3. Invert colors (MNIST is white text on black background)
21
+ # Most user uploads are black text on white background (paper), so we usually need to invert
22
+ # We check mean pixel value; if > 127, it's likely a white background.
23
+ if np.mean(image) > 127:
24
+ image = ImageOps.invert(image)
25
+
26
+ # 4. Convert to numpy array and normalize
27
+ image_array = np.array(image) / 255.0
28
+
29
+ # 5. Flatten to shape (1, 784) as expected by the Dense input layer
30
+ image_array = image_array.reshape(1, 784)
31
+
32
+ # Predict
33
+ prediction = model.predict(image_array)
34
+
35
+ # Return dictionary for Gradio Label output
36
+ return {str(i): float(prediction[0][i]) for i in range(10)}
37
+
38
+ iface = gr.Interface(
39
+ fn=predict_digit,
40
+ inputs=gr.Image(type="pil", label="Upload an Image"),
41
+ outputs=gr.Label(num_top_classes=3, label="Predictions"),
42
+ title="MNIST Digit Classifier",
43
+ description="Upload an image of a handwritten digit (0-9) to see the prediction. Works best with a single digit centered in the image."
44
+ )
45
+
46
+ if __name__ == "__main__":
47
+ iface.launch()
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ tensorflow
2
+ gradio
3
+ numpy
4
+ pillow