ved_T
commited on
Commit
·
e33c32a
1
Parent(s):
c47301b
doem
Browse files- app.py +60 -4
- model.pkl +3 -0
- requirements.txt +3 -0
app.py
CHANGED
|
@@ -1,7 +1,63 @@
|
|
| 1 |
import gradio as gr
|
|
|
|
|
|
|
|
|
|
| 2 |
|
| 3 |
-
|
| 4 |
-
|
|
|
|
| 5 |
|
| 6 |
-
|
| 7 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
+
import numpy as np
|
| 3 |
+
import pickle
|
| 4 |
+
from PIL import Image
|
| 5 |
|
| 6 |
+
# Load the model
|
| 7 |
+
with open('model.pkl', 'rb') as f:
|
| 8 |
+
model_params = pickle.load(f)
|
| 9 |
|
| 10 |
+
W1 = model_params['W1']
|
| 11 |
+
b1 = model_params['b1']
|
| 12 |
+
W2 = model_params['W2']
|
| 13 |
+
b2 = model_params['b2']
|
| 14 |
+
|
| 15 |
+
def ReLu(Z):
|
| 16 |
+
return np.maximum(Z, 0)
|
| 17 |
+
|
| 18 |
+
def softmax(Z):
|
| 19 |
+
return np.exp(Z) / sum(np.exp(Z))
|
| 20 |
+
|
| 21 |
+
def forward_prop(W1, b1, W2, b2, X):
|
| 22 |
+
Z1 = W1.dot(X) + b1
|
| 23 |
+
A1 = ReLu(Z1)
|
| 24 |
+
Z2 = W2.dot(A1) + b2
|
| 25 |
+
A2 = softmax(Z2)
|
| 26 |
+
return Z1, Z2, A1, A2
|
| 27 |
+
|
| 28 |
+
def get_predictions(A2):
|
| 29 |
+
return np.argmax(A2, 0)
|
| 30 |
+
|
| 31 |
+
def preprocess_image(image):
|
| 32 |
+
# Convert to grayscale
|
| 33 |
+
img = image.convert('L')
|
| 34 |
+
|
| 35 |
+
# Resize the image
|
| 36 |
+
img = img.resize((28, 28))
|
| 37 |
+
|
| 38 |
+
# Convert to numpy array and normalize
|
| 39 |
+
img_array = np.array(img).reshape(1, 28*28) / 255.0
|
| 40 |
+
|
| 41 |
+
return img_array.T # Transpose to match the shape (784, 1)
|
| 42 |
+
|
| 43 |
+
def predict_digit(image):
|
| 44 |
+
X = preprocess_image(image)
|
| 45 |
+
|
| 46 |
+
# Forward propagation
|
| 47 |
+
_, _, _, A2 = forward_prop(W1, b1, W2, b2, X)
|
| 48 |
+
|
| 49 |
+
# Get the prediction
|
| 50 |
+
prediction = get_predictions(A2)
|
| 51 |
+
|
| 52 |
+
return int(prediction[0])
|
| 53 |
+
|
| 54 |
+
# Gradio interface
|
| 55 |
+
iface = gr.Interface(
|
| 56 |
+
fn=predict_digit,
|
| 57 |
+
inputs=gr.Image(type="pil"),
|
| 58 |
+
outputs=gr.Label(num_top_classes=1),
|
| 59 |
+
title="Handwritten Digit Recognition",
|
| 60 |
+
description="Upload an image of a handwritten digit (0-9) and the model will predict which digit it is."
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
iface.launch()
|
model.pkl
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:508fef3cdc4adbc5402d9694b9519b70df7cd22bd231bb6dd469338e1dda3679
|
| 3 |
+
size 63956
|
requirements.txt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio
|
| 2 |
+
numpy
|
| 3 |
+
Pillow
|