File size: 3,054 Bytes
7f7cf81
ac29556
 
 
7f7cf81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac29556
 
 
 
 
 
 
 
 
7f7cf81
 
 
 
 
 
ac29556
 
 
 
 
 
 
 
 
7f7cf81
 
c39c3ec
 
 
ac29556
 
 
 
7f7cf81
ac29556
7f7cf81
ac29556
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f7cf81
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
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)