Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -1,29 +1,94 @@
|
|
1 |
-
import
|
2 |
-
|
3 |
-
import
|
4 |
-
from
|
|
|
|
|
5 |
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
|
10 |
-
|
11 |
-
|
12 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
13 |
|
14 |
-
|
15 |
-
|
16 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
17 |
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
|
22 |
-
|
23 |
-
|
24 |
-
snapshot = gr.Image(label="📸 Snapshot Image")
|
25 |
|
26 |
-
|
27 |
-
|
|
|
|
|
|
|
28 |
|
29 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import tensorflow as tf
|
3 |
+
import numpy as np
|
4 |
+
from PIL import Image
|
5 |
+
import io
|
6 |
+
import logging
|
7 |
|
8 |
+
# Set up logging
|
9 |
+
logging.basicConfig(level=logging.INFO)
|
10 |
+
logger = logging.getLogger(__name__)
|
11 |
|
12 |
+
# Load the pre-trained MNIST model
|
13 |
+
@st.cache_resource
|
14 |
+
def load_model():
|
15 |
+
try:
|
16 |
+
model = tf.keras.models.load_model('mnist_cnn.h5')
|
17 |
+
logger.info("MNIST model loaded successfully")
|
18 |
+
return model
|
19 |
+
except Exception as e:
|
20 |
+
logger.error(f"Error loading model: {e}")
|
21 |
+
st.error("Failed to load the model. Please check the model file.")
|
22 |
+
return None
|
23 |
|
24 |
+
# Preprocess the uploaded image
|
25 |
+
def preprocess_image(image):
|
26 |
+
try:
|
27 |
+
# Convert to grayscale
|
28 |
+
img = image.convert('L')
|
29 |
+
# Resize to 28x28 (MNIST model input size)
|
30 |
+
img = img.resize((28, 28), Image.Resampling.LANCZOS)
|
31 |
+
# Convert to numpy array and normalize
|
32 |
+
img_array = np.array(img)
|
33 |
+
# Ensure the image is inverted if necessary (MNIST expects white digits on black background)
|
34 |
+
img_array = 255 - img_array # Invert colors
|
35 |
+
img_array = img_array / 255.0 # Normalize to [0, 1]
|
36 |
+
# Reshape for model input (1, 28, 28, 1)
|
37 |
+
img_array = img_array.reshape(1, 28, 28, 1)
|
38 |
+
logger.info("Image preprocessed successfully")
|
39 |
+
return img_array
|
40 |
+
except Exception as e:
|
41 |
+
logger.error(f"Error preprocessing image: {e}")
|
42 |
+
st.error("Failed to preprocess the image. Please ensure it's a valid image.")
|
43 |
+
return None
|
44 |
|
45 |
+
# Streamlit app
|
46 |
+
st.title("AutoWeightLogger - Number Detection")
|
47 |
+
st.write("Upload an image containing a single handwritten digit to detect the number.")
|
48 |
|
49 |
+
# File uploader
|
50 |
+
uploaded_file = st.file_uploader("Choose an image...", type=["png", "jpg", "jpeg"])
|
|
|
51 |
|
52 |
+
if uploaded_file is not None:
|
53 |
+
try:
|
54 |
+
# Display the uploaded image
|
55 |
+
image = Image.open(uploaded_file)
|
56 |
+
st.image(image, caption="Uploaded Image", use_column_width=True)
|
57 |
|
58 |
+
# Preprocess the image
|
59 |
+
processed_image = preprocess_image(image)
|
60 |
+
if processed_image is None:
|
61 |
+
st.stop()
|
62 |
+
|
63 |
+
# Load the model
|
64 |
+
model = load_model()
|
65 |
+
if model is None:
|
66 |
+
st.stop()
|
67 |
+
|
68 |
+
# Make prediction
|
69 |
+
with st.spinner("Detecting number..."):
|
70 |
+
prediction = model.predict(processed_image)
|
71 |
+
predicted_digit = np.argmax(prediction, axis=1)[0]
|
72 |
+
confidence = np.max(prediction) * 100
|
73 |
+
|
74 |
+
# Display result
|
75 |
+
st.success(f"Detected Number: {predicted_digit}")
|
76 |
+
st.write(f"Confidence: {confidence:.2f}%")
|
77 |
+
|
78 |
+
# Provide feedback if confidence is low
|
79 |
+
if confidence < 70:
|
80 |
+
st.warning("Low confidence in prediction. Please ensure the image contains a clear, single handwritten digit.")
|
81 |
+
|
82 |
+
except Exception as e:
|
83 |
+
logger.error(f"Error processing image: {e}")
|
84 |
+
st.error("An error occurred while processing the image. Please try again with a different image.")
|
85 |
+
else:
|
86 |
+
st.info("Please upload an image to proceed.")
|
87 |
+
|
88 |
+
# Instructions for users
|
89 |
+
st.markdown("""
|
90 |
+
### Instructions
|
91 |
+
1. Upload an image containing a single handwritten digit (0-9).
|
92 |
+
2. Ensure the digit is clear, centered, and on a plain background for best results.
|
93 |
+
3. The model expects white digits on a black background, similar to MNIST dataset images.
|
94 |
+
""")
|