-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdesktop_app.py
More file actions
1856 lines (1561 loc) · 83.3 KB
/
Copy pathdesktop_app.py
File metadata and controls
1856 lines (1561 loc) · 83.3 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
"""
Unified Interface For Learned Image Compression (UI-LIC) - Graphical User Interface (GUI) Desktop Visualizer
This application (`GUI-Visualizer/desktop_app.py`) provides a cross-platform desktop visualizer for the UI-LIC framework.
It allows researchers to interactively discover testing interfaces, configure codec parameters, execute batch dataset inference,
visually compare reconstructed images side-by-side using an interactive split-viewport slider, view perceptual error map overlays
(LPIPS and color gradients), and generate tabular metric reports.
"""
import tkinter as tk
from tkinter import ttk, filedialog, messagebox
import os
import sys
# Add parent project root directory to sys.path to allow importing BaseInterface and framework utilities
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
import threading
import importlib.util
import inspect
from PIL import Image, ImageTk
import glob
import builtins
import queue
import json
import subprocess
import time
import numpy as np
from dispatcher import Dispatcher
try:
# Enable high-DPI scaling on Windows hosts
from ctypes import windll
windll.shcore.SetProcessDpiAwareness(1)
except Exception:
pass
ROOT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
if ROOT_DIR not in sys.path:
sys.path.append(ROOT_DIR)
class ComparisonCanvas(tk.Canvas):
def __init__(self, master, **kwargs):
super().__init__(master, **kwargs)
self.image1 = None # Right Image
self.image2 = None # Left Image
self.label1 = "Right"
self.label2 = "Left"
self.metrics1 = "" # Right metrics string
self.metrics2 = "" # Left metrics string
self.show_metrics = True
self.scaled_img1 = None # Cached resize
self.scaled_img2 = None # Cached resize
self.tk_image = None
self.slider_pos = 0.5
self.bind("<Configure>", self.on_resize)
self.bind("<B1-Motion>", self.on_drag)
self.bind("<Button-1>", self.on_drag)
def set_images(self, path1, path2=None, overlay_path1=None, overlay_path2=None,
label1="Right", label2="Left", metrics1="", metrics2="",
show_metrics=True, invert_overlay=True, overlay_mode="error",
lpips_layers=None):
"""
path1: Right Image
path2: Left Image
overlay_pathX: Path to error map for blending
invert_overlay: True for SSIM (brighter=good), False for PSNR/MSE (brighter=bad)
lpips_layers: List of 5 booleans for which LPIPS layers to show
"""
self.label1 = label1
self.label2 = label2
self.metrics1 = metrics1
self.metrics2 = metrics2
self.show_metrics = show_metrics
def load_and_blend(img_path, map_path):
if not img_path or not os.path.exists(img_path):
return None
is_direct_view = (map_path is None)
effective_map_path = map_path if map_path else img_path
img = Image.open(img_path).convert("RGB")
img_np = np.array(img).astype(np.float32)
if overlay_mode == "gradient" and not is_direct_view:
grad_map = Image.open(effective_map_path).convert("RGB")
if grad_map.size != img.size:
grad_map = grad_map.resize(img.size, Image.LANCZOS)
grad_np = np.array(grad_map).astype(np.float32)
alpha = (grad_np[:, :, 2] / 255.0) * 0.8
alpha_3d = np.expand_dims(alpha, axis=2)
blended = img_np * (1.0 - alpha_3d) + grad_np * alpha_3d
return Image.fromarray(blended.astype(np.uint8))
if overlay_mode == "lpips":
# Only attempt multi-layer blending if this is actually an LPIPS context
# and we have layers selected.
is_lpips_context = "lpips" in effective_map_path.lower()
if is_lpips_context and lpips_layers and any(lpips_layers):
colors = [
[255, 0, 0], # Layer 0: Red
[0, 255, 0], # Layer 1: Green
[0, 0, 255], # Layer 2: Blue
[255, 255, 0], # Layer 3: Yellow
[255, 0, 255] # Layer 4: Purple (Magenta)
]
# Direct view on black, overlay view on reconstruction
base_np = np.zeros_like(img_np) if is_direct_view else img_np
overlay_accum = np.zeros_like(img_np)
alpha_accum = np.zeros((img_np.shape[0], img_np.shape[1], 1), dtype=np.float32)
any_layer_found = False
for i, (show, color) in enumerate(zip(lpips_layers, colors)):
if not show: continue
if "_lpips.png" in effective_map_path:
layer_path = effective_map_path.replace("_lpips.png", f"_lpips_layer{i}.png")
else:
layer_path = effective_map_path.replace(".png", f"_layer{i}.png")
if not os.path.exists(layer_path): continue
any_layer_found = True
layer_map = Image.open(layer_path).convert("L")
if layer_map.size != img.size:
layer_map = layer_map.resize(img.size, Image.LANCZOS)
map_np = np.array(layer_map).astype(np.float32) / 255.0
alpha_val = 1.0 if is_direct_view else 0.8
alpha = map_np * alpha_val
alpha_3d = np.expand_dims(alpha, axis=2)
color_img = np.zeros_like(img_np)
color_img[:] = color
overlay_accum += color_img * alpha_3d
alpha_accum = np.maximum(alpha_accum, alpha_3d)
if any_layer_found:
overlay_accum = np.clip(overlay_accum, 0, 255)
blended = base_np * (1.0 - alpha_accum) + overlay_accum
return Image.fromarray(blended.astype(np.uint8))
elif is_direct_view:
# Layers selected but not found for this specific LPIPS map
# Return black for the model side, but this branch shouldn't hit GT
return Image.fromarray(np.zeros_like(img_np).astype(np.uint8))
# Fallback for LPIPS mode: if it's not an LPIPS map (like GT),
# or no layers were found/selected, just show the base image.
if is_direct_view:
return img
if is_direct_view:
return img
# Perform Blending (Standard error map)
if not os.path.exists(effective_map_path):
return img
error_map = Image.open(effective_map_path).convert("L")
if error_map.size != img.size:
error_map = error_map.resize(img.size, Image.LANCZOS)
map_np = np.array(error_map).astype(np.float32) / 255.0
# alpha scaling: 0.8 represents greatest error
if invert_overlay:
# For SSIM: High value (1.0) = similar, Low value (0.0) = error
alpha = (1.0 - map_np) * 0.8
else:
# For PSNR/MSE: High value (1.0) = error, Low value (0.0) = similar
alpha = map_np * 0.8
alpha_3d = np.expand_dims(alpha, axis=2)
red = np.zeros_like(img_np)
red[:, :, 0] = 255.0
blended = img_np * (1.0 - alpha_3d) + red * alpha_3d
return Image.fromarray(blended.astype(np.uint8))
try:
self.image1 = load_and_blend(path1, overlay_path1)
self.image2 = load_and_blend(path2, overlay_path2)
self.update_scaled_images()
self.render()
except Exception as e:
print(f"Error loading/blending images: {e}")
def on_resize(self, event):
self.update_scaled_images()
self.render()
def update_scaled_images(self):
"""Perform the expensive LANCZOS resize only once per window resize or image load."""
if not self.image1 and not self.image2: return
# Use the first available image to determine ratio
base_img = self.image1 if self.image1 else self.image2
w = self.winfo_width()
h = self.winfo_height()
if w < 10 or h < 10: return
img_w, img_h = base_img.size
ratio = min(w / img_w, h / img_h)
self.new_w = int(img_w * ratio)
self.new_h = int(img_h * ratio)
if self.image1:
self.scaled_img1 = self.image1.resize((self.new_w, self.new_h), Image.LANCZOS)
else:
self.scaled_img1 = None
if self.image2:
self.scaled_img2 = self.image2.resize((self.new_w, self.new_h), Image.LANCZOS)
else:
self.scaled_img2 = None
def on_drag(self, event):
width = self.winfo_width()
if width > 0 and self.scaled_img1 and self.scaled_img2:
self.slider_pos = max(0, min(1, event.x / width))
self.render()
def render(self):
if not self.scaled_img1 and not self.scaled_img2:
return
canvas_width = self.winfo_width()
canvas_height = self.winfo_height()
combined = Image.new("RGB", (self.new_w, self.new_h))
if self.scaled_img1 and self.scaled_img2:
split_x = int(self.new_w * self.slider_pos)
left_part = self.scaled_img2.crop((0, 0, split_x, self.new_h))
right_part = self.scaled_img1.crop((split_x, 0, self.new_w, self.new_h))
combined.paste(left_part, (0, 0))
combined.paste(right_part, (split_x, 0))
elif self.scaled_img1:
split_x = 0
combined.paste(self.scaled_img1, (0, 0))
elif self.scaled_img2:
split_x = self.new_w
combined.paste(self.scaled_img2, (0, 0))
self.tk_image = ImageTk.PhotoImage(combined)
self.delete("all")
offset_x = (canvas_width - self.new_w) // 2
offset_y = (canvas_height - self.new_h) // 2
self.create_image(offset_x, offset_y, anchor="nw", image=self.tk_image)
canvas_font = ("sans-serif", 24, "bold")
metrics_font = ("sans-serif", 14, "bold")
if self.scaled_img1 and self.scaled_img2:
line_x = offset_x + split_x
self.create_line(line_x, offset_y, line_x, offset_y + self.new_h, fill="#00ffff", width=5)
# Left Label
self.create_text(offset_x + 20, offset_y + 20, text=self.label2.upper(), fill="#00ffff", anchor="nw", font=canvas_font)
if self.show_metrics and self.metrics2:
self.create_text(offset_x + 20, offset_y + 90, text=self.metrics2, fill="#00ffff", anchor="nw", font=metrics_font)
# Right Label
self.create_text(offset_x + self.new_w - 20, offset_y + 20, text=self.label1.upper(), fill="#00ffff", anchor="ne", font=canvas_font)
if self.show_metrics and self.metrics1:
self.create_text(offset_x + self.new_w - 20, offset_y + 90, text=self.metrics1, fill="#00ffff", anchor="ne", font=metrics_font)
elif self.scaled_img1:
self.create_text(offset_x + self.new_w - 20, offset_y + 20, text=f"{self.label1.upper()} (ONLY)", fill="#ffcc00", anchor="ne", font=canvas_font)
if self.show_metrics and self.metrics1:
self.create_text(offset_x + self.new_w - 20, offset_y + 90, text=self.metrics1, fill="#ffcc00", anchor="ne", font=metrics_font)
elif self.scaled_img2:
self.create_text(offset_x + 20, offset_y + 20, text=f"{self.label2.upper()} (ONLY)", fill="#ffcc00", anchor="nw", font=canvas_font)
if self.show_metrics and self.metrics2:
self.create_text(offset_x + 20, offset_y + 90, text=self.metrics2, fill="#ffcc00", anchor="nw", font=metrics_font)
class LICApp:
def __init__(self, root):
self.root = root
self.root.title("LIC Model Visualizer - Desktop")
self.root.geometry("1600x1000")
self.zoom_level = 1.0
self.update_font_scales()
self.apply_styles()
self.registry = self.load_interfaces(os.path.join(ROOT_DIR, "Interfaces", "Testing-Interfaces"))
self.model_configs = {}
self.log_queue = queue.Queue()
self.selected_model_names = []
self.external_folders = {} # {display_name: folder_path}
self.metrics_data = {} # {model_name: {averages: {}, per_image: []}}
self.lpips_layer_vars = [tk.BooleanVar(value=True) for _ in range(5)]
self.load_external_folders()
self.setup_ui()
self.load_metrics() # Added to load existing results on startup
self.setup_bindings()
self.poll_log_queue()
def update_font_scales(self):
z = self.zoom_level
self.F_BASE = ("sans-serif", int(14 * z))
self.F_HEAD = ("sans-serif", int(18 * z), "bold")
self.F_BTN = ("sans-serif", int(14 * z), "bold")
self.F_RUN = ("sans-serif", int(20 * z), "bold")
self.F_LOG = ("monospace", int(12 * z))
def setup_bindings(self):
self.root.bind("<Control-plus>", self.zoom_in)
self.root.bind("<Control-equal>", self.zoom_in)
self.root.bind("<Control-KP_Add>", self.zoom_in)
self.root.bind("<Control-minus>", self.zoom_out)
self.root.bind("<Control-KP_Subtract>", self.zoom_out)
self.root.bind("<Control-0>", self.zoom_reset)
def zoom_in(self, event=None):
self.zoom_level = min(3.0, self.zoom_level + 0.1)
self.apply_zoom()
def zoom_out(self, event=None):
self.zoom_level = max(0.5, self.zoom_level - 0.1)
self.apply_zoom()
def zoom_reset(self, event=None):
self.zoom_level = 1.0
self.apply_zoom()
def apply_zoom(self):
self.update_font_scales()
self.apply_styles()
# Trigger UI refresh for some elements if needed, though apply_styles handles most
self.on_model_select()
def apply_styles(self):
style = ttk.Style()
if 'clam' in style.theme_names():
style.theme_use('clam')
style.configure('.', font=self.F_BASE)
style.configure('TLabel', font=self.F_BASE)
style.configure('Header.TLabel', font=self.F_HEAD, foreground="#003366")
style.configure('TButton', font=self.F_BTN, padding=8)
style.configure('Run.TButton', font=self.F_RUN, background='#28a745', foreground='white', padding=15)
style.map('Run.TButton', background=[('active', '#218838')])
style.configure('TLabelframe.Label', font=self.F_HEAD, foreground="#0055a4")
style.configure('TCheckbutton', font=self.F_BASE)
style.configure('TCombobox', font=self.F_BASE)
style.configure('TEntry', font=self.F_BASE, padding=4, fieldbackground='white')
style.configure('Treeview', font=self.F_BASE, rowheight=30)
style.configure('Treeview.Heading', font=self.F_BTN)
def _on_mousewheel(self, event):
# Platform-specific mouse wheel handling
if sys.platform == 'darwin':
self.config_canvas.yview_scroll(-1 * event.delta, "units")
else:
self.config_canvas.yview_scroll(int(-1 * (event.delta / 120)), "units")
def load_interfaces(self, directory):
registry = {}
if not os.path.isdir(directory):
return registry
for filename in os.listdir(directory):
if filename.endswith(".py") and not filename.startswith("__"):
filepath = os.path.join(directory, filename)
spec = importlib.util.spec_from_file_location(filename[:-3], filepath)
if spec and spec.loader:
module = importlib.util.module_from_spec(spec)
try:
spec.loader.exec_module(module)
for name, obj in inspect.getmembers(module, inspect.isclass):
if hasattr(obj, 'TASK_NAME') and getattr(obj, 'TASK_NAME') is not None:
registry[obj.TASK_NAME] = obj
except Exception as e:
print(f"Failed to load {filename}: {e}")
return registry
def setup_ui(self):
self.paned = ttk.PanedWindow(self.root, orient=tk.HORIZONTAL)
self.paned.pack(fill=tk.BOTH, expand=True)
self.sidebar = ttk.Frame(self.paned, width=400, padding=20)
self.paned.add(self.sidebar, weight=1)
# 1. Global Toggle at the top
self.show_advanced_var = tk.BooleanVar(value=False)
ttk.Checkbutton(self.sidebar, text="Advanced Mode", variable=self.show_advanced_var, command=self.refresh_sidebar_and_models).pack(anchor="w", pady=(0, 15))
# 2. Path Settings (GT is always shown)
self.path_header = ttk.Label(self.sidebar, text="1. Path Settings", style='Header.TLabel')
self.path_header.pack(anchor="w", pady=(0, 10))
self.gt_dir_var = tk.StringVar()
self.gt_label = ttk.Label(self.sidebar, text="Input Images (Ground Truth):", font=self.F_BASE)
self.gt_label.pack(anchor="w")
self.gt_frame = ttk.Frame(self.sidebar)
self.gt_frame.pack(fill=tk.X, pady=(0, 15))
ttk.Entry(self.gt_frame, textvariable=self.gt_dir_var, font=self.F_BASE).pack(side=tk.LEFT, fill=tk.X, expand=True)
ttk.Button(self.gt_frame, text="Browse", width=8, command=lambda: self.browse_dir(self.gt_dir_var, check_images=True)).pack(side=tk.LEFT, padx=(5,0))
# Advanced Global Settings (hidden by default)
self.adv_global_frame = ttk.Frame(self.sidebar)
self.out_dir_var = tk.StringVar(value=os.path.join(ROOT_DIR, "GUI-Visualizer/outputs"))
ttk.Label(self.adv_global_frame, text="Results Output:", font=self.F_BASE).pack(anchor="w")
out_f = ttk.Frame(self.adv_global_frame)
out_f.pack(fill=tk.X, pady=(0, 15))
ttk.Entry(out_f, textvariable=self.out_dir_var, font=self.F_BASE).pack(side=tk.LEFT, fill=tk.X, expand=True)
ttk.Button(out_f, text="Browse", width=8, command=lambda: self.browse_dir(self.out_dir_var)).pack(side=tk.LEFT, padx=(5,0))
default_base_env = os.path.join(ROOT_DIR, "envs")
self.base_env_dir_var = tk.StringVar(value=default_base_env if os.path.exists(default_base_env) else "")
ttk.Label(self.adv_global_frame, text="Environment Folder:", font=self.F_BASE).pack(anchor="w")
env_f = ttk.Frame(self.adv_global_frame)
env_f.pack(fill=tk.X, pady=(0, 20))
ttk.Entry(env_f, textvariable=self.base_env_dir_var, font=self.F_BASE).pack(side=tk.LEFT, fill=tk.X, expand=True)
ttk.Button(env_f, text="Browse", width=8, command=lambda: self.browse_dir(self.base_env_dir_var)).pack(side=tk.LEFT, padx=(5,0))
# 3. Model Selection
ttk.Label(self.sidebar, text="2. Select Models", style='Header.TLabel').pack(anchor="w", pady=(0, 10))
self.model_listbox = tk.Listbox(
self.sidebar,
selectmode=tk.MULTIPLE,
height=6,
exportselection=False,
font=self.F_BASE,
bg="#2b2b2b",
fg="#ffffff",
selectbackground="#007acc",
selectforeground="#ffffff",
highlightthickness=1,
highlightbackground="#555555"
)
for name in sorted(self.registry.keys()):
self.model_listbox.insert(tk.END, name)
self.model_listbox.pack(fill=tk.X, pady=(0, 15))
self.model_listbox.bind("<<ListboxSelect>>", self.on_model_select)
# External Folders Section
ttk.Label(self.sidebar, text="3. External Reconstructions", style='Header.TLabel').pack(anchor="w", pady=(10, 5))
ext_btn_f = ttk.Frame(self.sidebar)
ext_btn_f.pack(fill=tk.X, pady=(0, 5))
ttk.Button(ext_btn_f, text="+ Add Folder", command=self.add_external_folder).pack(side=tk.LEFT, expand=True, fill=tk.X, padx=(0, 2))
ttk.Button(ext_btn_f, text="- Remove", command=self.remove_external_folder).pack(side=tk.LEFT, expand=True, fill=tk.X, padx=(2, 0))
self.external_listbox = tk.Listbox(
self.sidebar,
selectmode=tk.MULTIPLE,
height=4,
exportselection=False,
font=self.F_BASE,
bg="#2b2b2b",
fg="#ffffff",
selectbackground="#007acc"
)
self.external_listbox.pack(fill=tk.X, pady=(0, 10))
self.external_listbox.bind("<<ListboxSelect>>", self.on_model_select)
self.run_btn = ttk.Button(self.sidebar, text="RUN EVALUATION", style='Run.TButton', command=self.run_evaluation)
self.run_btn.pack(fill=tk.X, pady=15)
self.progress = ttk.Progressbar(self.sidebar, mode='indeterminate')
self.progress.pack(fill=tk.X)
self.main_area = ttk.Notebook(self.paned)
self.paned.add(self.main_area, weight=4)
self.main_area.bind("<<NotebookTabChanged>>", self.on_main_tab_changed)
self.config_tab = ttk.Frame(self.main_area, padding=20)
self.main_area.add(self.config_tab, text="Configuration")
self.config_canvas = tk.Canvas(self.config_tab, highlightthickness=0)
self.config_scrollbar = ttk.Scrollbar(self.config_tab, orient="vertical", command=self.config_canvas.yview)
# Static control area for non-dynamic settings
self.config_static_frame = ttk.Frame(self.config_tab, padding=5)
self.config_static_frame.pack(fill=tk.X, side=tk.TOP)
self.equalize_var = tk.BooleanVar(value=True)
self.equalize_check = ttk.Checkbutton(self.config_static_frame, text="Equalize Bitrates", variable=self.equalize_var, command=self.on_equalize_toggle)
self.equalize_check.pack_forget() # Hidden by default
self.config_scrollable_frame = ttk.Frame(self.config_canvas)
self.config_scrollable_frame.bind(
"<Configure>",
lambda e: self.config_canvas.configure(scrollregion=self.config_canvas.bbox("all"))
)
self.config_canvas.create_window((0, 0), window=self.config_scrollable_frame, anchor="nw")
self.config_canvas.configure(yscrollcommand=self.config_scrollbar.set)
# Bind mouse wheel for scrolling
self.config_canvas.bind_all("<MouseWheel>", self._on_mousewheel)
self.config_canvas.pack(side="left", fill="both", expand=True)
self.config_scrollbar.pack(side="right", fill="y")
self.compare_tab = ttk.Frame(self.main_area, padding=15)
self.main_area.add(self.compare_tab, text="Visual Comparison")
comp_controls = ttk.Frame(self.compare_tab)
comp_controls.pack(fill=tk.X, pady=(0, 15))
ttk.Label(comp_controls, text="Image:", font=self.F_BTN).pack(side=tk.LEFT)
self.img_selector = ttk.Combobox(comp_controls, state="readonly", width=25, font=self.F_BASE)
self.img_selector.pack(side=tk.LEFT, padx=(5, 15))
self.img_selector.bind("<<ComboboxSelected>>", self.update_comparison)
ttk.Label(comp_controls, text="Left Side:", font=self.F_BTN).pack(side=tk.LEFT)
self.model_selector_left = ttk.Combobox(comp_controls, state="readonly", width=15, font=self.F_BASE, values=["Ground Truth"])
self.model_selector_left.set("Ground Truth")
self.model_selector_left.pack(side=tk.LEFT, padx=5)
self.model_selector_left.bind("<<ComboboxSelected>>", self.update_comparison)
ttk.Label(comp_controls, text="Right Side:", font=self.F_BTN).pack(side=tk.LEFT)
self.model_selector_right = ttk.Combobox(comp_controls, state="readonly", width=15, font=self.F_BASE, values=["Ground Truth"])
self.model_selector_right.set("Ground Truth")
self.model_selector_right.pack(side=tk.LEFT, padx=5)
self.model_selector_right.bind("<<ComboboxSelected>>", self.update_comparison)
self.equalize_compare_check = ttk.Checkbutton(comp_controls, text="Equalize", variable=self.equalize_var, command=self.on_equalize_toggle)
# Initially hidden
self.show_metrics_var = tk.BooleanVar(value=True)
ttk.Checkbutton(comp_controls, text="Show Metrics", variable=self.show_metrics_var, command=self.update_comparison).pack(side=tk.LEFT, padx=15)
ttk.Label(comp_controls, text="Show Error:", font=self.F_BTN).pack(side=tk.LEFT, padx=(10, 5))
self.error_type_var = tk.StringVar(value="None")
self.error_selector = ttk.Combobox(comp_controls, state="readonly", width=8, textvariable=self.error_type_var, values=["None", "PSNR", "SSIM", "LPIPS", "Gradient"], font=self.F_BASE)
self.error_selector.pack(side=tk.LEFT)
self.error_selector.bind("<<ComboboxSelected>>", self.toggle_error_options)
self.lpips_layers_frame = ttk.Frame(comp_controls)
layer_colors = ["Red", "Green", "Blue", "Yellow", "Purple"]
for i in range(5):
chk = ttk.Checkbutton(self.lpips_layers_frame, text=f"L{i}",
variable=self.lpips_layer_vars[i], command=self.update_comparison)
chk.pack(side=tk.LEFT, padx=2)
self.ssim_overlay_var = tk.BooleanVar(value=True)
self.ssim_overlay_check = ttk.Checkbutton(comp_controls, text="Overlay", variable=self.ssim_overlay_var, command=self.update_comparison)
self.comp_canvas = ComparisonCanvas(self.compare_tab, bg="#1e1e1e", highlightthickness=0)
self.comp_canvas.pack(fill=tk.BOTH, expand=True)
self.metrics_tab = ttk.Frame(self.main_area, padding=20)
self.main_area.add(self.metrics_tab, text="Metrics Report")
self.setup_metrics_ui()
self.log_area = tk.Text(self.sidebar, height=8, font=self.F_LOG, bg="#ffffff", fg="#333333", highlightthickness=1, highlightbackground="#cccccc")
self.log_area.pack(fill=tk.BOTH, expand=True, pady=(20, 0))
self.log_area.bind("<Key>", self.block_input)
self.refresh_external_listbox()
def on_main_tab_changed(self, event=None):
current_tab = self.main_area.tab(self.main_area.select(), "text")
if current_tab == "Visual Comparison":
self.load_metrics()
self.refresh_image_list()
self.update_comparison()
elif current_tab == "Metrics Report":
self.load_metrics()
self.refresh_metrics_display()
def on_equalize_toggle(self):
self.on_model_select() # Refresh UI to show/hide synchronized QPs
def sync_qp(self, source_var, *args):
if not self.equalize_var.get(): return
try:
new_val = source_var.get()
except:
return
standard_codecs = ["AVC", "HEVC", "AV1"]
for mname in self.selected_model_names:
if mname in standard_codecs:
qp_var = self.model_configs[mname]["args"].get("qp")
if qp_var and qp_var.get() != new_val:
qp_var.set(new_val)
def sync_standard_qps(self):
if not self.equalize_var.get():
return
standard_codecs = ["AVC", "HEVC", "AV1"]
first_qp_var = None
for mname in self.selected_model_names:
if mname in standard_codecs:
qp_var = self.model_configs.get(mname, {}).get("args", {}).get("qp")
if qp_var:
if first_qp_var is None:
first_qp_var = qp_var
elif qp_var.get() != first_qp_var.get():
qp_var.set(first_qp_var.get())
def _find_largest_weight(self, weights_dir):
if not os.path.isdir(weights_dir):
return None
candidates = []
for root, _, files in os.walk(weights_dir):
for fname in files:
if fname.endswith((".pth", ".pth.tar", ".pkl", ".pt")):
candidates.append(os.path.join(root, fname))
if not candidates:
return None
return max(candidates, key=lambda p: os.path.getsize(p))
def _find_checkpoint_weight(self, workdir):
search_dirs = [
os.path.join(workdir, "checkpoints"),
os.path.join(ROOT_DIR, "checkpoints")
]
found_files = []
for sd in search_dirs:
if os.path.exists(sd):
for ext in ["*.pth", "*.pth.tar", "*.pkl", "*.pt"]:
for depth in range(4):
wildcards = ["*"] * depth
pattern = os.path.join(sd, *wildcards, ext)
found_files.extend(glob.glob(pattern))
if not found_files:
return None
best_files = [f for f in found_files if 'best' in os.path.basename(f).lower()]
if best_files:
best_files.sort(key=os.path.getmtime, reverse=True)
return best_files[0]
found_files.sort(key=os.path.getmtime, reverse=True)
return found_files[0]
def _apply_weight_autofill(self, model_name, force=False):
config = self.model_configs.get(model_name)
if not config:
return
use_pretrained_var = config.get("use_pretrained")
if use_pretrained_var is None:
return
workdir = os.path.join(ROOT_DIR, config["workdir"].get())
weights_dir = os.path.join(workdir, "weights")
weight_path = self._find_largest_weight(weights_dir) if use_pretrained_var.get() else None
if weight_path is None:
weight_path = self._find_checkpoint_weight(workdir)
for arg_name, var in config["args"].items():
arg_lower = arg_name.lower()
is_weight_arg = any(k in arg_lower for k in ["checkpoint", "model_path", "codec_path", "weights", "weight"])
if not is_weight_arg:
continue
if any(k in arg_lower for k in ["sd_path", "elic_path"]):
continue
if not force and var.get() not in ("", None, "None"):
continue
if weight_path:
var.set(weight_path)
def on_use_pretrained_toggle(self, model_name):
self._apply_weight_autofill(model_name, force=True)
def toggle_error_options(self, event=None):
error_type = self.error_type_var.get()
if error_type != "None":
self.ssim_overlay_check.pack(side=tk.LEFT, padx=15)
else:
self.ssim_overlay_check.pack_forget()
if error_type == "LPIPS":
self.lpips_layers_frame.pack(side=tk.LEFT, padx=15)
else:
self.lpips_layers_frame.pack_forget()
self.update_comparison()
def on_main_tab_changed(self, event=None):
current_tab = self.main_area.tab(self.main_area.select(), "text")
if current_tab == "Visual Comparison":
self.load_metrics()
self.refresh_image_list()
self.update_comparison()
elif current_tab == "Metrics Report":
self.load_metrics()
self.refresh_metrics_display()
def on_equalize_toggle(self):
self.on_model_select() # Refresh UI to show/hide synchronized QPs
def sync_qp(self, source_var, *args):
if not self.equalize_var.get(): return
try:
new_val = source_var.get()
except:
return
standard_codecs = ["AVC", "HEVC", "AV1"]
for mname in self.selected_model_names:
if mname in standard_codecs:
qp_var = self.model_configs[mname]["args"].get("qp")
if qp_var and qp_var.get() != new_val:
qp_var.set(new_val)
def sync_standard_qps(self):
if not self.equalize_var.get():
return
standard_codecs = ["AVC", "HEVC", "AV1"]
first_qp_var = None
for mname in self.selected_model_names:
if mname in standard_codecs:
qp_var = self.model_configs.get(mname, {}).get("args", {}).get("qp")
if qp_var:
if first_qp_var is None:
first_qp_var = qp_var
elif qp_var.get() != first_qp_var.get():
qp_var.set(first_qp_var.get())
def _find_largest_weight(self, weights_dir):
if not os.path.isdir(weights_dir):
return None
candidates = []
for root, _, files in os.walk(weights_dir):
for fname in files:
if fname.endswith((".pth", ".pth.tar", ".pkl", ".pt")):
candidates.append(os.path.join(root, fname))
if not candidates:
return None
return max(candidates, key=lambda p: os.path.getsize(p))
def _find_checkpoint_weight(self, workdir):
search_dirs = [
os.path.join(workdir, "checkpoints"),
os.path.join(ROOT_DIR, "checkpoints")
]
found_files = []
for sd in search_dirs:
if os.path.exists(sd):
for ext in ["*.pth", "*.pth.tar", "*.pkl", "*.pt"]:
for depth in range(4):
wildcards = ["*"] * depth
pattern = os.path.join(sd, *wildcards, ext)
found_files.extend(glob.glob(pattern))
if not found_files:
return None
best_files = [f for f in found_files if 'best' in os.path.basename(f).lower()]
if best_files:
best_files.sort(key=os.path.getmtime, reverse=True)
return best_files[0]
found_files.sort(key=os.path.getmtime, reverse=True)
return found_files[0]
def _apply_weight_autofill(self, model_name, force=False):
config = self.model_configs.get(model_name)
if not config:
return
use_pretrained_var = config.get("use_pretrained")
if use_pretrained_var is None:
return
workdir = os.path.join(ROOT_DIR, config["workdir"].get())
weights_dir = os.path.join(workdir, "weights")
weight_path = self._find_largest_weight(weights_dir) if use_pretrained_var.get() else None
if weight_path is None:
weight_path = self._find_checkpoint_weight(workdir)
for arg_name, var in config["args"].items():
arg_lower = arg_name.lower()
is_weight_arg = any(k in arg_lower for k in ["checkpoint", "model_path", "codec_path", "weights", "weight"])
if not is_weight_arg:
continue
if any(k in arg_lower for k in ["sd_path", "elic_path"]):
continue
if not force and var.get() not in ("", None, "None"):
continue
if weight_path:
var.set(weight_path)
def on_use_pretrained_toggle(self, model_name):
self._apply_weight_autofill(model_name, force=True)
def toggle_error_options(self, event=None):
error_type = self.error_type_var.get()
if error_type != "None":
self.ssim_overlay_check.pack(side=tk.LEFT, padx=15)
else:
self.ssim_overlay_check.pack_forget()
if error_type == "LPIPS":
self.lpips_layers_frame.pack(side=tk.LEFT, padx=15)
else:
self.lpips_layers_frame.pack_forget()
self.update_comparison()
def refresh_sidebar_and_models(self):
"""Toggle global path visibility and refresh model config views."""
if self.show_advanced_var.get():
# In advanced mode, insert the global adv frame after GT settings
self.adv_global_frame.pack(after=self.gt_frame, fill=tk.X)
else:
self.adv_global_frame.pack_forget()
# Also refresh model configuration tabs
self.on_model_select()
def setup_metrics_ui(self):
self.metrics_notebook = ttk.Notebook(self.metrics_tab)
self.metrics_notebook.pack(fill=tk.BOTH, expand=True)
# Tab 1: Single Model Details
self.model_details_tab = ttk.Frame(self.metrics_notebook, padding=10)
self.metrics_notebook.add(self.model_details_tab, text="Single Model Details")
self.metrics_top = ttk.Frame(self.model_details_tab)
self.metrics_top.pack(fill=tk.X, pady=(0, 15))
ttk.Label(self.metrics_top, text="Model Performance Summary", style='Header.TLabel').pack(side=tk.LEFT)
self.metrics_model_sel = ttk.Combobox(self.metrics_top, state="readonly", font=self.F_BASE)
self.metrics_model_sel.pack(side=tk.RIGHT, padx=5)
self.metrics_model_sel.bind("<<ComboboxSelected>>", self.refresh_metrics_display)
ttk.Label(self.metrics_top, text="View Model:", font=self.F_BASE).pack(side=tk.RIGHT)
self.summary_frame = ttk.LabelFrame(self.model_details_tab, text="Averages", padding=10)
self.summary_frame.pack(fill=tk.X, pady=(0, 15))
self.summary_label = ttk.Label(self.summary_frame, text="No evaluation data loaded.", font=self.F_BTN)
self.summary_label.pack()
table_frame = ttk.Frame(self.model_details_tab)
table_frame.pack(fill=tk.BOTH, expand=True)
columns = ("image", "bpp", "psnr", "ssim", "lpips", "vmaf")
self.metrics_tree = ttk.Treeview(table_frame, columns=columns, show="headings")
for col in columns:
self.metrics_tree.heading(col, text=col.upper())
self.metrics_tree.column(col, anchor="center", width=120)
scrollbar = ttk.Scrollbar(table_frame, orient="vertical", command=self.metrics_tree.yview)
self.metrics_tree.configure(yscrollcommand=scrollbar.set)
self.metrics_tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
# Tab 2: Overall Summary
self.overall_summary_tab = ttk.Frame(self.metrics_notebook, padding=10)
self.metrics_notebook.add(self.overall_summary_tab, text="Summary Comparison")
summary_table_frame = ttk.Frame(self.overall_summary_tab)
summary_table_frame.pack(fill=tk.BOTH, expand=True)
sum_cols = ("model", "avg_bpp", "avg_psnr", "avg_ssim", "avg_lpips", "avg_vmaf", "best_img", "best_psnr", "worst_img", "worst_psnr", "time")
self.summary_tree = ttk.Treeview(summary_table_frame, columns=sum_cols, show="headings")
sum_col_widths = {
"model": 120,
"avg_bpp": 80,
"avg_psnr": 100,
"avg_ssim": 100,
"avg_lpips": 100,
"avg_vmaf": 90,
"best_img": 150,
"best_psnr": 100,
"worst_img": 150,
"worst_psnr": 100,
"time": 100
}
for col in sum_cols:
self.summary_tree.heading(col, text=col.replace("_", " ").upper())
self.summary_tree.column(col, anchor="center", width=sum_col_widths.get(col, 100))
sum_scroll = ttk.Scrollbar(summary_table_frame, orient="vertical", command=self.summary_tree.yview)
self.summary_tree.configure(yscrollcommand=sum_scroll.set)
self.summary_tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
sum_scroll.pack(side=tk.RIGHT, fill=tk.Y)
def block_input(self, event):
is_modifier = event.state & (0x4 | 0x8 | 0x10 | 0x40)
if is_modifier and event.keysym.lower() in ('c', 'a'):
return None
if event.keysym in ('Left', 'Right', 'Up', 'Down', 'Prior', 'Next', 'Home', 'End'):
return None
return "break"
def poll_log_queue(self):
try:
while True:
msg = self.log_queue.get_nowait()
self.log_area.insert(tk.END, msg)
self.log_area.see(tk.END)
except queue.Empty:
pass
self.root.after(100, self.poll_log_queue)
def browse_dir(self, var, check_images=False):
current = var.get()
initial = current if current and os.path.exists(current) else ROOT_DIR
path = filedialog.askdirectory(initialdir=initial)
if path:
path = os.path.abspath(os.path.expanduser(path))
if check_images:
try:
has_images = any(f.lower().endswith(('.png', '.jpg', '.jpeg')) for f in os.listdir(path))
if not has_images:
messagebox.showwarning("Warning", "The selected directory appears to have no images.")
except Exception as e:
self.log(f"[ERROR] Could not read directory {path}: {e}\n")
var.set(path)
if check_images:
self.refresh_image_list()
# Reload metrics if the output directory changed
if var == self.out_dir_var:
self.load_metrics()
def browse_file(self, var):
current = var.get()
initial = os.path.dirname(current) if current and os.path.exists(os.path.dirname(current)) else ROOT_DIR
path = filedialog.askopenfilename(initialdir=initial)
if path:
var.set(os.path.abspath(os.path.expanduser(path)))
def log(self, msg):
self.log_queue.put(msg)
def add_external_folder(self):
path = filedialog.askdirectory(title="Select folder with reconstructed images")
if path:
path = os.path.abspath(os.path.expanduser(path))
name = os.path.basename(path)
if not name: name = "External_Folder"
# Ensure unique name
base_name = name
counter = 1
while name in self.external_folders or name in self.registry:
name = f"{base_name}_{counter}"
counter += 1
self.external_folders[name] = path
self.save_external_folders()
self.refresh_external_listbox()
self.log(f"[GUI] Added external folder: {name} -> {path}\n")
def remove_external_folder(self):
selected = self.external_listbox.curselection()
if not selected: return
name = self.external_listbox.get(selected[0])
if name in self.external_folders:
del self.external_folders[name]
self.save_external_folders()
self.refresh_external_listbox()
self.on_model_select()
def refresh_external_listbox(self):
self.external_listbox.delete(0, tk.END)
for name in sorted(self.external_folders.keys()):
self.external_listbox.insert(tk.END, name)
def save_external_folders(self):
save_path = os.path.join(ROOT_DIR, ".gemini_external_folders.json")
try:
with open(save_path, 'w') as f:
json.dump(self.external_folders, f, indent=4)
except Exception as e:
print(f"Failed to save external folders: {e}")
def load_external_folders(self):
save_path = os.path.join(ROOT_DIR, ".gemini_external_folders.json")
if os.path.exists(save_path):
try:
with open(save_path, 'r') as f:
self.external_folders = json.load(f)
except Exception as e:
print(f"Failed to load external folders: {e}")
def on_model_select(self, event=None):
for widget in self.config_scrollable_frame.winfo_children():
widget.destroy()
selected_indices = self.model_listbox.curselection()
self.selected_model_names = [self.model_listbox.get(i) for i in selected_indices]
selected_ext_indices = self.external_listbox.curselection()
self.selected_external_names = [self.external_listbox.get(i) for i in selected_ext_indices]