-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathVisionDepth3D.py
More file actions
5335 lines (4495 loc) · 191 KB
/
VisionDepth3D.py
File metadata and controls
5335 lines (4495 loc) · 191 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
# ── Standard Library ─────────────────────────────
import os, platform, warnings
import sys
import cv2
import json
import tkinter as tk
from tkinter import ttk, filedialog, messagebox
import threading
from threading import Event
from core.audio import launch_audio_gui
import queue
import subprocess
# ── External Libraries ───────────────────────────
from PIL import Image, ImageTk
import torch.nn.functional as F
import numpy as np
import re
import webbrowser
import glob
from scenedetect import VideoManager, SceneManager
from scenedetect.detectors import ContentDetector
# ── VisionDepth3D Custom Modules ────────────────
# 3D Rendering
from core.render_3d import (
render_sbs_3d,
format_3d_output,
frame_to_tensor,
depth_to_tensor,
tensor_to_frame,
pixel_shift_cuda,
generate_anaglyph_3d,
apply_sharpening,
select_input_video,
select_depth_map,
select_output_video,
process_video,
parse_timecode,
render_sbs_3d_image,
)
# Depth Estimation
from core.render_depth import (
ensure_model_downloaded,
update_pipeline,
open_image,
open_video,
choose_output_directory,
process_image,
process_image_folder,
process_images_in_folder,
process_videos_in_folder,
update_progress,
cancel_requested,
request_depth_pause,
request_depth_resume,
request_depth_cancel,
)
from core.merged_pipeline import (
start_merged_pipeline,
start_threaded_pipeline,
select_video_and_generate_frames,
select_output_file,
select_frames_folder,
start_ffmpeg_writer,
)
# DB.py exports you already have
from core.DB import (
FramesWorker,
VideosWorker,
lighten_beta,
_put_label,
_resize_max,
)
from core.vd3d_live import launch_live_gui
from core.preview_gui import open_3d_preview_window
from core.models.depth_anything_v2.dpt import DepthAnythingV2
from transformers import logging
logging.set_verbosity_error()
# At the top of GUI.py
cancel_requested = threading.Event()
os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "expandable_segments:True"
process_thread = None
suspend_flag = Event()
cancel_flag = Event()
SETTINGS_FILE = "settings.json"
translations = {}
current_language = "en"
_loaded_language = None
tooltip_refs = {}
# global dict to store menu references and indices
MENUS = {"file_menu": None, "help_menu": None,
"file_btn": None, "help_btn": None, "lang_btn": None,
"FILE_IDX": {}, "HELP_IDX": {}}
# --- VisionDepth3D Links ---
VD_WEBSITE = "https://visiondepth.github.io/VisionDepth3D/"
VD_GITHUB = "https://github.com/VisionDepth/VisionDepth3D"
VD_METHOD = "https://github.com/VisionDepth/VisionDepth3D/blob/Main-Stable/VisionDepth3D_Method.md"
VD_RELEASES = "https://github.com/VisionDepth/VisionDepth3D/releases"
VD_ISSUES = "https://github.com/VisionDepth/VisionDepth3D/issues"
VD_REDDIT = "https://www.reddit.com/r/VisionDepth3D/"
if platform.system() == "Windows":
# If the env var is set anywhere, drop it so PyTorch won't warn
os.environ.pop("PYTORCH_CUDA_ALLOC_CONF", None)
# Also hide the specific warning just in case
warnings.filterwarnings(
"ignore",
message=".*expandable_segments not supported on this platform.*",
category=UserWarning,
)
try:
import torch
torch.set_grad_enabled(False)
if torch.cuda.is_available():
TORCH_DEVICE_NAME = "cuda"
elif hasattr(torch.backends, "mps") and torch.backends.mps.is_available():
TORCH_DEVICE_NAME = "mps"
else:
TORCH_DEVICE_NAME = "cpu"
TORCH_AVAILABLE = True
except Exception as e:
TORCH_AVAILABLE = False
TORCH_DEVICE_NAME = "cpu"
def _app_dir():
if getattr(sys, "frozen", False):
return os.path.dirname(sys.executable)
return os.path.dirname(os.path.abspath(__file__))
def launch_setup_downloader():
if not messagebox.askyesno(
"Update VisionDepth3D",
"This will close VisionDepth3D and open the updater.\n\nContinue?"
):
return
base = _app_dir()
exe_name = "VisionDepth3D_Updater.exe"
path = os.path.join(base, exe_name)
if not os.path.exists(path):
path2 = os.path.join(base, "tools", exe_name)
if os.path.exists(path2):
path = path2
if not os.path.exists(path):
messagebox.showerror(
"Updater not found",
f"Could not find:\n{exe_name}\n\nLooked in:\n{base}\n{os.path.join(base,'tools')}"
)
return
try:
subprocess.Popen([path], cwd=os.path.dirname(path))
except Exception as e:
messagebox.showerror("Failed to launch updater", str(e))
return
# close VD3D after updater starts
try:
root.after(150, root.quit) # root.destroy also works, quit is safer for Tk loops
except Exception:
pass
def gpu_available():
try:
import torch
return torch.device("cuda" if torch.cuda.is_available() else "cpu").type
except Exception:
return "cpu"
def _menu_set(menu, idx, label, accel=None):
"""Update a menu entry label with optional accelerator text aligned right."""
if not menu or idx is None:
return
if accel:
# \t is the magic: Tkinter aligns everything after \t flush right
menu.entryconfig(idx, label=f"{label}\t{accel}")
else:
menu.entryconfig(idx, label=label)
def offload_available():
try:
import accelerate
return torch.cuda.is_available()
except ImportError:
return False
def open_github():
"""Opens the GitHub repository in a web browser."""
webbrowser.open_new("https://github.com/VisionDepth/VisionDepth3D")
def open_aspect_ratio_CheatSheet():
"""Opens the Aspect Ratio Cheat Sheet."""
webbrowser.open_new("https://www.wearethefirehouse.com/aspect-ratio-cheat-sheet")
def ui_select_input_video():
path = select_input_video(
input_video_path,
video_thumbnail_label,
video_specs_label,
update_aspect_preview,
original_video_width,
original_video_height,
)
# if your select_* returns a path you can save after:
try:
if path: save_settings()
except Exception:
pass
def ui_select_depth_map():
path = select_depth_map(
selected_depth_map,
depth_map_label,
)
try:
if path: save_settings()
except Exception:
pass
def ui_select_output_path():
path = output_sbs_video_path(
selected_depth_map,
depth_map_label,
)
try:
if path: save_settings()
except Exception:
pass
def _apply_preset_config(config: dict):
"""
Applies preset JSON values to existing Tk variables safely.
Ignores unknown keys so older/newer presets never crash.
"""
if not isinstance(config, dict):
raise ValueError("Preset must be a JSON object")
missing = []
for key, value in config.items():
var = globals().get(key)
if var is None:
missing.append(key)
continue
try:
if hasattr(var, "set"):
var.set(value)
except Exception:
pass
# Optional: refresh UI after applying
try:
refresh_ui_labels()
except Exception:
pass
if missing:
print(f"Preset keys not bound to UI vars (ignored): {missing}")
def load_preset_dialog():
"""Pick any preset JSON (defaulting to PRESET_DIR) and apply it."""
initial = PRESET_DIR if os.path.isdir(PRESET_DIR) else os.getcwd()
path = filedialog.askopenfilename(
title="Load Preset",
initialdir=initial,
filetypes=[("Preset JSON", "*.json"), ("All files", "*.*")]
)
if not path:
return
try:
with open(path, "r", encoding="utf-8") as f:
config = json.load(f)
_apply_preset_config(config)
# If it was inside PRESET_DIR, reflect the name in any preset selector UI
try:
base = os.path.splitext(os.path.basename(path))[0]
if 'preset_var' in globals():
preset_var.set(base)
except Exception:
pass
print(f"Loaded preset from file: {path}")
except Exception as e:
messagebox.showerror("Load Preset", f"Failed to load preset:\n{e}")
def apply_3d_suffix(base_out: str, output_format: str, eye_mode: str) -> str:
base, ext = os.path.splitext(base_out)
# Normalize
fmt = output_format.strip().lower()
mode = eye_mode.strip().lower()
suffix = ""
if mode == "sbs":
if fmt == "full-sbs":
suffix = "_LRF_Full_SBS"
elif fmt == "half-sbs":
suffix = "_LRF_Half_SBS"
elif fmt == "vr":
suffix = "_VR"
elif fmt == "red-cyan anaglyph":
suffix = "_Anaglyph"
elif fmt == "passive interlaced":
suffix = "_Interlaced"
elif mode == "left":
suffix = "_LRF_Left"
elif mode == "right":
suffix = "_LRF_Right"
elif mode == "both":
# handled per-eye when you build left/right names
pass
# If no suffix matched, just return original
if not suffix:
return base_out
return f"{base}{suffix}{ext}"
def handle_generate_3d():
global process_thread, is_rendering
try:
# 🔀 Read current mode ("Single", "Batch", "Image")
current_mode = mode.get().strip() if 'mode' in globals() else "Single"
# 🧩 If we're in Image mode, validate paths *before* spawning a thread
if current_mode == "Image":
if (not input_image_path.get().strip() or
not depth_image_path.get().strip() or
not output_image_path.get().strip()):
messagebox.showerror(
"Missing paths",
"Please select input image, depth map image, and output image path before rendering."
)
return
if process_thread is not None and process_thread.is_alive():
print("⚠️ 3D processing already running! Use Suspend/Resume/Cancel.")
return
print("🚀 Starting new 3D processing thread...")
cancel_flag.clear()
suspend_flag.clear()
is_rendering = True
preserve_hdr10 = bool(preserve_hdr10_var.get())
# --- small helpers ---
def _get_time(v):
try:
s = v.get().strip()
return parse_timecode(s) if s else None
except Exception:
return None
def _get_num(varname, default=0.0):
return globals()[varname].get() if varname in globals() else default
# clip window (video only; harmless if unused for images)
start_s = _get_time(clip_start_var) if 'clip_start_var' in globals() else None
end_s = _get_time(clip_end_var) if 'clip_end_var' in globals() else None
if start_s is not None and end_s is not None:
if end_s <= start_s:
end_s = start_s + end_s
if end_s <= start_s:
end_s = start_s + 0.001
# colors
sat = (color_saturation.get() if 'color_saturation' in globals() else saturation.get())
con = (color_contrast.get() if 'color_contrast' in globals() else contrast.get())
bri = (color_brightness.get() if 'color_brightness' in globals() else brightness.get())
# IPD
ipd_value = 0.0
if 'ipd_enabled_var' in globals() and ipd_enabled_var.get():
ipd_value = _get_num('ipd_factor_var', 1.0)
# 👇 read output-mode from the UI ("sbs"|"left"|"right"|"both")
eye_mode = stereo_out_var.get().strip().lower()
# 👇 derive base output name depending on mode (Single / Batch / Image)
current_mode = mode.get().strip() if 'mode' in globals() else "Single"
if current_mode == "Image":
base_out = output_image_path.get().strip()
else:
base_out = output_sbs_video_path.get().strip()
if not base_out:
# For safety: if there's somehow no base_out, bail early
messagebox.showerror("Output path", "Please choose an output path before rendering.")
is_rendering = False
return
# Normalized format string from the 3D format dropdown
fmt = output_format.get().strip() if hasattr(output_format, "get") else str(output_format).strip()
# Precompute filenames with 3D suffixes
sbs_out = apply_3d_suffix(base_out, fmt, "sbs")
left_out = apply_3d_suffix(base_out, fmt, "left")
right_out = apply_3d_suffix(base_out, fmt, "right")
# what we will run
if eye_mode == "sbs":
jobs = [("sbs", sbs_out)]
elif eye_mode == "left":
jobs = [("left", left_out)]
elif eye_mode == "right":
jobs = [("right", right_out)]
elif eye_mode == "both":
# two separate renders, each gets its own suffix
jobs = [("left", left_out), ("right", right_out)]
else:
# fallback – treat as SBS
jobs = [("sbs", sbs_out)]
def run_and_clear_flag():
nonlocal start_s, end_s, sat, con, bri, ipd_value, preserve_hdr10, eye_mode
created = []
try:
for mode_name, out_path in jobs:
print(f"▶️ Render pass: {mode_name} → {out_path}")
# 🖼️ IMAGE MODE: use render_sbs_3d_image(...)
if current_mode == "Image":
out_path_done = render_sbs_3d_image(
input_image_path=input_image_path.get(),
depth_image_path=depth_image_path.get(),
output_image_path=out_path,
fg_shift=fg_shift.get(),
mg_shift=mg_shift.get(),
bg_shift=bg_shift.get(),
sharpness_factor=sharpness_factor.get(),
output_format=output_format.get(),
selected_aspect_ratio=selected_aspect_ratio,
aspect_ratios=aspect_ratios,
feather_strength=feather_strength.get(),
blur_ksize=blur_ksize.get(),
use_subject_tracking=use_subject_tracking.get(),
use_floating_window=use_floating_window.get(),
max_pixel_shift_percent=max_pixel_shift.get(),
auto_crop_black_bars=auto_crop_black_bars.get(),
parallax_balance=parallax_balance.get(),
zero_parallax_strength=zero_parallax_strength.get(),
enable_edge_masking=enable_edge_masking.get(),
enable_feathering=enable_feathering.get(),
dof_strength=dof_strength.get(),
convergence_strength=convergence_strength.get(),
enable_dynamic_convergence=enable_dynamic_convergence.get(),
ipd_factor=ipd_value,
depth_pop_gamma=depth_pop_gamma.get(),
depth_pop_mid=depth_pop_mid.get(),
depth_stretch_lo=depth_stretch_lo.get(),
depth_stretch_hi=depth_stretch_hi.get(),
fg_pop_multiplier=fg_pop_multiplier.get(),
bg_push_multiplier=bg_push_multiplier.get(),
subject_lock_strength=subject_lock_strength.get(),
color_saturation=sat,
color_contrast=con,
color_brightness=bri,
eye_mode=mode_name,
)
# 🎬 VIDEO MODES ("Single" or batch queue): use process_video(...)
else:
out_path_done = process_video(
input_video_path,
selected_depth_map,
output_sbs_video_path,
selected_codec,
fg_shift, mg_shift, bg_shift,
sharpness_factor,
output_format,
selected_aspect_ratio, aspect_ratios,
feather_strength, blur_ksize,
progress, progress_label,
suspend_flag, cancel_flag,
use_ffmpeg, preserve_hdr10,
selected_ffmpeg_codec, crf_value,
use_subject_tracking,
use_floating_window,
max_pixel_shift,
auto_crop_black_bars,
parallax_balance,
preserve_original_aspect,
zero_parallax_strength,
enable_edge_masking,
enable_feathering,
skip_blank_frames,
dof_strength,
convergence_strength,
enable_dynamic_convergence,
depth_pop_gamma, depth_pop_mid,
depth_stretch_lo, depth_stretch_hi,
fg_pop_multiplier, bg_push_multiplier,
subject_lock_strength,
sat, con, bri,
ipd_value,
start_s, end_s,
eye_mode=mode_name,
output_override=out_path,
keep_original_audio=keep_original_audio.get()
)
if out_path_done:
created.append(out_path_done)
if cancel_flag.is_set():
break
# UI notify (on main thread)
ui_root = progress_label.winfo_toplevel()
if created:
msg = "Created file(s):\n" + "\n".join(created)
ui_root.after(0, lambda: messagebox.showinfo("3D Render", msg))
else:
ui_root.after(0, lambda: messagebox.showwarning("3D Render", "Finished, but no outputs were created."))
except Exception as e:
print(f"❌ Error during 3D processing: {e}")
finally:
is_rendering = False
process_thread = threading.Thread(target=run_and_clear_flag, daemon=True)
process_thread.start()
except Exception as e:
print(f"❌ Error starting 3D processing: {e}")
def handle_open_preview():
# optional: mirror Start button behavior
try:
save_settings()
except Exception:
pass
# call the same preview function with the same args as your button
return open_3d_preview_window(
input_video_path,
selected_depth_map,
fg_shift,
mg_shift,
bg_shift,
blur_ksize,
feather_strength,
use_subject_tracking,
use_floating_window,
zero_parallax_strength,
parallax_balance,
enable_edge_masking,
enable_feathering,
sharpness_factor,
max_pixel_shift,
dof_strength,
convergence_strength,
enable_dynamic_convergence,
depth_pop_gamma,
depth_pop_mid,
depth_stretch_lo,
depth_stretch_hi,
fg_pop_multiplier,
bg_push_multiplier,
subject_lock_strength,
saturation,
contrast,
brightness,
)
def _val(v):
# Only call .get() on actual tk.Variable instances; otherwise return as-is.
return v.get() if isinstance(v, tk.Variable) else v
def rendering_in_progress():
return is_rendering
def is_render_done():
global process_thread
return process_thread is None or not process_thread.is_alive()
def set_language(lang_code, *, save=True):
global current_language
current_language = lang_code
load_language(lang_code)
refresh_ui_labels()
refresh_menu_labels()
if save:
save_settings()
def load_language(lang_code):
global translations, _loaded_language
if _loaded_language == lang_code:
return # already loaded, skip duplicate
try:
path = f"languages/{lang_code}.json"
with open(path, "r", encoding="utf-8") as f:
translations = json.load(f)
_loaded_language = lang_code
print(f"UI Language Loaded: '{lang_code}' with {len(translations)}")
except Exception as e:
print(f"⚠️ Failed to load language '{lang_code}': {e}")
translations = {}
_loaded_language = None
def t(key):
return translations.get(key, key)
# Load default language before building GUI
load_language("en")
# Get absolute path to resource (for PyInstaller compatibility)
def resource_path(relative_path):
try:
base_path = sys._MEIPASS
except AttributeError:
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
#Force include core/ into path
core_dir = resource_path("core")
if core_dir not in sys.path:
sys.path.insert(0, core_dir)
#Force include languages/ into path
languages_dir = resource_path("languages")
if languages_dir not in sys.path:
sys.path.insert(0, languages_dir)
#Inject DLL directory into PATH
#def inject_dll_directory():
# dll_dir = resource_path("dlls")
# if os.path.isdir(dll_dir):
# os.environ["PATH"] = dll_dir + os.pathsep + os.environ.get("PATH", "")
# else:
# print(f"[Warning] DLL folder not found: {dll_dir}")
# 🟢 Call this before any ONNX/TensorRT/CUDA init
#inject_dll_directory()
def save_settings():
settings = {name: var.get() for name, var in gui_variables.items()}
if root.winfo_exists():
settings["window_geometry"] = root.geometry()
settings["language"] = current_language
# ✅ Save input/depth video paths
if "input_video_path" in globals() and hasattr(input_video_path, "get"):
settings["input_video_path"] = input_video_path.get()
if "selected_depth_map" in globals() and hasattr(selected_depth_map, "get"):
settings["selected_depth_map"] = selected_depth_map.get()
with open(SETTINGS_FILE, "w", encoding="utf-8") as f:
json.dump(settings, f, indent=4)
print("Settings saved.")
def prompt_and_save_preset():
file_path = filedialog.asksaveasfilename(
title="Save Preset As",
defaultextension=".json",
filetypes=[("JSON Files", "*.json")],
initialdir=PRESET_DIR,
initialfile="custom_preset.json"
)
if file_path:
preset_name = os.path.basename(file_path)
save_current_preset(preset_name)
def load_settings():
global current_language
if not os.path.exists(SETTINGS_FILE):
return
try:
with open(SETTINGS_FILE, "r", encoding="utf-8") as f:
settings = json.load(f)
except json.JSONDecodeError as e:
print(f"❌ Error loading settings: {e}")
return
for name, value in settings.items():
if name in gui_variables:
try:
gui_variables[name].set(value)
except Exception as e:
print(f"⚠️ Failed to set variable '{name}': {e}")
# ✅ Restore input video path and refresh thumbnail + video info
input_path = settings.get("input_video_path", "")
if input_path and os.path.exists(input_path):
input_video_path.set(input_path)
try:
cap = cv2.VideoCapture(input_path)
ret, frame = cap.read()
fps = cap.get(cv2.CAP_PROP_FPS)
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
cap.release()
if ret:
THUMB_W, THUMB_H = 160, 90 # ⭐ sweet spot
rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
img = Image.fromarray(rgb).resize((THUMB_W, THUMB_H), Image.LANCZOS)
img_tk = ImageTk.PhotoImage(img)
video_thumbnail_label.config(image=img_tk)
video_thumbnail_label.image = img_tk # Retain reference
original_video_width.set(width)
original_video_height.set(height)
video_specs_label.config(
text=f"Resolution: {width}x{height}\nFPS: {fps:.2f}" if fps > 0 else "FPS: Unknown"
)
update_aspect_preview()
except Exception as e:
print(f"⚠️ Could not render video thumbnail: {e}")
# ✅ Restore depth map path and label
depth_path = settings.get("selected_depth_map", "")
if depth_path and os.path.exists(depth_path):
selected_depth_map.set(depth_path)
try:
depth_map_label.config(
text=f"Selected Depth Map:\n{os.path.basename(depth_path)}"
)
except Exception as e:
print(f"⚠️ Could not render depth label: {e}")
# ✅ Restore language and window size
if "language" in settings:
set_language(settings["language"], save=False)
if "window_geometry" in settings:
root.geometry(settings["window_geometry"])
print("Settings loaded from file.")
def reset_settings():
"""Resets all GUI values and UI elements to their default states."""
# 🎬 File Paths and Codecs
input_video_path.set("")
selected_depth_map.set("")
output_sbs_video_path.set("")
selected_codec.set("mp4v")
selected_ffmpeg_codec.set("H.264 / AVC (libx264 - CPU)")
output_format.set("Full-SBS")
# 🧠 3D Shifting Parameters
fg_shift.set(5.0)
mg_shift.set(0.5)
bg_shift.set(-1.5)
# --- NEW: Pop & Subject Controls ---
depth_pop_gamma.set(0.85) # mid-contrast gamma curve for depth
depth_pop_mid.set(0.50) # mid depth pivot point
depth_stretch_lo.set(0.05) # lower depth compression bound
depth_stretch_hi.set(0.95) # upper depth compression bound
fg_pop_multiplier.set(1.20) # extra push-out for FG
bg_push_multiplier.set(1.10) # extra push-back for BG
subject_lock_strength.set(1.00) # subject tracking lock weight
# ✨ Visual Enhancements
sharpness_factor.set(0.2)
# 🧼 Edge Cleanup
feather_strength.set(0.0)
blur_ksize.set(1)
# 🎛️ Advanced Stereo Controls
parallax_balance.set(0.80)
max_pixel_shift.set(0.20)
dof_strength.set(2.0)
# 🟢 Toggles
use_subject_tracking.set(False)
use_floating_window.set(False)
auto_crop_black_bars.set(False)
preserve_original_aspect.set(False)
zero_parallax_strength.set(0.000)
skip_blank_frames.set(False)
convergence_strength.set(0.0)
enable_dynamic_convergence.set(True)
# 🎥 CRF for FFmpeg
crf_value.set(23)
# 🎨 Color Grading
saturation.set(1.00) # 0.00..2.00
contrast.set(1.00) # 0.00..2.00
brightness.set(0.00) # -0.50..+0.50
# 🖼️ UI Resets
try:
video_thumbnail_label.config(image="", text="No preview")
video_thumbnail_label.image = None
video_specs_label.config(text="Video Info:\nResolution: -\nFPS: -")
except Exception as e:
print(f"⚠️ GUI reset skipped: {e}")
# 🔁 Reset aspect preview if available
try:
update_aspect_preview()
except Exception as e:
print(f"⚠️ Aspect preview reset skipped: {e}")
# --- IPD controls ---
ipd_enabled_var.set(True) # or False if you want it off by default
ipd_factor_var.set(1.00)
try:
ipd_readout.config(text=f"{ipd_factor_var.get():.2f}x" if ipd_enabled_var.get() else "OFF")
except Exception:
pass
# --- Clip window (start/end) ---
try:
clip_start_var.set("") # clears the UI entries
clip_end_var.set("")
except Exception:
pass
# --- Toggles that weren’t reset yet ---
use_ffmpeg.set(False) # you currently don’t reset this
enable_edge_masking.set(True) # whichever default you want
enable_feathering.set(True) # whichever default you want
# --- Aspect ratio choice ---
try:
selected_aspect_ratio.set("Default (16:9)")
except Exception:
pass
# --- Progress & flags ---
progress["value"] = 0
progress_label.config(text="0%")
cancel_flag.clear()
suspend_flag.clear()
# --- Original video dims cache (if these are tk variables in your UI) ---
try:
original_video_width.set(0)
original_video_height.set(0)
except Exception:
pass
messagebox.showinfo("Settings Reset", "✅ All settings and preview panels reset to default!")
def cancel_processing():
global cancel_flag, suspend_flag, cancel_requested, process_thread
cancel_flag.set()
cancel_requested.set()
cancel_requested.clear()
suspend_flag.clear()
# 🔥 Reset the thread if it's no longer running
if process_thread is not None and not process_thread.is_alive():
print("🧼 Cleaning up finished thread...")
process_thread = None
print("❌ Processing canceled (all systems).")
def suspend_processing():
global suspend_flag
suspend_flag.set()
print("⏸ Processing Suspended!")
def resume_processing():
global suspend_flag
suspend_flag.clear()
print("▶ Processing Resumed!")
is_rendering = False # Make sure this is defined globally at the top of your script
def grab_frame_from_video(video_path, frame_idx=0):
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():
print(f"❌ Failed to open video: {video_path}")
return None
cap.set(cv2.CAP_PROP_POS_FRAMES, frame_idx)
ret, frame = cap.read()
cap.release()
return frame if ret else None
def update_aspect_preview(*args):
try:
ratio = aspect_ratios[selected_aspect_ratio.get()]
format_selected = output_format.get()
# 👇 Use .get() to access live values
width = original_video_width.get()
height = original_video_height.get()
if format_selected == "Full-SBS":
base_width = width * 2
elif format_selected == "Half-SBS":
base_width = width
elif format_selected == "VR":
base_width = 4096
height = int(base_width / ratio)
else:
base_width = width
height = int(base_width / ratio)
aspect_preview_label.config(
text=f"🧮 {base_width}x{height} ({ratio:.2f}:1)"
)
except Exception as e:
aspect_preview_label.config(text="❌ Invalid Aspect Ratio")
print(f"[Aspect Preview Error] {e}")
class CreateToolTip:
def __init__(self, widget, text_provider):
self.widget = widget
self.text_provider = text_provider
self.tip_window = None
self.widget.bind("<Enter>", self._on_enter, add="+")
self.widget.bind("<Leave>", self._on_leave, add="+")
self.widget.bind("<ButtonPress>", self._on_leave, add="+") # hide on click
def _get_text(self):
try:
val = self.text_provider()
return (val or "").strip()
except Exception:
return ""
def _on_enter(self, _):
txt = self._get_text()
if not txt:
return
self.show_tooltip(txt)
def _on_leave(self, _):
self.hide_tooltip()
def show_tooltip(self, text):
if self.tip_window:
return
x = self.widget.winfo_rootx() + 20
y = self.widget.winfo_rooty() + self.widget.winfo_height() + 8
tw = tk.Toplevel(self.widget)
tw.wm_overrideredirect(True)
tw.wm_attributes("-topmost", True)
tw.wm_geometry(f"+{x}+{y}")
frm = tk.Frame(tw, bg="#2a2a2a", bd=1, highlightthickness=0)
lbl = tk.Label(frm, text=text, bg="#2a2a2a", fg="white",
font=("Segoe UI", 9), justify="left", padx=8, pady=5)
frm.pack()
lbl.pack()
self.tip_window = tw
def hide_tooltip(self):
if self.tip_window:
self.tip_window.destroy()
self.tip_window = None
# ---GUI Setup---
# -----------------------
# Global Variables & Setup