forked from Anjok07/ultimatevocalremovergui
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinference_v5_ensemble.py
4343 lines (3840 loc) · 232 KB
/
inference_v5_ensemble.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
from collections import defaultdict
from datetime import datetime
from demucs.apply import BagOfModels, apply_model
from demucs.hdemucs import HDemucs
from demucs.model_v2 import Demucs
from demucs.pretrained import get_model as _gm
from demucs.tasnet_v2 import ConvTasNet
from demucs.utils import apply_model_v1
from demucs.utils import apply_model_v2
from functools import total_ordering
from lib_v5 import dataset
from lib_v5 import spec_utils
from lib_v5.model_param_init import ModelParameters
from models import get_models, spec_effects
from pathlib import Path
from random import randrange
from statistics import mode
from tqdm import tqdm
from tqdm import tqdm
from tkinter import filedialog
import tkinter.ttk as ttk
import tkinter.messagebox
import tkinter.filedialog
import tkinter.simpledialog
import tkinter.font
import tkinter as tk
from tkinter import *
from tkinter.tix import *
import lib_v5.filelist
import cv2
import gzip
import hashlib
import importlib
import librosa
import json
import math
import numpy as np
import numpy as np
import onnxruntime as ort
import os
import pathlib
import psutil
import pydub
import re
import shutil
import soundfile as sf
import soundfile as sf
import subprocess
import sys
import time
import time # Timer
import tkinter as tk
import torch
import torch
import traceback # Error Message Recent Calls
import warnings
class Predictor():
def __init__(self):
pass
def mdx_options(self):
"""
Open Advanced MDX Options
"""
self.okVar = tk.IntVar()
self.n_fft_scale_set_var = tk.StringVar(value='6144')
self.dim_f_set_var = tk.StringVar(value='2048')
self.mdxnetModeltype_var = tk.StringVar(value='Vocals')
self.noise_pro_select_set_var = tk.StringVar(value='MDX-NET_Noise_Profile_14_kHz')
self.compensate_v_var = tk.StringVar(value=1.03597672895)
top= Toplevel()
top.geometry("740x550")
window_height = 740
window_width = 550
top.title("Specify Parameters")
top.resizable(False, False) # This code helps to disable windows from resizing
screen_width = top.winfo_screenwidth()
screen_height = top.winfo_screenheight()
x_cordinate = int((screen_width/2) - (window_width/2))
y_cordinate = int((screen_height/2) - (window_height/2))
top.geometry("{}x{}+{}+{}".format(window_width, window_height, x_cordinate, y_cordinate))
# change title bar icon
top.iconbitmap('img\\UVR-Icon-v2.ico')
tabControl = ttk.Notebook(top)
tabControl.pack(expand = 1, fill ="both")
tabControl.grid_rowconfigure(0, weight=1)
tabControl.grid_columnconfigure(0, weight=1)
frame0=Frame(tabControl,highlightbackground='red',highlightthicknes=0)
frame0.grid(row=0,column=0,padx=0,pady=0)
frame0.tkraise(frame0)
space_small = ' '*20
space_small_1 = ' '*10
l0=tk.Label(frame0, text=f'{space_small}Stem Type{space_small}', font=("Century Gothic", "9"), foreground='#13a4c9')
l0.grid(row=3,column=0,padx=0,pady=5)
l0=ttk.OptionMenu(frame0, self.mdxnetModeltype_var, None, 'Vocals', 'Instrumental')
l0.grid(row=4,column=0,padx=0,pady=5)
l0=tk.Label(frame0, text='N_FFT Scale', font=("Century Gothic", "9"), foreground='#13a4c9')
l0.grid(row=5,column=0,padx=0,pady=5)
l0=tk.Label(frame0, text=f'{space_small_1}(Manual Set){space_small_1}', font=("Century Gothic", "9"), foreground='#13a4c9')
l0.grid(row=5,column=1,padx=0,pady=5)
self.options_n_fft_scale_Opt = l0=ttk.OptionMenu(frame0, self.n_fft_scale_set_var, None, '4096', '6144', '7680', '8192', '16384')
self.options_n_fft_scale_Opt
l0.grid(row=6,column=0,padx=0,pady=5)
self.options_n_fft_scale_Entry = l0=ttk.Entry(frame0, textvariable=self.n_fft_scale_set_var, justify='center')
self.options_n_fft_scale_Entry
l0.grid(row=6,column=1,padx=0,pady=5)
l0=tk.Label(frame0, text='Dim_f', font=("Century Gothic", "9"), foreground='#13a4c9')
l0.grid(row=7,column=0,padx=0,pady=5)
l0=tk.Label(frame0, text='(Manual Set)', font=("Century Gothic", "9"), foreground='#13a4c9')
l0.grid(row=7,column=1,padx=0,pady=5)
self.options_dim_f_Opt = l0=ttk.OptionMenu(frame0, self.dim_f_set_var, None, '2048', '3072', '4096')
self.options_dim_f_Opt
l0.grid(row=8,column=0,padx=0,pady=5)
self.options_dim_f_Entry = l0=ttk.Entry(frame0, textvariable=self.dim_f_set_var, justify='center')
self.options_dim_f_Entry
l0.grid(row=8,column=1,padx=0,pady=5)
l0=tk.Label(frame0, text='Noise Profile', font=("Century Gothic", "9"), foreground='#13a4c9')
l0.grid(row=9,column=0,padx=0,pady=5)
l0=ttk.OptionMenu(frame0, self.noise_pro_select_set_var, None, 'MDX-NET_Noise_Profile_14_kHz', 'MDX-NET_Noise_Profile_17_kHz', 'MDX-NET_Noise_Profile_Full_Band')
l0.grid(row=10,column=0,padx=0,pady=5)
l0=tk.Label(frame0, text='Volume Compensation', font=("Century Gothic", "9"), foreground='#13a4c9')
l0.grid(row=11,column=0,padx=0,pady=10)
self.options_compensate = l0=ttk.Entry(frame0, textvariable=self.compensate_v_var, justify='center')
self.options_compensate
l0.grid(row=12,column=0,padx=0,pady=0)
l0=ttk.Button(frame0,text="Continue & Set These Parameters", command=lambda: self.okVar.set(1))
l0.grid(row=13,column=0,padx=0,pady=30)
def stop():
widget_text.write(f'Please configure the ONNX model settings accordingly and try again.\n\n')
widget_text.write(f'Time Elapsed: {time.strftime("%H:%M:%S", time.gmtime(int(time.perf_counter() - stime)))}')
torch.cuda.empty_cache()
gui_progress_bar.set(0)
widget_button.configure(state=tk.NORMAL) # Enable Button
top.destroy()
return
l0=ttk.Button(frame0,text="Stop Process", command=stop)
l0.grid(row=13,column=1,padx=0,pady=30)
#print('print from top ', model_hash)
#source_val = 0
def change_event():
self.okVar.set(1)
#top.destroy()
pass
top.protocol("WM_DELETE_WINDOW", change_event)
frame0.wait_variable(self.okVar)
global n_fft_scale_set
global dim_f_set
global modeltype
global stemset_n
global source_val
global noise_pro_set
global compensate
global demucs_model_set
stemtype = self.mdxnetModeltype_var.get()
if stemtype == 'Vocals':
modeltype = 'v'
stemset_n = '(Vocals)'
source_val = 3
if stemtype == 'Instrumental':
modeltype = 'v'
stemset_n = '(Instrumental)'
source_val = 2
if stemtype == 'Other':
modeltype = 'o'
stemset_n = '(Other)'
source_val = 2
if stemtype == 'Drums':
modeltype = 'd'
stemset_n = '(Drums)'
source_val = 1
if stemtype == 'Bass':
modeltype = 'b'
stemset_n = '(Bass)'
source_val = 0
compensate = self.compensate_v_var.get()
n_fft_scale_set = int(self.n_fft_scale_set_var.get())
dim_f_set = int(self.dim_f_set_var.get())
noise_pro_set = self.noise_pro_select_set_var.get()
mdx_model_params = {
'modeltype' : modeltype,
'stemset_n' : stemset_n,
'source_val' : source_val,
'compensate' : compensate,
'n_fft_scale_set' : n_fft_scale_set,
'dim_f_set' : dim_f_set,
'noise_pro' : noise_pro_set,
}
mdx_model_params_r = json.dumps(mdx_model_params, indent=4)
with open(f"lib_v5/filelists/model_cache/mdx_model_cache/{model_hash}.json", "w") as outfile:
outfile.write(mdx_model_params_r)
if stemset_n == '(Instrumental)':
if not 'UVR' in demucs_model_set:
widget_text.write(base_text + 'The selected Demucs model cannot be used with this model.\n')
widget_text.write(base_text + 'Only 2 stem Demucs models are compatible with this model.\n')
widget_text.write(base_text + 'Setting Demucs model to \"UVR_Demucs_Model_1\".\n\n')
demucs_model_set = 'UVR_Demucs_Model_1'
top.destroy()
def prediction_setup(self):
global device
if data['gpu'] >= 0:
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
if data['gpu'] == -1:
device = torch.device('cpu')
if demucs_switch == 'on':
#print('check model here: ', demucs_model_set)
#'demucs.th.gz', 'demucs_extra.th.gz', 'light.th.gz', 'light_extra.th.gz'
if 'tasnet.th' in demucs_model_set or 'tasnet_extra.th' in demucs_model_set or \
'demucs.th' in demucs_model_set or \
'demucs_extra.th' in demucs_model_set or 'light.th' in demucs_model_set or \
'light_extra.th' in demucs_model_set or 'v1' in demucs_model_set or '.gz' in demucs_model_set:
load_from = "models/Demucs_Models/"f"{demucs_model_set}"
if str(load_from).endswith(".gz"):
load_from = gzip.open(load_from, "rb")
klass, args, kwargs, state = torch.load(load_from)
self.demucs = klass(*args, **kwargs)
widget_text.write(base_text + 'Loading Demucs v1 model... ')
update_progress(**progress_kwargs,
step=0.05)
self.demucs.to(device)
self.demucs.load_state_dict(state)
widget_text.write('Done!\n')
elif 'tasnet-beb46fac.th' in demucs_model_set or 'tasnet_extra-df3777b2.th' in demucs_model_set or \
'demucs48_hq-28a1282c.th' in demucs_model_set or'demucs-e07c671f.th' in demucs_model_set or \
'demucs_extra-3646af93.th' in demucs_model_set or 'demucs_unittest-09ebc15f.th' in demucs_model_set or \
'v2' in demucs_model_set:
if '48' in demucs_model_set:
channels=48
elif 'unittest' in demucs_model_set:
channels=4
else:
channels=64
if 'tasnet' in demucs_model_set:
self.demucs = ConvTasNet(sources=["drums", "bass", "other", "vocals"], X=10)
else:
self.demucs = Demucs(sources=["drums", "bass", "other", "vocals"], channels=channels)
widget_text.write(base_text + 'Loading Demucs v2 model... ')
update_progress(**progress_kwargs,
step=0.05)
self.demucs.to(device)
self.demucs.load_state_dict(torch.load("models/Demucs_Models/"f"{demucs_model_set}"))
widget_text.write('Done!\n')
self.demucs.eval()
else:
if 'UVR' in demucs_model_set:
self.demucs = HDemucs(sources=["other", "vocals"])
else:
self.demucs = HDemucs(sources=["drums", "bass", "other", "vocals"])
widget_text.write(base_text + 'Loading Demucs model... ')
update_progress(**progress_kwargs,
step=0.05)
path_d = Path('models/Demucs_Models/v3_repo')
#print('What Demucs model was chosen? ', demucs_model_set)
self.demucs = _gm(name=demucs_model_set, repo=path_d)
self.demucs.to(device)
self.demucs.eval()
widget_text.write('Done!\n')
if isinstance(self.demucs, BagOfModels):
widget_text.write(base_text + f"Selected Demucs model is a bag of {len(self.demucs.models)} model(s).\n")
self.onnx_models = {}
c = 0
if demucs_only == 'on':
pass
else:
self.models = get_models('tdf_extra', load=False, device=cpu, stems=modeltype, n_fft_scale=n_fft_scale_set, dim_f=dim_f_set)
widget_text.write(base_text + 'Loading ONNX model... ')
update_progress(**progress_kwargs,
step=0.1)
c+=1
if data['gpu'] >= 0:
if torch.cuda.is_available():
run_type = ['CUDAExecutionProvider']
else:
data['gpu'] = -1
widget_text.write("\n" + base_text + "No NVIDIA GPU detected. Switching to CPU... ")
run_type = ['CPUExecutionProvider']
elif data['gpu'] == -1:
run_type = ['CPUExecutionProvider']
if demucs_only == 'off':
self.onnx_models[c] = ort.InferenceSession(os.path.join('models/MDX_Net_Models', model_set), providers=run_type)
#print(demucs_model_set)
widget_text.write('Done!\n')
elif demucs_only == 'on':
#print(demucs_model_set)
pass
def prediction(self, m):
mix, samplerate = librosa.load(m, mono=False, sr=44100)
if mix.ndim == 1:
mix = np.asfortranarray([mix,mix])
samplerate = samplerate
mix = mix.T
sources = self.demix(mix.T)
widget_text.write(base_text + 'Inferences complete!\n')
c = -1
inst_only = data['inst_only']
voc_only = data['voc_only']
if stemset_n == '(Instrumental)':
if data['inst_only'] == True:
voc_only = True
inst_only = False
if data['voc_only'] == True:
inst_only = True
voc_only = False
#Main Save Path
save_path = os.path.dirname(base_name)
#Write name
if stemset_n == '(Vocals)':
stem_text_a = 'Vocals'
stem_text_b = 'Instrumental'
elif stemset_n == '(Instrumental)':
stem_text_a = 'Instrumental'
stem_text_b = 'Vocals'
#Vocal Path
if stemset_n == '(Vocals)':
vocal_name = '(Vocals)'
elif stemset_n == '(Instrumental)':
vocal_name = '(Instrumental)'
if data['modelFolder']:
vocal_path = '{save_path}/{file_name}.wav'.format(
save_path=save_path,
file_name = f'{os.path.basename(base_name)}_{ModelName_2}_{vocal_name}',)
else:
vocal_path = '{save_path}/{file_name}.wav'.format(
save_path=save_path,
file_name = f'{os.path.basename(base_name)}_{ModelName_2}_{vocal_name}',)
#Instrumental Path
if stemset_n == '(Vocals)':
Instrumental_name = '(Instrumental)'
elif stemset_n == '(Instrumental)':
Instrumental_name = '(Vocals)'
if data['modelFolder']:
Instrumental_path = '{save_path}/{file_name}.wav'.format(
save_path=save_path,
file_name = f'{os.path.basename(base_name)}_{ModelName_2}_{Instrumental_name}',)
else:
Instrumental_path = '{save_path}/{file_name}.wav'.format(
save_path=save_path,
file_name = f'{os.path.basename(base_name)}_{ModelName_2}_{Instrumental_name}',)
#Non-Reduced Vocal Path
if stemset_n == '(Vocals)':
vocal_name = '(Vocals)'
elif stemset_n == '(Instrumental)':
vocal_name = '(Instrumental)'
if data['modelFolder']:
non_reduced_vocal_path = '{save_path}/{file_name}.wav'.format(
save_path=save_path,
file_name = f'{os.path.basename(base_name)}_{ModelName_2}_{vocal_name}_No_Reduction',)
else:
non_reduced_vocal_path = '{save_path}/{file_name}.wav'.format(
save_path=save_path,
file_name = f'{os.path.basename(base_name)}_{ModelName_2}_{vocal_name}_No_Reduction',)
if os.path.isfile(non_reduced_vocal_path):
file_exists_n = 'there'
else:
file_exists_n = 'not_there'
if os.path.isfile(vocal_path):
file_exists = 'there'
else:
file_exists = 'not_there'
if demucs_only == 'on':
data['noisereduc_s'] == 'None'
if not data['noisereduc_s'] == 'None':
c += 1
if demucs_switch == 'off':
if inst_only and not voc_only:
widget_text.write(base_text + f'Preparing to save {stem_text_b}...')
else:
widget_text.write(base_text + f'Saving {stem_text_a}... ')
sf.write(non_reduced_vocal_path, sources[c].T, samplerate, subtype=wav_type_set)
update_progress(**progress_kwargs,
step=(0.9))
widget_text.write('Done!\n')
widget_text.write(base_text + 'Performing Noise Reduction... ')
reduction_sen = float(int(data['noisereduc_s'])/10)
subprocess.call("lib_v5\\sox\\sox.exe" + ' "' +
f"{str(non_reduced_vocal_path)}" + '" "' + f"{str(vocal_path)}" + '" ' +
"noisered lib_v5\\sox\\" + noise_pro_set + ".prof " + f"{reduction_sen}",
shell=True, stdout=subprocess.PIPE,
stdin=subprocess.PIPE, stderr=subprocess.PIPE)
widget_text.write('Done!\n')
update_progress(**progress_kwargs,
step=(0.95))
else:
if inst_only and not voc_only:
widget_text.write(base_text + f'Preparing to save {stem_text_b}...')
else:
widget_text.write(base_text + f'Saving {stem_text_a}... ')
if demucs_only == 'on':
if 'UVR' in model_set_name:
sf.write(vocal_path, sources[1].T, samplerate, subtype=wav_type_set)
update_progress(**progress_kwargs,
step=(0.95))
widget_text.write('Done!\n')
if 'extra' in model_set_name:
sf.write(vocal_path, sources[3].T, samplerate, subtype=wav_type_set)
update_progress(**progress_kwargs,
step=(0.95))
widget_text.write('Done!\n')
else:
sf.write(non_reduced_vocal_path, sources[3].T, samplerate, subtype=wav_type_set)
update_progress(**progress_kwargs,
step=(0.9))
widget_text.write('Done!\n')
widget_text.write(base_text + 'Performing Noise Reduction... ')
reduction_sen = float(data['noisereduc_s'])/10
subprocess.call("lib_v5\\sox\\sox.exe" + ' "' +
f"{str(non_reduced_vocal_path)}" + '" "' + f"{str(vocal_path)}" + '" ' +
"noisered lib_v5\\sox\\" + noise_pro_set + ".prof " + f"{reduction_sen}",
shell=True, stdout=subprocess.PIPE,
stdin=subprocess.PIPE, stderr=subprocess.PIPE)
update_progress(**progress_kwargs,
step=(0.95))
widget_text.write('Done!\n')
else:
c += 1
if demucs_switch == 'off':
widget_text.write(base_text + f'Saving {stem_text_a}... ')
sf.write(vocal_path, sources[c].T, samplerate, subtype=wav_type_set)
update_progress(**progress_kwargs,
step=(0.9))
widget_text.write('Done!\n')
else:
widget_text.write(base_text + f'Saving {stem_text_a}... ')
if demucs_only == 'on':
if 'UVR' in model_set_name:
sf.write(vocal_path, sources[1].T, samplerate, subtype=wav_type_set)
if 'extra' in model_set_name:
sf.write(vocal_path, sources[3].T, samplerate, subtype=wav_type_set)
else:
sf.write(vocal_path, sources[3].T, samplerate, subtype=wav_type_set)
update_progress(**progress_kwargs,
step=(0.9))
widget_text.write('Done!\n')
if voc_only and not inst_only:
pass
else:
finalfiles = [
{
'model_params':'lib_v5/modelparams/1band_sr44100_hl512.json',
'files':[str(music_file), vocal_path],
}
]
widget_text.write(base_text + f'Saving {stem_text_b}... ')
for i, e in tqdm(enumerate(finalfiles)):
wave, specs = {}, {}
mp = ModelParameters(e['model_params'])
for i in range(len(e['files'])):
spec = {}
for d in range(len(mp.param['band']), 0, -1):
bp = mp.param['band'][d]
if d == len(mp.param['band']): # high-end band
wave[d], _ = librosa.load(
e['files'][i], bp['sr'], False, dtype=np.float32, res_type=bp['res_type'])
if len(wave[d].shape) == 1: # mono to stereo
wave[d] = np.array([wave[d], wave[d]])
else: # lower bands
wave[d] = librosa.resample(wave[d+1], mp.param['band'][d+1]['sr'], bp['sr'], res_type=bp['res_type'])
spec[d] = spec_utils.wave_to_spectrogram(wave[d], bp['hl'], bp['n_fft'], mp.param['mid_side'], mp.param['mid_side_b2'], mp.param['reverse'])
specs[i] = spec_utils.combine_spectrograms(spec, mp)
del wave
ln = min([specs[0].shape[2], specs[1].shape[2]])
specs[0] = specs[0][:,:,:ln]
specs[1] = specs[1][:,:,:ln]
X_mag = np.abs(specs[0])
y_mag = np.abs(specs[1])
max_mag = np.where(X_mag >= y_mag, X_mag, y_mag)
v_spec = specs[1] - max_mag * np.exp(1.j * np.angle(specs[0]))
update_progress(**progress_kwargs,
step=(0.95))
sf.write(Instrumental_path, normalization_set(spec_utils.cmb_spectrogram_to_wave(-v_spec, mp)), mp.param['sr'], subtype=wav_type_set)
if inst_only:
if file_exists == 'there':
pass
else:
try:
os.remove(vocal_path)
except:
pass
widget_text.write('Done!\n')
if data['noisereduc_s'] == 'None':
pass
elif inst_only:
if file_exists_n == 'there':
pass
else:
try:
os.remove(non_reduced_vocal_path)
except:
pass
else:
try:
os.remove(non_reduced_vocal_path)
except:
pass
widget_text.write(base_text + 'Completed Separation!\n\n')
def demix(self, mix):
# 1 = demucs only
# 0 = onnx only
if data['chunks'] == 'Full':
chunk_set = 0
else:
chunk_set = data['chunks']
if data['chunks'] == 'Auto':
if data['gpu'] == 0:
try:
gpu_mem = round(torch.cuda.get_device_properties(0).total_memory/1.074e+9)
except:
widget_text.write(base_text + 'NVIDIA GPU Required for conversion!\n')
if int(gpu_mem) <= int(6):
chunk_set = int(5)
widget_text.write(base_text + 'Chunk size auto-set to 5... \n')
if gpu_mem in [7, 8, 9, 10, 11, 12, 13, 14, 15]:
chunk_set = int(10)
widget_text.write(base_text + 'Chunk size auto-set to 10... \n')
if int(gpu_mem) >= int(16):
chunk_set = int(40)
widget_text.write(base_text + 'Chunk size auto-set to 40... \n')
if data['gpu'] == -1:
sys_mem = psutil.virtual_memory().total >> 30
if int(sys_mem) <= int(4):
chunk_set = int(1)
widget_text.write(base_text + 'Chunk size auto-set to 1... \n')
if sys_mem in [5, 6, 7, 8]:
chunk_set = int(10)
widget_text.write(base_text + 'Chunk size auto-set to 10... \n')
if sys_mem in [9, 10, 11, 12, 13, 14, 15, 16]:
chunk_set = int(25)
widget_text.write(base_text + 'Chunk size auto-set to 25... \n')
if int(sys_mem) >= int(17):
chunk_set = int(60)
widget_text.write(base_text + 'Chunk size auto-set to 60... \n')
elif data['chunks'] == 'Full':
chunk_set = 0
widget_text.write(base_text + "Chunk size set to full... \n")
else:
chunk_set = int(data['chunks'])
widget_text.write(base_text + "Chunk size user-set to "f"{chunk_set}... \n")
samples = mix.shape[-1]
margin = margin_set
chunk_size = chunk_set*44100
assert not margin == 0, 'margin cannot be zero!'
if margin > chunk_size:
margin = chunk_size
b = np.array([[[0.5]], [[0.5]], [[0.7]], [[0.9]]])
segmented_mix = {}
if chunk_set == 0 or samples < chunk_size:
chunk_size = samples
counter = -1
for skip in range(0, samples, chunk_size):
counter+=1
s_margin = 0 if counter == 0 else margin
end = min(skip+chunk_size+margin, samples)
start = skip-s_margin
segmented_mix[skip] = mix[:,start:end].copy()
if end == samples:
break
if demucs_switch == 'off':
sources = self.demix_base(segmented_mix, margin_size=margin)
elif demucs_only == 'on':
if 'tasnet.th' in demucs_model_set or 'tasnet_extra.th' in demucs_model_set or \
'demucs.th' in demucs_model_set or \
'demucs_extra.th' in demucs_model_set or 'light.th' in demucs_model_set or \
'light_extra.th' in demucs_model_set or 'v1' in demucs_model_set or '.gz' in demucs_model_set:
sources = self.demix_demucs_v1(segmented_mix, margin_size=margin)
elif 'tasnet-beb46fac.th' in demucs_model_set or 'tasnet_extra-df3777b2.th' in demucs_model_set or \
'demucs48_hq-28a1282c.th' in demucs_model_set or'demucs-e07c671f.th' in demucs_model_set or \
'demucs_extra-3646af93.th' in demucs_model_set or 'demucs_unittest-09ebc15f.th' in demucs_model_set or \
'v2' in demucs_model_set:
sources = self.demix_demucs_v2(segmented_mix, margin_size=margin)
else:
if split_mode == True:
sources = self.demix_demucs_split(mix)
if split_mode == False:
sources = self.demix_demucs(segmented_mix, margin_size=margin)
else: # both, apply spec effects
base_out = self.demix_base(segmented_mix, margin_size=margin)
if 'tasnet.th' in demucs_model_set or 'tasnet_extra.th' in demucs_model_set or \
'demucs.th' in demucs_model_set or \
'demucs_extra.th' in demucs_model_set or 'light.th' in demucs_model_set or \
'light_extra.th' in demucs_model_set or 'v1' in demucs_model_set or '.gz' in demucs_model_set:
demucs_out = self.demix_demucs_v1(segmented_mix, margin_size=margin)
elif 'tasnet-beb46fac.th' in demucs_model_set or 'tasnet_extra-df3777b2.th' in demucs_model_set or \
'demucs48_hq-28a1282c.th' in demucs_model_set or'demucs-e07c671f.th' in demucs_model_set or \
'demucs_extra-3646af93.th' in demucs_model_set or 'demucs_unittest-09ebc15f.th' in demucs_model_set or \
'v2' in demucs_model_set:
demucs_out = self.demix_demucs_v2(segmented_mix, margin_size=margin)
else:
if split_mode == True:
demucs_out = self.demix_demucs_split(mix)
if split_mode == False:
demucs_out = self.demix_demucs(segmented_mix, margin_size=margin)
nan_count = np.count_nonzero(np.isnan(demucs_out)) + np.count_nonzero(np.isnan(base_out))
if nan_count > 0:
print('Warning: there are {} nan values in the array(s).'.format(nan_count))
demucs_out, base_out = np.nan_to_num(demucs_out), np.nan_to_num(base_out)
sources = {}
if 'UVR' in demucs_model_set:
if stemset_n == '(Instrumental)':
sources[3] = (spec_effects(wave=[demucs_out[0],base_out[0]],
algorithm=data['mixing'],
value=b[3])*float(compensate)) # compensation
else:
sources[3] = (spec_effects(wave=[demucs_out[1],base_out[0]],
algorithm=data['mixing'],
value=b[3])*float(compensate)) # compensation
else:
sources[3] = (spec_effects(wave=[demucs_out[3],base_out[0]],
algorithm=data['mixing'],
value=b[3])*float(compensate)) # compensation
if demucs_switch == 'off':
return sources*float(compensate)
else:
return sources
def demix_base(self, mixes, margin_size):
chunked_sources = []
onnxitera = len(mixes)
onnxitera_calc = onnxitera * 2
gui_progress_bar_onnx = 0
widget_text.write(base_text + "Running ONNX Inference...\n")
widget_text.write(base_text + "Processing "f"{onnxitera} slices... ")
print(' Running ONNX Inference...')
for mix in mixes:
gui_progress_bar_onnx += 1
if demucs_switch == 'on':
update_progress(**progress_kwargs,
step=(0.1 + (0.5/onnxitera_calc * gui_progress_bar_onnx)))
else:
update_progress(**progress_kwargs,
step=(0.1 + (0.9/onnxitera * gui_progress_bar_onnx)))
cmix = mixes[mix]
sources = []
n_sample = cmix.shape[1]
mod = 0
for model in self.models:
mod += 1
trim = model.n_fft//2
gen_size = model.chunk_size-2*trim
pad = gen_size - n_sample%gen_size
mix_p = np.concatenate((np.zeros((2,trim)), cmix, np.zeros((2,pad)), np.zeros((2,trim))), 1)
mix_waves = []
i = 0
while i < n_sample + pad:
waves = np.array(mix_p[:, i:i+model.chunk_size])
mix_waves.append(waves)
i += gen_size
mix_waves = torch.tensor(mix_waves, dtype=torch.float32).to(cpu)
with torch.no_grad():
_ort = self.onnx_models[mod]
spek = model.stft(mix_waves)
tar_waves = model.istft(torch.tensor(_ort.run(None, {'input': spek.cpu().numpy()})[0]))#.cpu()
tar_signal = tar_waves[:,:,trim:-trim].transpose(0,1).reshape(2, -1).numpy()[:, :-pad]
start = 0 if mix == 0 else margin_size
end = None if mix == list(mixes.keys())[::-1][0] else -margin_size
if margin_size == 0:
end = None
sources.append(tar_signal[:,start:end])
chunked_sources.append(sources)
_sources = np.concatenate(chunked_sources, axis=-1)
del self.onnx_models
widget_text.write('Done!\n')
return _sources
def demix_demucs(self, mix, margin_size):
#print('shift_set ', shift_set)
processed = {}
demucsitera = len(mix)
demucsitera_calc = demucsitera * 2
gui_progress_bar_demucs = 0
widget_text.write(base_text + "Split Mode is off. (Chunks enabled for Demucs Model)\n")
widget_text.write(base_text + "Running Demucs Inference...\n")
widget_text.write(base_text + "Processing "f"{len(mix)} slices... ")
print('Running Demucs Inference...')
for nmix in mix:
gui_progress_bar_demucs += 1
update_progress(**progress_kwargs,
step=(0.35 + (1.05/demucsitera_calc * gui_progress_bar_demucs)))
cmix = mix[nmix]
cmix = torch.tensor(cmix, dtype=torch.float32)
ref = cmix.mean(0)
cmix = (cmix - ref.mean()) / ref.std()
with torch.no_grad():
sources = apply_model(self.demucs, cmix[None], split=split_mode, device=device, overlap=overlap_set, shifts=shift_set, progress=False)[0]
sources = (sources * ref.std() + ref.mean()).cpu().numpy()
sources[[0,1]] = sources[[1,0]]
start = 0 if nmix == 0 else margin_size
end = None if nmix == list(mix.keys())[::-1][0] else -margin_size
if margin_size == 0:
end = None
processed[nmix] = sources[:,:,start:end].copy()
sources = list(processed.values())
sources = np.concatenate(sources, axis=-1)
widget_text.write('Done!\n')
return sources
def demix_demucs_split(self, mix):
#print('shift_set ', shift_set)
widget_text.write(base_text + "Split Mode is on. (Chunks disabled for Demucs Model)\n")
widget_text.write(base_text + "Running Demucs Inference...\n")
widget_text.write(base_text + "Processing "f"{len(mix)} slices... ")
print(' Running Demucs Inference...')
mix = torch.tensor(mix, dtype=torch.float32)
ref = mix.mean(0)
mix = (mix - ref.mean()) / ref.std()
with torch.no_grad():
sources = apply_model(self.demucs, mix[None], split=split_mode, device=device, overlap=overlap_set, shifts=shift_set, progress=False)[0]
widget_text.write('Done!\n')
sources = (sources * ref.std() + ref.mean()).cpu().numpy()
sources[[0,1]] = sources[[1,0]]
return sources
def demix_demucs_v2(self, mix, margin_size):
processed = {}
demucsitera = len(mix)
demucsitera_calc = demucsitera * 2
gui_progress_bar_demucs = 0
widget_text.write(base_text + "Running Demucs v2 Inference...\n")
widget_text.write(base_text + "Processing "f"{len(mix)} slices... ")
print(' Running Demucs Inference...')
for nmix in mix:
gui_progress_bar_demucs += 1
update_progress(**progress_kwargs,
step=(0.35 + (1.05/demucsitera_calc * gui_progress_bar_demucs)))
cmix = mix[nmix]
cmix = torch.tensor(cmix, dtype=torch.float32)
ref = cmix.mean(0)
cmix = (cmix - ref.mean()) / ref.std()
with torch.no_grad():
sources = apply_model_v2(self.demucs, cmix.to(device), split=split_mode, overlap=overlap_set, shifts=shift_set)
sources = (sources * ref.std() + ref.mean()).cpu().numpy()
sources[[0,1]] = sources[[1,0]]
start = 0 if nmix == 0 else margin_size
end = None if nmix == list(mix.keys())[::-1][0] else -margin_size
if margin_size == 0:
end = None
processed[nmix] = sources[:,:,start:end].copy()
sources = list(processed.values())
sources = np.concatenate(sources, axis=-1)
widget_text.write('Done!\n')
return sources
def demix_demucs_v1(self, mix, margin_size):
processed = {}
demucsitera = len(mix)
demucsitera_calc = demucsitera * 2
gui_progress_bar_demucs = 0
widget_text.write(base_text + "Running Demucs v1 Inference...\n")
widget_text.write(base_text + "Processing "f"{len(mix)} slices... ")
print(' Running Demucs Inference...')
for nmix in mix:
gui_progress_bar_demucs += 1
update_progress(**progress_kwargs,
step=(0.35 + (1.05/demucsitera_calc * gui_progress_bar_demucs)))
cmix = mix[nmix]
cmix = torch.tensor(cmix, dtype=torch.float32)
ref = cmix.mean(0)
cmix = (cmix - ref.mean()) / ref.std()
with torch.no_grad():
sources = apply_model_v1(self.demucs, cmix.to(device), split=split_mode, shifts=shift_set)
sources = (sources * ref.std() + ref.mean()).cpu().numpy()
sources[[0,1]] = sources[[1,0]]
start = 0 if nmix == 0 else margin_size
end = None if nmix == list(mix.keys())[::-1][0] else -margin_size
if margin_size == 0:
end = None
processed[nmix] = sources[:,:,start:end].copy()
sources = list(processed.values())
sources = np.concatenate(sources, axis=-1)
widget_text.write('Done!\n')
return sources
def update_progress(progress_var, total_files, file_num, step: float = 1):
"""Calculate the progress for the progress widget in the GUI"""
base = (100 / total_files)
progress = base * (file_num - 1)
progress += base * step
progress_var.set(progress)
def get_baseText(total_files, file_num):
"""Create the base text for the command widget"""
text = 'File {file_num}/{total_files} '.format(file_num=file_num,
total_files=total_files)
return text
warnings.filterwarnings("ignore")
cpu = torch.device('cpu')
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
def hide_opt():
with open(os.devnull, "w") as devnull:
old_stdout = sys.stdout
sys.stdout = devnull
try:
yield
finally:
sys.stdout = old_stdout
class VocalRemover(object):
def __init__(self, data, text_widget: tk.Text):
self.data = data
self.text_widget = text_widget
self.models = defaultdict(lambda: None)
self.devices = defaultdict(lambda: None)
# self.offset = model.offset
def update_progress(progress_var, total_files, file_num, step: float = 1):
"""Calculate the progress for the progress widget in the GUI"""
base = (100 / total_files)
progress = base * (file_num - 1)
progress += base * step
progress_var.set(progress)
def get_baseText(total_files, file_num):
"""Create the base text for the command widget"""
text = 'File {file_num}/{total_files} '.format(file_num=file_num,
total_files=total_files)
return text
def determineModelFolderName():
"""
Determine the name that is used for the folder and appended
to the back of the music files
"""
modelFolderName = ''
if not data['modelFolder']:
# Model Test Mode not selected
return modelFolderName
# -Instrumental-
if os.path.isfile(data['instrumentalModel']):
modelFolderName += os.path.splitext(os.path.basename(data['instrumentalModel']))[0]
if modelFolderName:
modelFolderName = '/' + modelFolderName
return modelFolderName
class VocalRemover(object):
def __init__(self, data, text_widget: tk.Text):
self.data = data
self.text_widget = text_widget
# self.offset = model.offset
data = {
'agg': 10,
'algo': 'Instrumentals (Min Spec)',
'appendensem': False,
'autocompensate': True,
'chunks': 'auto',
'compensate': 1.03597672895,
'demucs_only': False,
'demucsmodel': False,
'DemucsModel_MDX': 'UVR_Demucs_Model_1',
'ensChoose': 'Basic VR Ensemble',
'export_path': None,
'gpu': -1,
'high_end_process': 'mirroring',
'input_paths': None,
'inst_only': False,
'instrumentalModel': None,