File size: 9,329 Bytes
8ce6557
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
618ca1d
 
8ce6557
 
 
 
 
 
 
 
 
 
 
 
 
 
eff825d
8ce6557
618ca1d
 
eff825d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8ce6557
eff825d
 
8ce6557
eff825d
 
 
8ce6557
eff825d
 
 
618ca1d
 
eff825d
 
 
 
 
8ce6557
618ca1d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8ce6557
 
 
 
 
eff825d
 
 
8ce6557
 
eff825d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8ce6557
 
 
 
 
 
 
 
 
 
 
618ca1d
8ce6557
eff825d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
618ca1d
 
eff825d
 
 
 
 
8ce6557
 
618ca1d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8ce6557
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66d6361
 
 
 
 
8ce6557
66d6361
618ca1d
8ce6557
 
 
 
 
eff825d
8ce6557
 
 
 
 
 
 
 
 
 
 
618ca1d
8ce6557
 
eff825d
8ce6557
 
618ca1d
 
 
 
 
 
 
 
 
 
 
 
8ce6557
 
 
 
 
 
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
from pathlib import Path

from src.handwriting.runtime import configure_runtime

configure_runtime()

import os

import gradio as gr
import numpy as np
import torch
from PIL import Image

from src.handwriting.ga import evolve_digit
from src.handwriting.infer import load_model, predict_single
from src.handwriting.preprocess import normalize_mnist
from src.handwriting.prototypes import load_prototypes
from src.handwriting.diffusion import load_ddpm


def to_mnist_tensor(img: Image.Image) -> torch.Tensor:
    img = img.convert("L").resize((28, 28), resample=Image.BILINEAR)
    arr = np.array(img).astype(np.float32) / 255.0
    arr = 1.0 - arr
    arr = np.clip(arr, 0.0, 1.0)
    t = torch.from_numpy(arr)[None, None, :, :]
    return t


class AppState:
    def __init__(self) -> None:
        self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
        self.weights_path = self._resolve_weights_path()
        self.model = None
        self.prototypes = None
        self.ddpm = None
        self.last_error = ""

    def _resolve_weights_path(self) -> Path:
        env = os.getenv("WEIGHTS_PATH")
        if env:
            return Path(env)
        candidates = [
            Path("cnn_mnist.pt"),
            Path("artifacts") / "cnn_mnist.pt",
        ]
        for p in candidates:
            if p.exists():
                return p
        return candidates[0]

    def ensure_model(self) -> tuple[bool, str]:
        if self.model is not None:
            return True, ""
        self.weights_path = self._resolve_weights_path()
        if not self.weights_path.exists():
            self.last_error = (
                "未找到模型权重文件。请先本地训练生成 `artifacts/cnn_mnist.pt`,"
                "然后将其放到项目根目录并命名为 `cnn_mnist.pt`,或设置环境变量 WEIGHTS_PATH 指向它。"
            )
            return False, self.last_error
        try:
            self.model = load_model(weights_path=self.weights_path, device=self.device)
            self.prototypes = self._try_load_prototypes()
            self.ddpm = self._try_load_ddpm()
            self.last_error = ""
            return True, ""
        except Exception as e:
            self.last_error = f"模型加载失败:{type(e).__name__}: {e}"
            return False, self.last_error

    def _try_load_prototypes(self):
        env = os.getenv("PROTOTYPES_PATH")
        candidates = []
        if env:
            candidates.append(Path(env))
        candidates.extend([
            Path("prototypes.pt"),
            Path("artifacts") / "prototypes.pt",
        ])
        for p in candidates:
            if p.exists():
                try:
                    return load_prototypes(p, device=self.device).vectors
                except Exception:
                    return None
        return None

    def _try_load_ddpm(self):
        env = os.getenv("DDPM_WEIGHTS_PATH")
        candidates = []
        if env:
            candidates.append(Path(env))
        candidates.extend([
            Path("ddpm_mnist.pt"),
            Path("artifacts") / "ddpm_mnist.pt",
        ])
        for p in candidates:
            if p.exists():
                try:
                    ddpm, _ = load_ddpm(p, device=self.device)
                    return ddpm
                except Exception:
                    return None
        return None


STATE = AppState()


def classify_drawn(img) -> tuple[str, float]:
    ok, msg = STATE.ensure_model()
    if not ok:
        return msg, 0.0
    if img is None:
        return "", 0.0
    try:
        if isinstance(img, dict):
            if "composite" in img and img["composite"] is not None:
                img = img["composite"]
            elif "layers" in img and img["layers"]:
                img = img["layers"][-1]
            elif "image" in img and img["image"] is not None:
                img = img["image"]

        if isinstance(img, np.ndarray):
            pil = Image.fromarray(img)
        else:
            pil = img
        x = normalize_mnist(to_mnist_tensor(pil).to(STATE.device))
        label, conf = predict_single(STATE.model, x)
        return str(label), float(conf)
    except Exception as e:
        return f"识别失败:{type(e).__name__}: {e}", 0.0


def generate_digit(
    target: int,
    generations: int,
    pop_size: int,
    elite: int,
    mutation_rate: float,
    mutation_sigma: float,
    crossover_rate: float,
    smoothness: float,
    proto_weight: float,
    seed: int,
) -> tuple[Image.Image | None, float, str]:
    ok, msg = STATE.ensure_model()
    if not ok:
        return None, 0.0, msg
    try:
        result = evolve_digit(
            model=STATE.model,
            device=STATE.device,
            target=int(target),
            generations=int(generations),
            pop_size=int(pop_size),
            elite=int(elite),
            mutation_rate=float(mutation_rate),
            mutation_sigma=float(mutation_sigma),
            crossover_rate=float(crossover_rate),
            smoothness=float(smoothness),
            prototypes=STATE.prototypes,
            proto_weight=float(proto_weight),
            seed=int(seed),
        )
        return result.to_pil(), float(result.target_confidence), ""
    except Exception as e:
        return None, 0.0, f"生成失败:{type(e).__name__}: {e}"


def generate_ddpm(target: int, steps: int, seed: int) -> tuple[Image.Image | None, str]:
    ok, msg = STATE.ensure_model()
    if not ok:
        return None, msg
    if STATE.ddpm is None:
        return (
            None,
            "未找到DDPM权重。请先运行 train_ddpm.py 生成 `artifacts/ddpm_mnist.pt`,"
            "并在部署时上传到 Space(或设置环境变量 DDPM_WEIGHTS_PATH 指向它)。",
        )
    try:
        torch.manual_seed(int(seed))
        torch.cuda.manual_seed_all(int(seed))
        y = torch.full((1,), int(target), device=STATE.device, dtype=torch.long)
        x = STATE.ddpm.sample(y=y, steps=int(steps))
        x = x.detach().float().cpu().clamp(-1, 1)
        x = (x + 1.0) * 0.5
        arr = (x[0, 0].numpy() * 255.0).clip(0, 255).astype(np.uint8)
        return Image.fromarray(arr, mode="L"), ""
    except Exception as e:
        return None, f"DDPM生成失败:{type(e).__name__}: {e}"


with gr.Blocks(title="手写数字识别与生成") as demo:
    gr.Markdown("# 交互式手写数字识别与生成(MNIST)")

    with gr.Row():
        with gr.Column():
            canvas = gr.Sketchpad(
                label="手写输入(建议用粗一些的笔画)",
                height=280,
                width=280,
            )
            pred_digit = gr.Textbox(label="识别结果")
            pred_conf = gr.Number(label="置信度", precision=4)
            canvas.change(fn=classify_drawn, inputs=canvas, outputs=[pred_digit, pred_conf])

        with gr.Column():
            target = gr.Dropdown(
                choices=[str(i) for i in range(10)], value="3", label="目标数字"
            )
            generations = gr.Slider(50, 400, value=300, step=10, label="迭代代数")
            pop_size = gr.Slider(50, 400, value=240, step=10, label="种群大小")
            elite = gr.Slider(2, 50, value=24, step=1, label="精英保留")
            mutation_rate = gr.Slider(0.0, 0.3, value=0.05, step=0.01, label="变异概率")
            mutation_sigma = gr.Slider(0.05, 0.6, value=0.15, step=0.01, label="变异强度")
            crossover_rate = gr.Slider(0.0, 1.0, value=0.75, step=0.05, label="交叉概率")
            smoothness = gr.Slider(0.0, 0.1, value=0.06, step=0.005, label="平滑正则")
            proto_weight = gr.Slider(0.0, 2.0, value=0.6, step=0.05, label="对比约束")
            seed = gr.Number(value=7, precision=0, label="随机种子")

            btn = gr.Button("生成")
            gen_img = gr.Image(label="生成结果", height=280, width=280)
            gen_conf = gr.Number(label="生成图像的目标置信度", precision=4)
            gen_status = gr.Textbox(label="生成状态")
            btn.click(
                fn=generate_digit,
                inputs=[
                    target,
                    generations,
                    pop_size,
                    elite,
                    mutation_rate,
                    mutation_sigma,
                    crossover_rate,
                    smoothness,
                    proto_weight,
                    seed,
                ],
                outputs=[gen_img, gen_conf, gen_status],
            )

            gr.Markdown("## Diffusion 生成(Conditional DDPM)")
            ddpm_steps = gr.Slider(10, 200, value=50, step=5, label="采样步数")
            ddpm_seed = gr.Number(value=7, precision=0, label="随机种子")
            ddpm_btn = gr.Button("DDPM生成")
            ddpm_img = gr.Image(label="DDPM结果", height=280, width=280)
            ddpm_status = gr.Textbox(label="DDPM状态")
            ddpm_btn.click(
                fn=generate_ddpm,
                inputs=[target, ddpm_steps, ddpm_seed],
                outputs=[ddpm_img, ddpm_status],
            )


if __name__ == "__main__":
    demo.launch(
        server_name="0.0.0.0",
        server_port=int(os.getenv("PORT", "7860")),
    )