Upload app.py with huggingface_hub
Browse files
app.py
ADDED
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 = tf.saved_model.load('https://huggingface.co/nivashuggingface/digit-recognition/resolve/main/saved_model')
|
9 |
+
|
10 |
+
def preprocess_image(img):
|
11 |
+
"""Preprocess the drawn image for prediction"""
|
12 |
+
# Convert to grayscale and resize
|
13 |
+
img = img.convert('L')
|
14 |
+
img = img.resize((28, 28))
|
15 |
+
# Convert to numpy array and normalize
|
16 |
+
img_array = np.array(img)
|
17 |
+
img_array = img_array.astype('float32') / 255.0
|
18 |
+
# Add batch dimension
|
19 |
+
img_array = np.expand_dims(img_array, axis=0)
|
20 |
+
# Add channel dimension
|
21 |
+
img_array = np.expand_dims(img_array, axis=-1)
|
22 |
+
return img_array
|
23 |
+
|
24 |
+
def predict_digit(img):
|
25 |
+
"""Predict digit from drawn image"""
|
26 |
+
# Preprocess the image
|
27 |
+
processed_img = preprocess_image(img)
|
28 |
+
# Make prediction
|
29 |
+
predictions = model(processed_img)
|
30 |
+
predicted_digit = tf.argmax(predictions, axis=1).numpy()[0]
|
31 |
+
# Get confidence scores
|
32 |
+
confidence_scores = tf.nn.softmax(predictions[0]).numpy()
|
33 |
+
# Create result string
|
34 |
+
result = f"Predicted Digit: {predicted_digit}\n\nConfidence Scores:\n"
|
35 |
+
for i, score in enumerate(confidence_scores):
|
36 |
+
result += f"Digit {i}: {score:.2%}\n"
|
37 |
+
return result
|
38 |
+
|
39 |
+
# Create Gradio interface
|
40 |
+
iface = gr.Interface(
|
41 |
+
fn=predict_digit,
|
42 |
+
inputs=gr.Image(type="pil", label="Draw a digit (0-9)"),
|
43 |
+
outputs=gr.Textbox(label="Prediction Results"),
|
44 |
+
title="Digit Recognition with CNN",
|
45 |
+
description="Draw a digit (0-9) in the box below. The model will predict which digit you drew.",
|
46 |
+
examples=[
|
47 |
+
["examples/0.png"],
|
48 |
+
["examples/1.png"],
|
49 |
+
["examples/2.png"],
|
50 |
+
],
|
51 |
+
theme=gr.themes.Soft()
|
52 |
+
)
|
53 |
+
|
54 |
+
# Launch the interface
|
55 |
+
if __name__ == "__main__":
|
56 |
+
iface.launch()
|