Spaces:
Runtime error
Runtime error
Jhun Brian Andam commited on
Commit ยท
601750a
1
Parent(s): 95b27b6
Initial commit: Dockerized Streamlit CNN digit classifier
Browse filesFiles changed (5)
- Dockerfile+16-7
- model/best_CNN.pthAdded+3
- requirements.txt+6-3
- src/cnn_app.pyAdded+85
- src/streamlit_app.pyDeleted-40
112345678981011121312141516151718191720212219232425262728292130FROM python:3.9-slimFROM python:3.10-slim
# Set working directoryWORKDIR /app
# Install system dependenciesRUN apt-get update && apt-get install -y \ build-essential \ curl \ software-properties-common \ git \ && rm -rf /var/lib/apt/lists/*
# Copy app codeCOPY requirements.txt ./COPY requirements.txt .COPY src/ ./src/
RUN pip3 install -r requirements.txt# Important if model file is needed at runtimeCOPY model/ ./model/
EXPOSE 8501# Install Python dependenciesRUN pip install --no-cache-dir -r requirements.txt
HEALTHCHECK CMD curl --fail http://localhost:8501/_stcore/health# Expose Streamlit default portEXPOSE 7860
# Health check endpoint (adjust if needed)HEALTHCHECK CMD curl --fail http://localhost:7860/_stcore/health || exit 1
# Start the Streamlit appENTRYPOINT ["streamlit", "run", "src/streamlit_app.py", "--server.port=8501", "--server.address=0.0.0.0"]ENTRYPOINT ["streamlit", "run", "src/cnn_app.py", "--server.port=7860", "--server.address=0.0.0.0"]123version https://git-lfs.github.com/spec/v1oid sha256:d5c2340175d0819fe49387db03b992552225fe2052815171402a35411e961adfsize 1690203123123456altairpandasstreamlitstreamlit==1.35.0streamlit-drawable-canvas==0.9.4torch==2.2.2torchvision==0.17.2Pillow==10.3.0numpy==1.26.412345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485import streamlit as stfrom streamlit_drawable_canvas import st_canvasfrom PIL import Image, ImageOpsimport numpy as npimport torchimport torch.nn as nnimport 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 modelmodel = CNN()model.load_state_dict(torch.load("model/best_CNN.pth"))model.eval()
# Prediction functiondef 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 UIst.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)
# Canvaswith 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)12345678910111213141516171819202122232425262728293031323334353637383940import altair as altimport numpy as npimport pandas as pdimport streamlit as st
"""# Welcome to Streamlit!
Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [communityforums](https://discuss.streamlit.io).
In the meantime, below is an example of what you can do with just a few lines of code:"""
num_points = st.slider("Number of points in spiral", 1, 10000, 1100)num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
indices = np.linspace(0, 1, num_points)theta = 2 * np.pi * num_turns * indicesradius = indices
x = radius * np.cos(theta)y = radius * np.sin(theta)
df = pd.DataFrame({ "x": x, "y": y, "idx": indices, "rand": np.random.randn(num_points),})
st.altair_chart(alt.Chart(df, height=700, width=700) .mark_point(filled=True) .encode( x=alt.X("x", axis=None), y=alt.Y("y", axis=None), color=alt.Color("idx", legend=None, scale=alt.Scale()), size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])), ))Dockerfile+16-7
model/best_CNN.pthAdded+3
requirements.txt+6-3
src/cnn_app.pyAdded+85
src/streamlit_app.pyDeleted-40