| import byt5_patch |
|
|
| import os |
| import threading |
| import numpy as np |
| import tkinter as tk |
| from tkinter import ttk, messagebox |
| from PIL import Image, ImageTk |
|
|
| import torch |
| from transformers import T5EncoderModel |
| from imagen_pytorch import Unet, Imagen, ImagenTrainer |
|
|
| |
| CHECKPOINT = "runs/checkpoint_step_20000.pt" |
| MODEL_DIR = "google/byt5-small" |
| IMAGE_SIZE = 28 |
| UNET_DIM = 64 |
|
|
| |
|
|
| def get_device(): |
| return torch.device("mps" if torch.backends.mps.is_available() else "cpu") |
|
|
| def load_model(checkpoint_path, device): |
| |
| |
| t5 = T5EncoderModel.from_pretrained(MODEL_DIR) |
| text_dim = int(t5.config.d_model) |
| del t5 |
| |
| |
| unet = Unet( |
| dim=UNET_DIM, |
| cond_dim=text_dim, |
| dim_mults=(1, 2, 4), |
| num_resnet_blocks=2, |
| layer_attns=(False, False, True), |
| layer_cross_attns=(False, True, True), |
| ) |
| |
| imagen = Imagen( |
| unets=unet, |
| text_encoder_name=MODEL_DIR, |
| image_sizes=IMAGE_SIZE, |
| timesteps=250, |
| cond_drop_prob=0.1, |
| ).to(device) |
| |
| trainer = ImagenTrainer(imagen=imagen).to(device) |
| |
| print(f"[INFO] Loading checkpoint: {checkpoint_path}") |
| trainer.load(checkpoint_path) |
| trainer.eval() |
| |
| return trainer |
|
|
| |
| class DiffusionApp: |
| def __init__(self, root: tk.Tk, checkpoint_path: str): |
| self.root = root |
| root.title("BULaMU-Dream") |
| |
| self.device = get_device() |
| print(f"[INFO] Using device: {self.device}") |
| |
| |
| try: |
| self.trainer = load_model(checkpoint_path, self.device) |
| print("[INFO] Model loaded successfully") |
| except Exception as e: |
| messagebox.showerror("Model load failed", str(e)) |
| raise |
| |
| |
| self.prompts = [ |
| "Bbuutu y'enkizi", |
| "Ekiteeteeyi/eky'okungulu", |
| "Ekiteteeyi", |
| "Empale", |
| "Ensawo", |
| "Kooti", |
| "Pulover ya Pulover", |
| "Saati", |
| "Sandal", |
| "Sneaker", |
| ] |
| |
| |
| self.prompt_var = tk.StringVar(value=self.prompts[0]) |
| self.status_var = tk.StringVar(value="Ready.") |
| self.cond_scale_var = tk.DoubleVar(value=1.0) |
| |
| top = ttk.Frame(root, padding=10) |
| top.pack(fill="x") |
| |
| ttk.Label(top, text="Prompt:").pack(side="left") |
| self.prompt_dropdown = ttk.Combobox(top, textvariable=self.prompt_var, |
| values=self.prompts, state="readonly", width=30) |
| self.prompt_dropdown.pack(side="left", padx=8) |
| |
| ttk.Label(top, text="Cond Scale:").pack(side="left") |
| self.scale_spin = ttk.Spinbox(top, from_=0.1, to=10.0, increment=0.5, |
| textvariable=self.cond_scale_var, width=6) |
| self.scale_spin.pack(side="left", padx=8) |
| |
| self.btn = ttk.Button(top, text="Generate", command=self.on_generate) |
| self.btn.pack(side="left", padx=8) |
| |
| self.stop_btn = ttk.Button(top, text="Stop", command=self.on_stop, state="disabled") |
| self.stop_btn.pack(side="left") |
| |
| ttk.Label(root, textvariable=self.status_var, padding=10).pack(fill="x") |
| |
| |
| self.canvas_size = IMAGE_SIZE * 10 |
| self.canvas = tk.Canvas(root, width=self.canvas_size, height=self.canvas_size, bg="black") |
| self.canvas.pack(padx=10, pady=10) |
| |
| self.tk_img = None |
| self.canvas_img_id = None |
| |
| self._stop_flag = False |
| self._worker = None |
| |
| |
| self.show_image((np.random.rand(IMAGE_SIZE, IMAGE_SIZE, 3) * 255).astype(np.uint8)) |
| |
| def on_stop(self): |
| self._stop_flag = True |
| self.status_var.set("Stopping...") |
| |
| def on_generate(self): |
| if self._worker and self._worker.is_alive(): |
| return |
| |
| self._stop_flag = False |
| self.btn.config(state="disabled") |
| self.stop_btn.config(state="normal") |
| |
| prompt = self.prompt_var.get().strip() |
| cond_scale = float(self.cond_scale_var.get()) |
| |
| self._worker = threading.Thread(target=self.generate_worker, |
| args=(prompt, cond_scale), daemon=True) |
| self._worker.start() |
| |
| def generate_worker(self, prompt: str, cond_scale: float): |
| try: |
| self.status_var.set(f"Generating '{prompt}' (scale={cond_scale:.1f})...") |
| |
| with torch.no_grad(): |
| samples = self.trainer.sample( |
| texts=[prompt], |
| cond_scale=cond_scale, |
| stop_at_unet_number=1, |
| return_pil_images=False, |
| ) |
| |
| |
| img = samples[0].clamp(0, 1).cpu() |
| img_np = (img.permute(1, 2, 0).numpy() * 255).astype(np.uint8) |
| |
| self.root.after(0, self.show_image, img_np) |
| self.status_var.set("Done.") |
| |
| except Exception as e: |
| self.status_var.set("Error.") |
| messagebox.showerror("Generation failed", str(e)) |
| import traceback |
| traceback.print_exc() |
| finally: |
| self.btn.config(state="normal") |
| self.stop_btn.config(state="disabled") |
| |
| def show_image(self, img_uint8_hwc): |
| pil = Image.fromarray(img_uint8_hwc) |
| pil = pil.resize((self.canvas_size, self.canvas_size), resample=Image.NEAREST) |
| |
| self.tk_img = ImageTk.PhotoImage(pil) |
| if self.canvas_img_id is None: |
| self.canvas_img_id = self.canvas.create_image( |
| self.canvas_size // 2, self.canvas_size // 2, image=self.tk_img |
| ) |
| else: |
| self.canvas.itemconfig(self.canvas_img_id, image=self.tk_img) |
|
|
|
|
| def main(): |
| import sys |
| |
| checkpoint = CHECKPOINT |
| if len(sys.argv) > 1: |
| checkpoint = sys.argv[1] |
| |
| if not os.path.exists(checkpoint): |
| print(f"Error: Checkpoint not found: {checkpoint}") |
| print(f"Usage: python3 {sys.argv[0]} [checkpoint_path]") |
| print(f"Example: python3 {sys.argv[0]} runs/checkpoint_step_20000.pt") |
| sys.exit(1) |
| |
| root = tk.Tk() |
| _ = DiffusionApp(root, checkpoint) |
| root.mainloop() |
|
|
|
|
| if __name__ == "__main__": |
| main() |