Mohitha/Handwritten-Digit-Recognition-Calculator
0
1import streamlit as st2from streamlit_drawable_canvas import st_canvas3from tensorflow.keras.models import load_model4import numpy as np5from PIL import Image, ImageOps6 7# Load pre-trained model (should be trained on MNIST)8model = load_model("mnist_calc.keras")9 10st.title("🧮 Handwritten Digit Calculator with Deep Learning")11 12# Canvas settings13stroke_width = st.slider("Stroke width: ", 1, 25, 9)14canvas_result_1 = st_canvas(15 fill_color="#000000",16 stroke_width=stroke_width,17 stroke_color="#FFFFFF",18 background_color="#000000",19 width=200,20 height=200,21 drawing_mode="freedraw",22 key="canvas1"23)24 25operator = st.selectbox("Select Operation", ["+", "-", "*", "/"])26 27canvas_result_2 = st_canvas(28 fill_color="#000000",29 stroke_width=stroke_width,30 stroke_color="#FFFFFF",31 background_color="#000000",32 width=200,33 height=200,34 drawing_mode="freedraw",35 key="canvas2"36)37 38def preprocess(image_data):39 img = Image.fromarray(image_data)40 img = img.convert("L") # Convert to grayscale41 img = ImageOps.invert(img)42 img = img.resize((28, 28))43 img = np.array(img).astype("float32") / 255.044 img = img.reshape(1, 28, 28, 1)45 return img46 47def predict_digit(canvas_data):48 if canvas_data is not None:49 img = canvas_data.image_data50 img = preprocess(img)51 prediction = model.predict(img)52 digit = np.argmax(prediction)53 return digit54 return None55 56if st.button("Calculate"):57 digit1 = predict_digit(canvas_result_1)58 digit2 = predict_digit(canvas_result_2)59 60 if digit1 is not None and digit2 is not None:61 if operator == "+":62 result = digit1 + digit263 elif operator == "-":64 result = digit1 - digit265 elif operator == "*":66 result = digit1 * digit267 elif operator == "/":68 result = digit1 / digit2 if digit2 != 0 else "∞"69 70 st.markdown(f"**Predicted:** {digit1} {operator} {digit2} = **{result}**")71 else:72 st.warning("Please draw digits on both canvases.")73 