nivashuggingface commited on
Commit
41e1bf7
·
verified ·
1 Parent(s): d2f2d21

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +68 -0
app.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import tensorflow as tf
3
+ import numpy as np
4
+ from PIL import Image
5
+ import io
6
+
7
+ # Load the model from Hugging Face
8
+ MODEL_PATH = "https://huggingface.co/nivashuggingface/digit-recognition/resolve/main/saved_model"
9
+ model = tf.saved_model.load(MODEL_PATH)
10
+
11
+ def preprocess_image(img):
12
+ """Preprocess the drawn image for prediction"""
13
+ # Convert to grayscale and resize
14
+ img = img.convert('L')
15
+ img = img.resize((28, 28))
16
+ # Convert to numpy array and normalize
17
+ img_array = np.array(img)
18
+ img_array = img_array.astype('float32') / 255.0
19
+ # Add batch dimension
20
+ img_array = np.expand_dims(img_array, axis=0)
21
+ # Add channel dimension
22
+ img_array = np.expand_dims(img_array, axis=-1)
23
+ return img_array
24
+
25
+ def predict_digit(img):
26
+ """Predict digit from drawn image"""
27
+ try:
28
+ # Preprocess the image
29
+ processed_img = preprocess_image(img)
30
+ # Make prediction
31
+ predictions = model(processed_img)
32
+ predicted_digit = tf.argmax(predictions, axis=1).numpy()[0]
33
+ # Get confidence scores
34
+ confidence_scores = tf.nn.softmax(predictions[0]).numpy()
35
+ # Create result string
36
+ result = f"Predicted Digit: {predicted_digit}\n\nConfidence Scores:\n"
37
+ for i, score in enumerate(confidence_scores):
38
+ result += f"Digit {i}: {score:.2%}\n"
39
+ return result
40
+ except Exception as e:
41
+ return f"Error during prediction: {str(e)}"
42
+
43
+ # Create Gradio interface
44
+ iface = gr.Interface(
45
+ fn=predict_digit,
46
+ inputs=gr.Image(type="pil", label="Draw a digit (0-9)"),
47
+ outputs=gr.Textbox(label="Prediction Results"),
48
+ title="Digit Recognition with CNN",
49
+ description="""
50
+ Draw a digit (0-9) in the box below. The model will predict which digit you drew.
51
+
52
+ Instructions:
53
+ 1. Click and drag to draw a digit
54
+ 2. Make sure the digit is clear and centered
55
+ 3. The model will show the predicted digit and confidence scores
56
+ """,
57
+ examples=[
58
+ ["examples/0.png"],
59
+ ["examples/1.png"],
60
+ ["examples/2.png"],
61
+ ],
62
+ theme=gr.themes.Soft(),
63
+ allow_flagging="never"
64
+ )
65
+
66
+ # Launch the interface
67
+ if __name__ == "__main__":
68
+ iface.launch()