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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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
import queue
import random
import threading
import tkinter as tk
from pathlib import Path
from tkinter import filedialog, messagebox, ttk

from PIL import Image, ImageOps, ImageTk
import engine


def duration(seconds):
    minutes, seconds = divmod(round(seconds), 60)
    hours, minutes = divmod(minutes, 60)
    if hours:
        return f"{hours}h {minutes:02}m"
    return f"{minutes}m {seconds:02}s" if minutes else f"{seconds}s"


def run(training):
    win = tk.Tk()
    title = "Model trainer" if training else "Image generator"
    win.title(f"AdamIMG  ·  {title}")
    win.configure(bg="#edf1f4")
    style = ttk.Style(win)
    style.theme_use("clam")
    style.configure(".", font=("Segoe UI", 10), background="#ffffff", foreground="#1d3243")
    style.configure("TEntry", padding=5, fieldbackground="#f7f9fa")
    style.configure("TButton", padding=(10, 5))
    style.configure("Primary.TButton", background="#136964", foreground="white")
    style.map("Primary.TButton", background=[("disabled", "#788c8b"), ("active", "#0c5450")])
    style.configure("TProgressbar", troughcolor="#e5edef", background="#208279",
                    borderwidth=0, thickness=8)
    banner = tk.Frame(win, bg="#183744", padx=20, pady=12)
    banner.pack(fill="x")
    tk.Label(banner, text="AdamIMG", font=("Segoe UI", 10, "bold"),
             bg="#183744", fg="#99d7c9").pack(anchor="w")
    tk.Label(banner, text=title, font=("Segoe UI", 19, "bold"),
             bg="#183744", fg="white").pack(side="left")
    tk.Label(banner, text=engine.DEVICE.upper(), font=("Segoe UI", 10),
             bg="#183744", fg="#cce0e5").pack(side="right")
    if training:
        gallery = ttk.Frame(win, padding=12)
        gallery.pack(side="right", fill="y", padx=(0, 14), pady=12)
        gallery_title = tk.StringVar(value="Training previews")
        ttk.Label(gallery, textvariable=gallery_title, font=("Segoe UI", 11, "bold")).pack(anchor="w")
        tiles = ttk.Frame(gallery)
        tiles.pack(anchor="nw", pady=8)
        ttk.Label(tiles, text="Waiting for a training run.").grid()
    panel = ttk.Frame(win, padding=14)
    panel.pack(fill="x", padx=14, pady=(12, 0))
    panel.columnconfigure(1, weight=1)
    events = queue.Queue()
    stop = threading.Event()
    busy = False
    analyzing = False
    size_info = None
    controls = []

    def field(row, title, default, browse=None):
        ttk.Label(panel, text=title).grid(row=row, column=0, sticky="w", padx=(0, 12))
        value = tk.StringVar(value=str(default))
        entry = ttk.Entry(panel, textvariable=value, width=48)
        entry.grid(row=row, column=1, columnspan=1 if browse else 2, sticky="ew", pady=3)
        controls.append(entry)
        if browse:
            def choose():
                path = browse()
                if path:
                    value.set(path)
            button = ttk.Button(panel, text="Browse…", command=choose)
            button.grid(row=row, column=2, padx=(6, 0))
            controls.append(button)
        return value

    ck = field(0, "Output / resume checkpoint" if training else "Checkpoint", engine.CHECKPOINT,
               (lambda: filedialog.asksaveasfilename(defaultextension=".pt", confirmoverwrite=False))
               if training else filedialog.askopenfilename)
    def choice(parent, title, values):
        ttk.Label(parent, text=title).pack(side="left", padx=(8, 3))
        value = tk.StringVar(value=values[0])
        widget = ttk.Combobox(parent, textvariable=value, values=values, state="readonly",
                              width=max(map(len, values)))
        widget.pack(side="left")
        controls.append(widget)
        return value

    geometry_row = ttk.Frame(panel)
    geometry_row.grid(row=4, column=1, columnspan=2, sticky="w")
    if training:
        data = field(1, "Image folder", engine.DATA, filedialog.askdirectory)
        amount = field(2, "Additional steps", "1000")
        base = field(3, "Fine-tune from (optional)", "", filedialog.askopenfilename)
        resolution = tk.StringVar(value="Auto")
        ttk.Label(panel, text="Resolution").grid(row=4, column=0, sticky="w")
        sizes = ttk.Combobox(geometry_row, textvariable=resolution, values=("Auto", "64", "96", "128"),
                             state="readonly", width=10)
        sizes.pack(side="left")
        ratio = choice(geometry_row, "Ratio", ("Auto", *engine.ASPECT_RATIOS))
        framing = choice(geometry_row, "Framing", ("Auto", "Center crop", "Fit with padding"))
        controls.append(sizes)
        rate = field(5, "Learning rate (optional)", "")
        batch = field(6, "Batch size", "16")
        folders = tk.BooleanVar(value=False)
        captions = ttk.Checkbutton(panel, text="Use folder names as captions", variable=folders)
        captions.grid(row=7, column=1, sticky="w")
        controls.append(captions)

        def preset():
            parent = engine.HOME / "model2.pt"
            output = parent.with_name("model2-96px.pt")
            i = 2
            while output.exists():
                output = parent.with_name(f"model2-96px-{i}.pt")
                i += 1
            base.set(str(parent))
            ck.set(str(output))
            resolution.set("96")
            amount.set("2000")
            rate.set("0.0001")
            batch.set("16")

        preset_button = ttk.Button(panel, text="Model2 preset", command=preset)
        preset_button.grid(row=7, column=2)
        controls.append(preset_button)
        preview_prompt = field(8, "Preview prompt", "")
        ttk.Label(panel, text="Leave blank to cycle through dataset captions.",
                  foreground="#42636b").grid(row=9, column=1, columnspan=2, sticky="w")
        ttk.Label(panel, text="Preview schedule").grid(row=10, column=0, sticky="w")
        schedule = ttk.Frame(panel)
        schedule.grid(row=10, column=1, columnspan=2, sticky="w", pady=(4, 0))
        interval = tk.StringVar(value="100")
        count_var = tk.StringVar(value="1")
        for text, var, options in [("Every", interval, None), ("steps · Images", count_var, ("0", "1", "2", "3", "4"))]:
            ttk.Label(schedule, text=text).pack(side="left", padx=(0, 5))
            control = (ttk.Combobox(schedule, values=options, state="readonly", width=3, textvariable=var)
                       if options else ttk.Entry(schedule, width=6, textvariable=var))
            control.pack(side="left", padx=(0, 6))
            controls.append(control)
        ttk.Label(schedule, text="(0 = off)", foreground="#42636b").pack(side="left")
        ttk.Label(panel, text="Additional model blocks").grid(row=11, column=0, sticky="w")
        blocks = tk.DoubleVar(value=0)
        size_label = tk.StringVar()
        block_params = engine.block_parameters()
        advice = tk.StringVar(value="Check the dataset for a suggested size and exact parameter counts.")

        def show_size(*_):
            added = round(blocks.get())
            label = f"+{added} blocks"
            if size_info:
                _, base_count, per_block, _ = size_info
                label += f"  ·  {base_count + added * per_block:,} parameters"
            else:
                label += f"  ·  +{added * block_params:,} parameters"
            size_label.set(label)

        slider = ttk.Scale(panel, from_=0, to=engine.MAX_ADDED_BLOCKS, variable=blocks,
                           command=show_size)
        slider.grid(row=11, column=1, sticky="ew", pady=5)
        controls.append(slider)
        ttk.Label(panel, textvariable=size_label).grid(row=12, column=1, sticky="w")
        ttk.Label(panel, textvariable=advice, wraplength=500, foreground="#42636b").grid(
            row=13, column=0, columnspan=3, sticky="w")

        def reset_size(*_):
            nonlocal size_info
            size_info = None
            advice.set("Check the dataset for a suggested size and exact parameter counts.")
            show_size()

        for setting in (data, folders, ck, base):
            setting.trace_add("write", reset_size)
        show_size()

        def analyze():
            nonlocal busy, analyzing
            if busy:
                return
            root = Path(data.get())
            if not data.get().strip() or not root.is_dir():
                messagebox.showerror("Check settings", "Choose an image folder.")
                return
            checkpoint = Path(base.get().strip()) if base.get().strip() else None
            if checkpoint is None and Path(ck.get()).is_file():
                checkpoint = Path(ck.get())
            use_folders = folders.get()
            reset_size()
            busy = analyzing = True
            stop.clear()
            for control in [go, *controls]:
                control.state(["disabled"])
            status.set("Checking dataset and model size…")
            bar.configure(mode="indeterminate", value=0)
            bar.start(18)

            def scan():
                try:
                    info = engine.analyze_size(root, checkpoint, lambda s: events.put(("status", s)),
                                               stop, use_folders)
                    events.put(("size", info))
                except Exception as exc:
                    events.put(("error", str(exc)))
                finally:
                    events.put(("done", None))
            threading.Thread(target=scan, daemon=True).start()

        analyze_button = ttk.Button(panel, text="Check dataset", command=analyze)
        analyze_button.grid(row=11, column=2, padx=(6, 0))
        controls.append(analyze_button)
    else:
        prompt = field(1, "Prompt", "")
        seed = field(2, "Starting seed (blank for random)", "")
        count_var = tk.StringVar(value="1")
        ttk.Label(panel, text="Images per prompt").grid(row=3, column=0, sticky="w")
        count_box = ttk.Combobox(panel, textvariable=count_var, values=("1", "2", "3", "4"),
                                 state="readonly", width=4)
        count_box.grid(row=3, column=1, sticky="w")
        controls.append(count_box)
        ratio = choice(geometry_row, "Output ratio", ("Auto", *engine.ASPECT_RATIOS))

    activity = ttk.Frame(win, padding=14)
    activity.pack(fill="both", expand=True, padx=14, pady=10)
    status = tk.StringVar(value="Ready to train" if training else "Ready to generate")
    metrics = tk.StringVar()
    ttk.Label(activity, textvariable=status, wraplength=580).pack(anchor="w")
    bar = ttk.Progressbar(activity, maximum=100)
    bar.pack(fill="x", pady=(9, 4))
    ttk.Label(activity, textvariable=metrics, foreground="#42636b").pack(anchor="w")
    if not training:
        preview = ttk.Frame(activity)
        preview.pack(pady=(8, 0))
    actions = ttk.Frame(win, padding=(14, 8))
    actions.pack(fill="x")

    def start():
        nonlocal busy
        if busy:
            return
        try:
            if not ck.get().strip() or Path(ck.get()).is_dir():
                raise ValueError("Choose a checkpoint filename.")
            path = Path(ck.get())
            selected_ratio = None if ratio.get() == "Auto" else ratio.get()
            if training:
                selected_framing = None if framing.get() == "Auto" else framing.get()
                root, steps = Path(data.get()), int(amount.get())
                added = round(blocks.get())
                preview_count = int(count_var.get())
                every = int(interval.get()) if preview_count else 100
                if every < 1:
                    raise ValueError("Steps per preview must be a positive integer.")
                caption = preview_prompt.get().strip()
                folder_captions = folders.get()
                batch_size = int(batch.get())
                if batch_size < 1:
                    raise ValueError("Batch size must be a positive integer.")
                source = Path(base.get().strip()) if base.get().strip() else None
                training_resolution = None if resolution.get() == "Auto" else int(resolution.get())
                lr = float(rate.get()) if rate.get().strip() else None
                if not data.get().strip() or not root.is_dir() or steps < 1:
                    raise ValueError("Choose an image folder and a positive step count.")
            else:
                description = prompt.get().strip()
                number = int(seed.get()) if seed.get().strip() else random.randrange(2**32)
                count = int(count_var.get())
                if number < -(2**63) or number + count > 2**64:
                    raise ValueError("Starting seed is outside the supported range for this batch.")
                if not description or not path.is_file():
                    raise ValueError("Choose a trained checkpoint and enter a prompt.")
        except ValueError as exc:
            messagebox.showerror("Check settings", str(exc))
            return
        stop.clear()
        if training:
            for tile in tiles.winfo_children():
                tile.destroy()
            gallery_title.set("Training previews")
            hint = f"First preview after {every:,} steps." if every <= steps else "Preview interval exceeds this run."
            ttk.Label(tiles, text=hint if preview_count else "Previews disabled.").grid()
        busy = True
        for control in [go, *controls]:
            control.state(["disabled"])
        if training:
            secondary.state(["!disabled"])
        status.set("Preparing training data…" if training else "Loading checkpoint…")
        metrics.set("Estimating after the first training step…" if training else "")
        bar.configure(mode="indeterminate", value=0)
        bar.start(18)

        def worker():
            try:
                if training:
                    completed = engine.train(root, path, steps, stop, lambda s: events.put(("status", s)),
                                         source=source, resolution=training_resolution, aspect_ratio=selected_ratio, framing=selected_framing,
                                         lr=lr, batch_size=batch_size,
                                         folder_captions=folder_captions, add_blocks=added,
                                         progress=lambda *p: events.put(("training", p)),
                                         preview=(lambda *p: events.put(("preview", p))) if preview_count else None,
                                         preview_interval=every, preview_count=preview_count, preview_prompt=caption)
                    if completed == steps:
                        message = "Training complete"
                    elif completed:
                        message = "Training stopped"
                    else:
                        message = "Stopped before the first step"
                    if completed:
                        message += f"  ·  Saved {path.name}"
                    events.put(("finished", message))
                else:
                    model, vocab, size = engine.load_generator(path)
                    if selected_ratio:
                        size = engine.canvas_size(size if isinstance(size, int) else max(size), selected_ratio)
                    for i in range(count):
                        def update(done, total):
                            events.put(("sampling", (i, count, done, total)))
                        image = engine.sample(model, vocab, size, description, number + i, progress=update)
                        events.put(("image", (i, count, image, number + i)))
            except Exception as exc:
                events.put(("error", str(exc)))
            finally:
                events.put(("done", None))
        threading.Thread(target=worker, daemon=True).start()

    def secondary_action():
        if training:
            stop.set()
            secondary.state(["disabled"])
            status.set("Stopping after the current operation…")

    def save_image(image, number):
        path = filedialog.asksaveasfilename(initialfile=f"adamimg-{number}.png",
                                            defaultextension=".png", filetypes=[("PNG", "*.png")])
        if path:
            try:
                image.save(path)
            except OSError as exc:
                messagebox.showerror("Save failed", str(exc))

    def progress(done, total):
        bar.stop()
        bar.configure(mode="determinate", maximum=100, value=100 * done / total)

    def poll():
        nonlocal busy, analyzing, size_info
        while not events.empty():
            kind, val = events.get()
            if kind == "size":
                size_info = val
                if val:
                    images, base_count, per_block, suggested = val
                    advice.set(f"{images:,} unique labeled images · Suggested starting size: "
                               f"+{suggested} blocks ({base_count + suggested * per_block:,} parameters). "
                               "This estimate uses image count alone.")
                    show_size()
                status.set("Dataset check complete" if val else "Dataset check stopped")
                metrics.set("")
            elif kind == "training":
                done, total, step, loss, elapsed = val
                progress(done, total)
                if not stop.is_set():
                    status.set(f"Training  ·  Checkpoint step {step:,}  ·  Loss {loss:.4f}")
                detail = f"{done:,} / {total:,} steps ({100*done/total:.1f}%)  ·  {duration(elapsed)} elapsed"
                if done < total and not stop.is_set():
                    eta = duration(elapsed * (total - done) / done)
                    detail += f"  ·  About {eta} left"
                metrics.set(detail)
            elif kind == "preview":
                step, samples = val
                gallery_title.set(f"Previews · Step {step:,}")
                for tile in tiles.winfo_children():
                    tile.destroy()
                for i, (caption, seed_value, img) in enumerate(samples):
                    tile = ttk.Frame(tiles, padding=3)
                    tile.grid(row=i // 2, column=i % 2, sticky="nw")
                    photo = ImageTk.PhotoImage(ImageOps.contain(img, (112, 112), Image.Resampling.NEAREST))
                    thumb = ttk.Label(tile, image=photo)
                    thumb.image = photo
                    thumb.pack()
                    label = caption if len(caption) <= 54 else caption[:53] + "…"
                    ttk.Label(tile, text=label, wraplength=112).pack(anchor="w")
                    ttk.Label(tile, text=f"Seed {seed_value}", foreground="#42636b").pack(anchor="w")
            elif kind == "sampling":
                i, count, done, total = val
                progress(i * total + done, count * total)
                status.set(f"Generating image {i+1} of {count}…")
                metrics.set(f"Sampling step {done} of {total}")
            elif kind == "image":
                i, count, img, number = val
                if i == 0:
                    for child in preview.winfo_children():
                        child.destroy()
                tile = ttk.Frame(preview, padding=4)
                tile.grid(row=i // 2, column=i % 2)
                width = 256 if count == 1 else 144
                photo = ImageTk.PhotoImage(ImageOps.contain(img, (width, width), Image.Resampling.NEAREST))
                thumb = ttk.Label(tile, image=photo)
                thumb.image = photo
                thumb.pack()
                ttk.Label(tile, text=f"Seed {number}").pack()
                ttk.Button(tile, text="Save PNG", command=lambda im=img, n=number: save_image(im, n)).pack()
                if i+1 == count:
                    status.set("Image ready" if count == 1 else f"{count} images ready")
                    metrics.set(f"{img.width} × {img.height} px")
            elif kind == "error":
                status.set("Dataset check failed" if analyzing else "Training failed" if training else "Generation failed")
                metrics.set("")
                messagebox.showerror("Operation failed", val)
            elif kind == "finished":
                status.set(val)
                if training and size_info and "Saved " in val and not base.get().strip():
                    reset_size()
                if str(bar.cget("mode")) == "indeterminate":
                    metrics.set("")
            elif kind == "status":
                if not stop.is_set():
                    status.set(val)
            elif kind == "done":
                if str(bar.cget("mode")) == "indeterminate":
                    progress(0, 1)
                busy = analyzing = False
                for control in [go, *controls]:
                    control.state(["!disabled"])
                if training:
                    secondary.state(["disabled"])
        win.after(100, poll)

    def close():
        if analyzing:
            stop.set()
            win.destroy()
        elif busy and training:
            secondary_action()
        else:
            win.destroy()

    go = ttk.Button(actions, text="Train / resume" if training else "Generate image",
                    style="Primary.TButton", command=start)
    go.pack(side="left")
    if training:
        secondary = ttk.Button(actions, text="Stop and save", command=secondary_action)
        secondary.pack(side="left", padx=8)
        secondary.state(["disabled"])
    win.protocol("WM_DELETE_WINDOW", close)
    poll()
    win.mainloop()