import streamlit as st import requests from PIL import Image import io import numpy as np import os import zipfile # ───────────────────────────────────────────── # PAGE CONFIG # ───────────────────────────────────────────── st.set_page_config( page_title="MNIST Digit Classifier", page_icon="🔢", layout="wide", initial_sidebar_state="expanded", ) # ───────────────────────────────────────────── # CUSTOM CSS – Dark / Professional Theme # ───────────────────────────────────────────── st.markdown(""" """, unsafe_allow_html=True) # ───────────────────────────────────────────── # CONSTANTS # ───────────────────────────────────────────── API_URL = "http://127.0.0.1:8000/predict/" SAMPLE_DIR = "sample_digits" # ───────────────────────────────────────────── # HELPERS # ───────────────────────────────────────────── def call_api(image_bytes: bytes, filename: str) -> dict | None: try: resp = requests.post( API_URL, files={"file": (filename, image_bytes, "image/png")}, timeout=10, ) resp.raise_for_status() return resp.json() except Exception as e: return {"error": str(e)} def make_zip_of_samples() -> bytes: buf = io.BytesIO() with zipfile.ZipFile(buf, "w") as zf: for i in range(10): path = os.path.join(SAMPLE_DIR, f"digit_{i}.png") if os.path.exists(path): zf.write(path, f"digit_{i}.png") return buf.getvalue() def confidence_html(conf: float) -> str: pct = round(conf * 100, 1) color = "#4ade80" if conf > 0.90 else "#facc15" if conf > 0.70 else "#f87171" return f"""

{pct}% confidence

""" # ───────────────────────────────────────────── # HERO # ───────────────────────────────────────────── st.markdown("""

🔢 MNIST Digit Classifier

Upload a handwritten digit image and get instant AI-powered prediction

🧠 Dense Neural Network 📊 97.65% Accuracy ⚡ FastAPI Backend 🐍 TensorFlow / Keras
""", unsafe_allow_html=True) # ───────────────────────────────────────────── # SIDEBAR # ───────────────────────────────────────────── with st.sidebar: # API health check try: health = requests.get("http://127.0.0.1:8000/", timeout=3) if health.status_code == 200: st.markdown('
✅ API Online
', unsafe_allow_html=True) else: raise Exception() except: st.markdown('
❌ API Offline — start uvicorn
', unsafe_allow_html=True) st.markdown("---") # Credits st.markdown("""

👨‍💻 Credits

Muhammad Taha Sattar Arain

Founder & CEO — Alpha Orbit

SMIT Batch 10 — AI & Data Science

📧 taha@alphaorbit.site
🔗 linkedin.com/in/taha-arain
🐙 github.com/funterpie 🌐 alphaorbit.site 📝 tahatradz.online

Assignment SMIT AI&DS — Deep Learning
MNIST Classification via FastAPI

""", unsafe_allow_html=True) # ───────────────────────────────────────────── # MAIN — TWO COLUMNS # ───────────────────────────────────────────── col_left, col_right = st.columns([1.1, 1], gap="large") # ── LEFT: Upload & Predict ────────────────── with col_left: st.markdown("### 📤 Upload Your Image") uploaded = st.file_uploader( "Choose a PNG / JPG of a handwritten digit", type=["png", "jpg", "jpeg"], help="Best results with white digit on black background, similar to MNIST format", ) if uploaded: img_bytes = uploaded.read() img = Image.open(io.BytesIO(img_bytes)) # Preview st.markdown("**Preview**") preview_col, info_col = st.columns([1, 1]) with preview_col: st.image(img, width=160, caption=uploaded.name) with info_col: st.markdown(f"""
📄 File: {uploaded.name}
📐 Size: {img.size[0]} × {img.size[1]} px
🎨 Mode: {img.mode}
💾 Bytes: {len(img_bytes):,}
""", unsafe_allow_html=True) st.markdown("") predict_btn = st.button("🚀 Predict Digit", use_container_width=True, type="primary") if predict_btn: with st.spinner("Sending to API..."): result = call_api(img_bytes, uploaded.name) if "error" in result: st.error(f"❌ API Error: {result['error']}\n\nMake sure `uvicorn main:app --reload` is running.") else: digit = result["predicted_digit"] conf = result["confidence"] fname = result["filename"] emoji_map = { 0:"0️⃣",1:"1️⃣",2:"2️⃣",3:"3️⃣",4:"4️⃣", 5:"5️⃣",6:"6️⃣",7:"7️⃣",8:"8️⃣",9:"9️⃣" } st.markdown(f"""
{emoji_map.get(digit,'🔢')}
{digit}
Predicted Digit
{confidence_html(conf)}

File: {fname}

""", unsafe_allow_html=True) # All-class probabilities st.markdown("---") st.markdown("**📊 Confidence Breakdown**") # Re-call just to get probs — or show a mock bar per class # Since API only returns top pred, show visual confidence indicator conf_pct = round(conf * 100, 1) others = round((100 - conf_pct) / 9, 1) bar_data = {} for d in range(10): bar_data[str(d)] = conf_pct if d == digit else others st.bar_chart(bar_data, height=180) st.caption(f"Digit {digit} scored {conf_pct}% · remaining probability distributed across other classes") # ── RIGHT: Sample Downloads ───────────────── with col_right: st.markdown("### 🖼️ Sample Test Images") st.markdown( "

Download sample MNIST-style images to test the classifier.

", unsafe_allow_html=True, ) # Download all as ZIP if os.path.exists(SAMPLE_DIR): zip_bytes = make_zip_of_samples() st.download_button( label="📦 Download All Samples (ZIP)", data=zip_bytes, file_name="mnist_sample_digits.zip", mime="application/zip", use_container_width=True, ) st.markdown("**Or download individually:**") # Display in 5-column grid rows = [range(0, 5), range(5, 10)] for row in rows: cols = st.columns(5) for i, digit in enumerate(row): path = os.path.join(SAMPLE_DIR, f"digit_{digit}.png") if os.path.exists(path): with cols[i]: img_sample = Image.open(path) # Scale up for display display_img = img_sample.resize((80, 80), Image.NEAREST) st.image(display_img, caption=f"Digit {digit}", use_container_width=False) with open(path, "rb") as f: st.download_button( label=f"↓ {digit}", data=f.read(), file_name=f"digit_{digit}.png", mime="image/png", key=f"dl_{digit}", use_container_width=True, ) else: st.warning("Sample images not found. Make sure `sample_digits/` folder is in the same directory as `app.py`.") # ───────────────────────────────────────────── # FOOTER # ───────────────────────────────────────────── st.markdown("---") st.markdown("""
Built by Muhammad Taha Sattar Arain · Alpha Orbit · SMIT Batch 10 AI & DS · Assignment 8
Model: Keras Sequential · Dataset: MNIST · Accuracy: 97.65% · Framework: TensorFlow 2.x
""", unsafe_allow_html=True)