import os os.environ["STREAMLIT_SERVER_HEADLESS"] = "true" import streamlit as st from streamlit_drawable_canvas import st_canvas from PIL import Image, ImageOps import numpy as np import torch import torch.nn as nn import torch.nn.functional as F class CNN(nn.Module): def __init__(self): super().__init__() # just the initialization self.conv1 = nn.Conv2d(1, 32, (3,3), 1, 1) self.pool1 = nn.MaxPool2d((2,2), 2) self.conv2 = nn.Conv2d(32, 64, (3,3), 1, 1) self.pool2 = nn.MaxPool2d((2,2), 2) self.fcn1 = nn.Linear(64*7*7, 128) self.fcn2 = nn.Linear(128, 10) def forward(self, x): # seuential x = F.relu(self.conv1(x)) x = self.pool1(x) x = F.relu(self.conv2(x)) x = self.pool2(x) x = x.view(-1, 64*7*7) x = self.fcn1(x) x = F.softmax(self.fcn2(x), dim=1) return x # Instantiate and load model model = CNN() model.load_state_dict(torch.load("model/best_CNN.pth")) model.eval() # Prediction function def predict(image_array): # Normalize to [0,1] and convert to tensor image_array = image_array.astype(np.float32) / 255.0 tensor_input = torch.tensor(image_array).unsqueeze(0).unsqueeze(0) # shape: [1, 1, 28, 28] with torch.no_grad(): output = model(tensor_input) print(output) return torch.argmax(output, dim=1).item() # Streamlit UI st.title("🧠 CNN Sketchpad Classifier (PyTorch)") st.markdown("Draw a digit (0–9) and click **Predict** to classify using your PyTorch CNN model.") col1, col2 = st.columns(2) # Canvas with col1: st.subheader("✍️ Sketchpad") canvas_result = st_canvas( fill_color="rgba(255, 255, 255, 1)", stroke_width=10, stroke_color="#000000", background_color="#FFFFFF", height=280, width=280, drawing_mode="freedraw", key="canvas", ) if st.button("Predict") and canvas_result.image_data is not None: # Convert canvas to PIL and preprocess img = Image.fromarray(canvas_result.image_data.astype("uint8")) img = img.convert("L") img = ImageOps.invert(img) img_resized = img.resize((28, 28), Image.Resampling.LANCZOS) # Convert to numpy array img_np = np.array(img_resized) # Predict predicted_class = predict(img_np) st.success(f"🎯 Predicted Class: {predicted_class}") # Show processed input with col2: st.subheader("📉 Processed Input (28×28)") st.image(img_resized.resize((280, 280), Image.Resampling.NEAREST), caption="Input fed to model", use_container_width=True)