Spaces:
Sleeping
Sleeping
Download app.py from Erenuo/Digit-Recognition-with-CNN: direct link, hf CLI and curl.
- Browser
- Download file 2.49 kB
-
https://huggingface.co/spaces/Erenuo/Digit-Recognition-with-CNN/resolve/main/app.py
- Command line
-
hf download hf://spaces/Erenuo/Digit-Recognition-with-CNN/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Erenuo/Digit-Recognition-with-CNN/resolve/main/app.py
2.49 kB
| from streamlit_drawable_canvas import st_canvas | |
| import tensorflow as tf | |
| import streamlit as st | |
| import numpy as np | |
| import cv2 | |
| # Page Configuration | |
| st.set_page_config(page_title="Digit Recognition", page_icon="🔢", layout="wide") | |
| # Modern styling | |
| st.markdown(""" | |
| <style> | |
| .main {background-color: #f8f9fa;} | |
| h1 {color: #2c3e50; font-weight: 700;} | |
| .stButton>button { | |
| width: 100%; | |
| background-color: #e74c3c; | |
| color: white; | |
| border-radius: 8px; | |
| padding: 12px; | |
| font-weight: 600; | |
| border: none; | |
| transition: 0.3s; | |
| } | |
| .stButton>button:hover {background-color: #c0392b;} | |
| </style> | |
| """, unsafe_allow_html=True) | |
| # Header | |
| st.title("🔢 Handwritten Digit Recognition") | |
| st.markdown("Draw a **digit (0-9)** on the black canvas, and let the model predict it.") | |
| # Cache Model | |
| def load_model(): | |
| try: | |
| return tf.keras.models.load_model('model.keras') | |
| except Exception as e: | |
| st.error(f"Error loading model: {e}") | |
| return None | |
| model = load_model() | |
| # Layout | |
| col1, col2 = st.columns([1, 1], gap="large") | |
| with col1: | |
| st.subheader("Drawing Area") | |
| canvas_result = st_canvas( | |
| fill_color="rgba(255, 165, 0, 0.3)", | |
| stroke_width=15, | |
| stroke_color="#FFFFFF", | |
| background_color="#000000", | |
| height=280, | |
| width=280, | |
| drawing_mode="freedraw", | |
| display_toolbar=True, | |
| key="canvas", | |
| ) | |
| with col2: | |
| st.subheader("Prediction") | |
| if canvas_result.image_data is not None: | |
| img = canvas_result.image_data | |
| if np.sum(img) > 0: | |
| img = cv2.cvtColor(img, cv2.COLOR_RGBA2GRAY) | |
| img_resized = cv2.resize(img, (28, 28), interpolation=cv2.INTER_AREA) | |
| img_normalized = img_resized / 255.0 | |
| img_reshaped = img_normalized.reshape(1, 28, 28, 1) | |
| prediction = model.predict(img_reshaped) | |
| predicted_class = np.argmax(prediction) | |
| confidence = np.max(prediction) | |
| st.markdown(f"<h1 style='text-align: center; color: #27ae60; font-size: 80px;'>{predicted_class}</h1>", unsafe_allow_html=True) | |
| st.success(f"Confidence: {confidence * 100:.2f}%") | |
| st.write("Model Input (28x28):") | |
| st.image(img_resized, width=100) | |
| else: | |
| st.info("Please draw a digit.") | |