cnn0 / space /app.py
shyo2's picture
Devin
Fix Sketchpad composite None check for numpy payloads
c39c3ec
Raw History Blame Contribute Delete
3.05 kB
import io
import os
import sys
# HF Space 컨테이너의 stdout 인코딩(cp949) 문제로 gradio 기동 시 크래시 방지
os.environ.setdefault("PYTHONIOENCODING", "utf-8")
for _stream in (sys.stdout, sys.stderr):
try:
_stream.reconfigure(encoding="utf-8", errors="replace")
except Exception:
try:
_buf = getattr(_stream, "buffer", None)
if _buf is not None:
_wrapped = io.TextIOWrapper(_buf, encoding="utf-8", errors="replace")
if _stream is sys.stdout:
sys.stdout = _wrapped
else:
sys.stderr = _wrapped
except Exception:
pass
import numpy as np
import torch
import gradio as gr
from PIL import Image
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "src"))
from model import CNN # noqa: E402
from preprocess import preprocess # noqa: E402
# gradio의 python->JS transpile이 cp949 stdout에서 크래시나는 것 우회
try:
gr.Blocks.transpile_to_js = lambda self, quiet=False: None
except Exception:
pass
MODEL_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)),
"runs", "depth5", "model.pt")
model = CNN(depth=5, use_residual=False)
model.load_state_dict(torch.load(MODEL_PATH, map_location="cpu", weights_only=True))
model.eval()
def predict(sketch):
# gradio 6 Sketchpad returns {"background":…, "layers":…, "composite":…}
if isinstance(sketch, dict):
sketch = sketch.get("composite")
if sketch is None:
sketch = sketch.get("background")
if sketch is None:
return "숫자를 그려주세요", ""
if isinstance(sketch, np.ndarray):
sketch = Image.fromarray(sketch)
if sketch.mode == "RGBA":
bg = Image.new("RGBA", sketch.size, (255, 255, 255, 255))
sketch = Image.alpha_composite(bg, sketch).convert("RGB")
gray = np.array(sketch.convert("L"), dtype=np.float32) / 255.0
ink = 1.0 - gray # strokes are dark on white -> bright ink on black
arr = preprocess(ink)
x = torch.from_numpy(arr)[None, None]
with torch.no_grad():
probs = torch.softmax(model(x), dim=1)[0]
top = probs.argsort(descending=True)[:3]
label = f"### 예측: **{int(top[0])}** ({float(probs[top[0]]):.1%})"
bars = "\n".join(
f"`{int(d)}` {'█' * int(float(probs[d]) * 40)} {float(probs[d]):.1%}"
for d in top)
return label, bars
demo = gr.Interface(
fn=predict,
inputs=gr.Sketchpad(
label="숫자를 그려보세요",
brush=gr.Brush(default_size=20, colors=["#000000"],
color_mode="fixed"),
eraser=gr.Eraser(default_size=40),
),
outputs=[gr.Markdown(label="결과"), gr.Textbox(label="Top-3", lines=3)],
title="MNIST Digit Classifier",
description="손으로 그린 숫자를 CNN(depth=5, val acc 99.7%)으로 분류합니다. "
"a0 프로젝트 실험 모델 데모.",
)
demo.launch(quiet=True)