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")), )