forked from tpc2233/tunet
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtunet.py
More file actions
2815 lines (2526 loc) · 119 KB
/
Copy pathtunet.py
File metadata and controls
2815 lines (2526 loc) · 119 KB
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
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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# ==============================================================================
# TuNet Combined UI — Training + Inference
#
# A unified PySide6 desktop application combining training control and
# batch inference into a single window, organized by workflow stage.
#
# Tabs: Data | Training | Previews | Export | Inference | About
#
# require: pip install PySide6
# ==============================================================================
import sys
import os
import json
import math
import queue
import shutil
import subprocess
import tempfile
import threading
import signal
import yaml
import logging
import time
import re
from pathlib import Path
from glob import glob as globglob
import platform
from PySide6.QtWidgets import (
QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, QTabWidget,
QLabel, QLineEdit, QPushButton, QComboBox, QSpinBox, QCheckBox,
QTextEdit, QFileDialog, QFormLayout, QMessageBox, QSizePolicy, QScrollArea,
QSplitter, QProgressDialog, QDoubleSpinBox, QListWidget, QGroupBox,
QProgressBar, QStackedWidget, QFrame, QSlider,
)
from PySide6.QtCore import Qt, QObject, Signal, Slot, QFileSystemWatcher, QTimer, QThread
from PySide6.QtGui import QPixmap, QTextCursor, QIcon, QPainter, QColor, QFont, QPen, QBrush, QPainterPath
from gui import (
IndentDumper, ProcessStreamReader, FileCopyWorker, ZoomPanScrollArea, QTextEditLogHandler,
NoScrollEventFilter,
DataTabMixin, TrainingTabMixin, PreviewsTabMixin, ExportTabMixin, InferenceTabMixin, AboutTabMixin,
)
# =============================================================================
# Session file paths
# =============================================================================
_APP_DIR = Path(__file__).parent
_SESSION_FILE = _APP_DIR / 'tunet_session.yaml'
_LEGACY_INFERENCE_SETTINGS = _APP_DIR / 'inference_gui_settings.json'
# =============================================================================
# MainWindow
# =============================================================================
class MainWindow(DataTabMixin, TrainingTabMixin, PreviewsTabMixin, ExportTabMixin, InferenceTabMixin, AboutTabMixin, QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle(f"TuNet — {platform.system()}")
self.setGeometry(100, 100, 1000, 750)
# --- Training state ---
self.process = None
self.utility_process = None
self.config_file_path = Path("config_from_ui.yaml")
self.training_queue = []
self.queue_running = False
self.queue_stop_requested = False
self._last_config_dir = ""
self.copy_thread = None
self.conversion_target = None
# --- Preview state ---
self.preview_image_path = None
self.val_preview_image_path = None
self.original_pixmap = None
self.val_original_pixmap = None
self._preview_zoom_factor = None
self._val_preview_zoom_factor = None
# --- Inference state ---
self.inference_running = False
self.inference_stop_requested = False
self.inference_queue = []
self._cached_model = None
self._cached_checkpoint = None
self._cached_resolution = None
self._cached_loss_mode = None
self._cached_color_space = 'srgb'
self._cached_predict_residual = False
# --- Build UI ---
self.central_widget = QWidget()
self.setCentralWidget(self.central_widget)
self.main_layout = QHBoxLayout(self.central_widget)
# Left side: tabs + console + bottom controls
left_layout = QVBoxLayout()
self.tabs = QTabWidget()
self.console_output = QTextEdit()
self.console_output.setReadOnly(True)
self.console_output.setFontFamily("monospace")
self.console_output.setPlaceholderText("Console — training output will appear here")
splitter = QSplitter(Qt.Vertical)
splitter.addWidget(self.tabs)
splitter.addWidget(self.console_output)
splitter.setSizes([550, 150])
left_layout.addWidget(splitter)
left_layout.addLayout(self._create_control_panel())
self.main_layout.addLayout(left_layout, stretch=1)
# Right side: context-sensitive sidebar
self.main_layout.addLayout(self._create_sidebar())
# --- Create tabs ---
self._create_training_tab() # Tab 0 (includes project folder)
self._create_previews_tab() # Tab 1
self._create_export_tab() # Tab 2
self._create_inference_tab() # Tab 3
self._create_about_tab() # Tab 4
# Remember the inference tab index for sidebar switching
self._inference_tab_index = 3
# --- Prevent scroll-wheel from changing unfocused widgets ---
self._no_scroll_filter = NoScrollEventFilter(self)
from PySide6.QtWidgets import QComboBox, QSpinBox, QDoubleSpinBox, QAbstractSlider
for widget_type in (QComboBox, QSpinBox, QDoubleSpinBox, QAbstractSlider):
for w in self.findChildren(widget_type):
w.setFocusPolicy(Qt.StrongFocus)
w.installEventFilter(self._no_scroll_filter)
# --- Signals ---
self.tabs.currentChanged.connect(self._on_tab_changed)
self.verify_btn.clicked.connect(self._verify_inputs)
# --- File watcher for previews ---
self.file_watcher = QFileSystemWatcher()
self.file_watcher.fileChanged.connect(self._on_watched_file_changed)
# --- Timers ---
self.preview_timer = QTimer(self)
self.preview_timer.setInterval(2500)
self.preview_timer.timeout.connect(self._update_all_previews)
self.process_monitor = QTimer(self)
self.process_monitor.setInterval(500)
self.process_monitor.timeout.connect(self._check_process_status)
self.utility_monitor = QTimer(self)
self.utility_monitor.setInterval(500)
self.utility_monitor.timeout.connect(self._check_utility_status)
# --- Logging handler for inference ---
self._log_handler = QTextEditLogHandler(self.console_output)
self._log_handler.setFormatter(logging.Formatter('%(asctime)s - %(message)s', datefmt='%H:%M:%S'))
logging.getLogger().addHandler(self._log_handler)
logging.getLogger().setLevel(logging.INFO)
# --- Populate defaults ---
self._load_session()
# =========================================================================
# UI helpers
# =========================================================================
def _create_path_selector(self, label_text, is_output=False, is_file=False, file_filter=None):
"""Create a line edit + browse button widget."""
widget = QWidget()
layout = QHBoxLayout(widget)
layout.setContentsMargins(0, 0, 0, 0)
line_edit = QLineEdit()
button = QPushButton("Browse...")
if is_file:
if file_filter:
button.clicked.connect(lambda: self._select_file(line_edit, file_filter))
else:
button.clicked.connect(lambda: self._select_file(line_edit, "Python Files (*.py)"))
else:
button.clicked.connect(lambda: self._select_directory(line_edit))
layout.addWidget(line_edit)
layout.addWidget(button)
if is_output:
line_edit.textChanged.connect(self._setup_preview_watcher)
return widget
def _select_directory(self, line_edit):
dir_path = QFileDialog.getExistingDirectory(self, "Select Directory")
if dir_path:
line_edit.setText(dir_path)
def _select_file(self, line_edit, file_filter):
file_path, _ = QFileDialog.getOpenFileName(self, "Select File", "", file_filter)
if file_path:
line_edit.setText(file_path)
def _show_skip_filter_preview(self):
"""Scan dataset patches and show a live grid of kept (green) vs skipped (red) patches."""
import numpy as np
from glob import glob as _glob
from PIL import Image as _Image, ImageDraw, ImageFilter
from PySide6.QtGui import QImage
def _refine_mask_np(diff_uint8, gamma=1.0):
"""Numpy port of training/loss.py:refine_auto_mask, computed at the
thumbnail's resolution for fast preview. Input is a uint8 grayscale
diff (0-255); returns uint8 mask (0-255). Visual fidelity not
byte-exact with the runtime mask (PIL gaussian vs torch's, no
torch-style edge handling) — close enough for picking a gamma."""
diff = diff_uint8.astype(np.float32) / 255.0
res = diff.shape[-1]
# Match the runtime's kernel size scaling (max(31, 31*res/256)).
# PIL's GaussianBlur radius ≈ sigma; sigma ≈ kernel/6 is a fine
# approximation for visual purposes.
kernel = max(31, int(31 * res / 256) | 1)
pil = _Image.fromarray((diff * 255).astype(np.uint8), mode='L')
pil = pil.filter(ImageFilter.GaussianBlur(radius=kernel / 6.0))
diff = np.array(pil, dtype=np.float32) / 255.0
max_val = float(diff.max()) + 1e-8
if max_val < 0.01:
return np.zeros_like(diff_uint8)
diff = diff / max_val
diff = 1.0 / (1.0 + np.exp(-20.0 * (diff - 0.15)))
mn = float(diff.min())
mx = float(diff.max())
diff = (diff - mn) / (mx - mn + 1e-8)
if gamma != 1.0:
diff = np.power(diff, gamma)
return (diff * 255).clip(0, 255).astype(np.uint8)
src_dir = self._get_path(self.src_dir_input).strip()
dst_dir = self._get_path(self.dst_dir_input).strip()
if not src_dir or not os.path.isdir(src_dir):
QMessageBox.warning(self, "Skip Filter Preview", "Source directory not set.")
return
if not dst_dir or not os.path.isdir(dst_dir):
QMessageBox.warning(self, "Skip Filter Preview", "Target directory not set.")
return
resolution = int(self._combo_value(self.resolution_input))
overlap_factor = float(self._combo_value(self.overlap_factor_input))
stride = max(1, resolution - int(resolution * overlap_factor))
color_space = self.color_space_input.currentText()
is_linear = color_space == 'linear'
# --- Build the window ---
win = QWidget(self, Qt.WindowType.Window)
win.setWindowTitle("Skip Filter Preview")
win.resize(1200, 800)
win_layout = QVBoxLayout(win)
# Controls row
ctrl_row = QHBoxLayout()
thresh_label = QLabel("Threshold:")
thresh_spin = QDoubleSpinBox()
thresh_spin.setRange(0.1, 50.0)
thresh_spin.setSingleStep(0.5)
thresh_spin.setDecimals(1)
thresh_spin.setValue(self.skip_empty_threshold_input.value())
size_label = QLabel("Size:")
size_slider = QSlider(Qt.Orientation.Horizontal)
size_slider.setRange(40, 200)
size_slider.setValue(80)
size_slider.setFixedWidth(120)
size_slider.setTickInterval(20)
sort_check = QCheckBox("Sort skipped first")
# View selector: Source / Diff / Mask. Diff shows |src - dst| amplified
# by `amp`; Mask shows the auto-mask that training will actually weight
# the loss with, computed at the current `gamma`. Picking a gamma here
# before training is way cheaper than burning compute to find out the
# mask collapses to 100%-coverage.
view_label = QLabel("View:")
view_combo = QComboBox()
view_combo.addItems(["Source", "Diff", "Mask"])
view_combo.setToolTip(
"What each tile shows:\n\n"
" Source — the src patch as-is.\n"
" Diff — |src - dst| as a grayscale map (use Amp to brighten).\n"
" Mask — the auto-mask weight map at the current gamma. This\n"
" is the actual signal training will weight the loss by.\n"
" Coverage / mean stats appear in the stats line.")
# Multiplier applied to raw diff (0-255) before display. 1× shows the
# raw signal; higher values make faint smudges glow. Re-render only —
# doesn't affect the threshold math, which always uses raw max_diff.
amp_label = QLabel("Amp:")
amp_spin = QDoubleSpinBox()
amp_spin.setRange(1.0, 20.0)
amp_spin.setSingleStep(0.5)
amp_spin.setDecimals(1)
amp_spin.setValue(2.5)
amp_spin.setSuffix("×")
amp_spin.setFixedWidth(70)
amp_spin.setToolTip(
"Multiplier applied to the diff brightness before display.\n\n"
" 1.0× — raw diff (faint smudges may be hard to see)\n"
" 2.5× — default; good for most data\n"
" 5–10× — for very small or low-contrast regions of interest\n"
" 20× — saturates aggressively; useful for finding sub-pixel diffs\n\n"
"Affects display only — the skip-empty threshold above still "
"uses the raw diff values, so cranking amp doesn't change which "
"patches are kept vs skipped.")
# Gamma applied to the auto-mask preview. Mirrors the actual training
# path (training/loss.py:refine_auto_mask) so you can pick a gamma
# that gives sensible coverage *before* committing to a run.
gamma_label = QLabel("Gamma:")
gamma_spin = QDoubleSpinBox()
gamma_spin.setRange(0.1, 3.0)
gamma_spin.setSingleStep(0.1)
gamma_spin.setDecimals(2)
gamma_spin.setValue(self.auto_mask_gamma_input.value() if hasattr(self, 'auto_mask_gamma_input') else 1.0)
gamma_spin.setFixedWidth(70)
gamma_spin.setToolTip(
"Gamma applied to the auto-mask weight map.\n\n"
" < 1.0 — expands white (e.g. 0.5 makes weak signals louder).\n"
" Watch out for coverage ≈ 100% — every pixel weighted.\n"
" 1.0 — no adjustment (raw normalized mask).\n"
" > 1.0 — contracts the mask, focusing on strong signals.\n"
" Good when src/dst pairs have noise everywhere.\n"
" 2.0+ — very tight, only the brightest diff regions stay white.\n\n"
"Changing here also updates the Auto Mask Gamma in the main form\n"
"so you can preview, find a good value, then close the dialog.")
stats_label = QLabel("Scanning…")
stats_label.setStyleSheet("font-weight: bold;")
ctrl_row.addWidget(thresh_label)
ctrl_row.addWidget(thresh_spin)
ctrl_row.addSpacing(16)
ctrl_row.addWidget(size_label)
ctrl_row.addWidget(size_slider)
ctrl_row.addSpacing(16)
ctrl_row.addWidget(sort_check)
ctrl_row.addSpacing(12)
ctrl_row.addWidget(view_label)
ctrl_row.addWidget(view_combo)
ctrl_row.addSpacing(4)
ctrl_row.addWidget(amp_label)
ctrl_row.addWidget(amp_spin)
ctrl_row.addWidget(gamma_label)
ctrl_row.addWidget(gamma_spin)
ctrl_row.addStretch()
ctrl_row.addWidget(stats_label)
win_layout.addLayout(ctrl_row)
# Hide the per-view controls until they're relevant — the controls row
# would get crowded if Amp + Gamma were always visible side-by-side.
def _sync_view_controls():
v = view_combo.currentText()
for w in (amp_label, amp_spin):
w.setVisible(v == 'Diff')
for w in (gamma_label, gamma_spin):
w.setVisible(v == 'Mask')
_sync_view_controls()
view_combo.currentTextChanged.connect(lambda _: _sync_view_controls())
# Scroll area for the grid
scroll = QScrollArea()
scroll.setWidgetResizable(True)
grid_container = QWidget()
grid_layout = QVBoxLayout(grid_container)
grid_layout.setSpacing(2)
scroll.setWidget(grid_container)
win_layout.addWidget(scroll)
win.show()
# patch_data stores full-res (SCAN_SIZE) thumbnails; render scales to current slider value
SCAN_SIZE = 128
patch_data = [] # list of (max_diff, PIL Image at SCAN_SIZE)
scan_errors = []
def _scan():
from utils.pair_matching import find_dst_file
from image_io import load_image_any_format, load_image_linear, linear_to_log
src_files = sorted(_glob(os.path.join(src_dir, '*.*')))
no_dst = 0
for src_path in src_files:
dst_path = find_dst_file(src_path, dst_dir)
if dst_path is None:
no_dst += 1
continue
try:
if is_linear:
src_np = load_image_linear(src_path).astype(np.float32)
dst_np = load_image_linear(dst_path).astype(np.float32)
h, w = src_np.shape[:2]
dh, dw = dst_np.shape[:2]
diff = np.abs(linear_to_log(src_np) - linear_to_log(dst_np)).mean(axis=2) * 255.0
src_display = (src_np / (1.0 + src_np) * 255).clip(0, 255).astype(np.uint8)
else:
src_pil = load_image_any_format(src_path)
dst_pil = load_image_any_format(dst_path)
w, h = src_pil.size
dw, dh = dst_pil.size
src_np = np.array(src_pil).astype(np.float32)
dst_np = np.array(dst_pil).astype(np.float32)
diff = np.abs(src_np - dst_np).mean(axis=2)
src_display = src_np.clip(0, 255).astype(np.uint8)
src_pil.close(); dst_pil.close()
if (w, h) != (dw, dh) or w < resolution or h < resolution:
continue
y_coords = list(range(0, max(0, h - resolution) + 1, stride))
x_coords = list(range(0, max(0, w - resolution) + 1, stride))
if h > resolution and (h - resolution) % stride != 0:
y_coords.append(h - resolution)
if w > resolution and (w - resolution) % stride != 0:
x_coords.append(w - resolution)
for y in sorted(set(y_coords)):
for x in sorted(set(x_coords)):
patch_diff = diff[y:y+resolution, x:x+resolution]
max_diff = float(patch_diff.max())
patch_rgb = src_display[y:y+resolution, x:x+resolution]
src_thumb = _Image.fromarray(patch_rgb).resize((SCAN_SIZE, SCAN_SIZE), _Image.BILINEAR)
# Pre-shrink the diff to SCAN_SIZE and store as raw
# uint8 (0-255). Amplification happens at render
# time so the user can crank it interactively
# without re-scanning the dataset. PIL.NEAREST so
# we preserve max values for the brightest pixel
# rather than smoothing them away.
diff_raw_pil = _Image.fromarray(
patch_diff.clip(0, 255).astype(np.uint8), mode='L'
).resize((SCAN_SIZE, SCAN_SIZE), _Image.BILINEAR)
diff_raw = np.array(diff_raw_pil, dtype=np.uint8)
patch_data.append((max_diff, src_thumb, diff_raw))
except Exception as e:
scan_errors.append(f"{os.path.basename(src_path)}: {e}")
if no_dst == len(src_files) and len(src_files) > 0:
scan_errors.append(f"No destination matches found for any of {len(src_files)} source files.")
stats_label.setText("Scanning…")
scan_thread = threading.Thread(target=_scan, daemon=True)
scan_thread.start()
def _wait_for_scan():
if scan_thread.is_alive():
QTimer.singleShot(150, _wait_for_scan)
return
if scan_errors and not patch_data:
stats_label.setText(f"<span style='color:#EF4444'>Scan failed: {scan_errors[0]}</span>")
return
_render_grid()
def _render_grid():
threshold = thresh_spin.value()
thumb_size = size_slider.value()
do_sort = sort_check.isChecked()
view = view_combo.currentText()
amp = amp_spin.value()
gamma = gamma_spin.value()
# Clear existing grid
while grid_layout.count():
item = grid_layout.takeAt(0)
if item.widget():
item.widget().deleteLater()
kept = sum(1 for d, _, _ in patch_data if d >= threshold)
skipped = len(patch_data) - kept
base_stats = (
f"Total: {len(patch_data)} "
f"<span style='color:#16A34A'>Kept: {kept}</span> "
f"<span style='color:#EF4444'>Skipped: {skipped}</span> "
f"({100*skipped/max(1,len(patch_data)):.0f}% filtered)"
)
# Pre-compute mask thumbnails for Mask view + aggregate coverage
# so the stats line can show the same numbers training prints in
# the [Mask diag] log on the first step.
mask_thumbs = None
if view == 'Mask' and patch_data:
mask_thumbs = []
total_pixels = 0
covered_pixels = 0
weight_sum = 0.0
weight_max = 0.0
# mask_weight is read from the main form. weight_map is
# 1 + mask * (mask_weight - 1), matching training/loss.py.
try:
mw = float(self.mask_weight_input.value())
except Exception:
mw = 10.0
for _, _, diff_raw in patch_data:
mask = _refine_mask_np(diff_raw, gamma=gamma)
mask_thumbs.append(mask)
weight_map = 1.0 + (mask.astype(np.float32) / 255.0) * (mw - 1.0)
total_pixels += weight_map.size
covered_pixels += int((weight_map > 1.0).sum())
weight_sum += float(weight_map.sum())
if weight_map.max() > weight_max:
weight_max = float(weight_map.max())
if total_pixels > 0:
coverage = 100.0 * covered_pixels / total_pixels
mean_w = weight_sum / total_pixels
base_stats += (
f" | <span style='color:#7E3AF2'>"
f"coverage={coverage:.1f}% mean_w={mean_w:.2f} max_w={weight_max:.1f}"
f"</span>"
)
stats_label.setText(base_stats)
items = list(enumerate(patch_data))
if do_sort:
# skipped (red) first, then kept (green), each group by ascending diff
items.sort(key=lambda it: (it[1][0] >= threshold, it[1][0]))
else:
# preserve original order but stable-sort red/green within original
pass
COLS = max(1, (win.width() - 40) // (thumb_size + 4))
row_widget = None
row_layout = None
col = 0
border = max(2, thumb_size // 30)
for orig_idx, (max_diff, src_thumb, diff_raw) in items:
if view == 'Diff':
# Build diff thumbnail at current amp. uint8 multiply with
# np.clip handles overflow safely.
amped = np.clip(diff_raw.astype(np.float32) * amp, 0, 255).astype(np.uint8)
thumb = _Image.fromarray(amped, mode='L').convert('RGB')
elif view == 'Mask' and mask_thumbs is not None:
mask = mask_thumbs[orig_idx]
thumb = _Image.fromarray(mask, mode='L').convert('RGB')
else:
thumb = src_thumb
if col % COLS == 0:
row_widget = QWidget()
row_layout = QHBoxLayout(row_widget)
row_layout.setSpacing(2)
row_layout.setContentsMargins(0, 0, 0, 0)
grid_layout.addWidget(row_widget)
scaled = thumb.resize((thumb_size, thumb_size), _Image.BILINEAR)
bordered = scaled.copy()
draw = ImageDraw.Draw(bordered)
color = (34, 197, 94) if max_diff >= threshold else (239, 68, 68)
for i in range(border):
draw.rectangle([i, i, thumb_size-1-i, thumb_size-1-i], outline=color)
img_data = bordered.tobytes("raw", "RGB")
qimg = QImage(img_data, thumb_size, thumb_size, thumb_size * 3, QImage.Format.Format_RGB888)
lbl = QLabel()
lbl.setPixmap(QPixmap.fromImage(qimg))
lbl.setToolTip(f"max diff: {max_diff:.1f}")
row_layout.addWidget(lbl)
col += 1
if row_layout:
row_layout.addStretch()
grid_layout.addStretch()
thresh_spin.valueChanged.connect(lambda v: (_render_grid(), self.skip_empty_threshold_input.setValue(v)) if patch_data else None)
size_slider.valueChanged.connect(lambda _: _render_grid() if patch_data else None)
sort_check.stateChanged.connect(lambda _: _render_grid() if patch_data else None)
view_combo.currentTextChanged.connect(lambda _: _render_grid() if patch_data else None)
# Only re-render on amp / gamma changes when the relevant view is
# actually selected — cheap guard against thrashing the grid while
# the user is scrubbing values that have no visible effect.
amp_spin.valueChanged.connect(lambda _: _render_grid() if (patch_data and view_combo.currentText() == 'Diff') else None)
# Gamma changes also propagate to the main form's gamma input so the
# user can preview, find a good value, and have it saved when they
# close the dialog (no need to re-type the number).
def _on_gamma_changed(v):
if hasattr(self, 'auto_mask_gamma_input'):
self.auto_mask_gamma_input.setValue(v)
if patch_data and view_combo.currentText() == 'Mask':
_render_grid()
gamma_spin.valueChanged.connect(_on_gamma_changed)
QTimer.singleShot(50, _wait_for_scan)
def _check_finetune_compat(self):
"""Load the selected finetune .pth and compare its arch against current UI settings."""
import torch
from types import SimpleNamespace
path = self._get_path(self.finetune_from_input).strip()
if not path:
QMessageBox.warning(self, "No File", "Select a .pth file in 'Resume From' first.")
return
if not os.path.isfile(path):
QMessageBox.warning(self, "Not Found", f"File not found:\n{path}")
return
try:
ckpt = torch.load(path, map_location='cpu', weights_only=False)
except Exception as e:
QMessageBox.critical(self, "Load Error", f"Could not load checkpoint:\n{e}")
return
# --- Read checkpoint metadata ---
ckpt_cfg = ckpt.get('config', {})
if isinstance(ckpt_cfg, dict):
model_cfg = ckpt_cfg.get('model', {})
training_cfg = ckpt_cfg.get('training', {})
else:
# SimpleNamespace
model_cfg_ns = getattr(ckpt_cfg, 'model', SimpleNamespace())
training_cfg_ns = getattr(ckpt_cfg, 'training', SimpleNamespace())
model_cfg = vars(model_cfg_ns) if hasattr(model_cfg_ns, '__dict__') else {}
training_cfg = vars(training_cfg_ns) if hasattr(training_cfg_ns, '__dict__') else {}
def_h, bump_h = 64, 96
ckpt_base = model_cfg.get('model_size_dims', def_h)
ckpt_loss = training_cfg.get('loss', 'l1')
ckpt_model_type = ckpt.get('model_type',
model_cfg.get('model_type', 'unet'))
ckpt_n_ch = ckpt.get('n_input_channels', 3)
# Apply same bump logic as train.py
needs_bump = ((ckpt_loss == 'l1+lpips' and ckpt_base == def_h)
or (ckpt_loss == 'weighted' and ckpt_base == def_h
and training_cfg.get('lpips_weight', 0) > 0))
ckpt_eff = bump_h if needs_bump else ckpt_base
# --- Read current UI settings ---
ui_size = int(self.model_size_dims_input.currentText())
ui_type = self.model_type_input.currentText()
ui_loss = self.loss_input.currentText()
ui_n_ch = 4 if self.use_mask_input_input.isChecked() else 3
# Apply bump to UI side too
ui_needs_bump = ((ui_loss == 'l1+lpips' and ui_size == def_h)
or (ui_loss == 'weighted' and ui_size == def_h
and self.lpips_weight_input.value() > 0))
ui_eff = bump_h if ui_needs_bump else ui_size
lines = [f"Checkpoint: {os.path.basename(path)}", ""]
ok = True
def row(label, ckpt_val, ui_val, match):
mark = "OK" if match else "MISMATCH"
return f" [{mark}] {label}: checkpoint={ckpt_val} / current={ui_val}"
size_match = (ckpt_eff == ui_eff)
type_match = (ckpt_model_type == ui_type)
ch_match = (ckpt_n_ch == ui_n_ch)
lines.append(row("Model Type", ckpt_model_type, ui_type, type_match))
lines.append(row("Hidden Size", ckpt_eff, ui_eff, size_match))
lines.append(row("Input Channels",ckpt_n_ch, ui_n_ch, ch_match))
ok = size_match and type_match and ch_match
lines.append("")
if ok:
lines.append("Compatible — weights will load cleanly.")
icon = QMessageBox.Icon.Information
title = "Compatible"
else:
lines.append("Incompatible — fix the mismatched settings before training.")
if not type_match:
lines.append(f" Set Model Type to: {ckpt_model_type}")
if not size_match:
lines.append(f" Set Model Capacity to: {ckpt_base}"
+ (f" (effective {ckpt_eff} with bump)" if needs_bump else ""))
if not ch_match:
lines.append(f" {'Enable' if ckpt_n_ch == 4 else 'Disable'} 'Feed mask as 4th input channel'")
icon = QMessageBox.Icon.Warning
title = "Incompatible"
msg = QMessageBox(self)
msg.setIcon(icon)
msg.setWindowTitle(title)
msg.setText("\n".join(lines))
msg.exec()
def _create_range_layout(self, min_widget, max_widget):
layout = QHBoxLayout()
layout.addWidget(min_widget)
layout.addWidget(QLabel("to"))
layout.addWidget(max_widget)
widget = QWidget()
widget.setLayout(layout)
return widget
@staticmethod
def _combo_value(combo):
"""Extract the numeric/value prefix from a combo item like '512 — Good default'."""
return combo.currentText().split("\u2014")[0].strip()
@staticmethod
def _set_combo_by_prefix(combo, value):
"""Select the combo item whose text starts with the given value."""
value_str = str(value)
for i in range(combo.count()):
if combo.itemText(i).split("\u2014")[0].strip() == value_str:
combo.setCurrentIndex(i)
return
# Fallback: set as raw text (works for editable combos)
combo.setCurrentText(value_str)
@staticmethod
def _get_path(widget):
"""Extract path string from a path selector widget."""
return widget.findChild(QLineEdit).text()
@staticmethod
def _set_path(widget, text):
"""Set path string on a path selector widget."""
le = widget.findChild(QLineEdit)
if le:
le.setText(text)
# =========================================================================
# Sidebar — context-sensitive queue
# =========================================================================
def _create_sidebar(self):
sidebar_layout = QHBoxLayout()
sidebar_layout.setSpacing(0)
sidebar_layout.setContentsMargins(0, 0, 0, 0)
# --- Toggle button (thin vertical strip, always visible) ---
self.sidebar_toggle = QPushButton("▶")
self.sidebar_toggle.setCheckable(True)
self.sidebar_toggle.setChecked(False)
self.sidebar_toggle.setProperty("cssClass", "sidebar-toggle")
self.sidebar_toggle.setFixedWidth(22)
self.sidebar_toggle.setToolTip("Show / hide the queue panel")
self.sidebar_toggle.toggled.connect(self._on_sidebar_toggled)
sidebar_layout.addWidget(self.sidebar_toggle)
# --- Panel (the part that expands/collapses) ---
self.sidebar_panel = QWidget()
self.sidebar_panel.setMinimumWidth(200)
self.sidebar_panel.setMaximumWidth(280)
panel_layout = QVBoxLayout(self.sidebar_panel)
panel_layout.setContentsMargins(4, 0, 0, 0)
# Queue title label
self.sidebar_queue_label = QLabel("Training Queue")
self.sidebar_queue_label.setStyleSheet("font-weight: 600; padding: 4px 0;")
panel_layout.addWidget(self.sidebar_queue_label)
# Stacked widget for switching between training/inference queues
self.sidebar_stack = QStackedWidget()
# --- Page 0: Training Queue ---
train_queue_page = QWidget()
tq_layout = QVBoxLayout(train_queue_page)
tq_layout.setContentsMargins(0, 0, 0, 0)
self.queue_listbox = QListWidget()
self.queue_listbox.setSelectionMode(QListWidget.ExtendedSelection)
tq_layout.addWidget(self.queue_listbox, stretch=1)
self.queue_add_btn = QPushButton("Add to Queue")
self.queue_add_btn.clicked.connect(self._add_to_training_queue)
self.queue_remove_btn = QPushButton("Remove")
self.queue_remove_btn.clicked.connect(self._remove_from_training_queue)
self.queue_clear_btn = QPushButton("Clear")
self.queue_clear_btn.clicked.connect(self._clear_training_queue)
self.queue_run_btn = QPushButton("Run Queue")
self.queue_run_btn.clicked.connect(self._run_training_queue)
self.queue_run_btn.setProperty("cssClass", "start")
tq_layout.addWidget(self.queue_add_btn)
tq_layout.addWidget(self.queue_remove_btn)
tq_layout.addWidget(self.queue_clear_btn)
tq_layout.addWidget(self.queue_run_btn)
self.sidebar_stack.addWidget(train_queue_page)
# --- Page 1: Inference Queue ---
inf_queue_page = QWidget()
iq_layout = QVBoxLayout(inf_queue_page)
iq_layout.setContentsMargins(0, 0, 0, 0)
self.inf_queue_listbox = QListWidget()
self.inf_queue_listbox.setSelectionMode(QListWidget.ExtendedSelection)
iq_layout.addWidget(self.inf_queue_listbox, stretch=1)
self.inf_queue_add_btn = QPushButton("Add to Queue")
self.inf_queue_add_btn.clicked.connect(self._inf_add_to_queue)
self.inf_queue_remove_btn = QPushButton("Remove")
self.inf_queue_remove_btn.clicked.connect(self._inf_remove_from_queue)
self.inf_queue_clear_btn = QPushButton("Clear")
self.inf_queue_clear_btn.clicked.connect(self._inf_clear_queue)
iq_layout.addWidget(self.inf_queue_add_btn)
iq_layout.addWidget(self.inf_queue_remove_btn)
iq_layout.addWidget(self.inf_queue_clear_btn)
self.sidebar_stack.addWidget(inf_queue_page)
panel_layout.addWidget(self.sidebar_stack, stretch=1)
sidebar_layout.addWidget(self.sidebar_panel)
return sidebar_layout
def _on_sidebar_toggled(self, expanded):
self.sidebar_panel.setVisible(expanded)
self.sidebar_toggle.setText("▶" if expanded else "◀")
# =========================================================================
# Bottom control panel
# =========================================================================
def _create_control_panel(self):
layout = QHBoxLayout()
self.load_btn = QPushButton("Load Config")
self.load_btn.clicked.connect(self._load_config_from_file)
self.save_btn = QPushButton("Save Config")
self.save_btn.clicked.connect(self._save_config_to_file)
self.monitor_btn = QPushButton("Training Monitor")
self.monitor_btn.setProperty("cssClass", "accent")
self.monitor_btn.clicked.connect(self._launch_training_monitor)
self.start_btn = QPushButton("Start Training")
self.start_btn.setProperty("cssClass", "start")
self.start_btn.clicked.connect(self._start_training)
self.stop_btn = QPushButton("Stop Training")
self.stop_btn.setProperty("cssClass", "stop")
self.stop_btn.setEnabled(False)
self.stop_btn.clicked.connect(self._stop_training)
layout.addWidget(self.load_btn)
layout.addWidget(self.save_btn)
layout.addWidget(self.monitor_btn)
layout.addStretch()
layout.addWidget(self.start_btn)
layout.addWidget(self.stop_btn)
return layout
# =========================================================================
# Tab switching / sidebar context
# =========================================================================
@Slot(int)
def _on_tab_changed(self, index):
if index == self._inference_tab_index:
self.sidebar_stack.setCurrentIndex(1)
self.sidebar_queue_label.setText("Inference Queue")
else:
self.sidebar_stack.setCurrentIndex(0)
self.sidebar_queue_label.setText("Training Queue")
# Refresh previews when switching to previews tab
tab_name = self.tabs.tabText(index)
if tab_name == "Previews":
self._apply_preview_zoom()
# =========================================================================
# Preview management
# =========================================================================
def _switch_preview(self, mode):
"""Toggle between training and validation preview."""
self._active_preview = mode
self.preview_train_btn.setChecked(mode == 'train')
self.preview_val_btn.setChecked(mode == 'val')
self._apply_preview_zoom()
def _apply_preview_zoom(self):
"""Apply current zoom to the active preview pixmap."""
if self._active_preview == 'train':
pixmap = self.original_pixmap
zoom = self._preview_zoom_factor
else:
pixmap = self.val_original_pixmap
zoom = self._val_preview_zoom_factor
if not pixmap:
label_text = "Waiting for training preview..." if self._active_preview == 'train' else "Waiting for validation preview..."
self.preview_label.setText(label_text)
self.labels_container.setVisible(False)
return
self.labels_container.setVisible(True)
if zoom is None:
scaled = pixmap.scaled(self.scroll_area.viewport().size(), Qt.KeepAspectRatio, Qt.SmoothTransformation)
else:
new_w = int(pixmap.width() * zoom)
new_h = int(pixmap.height() * zoom)
scaled = pixmap.scaled(new_w, new_h, Qt.KeepAspectRatio, Qt.SmoothTransformation)
self.preview_label.setPixmap(scaled)
self.preview_label.adjustSize()
image_width = scaled.width()
container_width = self.scroll_area.viewport().width()
margin = max(0, (container_width - image_width) // 2)
self.labels_container.setContentsMargins(margin, 0, margin, 0)
def _on_zoom_combo_changed(self, text):
if self._active_preview == 'train':
if text == "Fit":
self._preview_zoom_factor = None
else:
self._preview_zoom_factor = float(text.replace('%', '')) / 100.0
else:
if text == "Fit":
self._val_preview_zoom_factor = None
else:
self._val_preview_zoom_factor = float(text.replace('%', '')) / 100.0
self._apply_preview_zoom()
def _on_preview_wheel_zoom(self, factor):
if self._active_preview == 'train':
pixmap = self.original_pixmap
current_zoom = self._preview_zoom_factor
else:
pixmap = self.val_original_pixmap
current_zoom = self._val_preview_zoom_factor
if current_zoom is None:
if pixmap and not pixmap.isNull():
vp = self.scroll_area.viewport().size()
current_zoom = min(vp.width() / pixmap.width(), vp.height() / pixmap.height())
else:
return
new_zoom = max(0.05, min(10.0, current_zoom * factor))
if self._active_preview == 'train':
self._preview_zoom_factor = new_zoom
else:
self._val_preview_zoom_factor = new_zoom
self._apply_preview_zoom()
@Slot(str)
def _setup_preview_watcher(self, model_folder):
if self.preview_image_path and self.file_watcher.files():
self.file_watcher.removePath(self.preview_image_path)
if self.val_preview_image_path and self.val_preview_image_path in self.file_watcher.files():
self.file_watcher.removePath(self.val_preview_image_path)
if model_folder and Path(model_folder).is_dir():
self.preview_image_path = str(Path(model_folder) / "training_preview.jpg")
self.val_preview_image_path = str(Path(model_folder) / "val_preview.jpg")
self.file_watcher.addPath(self.preview_image_path)
self.file_watcher.addPath(self.val_preview_image_path)
self._update_preview_image()
self._update_val_preview_image()
@Slot(str)
def _on_watched_file_changed(self, path):
if self.preview_image_path and path == self.preview_image_path:
self._update_preview_image()
elif self.val_preview_image_path and path == self.val_preview_image_path:
self._update_val_preview_image()
def _update_all_previews(self):
self._update_preview_image()
self._update_val_preview_image()
def _update_preview_image(self):
if self.preview_image_path and Path(self.preview_image_path).exists():
try:
with open(self.preview_image_path, 'rb') as f:
image_data = f.read()
pixmap = QPixmap()
pixmap.loadFromData(image_data)
if not pixmap.isNull():
self.original_pixmap = pixmap
if self._active_preview == 'train':
self._apply_preview_zoom()
except Exception:
pass
else:
self.original_pixmap = None
if self._active_preview == 'train':
self._apply_preview_zoom()
def _update_val_preview_image(self):
if self.val_preview_image_path and Path(self.val_preview_image_path).exists():
try:
with open(self.val_preview_image_path, 'rb') as f:
image_data = f.read()
pixmap = QPixmap()
pixmap.loadFromData(image_data)
if not pixmap.isNull():
self.val_original_pixmap = pixmap
if self._active_preview == 'val':
self._apply_preview_zoom()
except Exception:
pass
else:
self.val_original_pixmap = None
if self._active_preview == 'val':
self._apply_preview_zoom()
def resizeEvent(self, event):
super().resizeEvent(event)
self._apply_preview_zoom()
# =========================================================================
# Config gather / populate
# =========================================================================
def gather_config_from_ui(self):
"""Collect all UI state into a single config dict."""
gp = self._get_path
augs = []
if self.hflip_check.isChecked():
augs.append({'_target_': 'albumentations.HorizontalFlip', 'p': self.hflip_p.value() / 100.0})
if self.affine_check.isChecked():
augs.append({
'_target_': 'albumentations.Affine',