forked from Anjok07/ultimatevocalremovergui
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUVR.py
5025 lines (4056 loc) · 285 KB
/
UVR.py
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
# GUI modules
import audioread
import base64
import gui_data.sv_ttk
import hashlib
import json
import librosa
import logging
import math
import natsort
import onnx
import os
import pickle # Save Data
import psutil
from pyglet import font
import pyperclip
import base64
import queue
import re
import shutil
import subprocess
import sys
import soundfile as sf
import time
#import timeit
import tkinter as tk
import tkinter.filedialog
import tkinter.font
import tkinter.messagebox
import tkinter.ttk as ttk
import torch
import urllib.request
import webbrowser
import wget
import traceback
from __version__ import VERSION, PATCH, PATCH_MAC, PATCH_LINUX
from cryptography.fernet import Fernet
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from datetime import datetime
from gui_data.app_size_values import ImagePath, AdjustedValues as av
from gui_data.constants import *
from gui_data.error_handling import error_text, error_dialouge
from gui_data.old_data_check import file_check, remove_unneeded_yamls, remove_temps
from gui_data.tkinterdnd2 import TkinterDnD, DND_FILES
from lib_v5.vr_network.model_param_init import ModelParameters
from kthread import KThread
from lib_v5 import spec_utils
from pathlib import Path
from separate import SeperateDemucs, SeperateMDX, SeperateVR, save_format
from playsound import playsound
from tkinter import *
from tkinter.tix import *
import re
from typing import List
import ssl
logging.basicConfig(format='%(asctime)s - %(message)s', level=logging.INFO)
logging.info('UVR BEGIN')
is_dnd_compatible = True
banner_placement = -2
if OPERATING_SYSTEM=="Darwin":
OPEN_FILE_func = lambda input_string:subprocess.Popen(["open", input_string])
dnd_path_check = MAC_DND_CHECK
banner_placement = -8
current_patch = PATCH_MAC
is_windows = False
right_click_button = '<Button-2>'
application_extension = ".dmg"
elif OPERATING_SYSTEM=="Linux":
OPEN_FILE_func = lambda input_string:subprocess.Popen(["open", input_string])
dnd_path_check = LINUX_DND_CHECK
current_patch = PATCH_LINUX
is_windows = False
right_click_button = '<Button-3>'
application_extension = ".zip"
elif OPERATING_SYSTEM=="Windows":
OPEN_FILE_func = lambda input_string:os.startfile(input_string)
dnd_path_check = WINDOWS_DND_CHECK
current_patch = PATCH
is_windows = True
right_click_button = '<Button-3>'
application_extension = ".exe"
def right_click_release_linux(window, top_win=None):
if OPERATING_SYSTEM=="Linux":
root.bind('<Button-1>', lambda e:window.destroy())
if top_win:
top_win.bind('<Button-1>', lambda e:window.destroy())
if not is_windows:
ssl._create_default_https_context = ssl._create_unverified_context
try:
with open(os.path.join(os.getcwd(), 'tmp', 'splash.txt'), 'w') as f:
f.write('1')
except:
print('No splash screen.')
def save_data(data):
"""
Saves given data as a .pkl (pickle) file
Paramters:
data(dict):
Dictionary containing all the necessary data to save
"""
# Open data file, create it if it does not exist
with open('data.pkl', 'wb') as data_file:
pickle.dump(data, data_file)
def load_data() -> dict:
"""
Loads saved pkl file and returns the stored data
Returns(dict):
Dictionary containing all the saved data
"""
try:
with open('data.pkl', 'rb') as data_file: # Open data file
data = pickle.load(data_file)
return data
except (ValueError, FileNotFoundError):
# Data File is corrupted or not found so recreate it
save_data(data=DEFAULT_DATA)
return load_data()
def load_model_hash_data(dictionary):
'''Get the model hash dictionary'''
with open(dictionary) as d:
data = d.read()
return json.loads(data)
# Change the current working directory to the directory
# this file sits in
if getattr(sys, 'frozen', False):
# If the application is run as a bundle, the PyInstaller bootloader
# extends the sys module by a flag frozen=True and sets the app
# path into variable _MEIPASS'.
BASE_PATH = sys._MEIPASS
else:
BASE_PATH = os.path.dirname(os.path.abspath(__file__))
os.chdir(BASE_PATH) # Change the current working directory to the base path
debugger = []
#--Constants--
#Models
MODELS_DIR = os.path.join(BASE_PATH, 'models')
VR_MODELS_DIR = os.path.join(MODELS_DIR, 'VR_Models')
MDX_MODELS_DIR = os.path.join(MODELS_DIR, 'MDX_Net_Models')
DEMUCS_MODELS_DIR = os.path.join(MODELS_DIR, 'Demucs_Models')
DEMUCS_NEWER_REPO_DIR = os.path.join(DEMUCS_MODELS_DIR, 'v3_v4_repo')
#Cache & Parameters
VR_HASH_DIR = os.path.join(VR_MODELS_DIR, 'model_data')
VR_HASH_JSON = os.path.join(VR_MODELS_DIR, 'model_data', 'model_data.json')
MDX_HASH_DIR = os.path.join(MDX_MODELS_DIR, 'model_data')
MDX_HASH_JSON = os.path.join(MDX_MODELS_DIR, 'model_data', 'model_data.json')
ENSEMBLE_CACHE_DIR = os.path.join(BASE_PATH, 'gui_data', 'saved_ensembles')
SETTINGS_CACHE_DIR = os.path.join(BASE_PATH, 'gui_data', 'saved_settings')
VR_PARAM_DIR = os.path.join(BASE_PATH, 'lib_v5', 'vr_network', 'modelparams')
SAMPLE_CLIP_PATH = os.path.join(BASE_PATH, 'temp_sample_clips')
ENSEMBLE_TEMP_PATH = os.path.join(BASE_PATH, 'ensemble_temps')
#Style
ICON_IMG_PATH = os.path.join(BASE_PATH, 'gui_data', 'img', 'GUI-Icon.ico')
if not is_windows:
MAIN_ICON_IMG_PATH = os.path.join(BASE_PATH, 'gui_data', 'img', 'GUI-Icon.png')
FONT_PATH = os.path.join(BASE_PATH, 'gui_data', 'fonts', 'centurygothic', 'GOTHIC.TTF')#ensemble_temps
#Other
COMPLETE_CHIME = os.path.join(BASE_PATH, 'gui_data', 'complete_chime.wav')
FAIL_CHIME = os.path.join(BASE_PATH, 'gui_data', 'fail_chime.wav')
CHANGE_LOG = os.path.join(BASE_PATH, 'gui_data', 'change_log.txt')
SPLASH_DOC = os.path.join(BASE_PATH, 'tmp', 'splash.txt')
file_check(os.path.join(MODELS_DIR, 'Main_Models'), VR_MODELS_DIR)
file_check(os.path.join(DEMUCS_MODELS_DIR, 'v3_repo'), DEMUCS_NEWER_REPO_DIR)
remove_unneeded_yamls(DEMUCS_MODELS_DIR)
remove_temps(ENSEMBLE_TEMP_PATH)
remove_temps(SAMPLE_CLIP_PATH)
remove_temps(os.path.join(BASE_PATH, 'img'))
if not os.path.isdir(ENSEMBLE_TEMP_PATH):
os.mkdir(ENSEMBLE_TEMP_PATH)
if not os.path.isdir(SAMPLE_CLIP_PATH):
os.mkdir(SAMPLE_CLIP_PATH)
model_hash_table = {}
data = load_data()
def drop(event, accept_mode: str = 'files'):
"""Drag & Drop verification process"""
path = event.data
if accept_mode == 'folder':
path = path.replace('{', '').replace('}', '')
if not os.path.isdir(path):
tk.messagebox.showerror(parent=root,
title='Invalid Folder',
message='Your given export path is not a valid folder!')
return
# Set Variables
root.export_path_var.set(path)
elif accept_mode == 'files':
# Clean path text and set path to the list of paths
path = path.replace("{", "").replace("}", "")
for dnd_file in dnd_path_check:
path = path.replace(f" {dnd_file}", f";{dnd_file}")
path = path.split(';')
path[-1] = path[-1].replace(';', '')
# Set Variables
root.inputPaths = tuple(path)
root.process_input_selections()
root.update_inputPaths()
else:
# Invalid accept mode
return
class ModelData():
def __init__(self, model_name: str,
selected_process_method=ENSEMBLE_MODE,
is_secondary_model=False,
primary_model_primary_stem=None,
is_primary_model_primary_stem_only=False,
is_primary_model_secondary_stem_only=False,
is_pre_proc_model=False,
is_dry_check=False):
self.is_gpu_conversion = 0 if root.is_gpu_conversion_var.get() else -1
self.is_normalization = root.is_normalization_var.get()
self.is_primary_stem_only = root.is_primary_stem_only_var.get()
self.is_secondary_stem_only = root.is_secondary_stem_only_var.get()
self.is_denoise = root.is_denoise_var.get()
self.wav_type_set = root.wav_type_set
self.mp3_bit_set = root.mp3_bit_set_var.get()
self.save_format = root.save_format_var.get()
self.is_invert_spec = root.is_invert_spec_var.get()
self.demucs_stems = root.demucs_stems_var.get()
self.demucs_source_list = []
self.demucs_stem_count = 0
self.model_name = model_name
self.process_method = selected_process_method
self.model_status = False if self.model_name == CHOOSE_MODEL or self.model_name == NO_MODEL else True
self.primary_stem = None
self.secondary_stem = None
self.is_ensemble_mode = False
self.ensemble_primary_stem = None
self.ensemble_secondary_stem = None
self.primary_model_primary_stem = primary_model_primary_stem
self.is_secondary_model = is_secondary_model
self.secondary_model = None
self.secondary_model_scale = None
self.demucs_4_stem_added_count = 0
self.is_demucs_4_stem_secondaries = False
self.is_4_stem_ensemble = False
self.pre_proc_model = None
self.pre_proc_model_activated = False
self.is_pre_proc_model = is_pre_proc_model
self.is_dry_check = is_dry_check
self.model_samplerate = 44100
self.is_demucs_pre_proc_model_inst_mix = False
self.manual_download_Button = None
self.secondary_model_4_stem = []
self.secondary_model_4_stem_scale = []
self.secondary_model_4_stem_names = []
self.secondary_model_4_stem_model_names_list = []
self.all_models = []
self.secondary_model_other = None
self.secondary_model_scale_other = None
self.secondary_model_bass = None
self.secondary_model_scale_bass = None
self.secondary_model_drums = None
self.secondary_model_scale_drums = None
if selected_process_method == ENSEMBLE_MODE:
partitioned_name = model_name.partition(ENSEMBLE_PARTITION)
self.process_method = partitioned_name[0]
self.model_name = partitioned_name[2]
self.model_and_process_tag = model_name
self.ensemble_primary_stem, self.ensemble_secondary_stem = root.return_ensemble_stems()
self.is_ensemble_mode = True if not is_secondary_model and not is_pre_proc_model else False
self.is_4_stem_ensemble = True if root.ensemble_main_stem_var.get() == FOUR_STEM_ENSEMBLE and self.is_ensemble_mode else False
self.pre_proc_model_activated = root.is_demucs_pre_proc_model_activate_var.get() if not self.ensemble_primary_stem == VOCAL_STEM else False
if self.process_method == VR_ARCH_TYPE:
self.is_secondary_model_activated = root.vr_is_secondary_model_activate_var.get() if not self.is_secondary_model else False
self.aggression_setting = float(int(root.aggression_setting_var.get())/100)
self.is_tta = root.is_tta_var.get()
self.is_post_process = root.is_post_process_var.get()
self.window_size = int(root.window_size_var.get())
self.batch_size = int(root.batch_size_var.get())
self.crop_size = int(root.crop_size_var.get())
self.is_high_end_process = 'mirroring' if root.is_high_end_process_var.get() else 'None'
self.post_process_threshold = float(root.post_process_threshold_var.get())
self.model_path = os.path.join(VR_MODELS_DIR, f"{self.model_name}.pth")
self.get_model_hash()
if self.model_hash:
self.model_data = self.get_model_data(VR_HASH_DIR, root.vr_hash_MAPPER)
if self.model_data:
vr_model_param = os.path.join(VR_PARAM_DIR, "{}.json".format(self.model_data["vr_model_param"]))
self.primary_stem = self.model_data["primary_stem"]
self.secondary_stem = STEM_PAIR_MAPPER[self.primary_stem]
self.vr_model_param = ModelParameters(vr_model_param)
self.model_samplerate = self.vr_model_param.param['sr']
else:
self.model_status = False
if self.process_method == MDX_ARCH_TYPE:
self.is_secondary_model_activated = root.mdx_is_secondary_model_activate_var.get() if not is_secondary_model else False
self.margin = int(root.margin_var.get())
self.chunks = root.determine_auto_chunks(root.chunks_var.get(), self.is_gpu_conversion)
self.get_mdx_model_path()
self.get_model_hash()
if self.model_hash:
self.model_data = self.get_model_data(MDX_HASH_DIR, root.mdx_hash_MAPPER)
if self.model_data:
self.compensate = self.model_data["compensate"] if root.compensate_var.get() == AUTO_SELECT else float(root.compensate_var.get())
self.mdx_dim_f_set = self.model_data["mdx_dim_f_set"]
self.mdx_dim_t_set = self.model_data["mdx_dim_t_set"]
self.mdx_n_fft_scale_set = self.model_data["mdx_n_fft_scale_set"]
self.primary_stem = self.model_data["primary_stem"]
self.secondary_stem = STEM_PAIR_MAPPER[self.primary_stem]
else:
self.model_status = False
if self.process_method == DEMUCS_ARCH_TYPE:
self.is_secondary_model_activated = root.demucs_is_secondary_model_activate_var.get() if not is_secondary_model else False
if not self.is_ensemble_mode:
self.pre_proc_model_activated = root.is_demucs_pre_proc_model_activate_var.get() if not root.demucs_stems_var.get() in [VOCAL_STEM, INST_STEM] else False
self.overlap = float(root.overlap_var.get())
self.margin_demucs = int(root.margin_demucs_var.get())
self.chunks_demucs = root.determine_auto_chunks(root.chunks_demucs_var.get(), self.is_gpu_conversion)
self.shifts = int(root.shifts_var.get())
self.is_split_mode = root.is_split_mode_var.get()
self.segment = root.segment_var.get()
self.is_chunk_demucs = root.is_chunk_demucs_var.get()
self.is_demucs_combine_stems = root.is_demucs_combine_stems_var.get()
self.is_primary_stem_only = root.is_primary_stem_only_var.get() if self.is_ensemble_mode else root.is_primary_stem_only_Demucs_var.get()
self.is_secondary_stem_only = root.is_secondary_stem_only_var.get() if self.is_ensemble_mode else root.is_secondary_stem_only_Demucs_var.get()
self.get_demucs_model_path()
self.get_demucs_model_data()
self.model_basename = os.path.splitext(os.path.basename(self.model_path))[0] if self.model_status else None
self.pre_proc_model_activated = self.pre_proc_model_activated if not self.is_secondary_model else False
self.is_primary_model_primary_stem_only = is_primary_model_primary_stem_only
self.is_primary_model_secondary_stem_only = is_primary_model_secondary_stem_only
if self.is_secondary_model_activated and self.model_status:
if (not self.is_ensemble_mode and root.demucs_stems_var.get() == ALL_STEMS and self.process_method == DEMUCS_ARCH_TYPE) or self.is_4_stem_ensemble:
for key in DEMUCS_4_SOURCE_LIST:
self.secondary_model_data(key)
self.secondary_model_4_stem.append(self.secondary_model)
self.secondary_model_4_stem_scale.append(self.secondary_model_scale)
self.secondary_model_4_stem_names.append(key)
self.demucs_4_stem_added_count = sum(i is not None for i in self.secondary_model_4_stem)
self.is_secondary_model_activated = False if all(i is None for i in self.secondary_model_4_stem) else True
self.demucs_4_stem_added_count = self.demucs_4_stem_added_count - 1 if self.is_secondary_model_activated else self.demucs_4_stem_added_count
if self.is_secondary_model_activated:
self.secondary_model_4_stem_model_names_list = [None if i is None else i.model_basename for i in self.secondary_model_4_stem]
self.is_demucs_4_stem_secondaries = True
else:
primary_stem = self.ensemble_primary_stem if self.is_ensemble_mode and self.process_method == DEMUCS_ARCH_TYPE else self.primary_stem
self.secondary_model_data(primary_stem)
if self.process_method == DEMUCS_ARCH_TYPE and not is_secondary_model:
if self.demucs_stem_count >= 3 and self.pre_proc_model_activated:
self.pre_proc_model_activated = True
self.pre_proc_model = root.process_determine_demucs_pre_proc_model(self.primary_stem)
self.is_demucs_pre_proc_model_inst_mix = root.is_demucs_pre_proc_model_inst_mix_var.get() if self.pre_proc_model else False
def secondary_model_data(self, primary_stem):
secondary_model_data = root.process_determine_secondary_model(self.process_method, primary_stem, self.is_primary_stem_only, self.is_secondary_stem_only)
self.secondary_model = secondary_model_data[0]
self.secondary_model_scale = secondary_model_data[1]
self.is_secondary_model_activated = False if not self.secondary_model else True
if self.secondary_model:
self.is_secondary_model_activated = False if self.secondary_model.model_basename == self.model_basename else True
def get_mdx_model_path(self):
for file_name, chosen_mdx_model in MDX_NAME_SELECT.items():
if self.model_name in chosen_mdx_model:
self.model_path = os.path.join(MDX_MODELS_DIR, f"{file_name}.onnx")
break
else:
self.model_path = os.path.join(MDX_MODELS_DIR, f"{self.model_name}.onnx")
self.mixer_path = os.path.join(MDX_MODELS_DIR, f"mixer_val.ckpt")
def get_demucs_model_path(self):
demucs_newer = [True for x in DEMUCS_NEWER_TAGS if x in self.model_name]
demucs_model_dir = DEMUCS_NEWER_REPO_DIR if demucs_newer else DEMUCS_MODELS_DIR
for file_name, chosen_model in DEMUCS_NAME_SELECT.items():
if self.model_name in chosen_model:
self.model_path = os.path.join(demucs_model_dir, file_name)
break
else:
self.model_path = os.path.join(DEMUCS_NEWER_REPO_DIR, f'{self.model_name}.yaml')
def get_demucs_model_data(self):
self.demucs_version = DEMUCS_V4
for key, value in DEMUCS_VERSION_MAPPER.items():
if value in self.model_name:
self.demucs_version = key
self.demucs_source_list = DEMUCS_2_SOURCE if DEMUCS_UVR_MODEL in self.model_name else DEMUCS_4_SOURCE
self.demucs_source_map = DEMUCS_2_SOURCE_MAPPER if DEMUCS_UVR_MODEL in self.model_name else DEMUCS_4_SOURCE_MAPPER
self.demucs_stem_count = 2 if DEMUCS_UVR_MODEL in self.model_name else 4
if not self.is_ensemble_mode:
self.primary_stem = PRIMARY_STEM if self.demucs_stems == ALL_STEMS else self.demucs_stems
self.secondary_stem = STEM_PAIR_MAPPER[self.primary_stem]
def get_model_data(self, model_hash_dir, hash_mapper):
model_settings_json = os.path.join(model_hash_dir, "{}.json".format(self.model_hash))
if os.path.isfile(model_settings_json):
return json.load(open(model_settings_json))
else:
for hash, settings in hash_mapper.items():
if self.model_hash in hash:
return settings
else:
return self.get_model_data_from_popup()
def get_model_data_from_popup(self):
if not self.is_dry_check:
confirm = tk.messagebox.askyesno(title=UNRECOGNIZED_MODEL[0],
message=f"\"{self.model_name}\"{UNRECOGNIZED_MODEL[1]}",
parent=root)
if confirm:
if self.process_method == VR_ARCH_TYPE:
root.pop_up_vr_param(self.model_hash)
return root.vr_model_params
if self.process_method == MDX_ARCH_TYPE:
root.pop_up_mdx_model(self.model_hash, self.model_path)
return root.mdx_model_params
else:
return None
else:
return None
def get_model_hash(self):
self.model_hash = None
if not os.path.isfile(self.model_path):
self.model_status = False
self.model_hash is None
else:
if model_hash_table:
for (key, value) in model_hash_table.items():
if self.model_path == key:
self.model_hash = value
break
if not self.model_hash:
with open(self.model_path, 'rb') as f:
f.seek(- 10000 * 1024, 2)
self.model_hash = hashlib.md5(f.read()).hexdigest()
table_entry = {self.model_path: self.model_hash}
model_hash_table.update(table_entry)
class Ensembler():
def __init__(self, is_manual_ensemble=False):
self.is_save_all_outputs_ensemble = root.is_save_all_outputs_ensemble_var.get()
chosen_ensemble_name = '{}'.format(root.chosen_ensemble_var.get().replace(" ", "_")) if not root.chosen_ensemble_var.get() == CHOOSE_ENSEMBLE_OPTION else 'Ensembled'
ensemble_algorithm = root.ensemble_type_var.get().partition("/")
ensemble_main_stem_pair = root.ensemble_main_stem_var.get().partition("/")
time_stamp = round(time.time())
self.audio_tool = MANUAL_ENSEMBLE
self.main_export_path = Path(root.export_path_var.get())
self.chosen_ensemble = f"_{chosen_ensemble_name}" if root.is_append_ensemble_name_var.get() else ''
ensemble_folder_name = self.main_export_path if self.is_save_all_outputs_ensemble else ENSEMBLE_TEMP_PATH
self.ensemble_folder_name = os.path.join(ensemble_folder_name, '{}_Outputs_{}'.format(chosen_ensemble_name, time_stamp))
self.is_testing_audio = f"{time_stamp}_" if root.is_testing_audio_var.get() else ''
self.primary_algorithm = ensemble_algorithm[0]
self.secondary_algorithm = ensemble_algorithm[2]
self.ensemble_primary_stem = ensemble_main_stem_pair[0]
self.ensemble_secondary_stem = ensemble_main_stem_pair[2]
self.is_normalization = root.is_normalization_var.get()
self.wav_type_set = root.wav_type_set
self.mp3_bit_set = root.mp3_bit_set_var.get()
self.save_format = root.save_format_var.get()
if not is_manual_ensemble:
os.mkdir(self.ensemble_folder_name)
def ensemble_outputs(self, audio_file_base, export_path, stem, is_4_stem=False, is_inst_mix=False):
"""Processes the given outputs and ensembles them with the chosen algorithm"""
if is_4_stem:
algorithm = root.ensemble_type_var.get()
stem_tag = stem
else:
if is_inst_mix:
algorithm = self.secondary_algorithm
stem_tag = f"{self.ensemble_secondary_stem} {INST_STEM}"
else:
algorithm = self.primary_algorithm if stem == PRIMARY_STEM else self.secondary_algorithm
stem_tag = self.ensemble_primary_stem if stem == PRIMARY_STEM else self.ensemble_secondary_stem
stem_outputs = self.get_files_to_ensemble(folder=export_path, prefix=audio_file_base, suffix=f"_({stem_tag}).wav")
audio_file_output = f"{self.is_testing_audio}{audio_file_base}{self.chosen_ensemble}_({stem_tag})"
stem_save_path = os.path.join('{}'.format(self.main_export_path),'{}.wav'.format(audio_file_output))
if stem_outputs:
spec_utils.ensemble_inputs(stem_outputs, algorithm, self.is_normalization, self.wav_type_set, stem_save_path)
save_format(stem_save_path, self.save_format, self.mp3_bit_set)
if self.is_save_all_outputs_ensemble:
for i in stem_outputs:
save_format(i, self.save_format, self.mp3_bit_set)
else:
for i in stem_outputs:
try:
os.remove(i)
except Exception as e:
print(e)
def ensemble_manual(self, audio_inputs, audio_file_base):
"""Processes the given outputs and ensembles them with the chosen algorithm"""
algorithm = root.choose_algorithm_var.get()
stem_save_path = os.path.join('{}'.format(self.main_export_path),'{}{}_({}).wav'.format(self.is_testing_audio, audio_file_base, algorithm))
spec_utils.ensemble_inputs(audio_inputs, algorithm, self.is_normalization, self.wav_type_set, stem_save_path)
save_format(stem_save_path, self.save_format, self.mp3_bit_set)
def get_files_to_ensemble(self, folder="", prefix="", suffix=""):
"""Grab all the files to be ensembled"""
return [os.path.join(folder, i) for i in os.listdir(folder) if i.startswith(prefix) and i.endswith(suffix)]
class AudioTools():
def __init__(self, audio_tool):
time_stamp = round(time.time())
self.audio_tool = audio_tool
self.main_export_path = Path(root.export_path_var.get())
self.wav_type_set = root.wav_type_set
self.is_normalization = root.is_normalization_var.get()
self.is_testing_audio = f"{time_stamp}_" if root.is_testing_audio_var.get() else ''
self.save_format = lambda save_path:save_format(save_path, root.save_format_var.get(), root.mp3_bit_set_var.get())
def align_inputs(self, audio_inputs, audio_file_base, audio_file_2_base, command_Text):
audio_file_base = f"{self.is_testing_audio}{audio_file_base}"
audio_file_2_base = f"{self.is_testing_audio}{audio_file_2_base}"
aligned_path = os.path.join('{}'.format(self.main_export_path),'{}_aligned.wav'.format(audio_file_2_base))
inverted_path = os.path.join('{}'.format(self.main_export_path),'{}_inverted.wav'.format(audio_file_base))
spec_utils.align_audio(audio_inputs[0], audio_inputs[1], aligned_path, inverted_path, self.wav_type_set, self.is_normalization, command_Text, root.progress_bar_main_var, self.save_format)
def pitch_or_time_shift(self, audio_file, audio_file_base):
rate = float(root.time_stretch_rate_var.get()) if self.audio_tool == TIME_STRETCH else float(root.pitch_rate_var.get())
is_pitch = False if self.audio_tool == TIME_STRETCH else True
file_text = TIME_TEXT if self.audio_tool == TIME_STRETCH else PITCH_TEXT
save_path = os.path.join(self.main_export_path, f"{self.is_testing_audio}{audio_file_base}{file_text}.wav")
spec_utils.augment_audio(save_path, audio_file, rate, self.is_normalization, self.wav_type_set, self.save_format, is_pitch=is_pitch)
class ToolTip(object):
def __init__(self, widget):
self.widget = widget
self.tipwindow = None
self.id = None
self.x = self.y = 0
def showtip(self, text):
"Display text in tooltip window"
self.text = text
if self.tipwindow or not self.text:
return
x, y, cx, cy = self.widget.bbox("insert")
x = x + self.widget.winfo_rootx() + 57
y = y + cy + self.widget.winfo_rooty() +27
self.tipwindow = tw = Toplevel(self.widget)
tw.wm_overrideredirect(1)
tw.wm_geometry("+%d+%d" % (x, y))
label = Label(tw, text=self.text, justify=LEFT,
background="#151515", foreground="#dedede", highlightcolor="#898b8e", relief=SOLID, borderwidth=1,
font=(MAIN_FONT_NAME, f"{FONT_SIZE_1}", "normal"))#('Century Gothic', FONT_SIZE_4)
label.pack(ipadx=1)
def hidetip(self):
tw = self.tipwindow
self.tipwindow = None
if tw:
tw.destroy()
class ThreadSafeConsole(tk.Text):
"""
Text Widget which is thread safe for tkinter
"""
def __init__(self, master, **options):
tk.Text.__init__(self, master, **options)
self.queue = queue.Queue()
self.update_me()
def write(self, line):
self.queue.put(line)
def clear(self):
self.queue.put(None)
def update_me(self):
self.configure(state=tk.NORMAL)
try:
while 1:
line = self.queue.get_nowait()
if line is None:
self.delete(1.0, tk.END)
else:
self.insert(tk.END, str(line))
self.see(tk.END)
self.update_idletasks()
except queue.Empty:
pass
self.configure(state=tk.DISABLED)
self.after(100, self.update_me)
def copy_text(self):
hightlighted_text = self.selection_get()
self.clipboard_clear()
self.clipboard_append(hightlighted_text)
def select_all_text(self):
self.tag_add('sel', '1.0', 'end')
class MainWindow(TkinterDnD.Tk if is_dnd_compatible else tk.Tk):
# --Constants--
# Layout
IMAGE_HEIGHT = av.IMAGE_HEIGHT
FILEPATHS_HEIGHT = av.FILEPATHS_HEIGHT
OPTIONS_HEIGHT = av.OPTIONS_HEIGHT
CONVERSIONBUTTON_HEIGHT = av.CONVERSIONBUTTON_HEIGHT
COMMAND_HEIGHT = av.COMMAND_HEIGHT
PROGRESS_HEIGHT = av.PROGRESS_HEIGHT
PADDING = av.PADDING
COL1_ROWS = 11
COL2_ROWS = 11
def __init__(self):
#Run the __init__ method on the tk.Tk class
super().__init__()
gui_data.sv_ttk.set_theme("dark")
gui_data.sv_ttk.use_dark_theme() # Set dark theme
# Calculate window height
height = self.IMAGE_HEIGHT + self.FILEPATHS_HEIGHT + self.OPTIONS_HEIGHT
height += self.CONVERSIONBUTTON_HEIGHT + self.COMMAND_HEIGHT + self.PROGRESS_HEIGHT
height += self.PADDING * 5 # Padding
width = 680
self.main_window_width = width
self.main_window_height = height
# --Window Settings--
self.title('Ultimate Vocal Remover')
# Set Geometry and Center Window
self.geometry('{width}x{height}+{xpad}+{ypad}'.format(
width=self.main_window_width,
height=height,
xpad=int(self.winfo_screenwidth()/2 - width/2),
ypad=int(self.winfo_screenheight()/2 - height/2 - 30)))
self.iconbitmap(ICON_IMG_PATH) if is_windows else self.tk.call('wm', 'iconphoto', self._w, tk.PhotoImage(file=MAIN_ICON_IMG_PATH))
self.configure(bg='#0e0e0f') # Set background color to #0c0c0d
self.protocol("WM_DELETE_WINDOW", self.save_values)
self.resizable(False, False)
self.update()
#Load Images
img = ImagePath(BASE_PATH)
self.logo_img = img.open_image(path=img.banner_path, size=(self.winfo_width(), 9999))
self.efile_img = img.efile_img
self.stop_img = img.stop_img
self.help_img = img.help_img
self.download_img = img.download_img
self.donate_img = img.donate_img
self.key_img = img.key_img
self.credits_img = img.credits_img
#Placeholders
self.error_log_var = tk.StringVar(value='')
self.vr_secondary_model_names = []
self.mdx_secondary_model_names = []
self.demucs_secondary_model_names = []
self.vr_primary_model_names = []
self.mdx_primary_model_names = []
self.demucs_primary_model_names = []
self.vr_cache_source_mapper = {}
self.mdx_cache_source_mapper = {}
self.demucs_cache_source_mapper = {}
# -Tkinter Value Holders-
try:
self.load_saved_vars(data)
except Exception as e:
self.error_log_var.set(error_text('Loading Saved Variables', e))
self.load_saved_vars(DEFAULT_DATA)
self.cached_sources_clear()
self.method_mapper = {
VR_ARCH_PM: self.vr_model_var,
MDX_ARCH_TYPE: self.mdx_net_model_var,
DEMUCS_ARCH_TYPE: self.demucs_model_var}
self.vr_secondary_model_vars = {'voc_inst_secondary_model': self.vr_voc_inst_secondary_model_var,
'other_secondary_model': self.vr_other_secondary_model_var,
'bass_secondary_model': self.vr_bass_secondary_model_var,
'drums_secondary_model': self.vr_drums_secondary_model_var,
'is_secondary_model_activate': self.vr_is_secondary_model_activate_var,
'voc_inst_secondary_model_scale': self.vr_voc_inst_secondary_model_scale_var,
'other_secondary_model_scale': self.vr_other_secondary_model_scale_var,
'bass_secondary_model_scale': self.vr_bass_secondary_model_scale_var,
'drums_secondary_model_scale': self.vr_drums_secondary_model_scale_var}
self.demucs_secondary_model_vars = {'voc_inst_secondary_model': self.demucs_voc_inst_secondary_model_var,
'other_secondary_model': self.demucs_other_secondary_model_var,
'bass_secondary_model': self.demucs_bass_secondary_model_var,
'drums_secondary_model': self.demucs_drums_secondary_model_var,
'is_secondary_model_activate': self.demucs_is_secondary_model_activate_var,
'voc_inst_secondary_model_scale': self.demucs_voc_inst_secondary_model_scale_var,
'other_secondary_model_scale': self.demucs_other_secondary_model_scale_var,
'bass_secondary_model_scale': self.demucs_bass_secondary_model_scale_var,
'drums_secondary_model_scale': self.demucs_drums_secondary_model_scale_var}
self.mdx_secondary_model_vars = {'voc_inst_secondary_model': self.mdx_voc_inst_secondary_model_var,
'other_secondary_model': self.mdx_other_secondary_model_var,
'bass_secondary_model': self.mdx_bass_secondary_model_var,
'drums_secondary_model': self.mdx_drums_secondary_model_var,
'is_secondary_model_activate': self.mdx_is_secondary_model_activate_var,
'voc_inst_secondary_model_scale': self.mdx_voc_inst_secondary_model_scale_var,
'other_secondary_model_scale': self.mdx_other_secondary_model_scale_var,
'bass_secondary_model_scale': self.mdx_bass_secondary_model_scale_var,
'drums_secondary_model_scale': self.mdx_drums_secondary_model_scale_var}
#Main Application Vars
self.progress_bar_main_var = tk.IntVar(value=0)
self.inputPathsEntry_var = tk.StringVar(value='')
self.conversion_Button_Text_var = tk.StringVar(value=START_PROCESSING)
self.chosen_ensemble_var = tk.StringVar(value=CHOOSE_ENSEMBLE_OPTION)
self.ensemble_main_stem_var = tk.StringVar(value=CHOOSE_STEM_PAIR)
self.ensemble_type_var = tk.StringVar(value=MAX_MIN)
self.save_current_settings_var = tk.StringVar(value=SELECT_SAVED_SET)
self.demucs_stems_var = tk.StringVar(value=ALL_STEMS)
self.is_primary_stem_only_Text_var = tk.StringVar(value='')
self.is_secondary_stem_only_Text_var = tk.StringVar(value='')
self.is_primary_stem_only_Demucs_Text_var = tk.StringVar(value='')
self.is_secondary_stem_only_Demucs_Text_var = tk.StringVar(value='')
self.scaling_var = tk.DoubleVar(value=1.0)
self.active_processing_thread = None
self.verification_thread = None
self.is_menu_settings_open = False
self.is_open_menu_advanced_vr_options = tk.BooleanVar(value=False)
self.is_open_menu_advanced_demucs_options = tk.BooleanVar(value=False)
self.is_open_menu_advanced_mdx_options = tk.BooleanVar(value=False)
self.is_open_menu_advanced_ensemble_options = tk.BooleanVar(value=False)
self.is_open_menu_view_inputs = tk.BooleanVar(value=False)
self.is_open_menu_help = tk.BooleanVar(value=False)
self.is_open_menu_error_log = tk.BooleanVar(value=False)
self.mdx_model_params = None
self.vr_model_params = None
self.current_text_box = None
self.wav_type_set = None
self.is_online_model_menu = None
self.progress_bar_var = tk.IntVar(value=0)
self.is_confirm_error_var = tk.BooleanVar(value=False)
self.clear_cache_torch = False
self.vr_hash_MAPPER = load_model_hash_data(VR_HASH_JSON)
self.mdx_hash_MAPPER = load_model_hash_data(MDX_HASH_JSON)
self.is_gpu_available = torch.cuda.is_available() if not OPERATING_SYSTEM == 'Darwin' else torch.backends.mps.is_available()
self.is_process_stopped = False
self.inputs_from_dir = []
self.iteration = 0
self.vr_primary_source = None
self.vr_secondary_source = None
self.mdx_primary_source = None
self.mdx_secondary_source = None
self.demucs_primary_source = None
self.demucs_secondary_source = None
#Download Center Vars
self.online_data = {}
self.is_online = False
self.lastest_version = ''
self.model_download_demucs_var = tk.StringVar(value='')
self.model_download_mdx_var = tk.StringVar(value='')
self.model_download_vr_var = tk.StringVar(value='')
self.selected_download_var = tk.StringVar(value=NO_MODEL)
self.select_download_var = tk.StringVar(value='')
self.download_progress_info_var = tk.StringVar(value='')
self.download_progress_percent_var = tk.StringVar(value='')
self.download_progress_bar_var = tk.IntVar(value=0)
self.download_stop_var = tk.StringVar(value='')
self.app_update_status_Text_var = tk.StringVar(value='')
self.app_update_button_Text_var = tk.StringVar(value='')
self.user_code_validation_var = tk.StringVar(value='')
self.download_link_path_var = tk.StringVar(value='')
self.download_save_path_var = tk.StringVar(value='')
self.download_update_link_var = tk.StringVar(value='')
self.download_update_path_var = tk.StringVar(value='')
self.download_demucs_models_list = []
self.download_demucs_newer_models = []
self.refresh_list_Button = None
self.stop_download_Button_DISABLE = None
self.enable_tabs = None
self.is_download_thread_active = False
self.is_process_thread_active = False
self.is_active_processing_thread = False
self.active_download_thread = None
# Font
font.add_file(FONT_PATH)
self.font = tk.font.Font(family=MAIN_FONT_NAME, size=FONT_SIZE_F1)
self.font_smaller = tk.font.Font(family=MAIN_FONT_NAME, size=FONT_SIZE_F2)
self.fontRadio = tk.font.Font(family=MAIN_FONT_NAME, size=FONT_SIZE_F3)
#Model Update
self.last_found_ensembles = ENSEMBLE_OPTIONS
self.last_found_settings = ENSEMBLE_OPTIONS
self.last_found_models = ()
self.model_data_table = ()
self.ensemble_model_list = ()
# --Widgets--
self.fill_main_frame()
self.bind_widgets()
# --Update Widgets--
self.update_available_models()
self.update_main_widget_states()
self.update_loop()
self.update_button_states()
self.delete_temps()
self.download_validate_code()
self.ensemble_listbox_Option.configure(state=tk.DISABLED)
self.command_Text.write(f'Ultimate Vocal Remover {VERSION} [{datetime.now().strftime("%Y-%m-%d %H:%M:%S")}]')
self.update_checkbox_text = lambda:self.selection_action_process_method(self.chosen_process_method_var.get())
self.online_data_refresh(user_refresh=False)
# Menu Functions
def main_window_LABEL_SET(self, master, text):return ttk.Label(master=master, text=text, background='#0e0e0f', font=self.font_smaller, foreground='#13849f', anchor=tk.CENTER)
def menu_title_LABEL_SET(self, frame, text, width=35):return ttk.Label(master=frame, text=text, font=(MAIN_FONT_NAME, f"{FONT_SIZE_5}", "underline"), justify="center", foreground="#13849f", width=width, anchor=tk.CENTER)
def menu_sub_LABEL_SET(self, frame, text, font_size=FONT_SIZE_2):return ttk.Label(master=frame, text=text, font=(MAIN_FONT_NAME, f"{font_size}"), foreground='#13849f', anchor=tk.CENTER)
def menu_FRAME_SET(self, frame, thickness=20):return Frame(frame, highlightbackground='#0e0e0f', highlightcolor='#0e0e0f', highlightthicknes=thickness)
def check_is_menu_settings_open(self):self.menu_settings() if not self.is_menu_settings_open else None
def check_is_open_menu_advanced_vr_options(self):
try:
if not self.is_open_menu_advanced_vr_options.get():
self.menu_advanced_vr_options()
else:
self.menu_advanced_vr_options_close_window()
self.menu_advanced_vr_options()
except Exception as e:
self.error_log_var.set("{}".format(error_text('VR Menu', e)))
def check_is_open_menu_advanced_demucs_options(self):
try:
if not self.is_open_menu_advanced_demucs_options.get():
self.menu_advanced_demucs_options()
else:
self.menu_advanced_demucs_options_close_window()
self.menu_advanced_demucs_options()
except Exception as e:
self.error_log_var.set("{}".format(error_text('Demucs Menu', e)))
def check_is_open_menu_advanced_mdx_options(self):
try:
if not self.is_open_menu_advanced_mdx_options.get():
self.menu_advanced_mdx_options()
else:
self.menu_advanced_mdx_options_close_window()
self.menu_advanced_mdx_options()
except Exception as e:
self.error_log_var.set("{}".format(error_text('MDX-Net Menu', e)))
def check_is_open_menu_advanced_ensemble_options(self):
try:
if not self.is_open_menu_advanced_ensemble_options.get():
self.menu_advanced_ensemble_options()
else:
self.menu_advanced_ensemble_options_close_window()
self.menu_advanced_ensemble_options()
except Exception as e:
self.error_log_var.set("{}".format(error_text('Ensemble Menu', e)))
def check_is_open_menu_help(self):
if not self.is_open_menu_help.get():
self.menu_help()
else:
self.menu_help_close_window()
self.menu_help()
def check_is_open_menu_error_log(self):
if not self.is_open_menu_error_log.get():
self.menu_error_log()
else:
self.menu_error_log_close_window()
self.menu_error_log()
def check_is_open_menu_view_inputs(self):
try:
if not self.is_open_menu_view_inputs.get():
self.menu_view_inputs()
else:
self.menu_view_inputs_close_window()
self.menu_view_inputs()
except Exception as e:
self.error_log_var.set("{}".format(error_text('Inputs Menu', e)))
#Ensemble Listbox Functions
def ensemble_listbox_get_all_selected_models(self):return [self.ensemble_listbox_Option.get(i) for i in self.ensemble_listbox_Option.curselection()]
def ensemble_listbox_select_from_indexs(self, indexes):return [self.ensemble_listbox_Option.selection_set(i) for i in indexes]
def ensemble_listbox_clear_and_insert_new(self, model_ensemble_updated):return (self.ensemble_listbox_Option.delete(0, 'end'), [self.ensemble_listbox_Option.insert(tk.END, models) for models in model_ensemble_updated])
def ensemble_listbox_get_indexes_for_files(self, updated, selected):return [updated.index(model) for model in selected if model in updated]
def process_iteration(self):
self.iteration = self.iteration + 1
def assemble_model_data(self, model=None, arch_type=ENSEMBLE_MODE, is_dry_check=False):
if arch_type == ENSEMBLE_STEM_CHECK:
model_data = self.model_data_table
missing_models = [model.model_status for model in model_data if not model.model_status]
if missing_models or not model_data:
model_data: List[ModelData] = [ModelData(model_name, is_dry_check=is_dry_check) for model_name in self.ensemble_model_list]
self.model_data_table = model_data
if arch_type == ENSEMBLE_MODE:
model_data: List[ModelData] = [ModelData(model_name) for model_name in self.ensemble_listbox_get_all_selected_models()]
if arch_type == ENSEMBLE_CHECK:
model_data: List[ModelData] = [ModelData(model)]
if arch_type == VR_ARCH_TYPE or arch_type == VR_ARCH_PM:
model_data: List[ModelData] = [ModelData(model, VR_ARCH_TYPE)]
if arch_type == MDX_ARCH_TYPE:
model_data: List[ModelData] = [ModelData(model, MDX_ARCH_TYPE)]
if arch_type == DEMUCS_ARCH_TYPE:
model_data: List[ModelData] = [ModelData(model, DEMUCS_ARCH_TYPE)]
return model_data
def clear_cache(self, network):
if network == VR_ARCH_TYPE:
dir = VR_HASH_DIR
if network == MDX_ARCH_TYPE:
dir = MDX_HASH_DIR
[os.remove(os.path.join(dir, x)) for x in os.listdir(dir) if x not in 'model_data.json']
self.vr_model_var.set(CHOOSE_MODEL)
self.mdx_net_model_var.set(CHOOSE_MODEL)
self.model_data_table.clear()
self.chosen_ensemble_var.set(CHOOSE_ENSEMBLE_OPTION)
self.ensemble_main_stem_var.set(CHOOSE_STEM_PAIR)
self.ensemble_listbox_Option.configure(state=tk.DISABLED)
self.update_checkbox_text()
def thread_check(self, thread_to_check):
'''Checks if thread is alive'''
is_running = False
if type(thread_to_check) is KThread:
if thread_to_check.is_alive():
is_running = True
return is_running