Spaces:
Sleeping
Sleeping
Download quickdraw_app.py from DS-Outputs/QuickDraw10: direct link, hf CLI and curl.
- Browser
- Download file 5.88 kB
-
https://huggingface.co/spaces/DS-Outputs/QuickDraw10/resolve/main/quickdraw_app.py
- Command line
-
hf download hf://spaces/DS-Outputs/QuickDraw10/quickdraw_app.py
-
curl -L -o quickdraw_app.py https://huggingface.co/spaces/DS-Outputs/QuickDraw10/resolve/main/quickdraw_app.py
5.88 kB
| # quickdraw_app.py | |
| import streamlit as st | |
| from streamlit_drawable_canvas import st_canvas | |
| import streamlit.components.v1 as components | |
| from model import ImageClassifier | |
| import torch | |
| from torchvision import transforms | |
| from PIL import Image | |
| import numpy as np | |
| import random | |
| import time | |
| # ----------------------------- | |
| # Constants and Configurations | |
| # ----------------------------- | |
| CLASS_MAP = { | |
| 'bat': 0, 'bird': 1, 'book': 2, 'bowtie': 3, 'broccoli': 4, | |
| 'apple': 5, 'banana': 6, 'angel': 7, 'ant': 8, 'airplane': 9 | |
| } | |
| CLASS_NAMES = list(CLASS_MAP.keys()) | |
| MODEL_PATH = "model/quickdraw_10_epoch2.pth" | |
| NUM_ROUNDS = 5 | |
| CANVAS_SIZE = 280 | |
| INPUT_SIZE = 28 | |
| # ----------------------------- | |
| # Load Model | |
| # ----------------------------- | |
| def load_model(): | |
| model = ImageClassifier.load_from_checkpoint( | |
| "ckpt/epoch=9-step=6570.ckpt", | |
| num_classes=10 | |
| ) | |
| model.eval() | |
| model.to("cuda" if torch.cuda.is_available() else "cpu") # ✅ Add this | |
| return model | |
| model = load_model() | |
| # ----------------------------- | |
| # Preprocess Function | |
| # ----------------------------- | |
| def preprocess(image_data): | |
| # Convert canvas (white strokes on black background) to PIL grayscale image | |
| image = Image.fromarray((image_data[:, :, 0]).astype("uint8")).convert("L") | |
| # Invert colors if needed — resnet expects black strokes on white background | |
| image = Image.eval(image, lambda px: 255 - px) | |
| transform = transforms.Compose([ | |
| transforms.Resize((INPUT_SIZE, INPUT_SIZE)), | |
| transforms.ToTensor(), # Converts [0,255] to [0.0,1.0], shape [1, H, W] | |
| transforms.Normalize((0.5,), (0.5,)) # for grayscale (1 channel) | |
| ]) | |
| tensor = transform(image) # shape: [1, 28, 28] | |
| tensor = tensor.expand(3, -1, -1) # replicate to [3, 28, 28] for resnet18 | |
| return tensor.unsqueeze(0) # [1, 3, 28, 28] | |
| # ----------------------------- | |
| # Game State Initialization | |
| # ----------------------------- | |
| if "round" not in st.session_state: | |
| st.session_state.round = 0 | |
| st.session_state.score = 0 | |
| st.session_state.prompts = random.sample(CLASS_NAMES, NUM_ROUNDS) | |
| st.session_state.current_prompt = st.session_state.prompts[0] | |
| st.session_state.start_time = time.time() | |
| # ----------------------------- | |
| # UI Layout | |
| # ----------------------------- | |
| st.title("🖌️ QuickDraw Mini Game") | |
| st.markdown("Draw the object before time runs out (20 seconds per item)!") | |
| st.markdown(f"### Draw: **{st.session_state.current_prompt.upper()}**") | |
| st.markdown(f"**Round {st.session_state.round + 1} of {NUM_ROUNDS}** | **Score: {st.session_state.score}**") | |
| # ----------------------------- | |
| # Timer | |
| # ----------------------------- | |
| components.html(""" | |
| <script> | |
| let seconds = 20; | |
| function countdown() { | |
| let timer = document.getElementById("timer"); | |
| setInterval(() => { | |
| if (seconds >= 0) { | |
| timer.innerText = `⏰ Time Remaining: ${seconds} seconds`; | |
| seconds--; | |
| } | |
| }, 1000); | |
| } | |
| countdown(); | |
| </script> | |
| <div id="timer"></div> | |
| """, height=50) | |
| elapsed = int(time.time() - st.session_state.start_time) | |
| remaining_time = max(0, 20 - elapsed) | |
| st.markdown(f"⏰ Time Remaining: `{remaining_time}` seconds") | |
| if remaining_time == 0: | |
| st.error("Time's up! Try again.") | |
| if st.button("Next"): | |
| st.session_state.round += 1 | |
| if st.session_state.round < NUM_ROUNDS: | |
| st.session_state.current_prompt = st.session_state.prompts[st.session_state.round] | |
| st.session_state.start_time = time.time() | |
| st.rerun() | |
| else: | |
| st.success("Game Over!") | |
| st.stop() | |
| # ----------------------------- | |
| # Drawing Canvas | |
| # ----------------------------- | |
| canvas_result = st_canvas( | |
| fill_color="black", | |
| stroke_width=6, | |
| stroke_color="white", | |
| background_color="black", | |
| height=CANVAS_SIZE, | |
| width=CANVAS_SIZE, | |
| drawing_mode="freedraw", | |
| key="canvas", | |
| update_streamlit=True | |
| ) | |
| # ----------------------------- | |
| # Model Prediction | |
| # ----------------------------- | |
| if canvas_result.image_data is not None: | |
| input_tensor = preprocess(canvas_result.image_data) | |
| # ✅ Move input to same device as model | |
| device = next(model.parameters()).device | |
| input_tensor = input_tensor.to(device) | |
| with torch.no_grad(): | |
| outputs = model(input_tensor) | |
| pred_idx = torch.argmax(outputs, dim=1).item() | |
| pred_label = CLASS_NAMES[pred_idx] | |
| st.markdown(f"🤖 Prediction: **{pred_label}**") | |
| if pred_label == st.session_state.current_prompt: | |
| st.success("✅ Correct!") | |
| st.session_state.score += 1 | |
| st.session_state.round += 1 | |
| if st.session_state.round < NUM_ROUNDS: | |
| st.session_state.current_prompt = st.session_state.prompts[st.session_state.round] | |
| st.session_state.start_time = time.time() | |
| st.rerun() | |
| else: | |
| st.balloons() | |
| st.success(f"🏁 Game Over! Final Score: {st.session_state.score} / {NUM_ROUNDS}") | |
| st.stop() | |
| # Show prediction and preprocessed image for verification | |
| st.markdown(f"🤖 Prediction: **{pred_label}**") | |
| st.image( | |
| input_tensor.squeeze().permute(1, 2, 0).clamp(0, 1).cpu().numpy(), | |
| caption="Model Input (Preview)" | |
| ) | |
| # st.image(input_tensor.squeeze().permute(1, 2, 0).cpu().numpy(), caption="Model Input (Preview)") | |
| # ----------------------------- | |
| # Optional: Reset Game | |
| # ----------------------------- | |
| st.markdown("---") | |
| if st.button("🔄 Reset Game"): | |
| st.session_state.round = 0 | |
| st.session_state.score = 0 | |
| st.session_state.prompts = random.sample(CLASS_NAMES, NUM_ROUNDS) | |
| st.session_state.current_prompt = st.session_state.prompts[0] | |
| st.session_state.start_time = time.time() | |
| st.rerun() | |