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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e86b53b
 
 
 
 
 
 
 
 
 
 
273d4fa
 
 
 
 
 
 
 
 
e86b53b
 
 
 
 
 
 
 
 
 
 
273d4fa
 
 
 
 
e86b53b
 
 
 
 
 
 
 
273d4fa
 
 
 
 
 
 
 
 
e86b53b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
import os
# os.system("pip install ./ort_nightly_gpu-1.17.0.dev20240118002-cp310-cp310-manylinux_2_28_x86_64.whl")
os.system("pip install ort-nightly-gpu --index-url=https://aiinfra.pkgs.visualstudio.com/PublicPackages/_packaging/ort-cuda-12-nightly/pypi/simple/")
import gc
import hashlib
import queue
import threading
import json
import shlex
import sys
import subprocess
import librosa
import numpy as np
import soundfile as sf
import torch
from tqdm import tqdm
from utils import (
    remove_directory_contents,
    create_directories,
    download_manager,
)
import random
import spaces
from utils import logger
import onnxruntime as ort
import warnings
import spaces
import gradio as gr
import logging
import time
import traceback
from pedalboard import Pedalboard, Reverb, Delay, Chorus, Compressor, Gain, HighpassFilter, LowpassFilter
from pedalboard.io import AudioFile
import numpy as np
import yt_dlp

warnings.filterwarnings("ignore")

title = "<center><strong><font size='7'>Audio🔹separator</font></strong></center>"
description = "This demo uses the MDX-Net models for vocal and background sound separation."
theme = "NoCrypt/miku"

stem_naming = {
    "Vocals": "Instrumental",
    "Other": "Instruments",
    "Instrumental": "Vocals",
    "Drums": "Drumless",
    "Bass": "Bassless",
}


class MDXModel:
    def __init__(
        self,
        device,
        dim_f,
        dim_t,
        n_fft,
        hop=1024,
        stem_name=None,
        compensation=1.000,
    ):
        self.dim_f = dim_f
        self.dim_t = dim_t
        self.dim_c = 4
        self.n_fft = n_fft
        self.hop = hop
        self.stem_name = stem_name
        self.compensation = compensation

        self.n_bins = self.n_fft // 2 + 1
        self.chunk_size = hop * (self.dim_t - 1)
        self.window = torch.hann_window(
            window_length=self.n_fft, periodic=True
        ).to(device)

        out_c = self.dim_c

        self.freq_pad = torch.zeros(
            [1, out_c, self.n_bins - self.dim_f, self.dim_t]
        ).to(device)

    def stft(self, x):
        x = x.reshape([-1, self.chunk_size])
        x = torch.stft(
            x,
            n_fft=self.n_fft,
            hop_length=self.hop,
            window=self.window,
            center=True,
            return_complex=True,
        )
        x = torch.view_as_real(x)
        x = x.permute([0, 3, 1, 2])
        x = x.reshape([-1, 2, 2, self.n_bins, self.dim_t]).reshape(
            [-1, 4, self.n_bins, self.dim_t]
        )
        return x[:, :, : self.dim_f]

    def istft(self, x, freq_pad=None):
        freq_pad = (
            self.freq_pad.repeat([x.shape[0], 1, 1, 1])
            if freq_pad is None
            else freq_pad
        )
        x = torch.cat([x, freq_pad], -2)
        # c = 4*2 if self.target_name=='*' else 2
        x = x.reshape([-1, 2, 2, self.n_bins, self.dim_t]).reshape(
            [-1, 2, self.n_bins, self.dim_t]
        )
        x = x.permute([0, 2, 3, 1])
        x = x.contiguous()
        x = torch.view_as_complex(x)
        x = torch.istft(
            x,
            n_fft=self.n_fft,
            hop_length=self.hop,
            window=self.window,
            center=True,
        )
        return x.reshape([-1, 2, self.chunk_size])


class MDX:
    DEFAULT_SR = 44100
    # Unit: seconds
    DEFAULT_CHUNK_SIZE = 0 * DEFAULT_SR
    DEFAULT_MARGIN_SIZE = 1 * DEFAULT_SR

    def __init__(
        self, model_path: str, params: MDXModel, processor=0
    ):
        # Set the device and the provider (CPU or CUDA)
        self.device = (
            torch.device(f"cuda:{processor}")
            if processor >= 0
            else torch.device("cpu")
        )
        self.provider = (
            ["CUDAExecutionProvider"]
            if processor >= 0
            else ["CPUExecutionProvider"]
        )

        self.model = params

        # Load the ONNX model using ONNX Runtime
        self.ort = ort.InferenceSession(model_path, providers=self.provider)
        # Preload the model for faster performance
        self.ort.run(
            None,
            {"input": torch.rand(1, 4, params.dim_f, params.dim_t).numpy()},
        )
        self.process = lambda spec: self.ort.run(
            None, {"input": spec.cpu().numpy()}
        )[0]

        self.prog = None

    @staticmethod
    def get_hash(model_path):
        try:
            with open(model_path, "rb") as f:
                f.seek(-10000 * 1024, 2)
                model_hash = hashlib.md5(f.read()).hexdigest()
        except: # noqa
            model_hash = hashlib.md5(open(model_path, "rb").read()).hexdigest()

        return model_hash

    @staticmethod
    def segment(
        wave,
        combine=True,
        chunk_size=DEFAULT_CHUNK_SIZE,
        margin_size=DEFAULT_MARGIN_SIZE,
    ):
        """
        Segment or join segmented wave array

        Args:
            wave: (np.array) Wave array to be segmented or joined
            combine: (bool) If True, combines segmented wave array.
                If False, segments wave array.
            chunk_size: (int) Size of each segment (in samples)
            margin_size: (int) Size of margin between segments (in samples)

        Returns:
            numpy array: Segmented or joined wave array
        """

        if combine:
            # Initializing as None instead of [] for later numpy array concatenation
            processed_wave = None
            for segment_count, segment in enumerate(wave):
                start = 0 if segment_count == 0 else margin_size
                end = None if segment_count == len(wave) - 1 else -margin_size
                if margin_size == 0:
                    end = None
                if processed_wave is None:  # Create array for first segment
                    processed_wave = segment[:, start:end]
                else:  # Concatenate to existing array for subsequent segments
                    processed_wave = np.concatenate(
                        (processed_wave, segment[:, start:end]), axis=-1
                    )

        else:
            processed_wave = []
            sample_count = wave.shape[-1]

            if chunk_size <= 0 or chunk_size > sample_count:
                chunk_size = sample_count

            if margin_size > chunk_size:
                margin_size = chunk_size

            for segment_count, skip in enumerate(
                range(0, sample_count, chunk_size)
            ):
                margin = 0 if segment_count == 0 else margin_size
                end = min(skip + chunk_size + margin_size, sample_count)
                start = skip - margin

                cut = wave[:, start:end].copy()
                processed_wave.append(cut)

                if end == sample_count:
                    break

        return processed_wave

    def pad_wave(self, wave):
        """
        Pad the wave array to match the required chunk size

        Args:
            wave: (np.array) Wave array to be padded

        Returns:
            tuple: (padded_wave, pad, trim)
                - padded_wave: Padded wave array
                - pad: Number of samples that were padded
                - trim: Number of samples that were trimmed
        """
        n_sample = wave.shape[1]
        trim = self.model.n_fft // 2
        gen_size = self.model.chunk_size - 2 * trim
        pad = gen_size - n_sample % gen_size

        # Padded wave
        wave_p = np.concatenate(
            (
                np.zeros((2, trim)),
                wave,
                np.zeros((2, pad)),
                np.zeros((2, trim)),
            ),
            1,
        )

        mix_waves = []
        for i in range(0, n_sample + pad, gen_size):
            waves = np.array(wave_p[:, i:i + self.model.chunk_size])
            mix_waves.append(waves)

        mix_waves = torch.tensor(mix_waves, dtype=torch.float32).to(
            self.device
        )

        return mix_waves, pad, trim

    def _process_wave(self, mix_waves, trim, pad, q: queue.Queue, _id: int):
        """
        Process each wave segment in a multi-threaded environment

        Args:
            mix_waves: (torch.Tensor) Wave segments to be processed
            trim: (int) Number of samples trimmed during padding
            pad: (int) Number of samples padded during padding
            q: (queue.Queue) Queue to hold the processed wave segments
            _id: (int) Identifier of the processed wave segment

        Returns:
            numpy array: Processed wave segment
        """
        mix_waves = mix_waves.split(1)
        with torch.no_grad():
            pw = []
            for mix_wave in mix_waves:
                self.prog.update()
                spec = self.model.stft(mix_wave)
                processed_spec = torch.tensor(self.process(spec))
                processed_wav = self.model.istft(
                    processed_spec.to(self.device)
                )
                processed_wav = (
                    processed_wav[:, :, trim:-trim]
                    .transpose(0, 1)
                    .reshape(2, -1)
                    .cpu()
                    .numpy()
                )
                pw.append(processed_wav)
        processed_signal = np.concatenate(pw, axis=-1)[:, :-pad]
        q.put({_id: processed_signal})
        return processed_signal

    def process_wave(self, wave: np.array, mt_threads=1):
        """
        Process the wave array in a multi-threaded environment

        Args:
            wave: (np.array) Wave array to be processed
            mt_threads: (int) Number of threads to be used for processing

        Returns:
            numpy array: Processed wave array
        """
        self.prog = tqdm(total=0)
        chunk = wave.shape[-1] // mt_threads
        waves = self.segment(wave, False, chunk)

        # Create a queue to hold the processed wave segments
        q = queue.Queue()
        threads = []
        for c, batch in enumerate(waves):
            mix_waves, pad, trim = self.pad_wave(batch)
            self.prog.total = len(mix_waves) * mt_threads
            thread = threading.Thread(
                target=self._process_wave, args=(mix_waves, trim, pad, q, c)
            )
            thread.start()
            threads.append(thread)
        for thread in threads:
            thread.join()
        self.prog.close()

        processed_batches = []
        while not q.empty():
            processed_batches.append(q.get())
        processed_batches = [
            list(wave.values())[0]
            for wave in sorted(
                processed_batches, key=lambda d: list(d.keys())[0]
            )
        ]
        assert len(processed_batches) == len(
            waves
        ), "Incomplete processed batches, please reduce batch size!"
        return self.segment(processed_batches, True, chunk)


@spaces.GPU()
def run_mdx(
    model_params,
    output_dir,
    model_path,
    filename,
    exclude_main=False,
    exclude_inversion=False,
    suffix=None,
    invert_suffix=None,
    denoise=False,
    keep_orig=True,
    m_threads=2,
    device_base="cuda",
):

    if device_base == "cuda":
        device = torch.device("cuda:0")
        processor_num = 0
        device_properties = torch.cuda.get_device_properties(device)
        vram_gb = device_properties.total_memory / 1024**3
        m_threads = 1 if vram_gb < 8 else (8 if vram_gb > 32 else 2)
        logger.info(f"threads: {m_threads} vram: {vram_gb}")
    else:
        device = torch.device("cpu")
        processor_num = -1
        m_threads = 1

    model_hash = MDX.get_hash(model_path)
    mp = model_params.get(model_hash)
    model = MDXModel(
        device,
        dim_f=mp["mdx_dim_f_set"],
        dim_t=2 ** mp["mdx_dim_t_set"],
        n_fft=mp["mdx_n_fft_scale_set"],
        stem_name=mp["primary_stem"],
        compensation=mp["compensate"],
    )

    mdx_sess = MDX(model_path, model, processor=processor_num)
    wave, sr = librosa.load(filename, mono=False, sr=44100)
    # normalizing input wave gives better output
    peak = max(np.max(wave), abs(np.min(wave)))
    wave /= peak
    if denoise:
        wave_processed = -(mdx_sess.process_wave(-wave, m_threads)) + (
            mdx_sess.process_wave(wave, m_threads)
        )
        wave_processed *= 0.5
    else:
        wave_processed = mdx_sess.process_wave(wave, m_threads)
    # return to previous peak
    wave_processed *= peak
    stem_name = model.stem_name if suffix is None else suffix

    main_filepath = None
    if not exclude_main:
        main_filepath = os.path.join(
            output_dir,
            f"{os.path.basename(os.path.splitext(filename)[0])}_{stem_name}.wav",
        )
        sf.write(main_filepath, wave_processed.T, sr)

    invert_filepath = None
    if not exclude_inversion:
        diff_stem_name = (
            stem_naming.get(stem_name)
            if invert_suffix is None
            else invert_suffix
        )
        stem_name = (
            f"{stem_name}_diff" if diff_stem_name is None else diff_stem_name
        )
        invert_filepath = os.path.join(
            output_dir,
            f"{os.path.basename(os.path.splitext(filename)[0])}_{stem_name}.wav",
        )
        sf.write(
            invert_filepath,
            (-wave_processed.T * model.compensation) + wave.T,
            sr,
        )

    if not keep_orig:
        os.remove(filename)

    del mdx_sess, wave_processed, wave
    gc.collect()
    torch.cuda.empty_cache()
    return main_filepath, invert_filepath


def run_mdx_beta(
    model_params,
    output_dir,
    model_path,
    filename,
    exclude_main=False,
    exclude_inversion=False,
    suffix=None,
    invert_suffix=None,
    denoise=False,
    keep_orig=True,
    m_threads=2,
    device_base="",
):

    m_threads = 1
    duration = librosa.get_duration(filename=filename)
    if duration >= 60 and duration <= 120:
        m_threads = 8
    elif duration > 120:
        m_threads = 16

    logger.info(f"threads: {m_threads}")

    model_hash = MDX.get_hash(model_path)
    device = torch.device("cpu")
    processor_num = -1
    mp = model_params.get(model_hash)
    model = MDXModel(
        device,
        dim_f=mp["mdx_dim_f_set"],
        dim_t=2 ** mp["mdx_dim_t_set"],
        n_fft=mp["mdx_n_fft_scale_set"],
        stem_name=mp["primary_stem"],
        compensation=mp["compensate"],
    )

    mdx_sess = MDX(model_path, model, processor=processor_num)
    wave, sr = librosa.load(filename, mono=False, sr=44100)
    # normalizing input wave gives better output
    peak = max(np.max(wave), abs(np.min(wave)))
    wave /= peak
    if denoise:
        wave_processed = -(mdx_sess.process_wave(-wave, m_threads)) + (
            mdx_sess.process_wave(wave, m_threads)
        )
        wave_processed *= 0.5
    else:
        wave_processed = mdx_sess.process_wave(wave, m_threads)
    # return to previous peak
    wave_processed *= peak
    stem_name = model.stem_name if suffix is None else suffix

    main_filepath = None
    if not exclude_main:
        main_filepath = os.path.join(
            output_dir,
            f"{os.path.basename(os.path.splitext(filename)[0])}_{stem_name}.wav",
        )
        sf.write(main_filepath, wave_processed.T, sr)

    invert_filepath = None
    if not exclude_inversion:
        diff_stem_name = (
            stem_naming.get(stem_name)
            if invert_suffix is None
            else invert_suffix
        )
        stem_name = (
            f"{stem_name}_diff" if diff_stem_name is None else diff_stem_name
        )
        invert_filepath = os.path.join(
            output_dir,
            f"{os.path.basename(os.path.splitext(filename)[0])}_{stem_name}.wav",
        )
        sf.write(
            invert_filepath,
            (-wave_processed.T * model.compensation) + wave.T,
            sr,
        )

    if not keep_orig:
        os.remove(filename)

    del mdx_sess, wave_processed, wave
    gc.collect()
    torch.cuda.empty_cache()
    return main_filepath, invert_filepath


MDX_DOWNLOAD_LINK = "https://github.com/TRvlvr/model_repo/releases/download/all_public_uvr_models/"
UVR_MODELS = [
    "UVR-MDX-NET-Voc_FT.onnx",
    "UVR_MDXNET_KARA_2.onnx",
    "Reverb_HQ_By_FoxJoy.onnx",
    "UVR-MDX-NET-Inst_HQ_4.onnx",
]
BASE_DIR = "."  # os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
mdxnet_models_dir = os.path.join(BASE_DIR, "mdx_models")
output_dir = os.path.join(BASE_DIR, "clean_song_output")


def convert_to_stereo_and_wav(audio_path):
    wave, sr = librosa.load(audio_path, mono=False, sr=44100)

    # check if mono
    if type(wave[0]) != np.ndarray or audio_path[-4:].lower() != ".wav": # noqa
        stereo_path = f"{os.path.splitext(audio_path)[0]}_stereo.wav"
        stereo_path = os.path.join(output_dir, stereo_path)

        command = shlex.split(
            f'ffmpeg -y -loglevel error -i "{audio_path}" -ac 2 -f wav "{stereo_path}"'
        )
        sub_params = {
            "stdout": subprocess.PIPE,
            "stderr": subprocess.PIPE,
            "creationflags": subprocess.CREATE_NO_WINDOW
            if sys.platform == "win32"
            else 0,
        }
        process_wav = subprocess.Popen(command, **sub_params)
        output, errors = process_wav.communicate()
        if process_wav.returncode != 0 or not os.path.exists(stereo_path):
            raise Exception("Error processing audio to stereo wav")

        return stereo_path
    else:
        return audio_path


def get_hash(filepath):
    with open(filepath, 'rb') as f:
        file_hash = hashlib.blake2b()
        while chunk := f.read(8192):
            file_hash.update(chunk)

    return file_hash.hexdigest()[:18]

def random_sleep():
    sleep_time = round(random.uniform(5.2, 7.9), 1)
    time.sleep(sleep_time)

def process_uvr_task(
    orig_song_path: str = "aud_test.mp3",
    main_vocals: bool = False,
    dereverb: bool = True,
    song_id: str = "mdx",  # folder output name
    only_voiceless: bool = False,
    remove_files_output_dir: bool = False,
):

    device_base = "cuda" if torch.cuda.is_available() else "cpu"
    logger.info(f"Device: {device_base}")

    if remove_files_output_dir:
        remove_directory_contents(output_dir)

    with open(os.path.join(mdxnet_models_dir, "data.json")) as infile:
        mdx_model_params = json.load(infile)

    song_output_dir = os.path.join(output_dir, song_id)
    create_directories(song_output_dir)
    orig_song_path = convert_to_stereo_and_wav(orig_song_path)

    logger.info(f"onnxruntime device >> {ort.get_device()}")

    if only_voiceless:
        logger.info("Voiceless Track Separation...")

        process = run_mdx(
            mdx_model_params,
            song_output_dir,
            os.path.join(mdxnet_models_dir, "UVR-MDX-NET-Inst_HQ_4.onnx"),
            orig_song_path,
            suffix="Voiceless",
            denoise=False,
            keep_orig=True,
            exclude_inversion=True,
            device_base=device_base,
        )

        return process

    logger.info("Vocal Track Isolation...")
    vocals_path, instrumentals_path = run_mdx(
        mdx_model_params,
        song_output_dir,
        os.path.join(mdxnet_models_dir, "UVR-MDX-NET-Voc_FT.onnx"),
        orig_song_path,
        denoise=True,
        keep_orig=True,
        device_base=device_base,
    )

    if main_vocals:
        random_sleep()
        msg_main = "Main Voice Separation from Supporting Vocals..."
        logger.info(msg_main)
        gr.Info(msg_main)
        try:
            backup_vocals_path, main_vocals_path = run_mdx(
                mdx_model_params,
                song_output_dir,
                os.path.join(mdxnet_models_dir, "UVR_MDXNET_KARA_2.onnx"),
                vocals_path,
                suffix="Backup",
                invert_suffix="Main",
                denoise=True,
                device_base=device_base,
            )
        except Exception as e:
                backup_vocals_path, main_vocals_path = run_mdx_beta(
                    mdx_model_params,
                    song_output_dir,
                    os.path.join(mdxnet_models_dir, "UVR_MDXNET_KARA_2.onnx"),
                    vocals_path,
                    suffix="Backup",
                    invert_suffix="Main",
                    denoise=True,
                    device_base=device_base,
                )
    else:
        backup_vocals_path, main_vocals_path = None, vocals_path

    if dereverb:
        random_sleep()
        msg_dereverb = "Vocal Clarity Enhancement through De-Reverberation..."
        logger.info(msg_dereverb)
        gr.Info(msg_dereverb)
        try:
            _, vocals_dereverb_path = run_mdx(
                mdx_model_params,
                song_output_dir,
                os.path.join(mdxnet_models_dir, "Reverb_HQ_By_FoxJoy.onnx"),
                main_vocals_path,
                invert_suffix="DeReverb",
                exclude_main=True,
                denoise=True,
                device_base=device_base,
            )
        except Exception as e:
                _, vocals_dereverb_path = run_mdx_beta(
                    mdx_model_params,
                    song_output_dir,
                    os.path.join(mdxnet_models_dir, "Reverb_HQ_By_FoxJoy.onnx"),
                    main_vocals_path,
                    invert_suffix="DeReverb",
                    exclude_main=True,
                    denoise=True,
                    device_base=device_base,
                )
    else:
        vocals_dereverb_path = main_vocals_path

    return (
        vocals_path,
        instrumentals_path,
        backup_vocals_path,
        main_vocals_path,
        vocals_dereverb_path,
    )


def add_vocal_effects(input_file, output_file, reverb_room_size=0.6, vocal_reverb_dryness=0.8, reverb_damping=0.6, reverb_wet_level=0.35,
                      delay_seconds=0.4, delay_mix=0.25,
                      compressor_threshold_db=-25, compressor_ratio=3.5, compressor_attack_ms=10, compressor_release_ms=60,
                      gain_db=3):

    effects = [HighpassFilter()]

    effects.append(Reverb(room_size=reverb_room_size, damping=reverb_damping, wet_level=reverb_wet_level, dry_level=vocal_reverb_dryness))

    effects.append(Compressor(threshold_db=compressor_threshold_db, ratio=compressor_ratio,
                              attack_ms=compressor_attack_ms, release_ms=compressor_release_ms))

    if delay_seconds > 0 or delay_mix > 0:
        effects.append(Delay(delay_seconds=delay_seconds, mix=delay_mix))
        print("delay applied")
    # effects.append(Chorus())

    if gain_db:
        effects.append(Gain(gain_db=gain_db))
        print("added gain db")

    board = Pedalboard(effects)

    with AudioFile(input_file) as f:
        with AudioFile(output_file, 'w', f.samplerate, f.num_channels) as o:
            # Read one second of audio at a time, until the file is empty:
            while f.tell() < f.frames:
                chunk = f.read(int(f.samplerate))
                effected = board(chunk, f.samplerate, reset=False)
                o.write(effected)


def add_instrumental_effects(input_file, output_file, highpass_freq=100, lowpass_freq=12000,
                             reverb_room_size=0.5, reverb_damping=0.5, reverb_wet_level=0.25,
                             compressor_threshold_db=-20, compressor_ratio=2.5, compressor_attack_ms=15, compressor_release_ms=80,
                             gain_db=2):

    effects = [
        HighpassFilter(cutoff_frequency_hz=highpass_freq),
        LowpassFilter(cutoff_frequency_hz=lowpass_freq),
    ]
    if reverb_room_size > 0 or reverb_damping > 0 or reverb_wet_level > 0:
        effects.append(Reverb(room_size=reverb_room_size, damping=reverb_damping, wet_level=reverb_wet_level))

    effects.append(Compressor(threshold_db=compressor_threshold_db, ratio=compressor_ratio,
                              attack_ms=compressor_attack_ms, release_ms=compressor_release_ms))

    if gain_db:
        effects.append(Gain(gain_db=gain_db))

    board = Pedalboard(effects)

    with AudioFile(input_file) as f:
        with AudioFile(output_file, 'w', f.samplerate, f.num_channels) as o:
            # Read one second of audio at a time, until the file is empty:
            while f.tell() < f.frames:
                chunk = f.read(int(f.samplerate))
                effected = board(chunk, f.samplerate, reset=False)
                o.write(effected)

    
def sound_separate(media_file, stem, main, dereverb, vocal_effects=True, background_effects=True,
                   vocal_reverb_room_size=0.6, vocal_reverb_damping=0.6, vocal_reverb_wet_level=0.35,
                   vocal_delay_seconds=0.4, vocal_delay_mix=0.25,
                   vocal_compressor_threshold_db=-25, vocal_compressor_ratio=3.5, vocal_compressor_attack_ms=10, vocal_compressor_release_ms=60,
                   vocal_gain_db=4,
                   background_highpass_freq=120, background_lowpass_freq=11000,
                   background_reverb_room_size=0.5, background_reverb_damping=0.5, background_reverb_wet_level=0.25,
                   background_compressor_threshold_db=-20, background_compressor_ratio=2.5, background_compressor_attack_ms=15, background_compressor_release_ms=80,
                   background_gain_db=3):
    if not media_file:
        raise ValueError("The audio path is missing.")

    if not stem:
        raise ValueError("Please select 'vocal' or 'background' stem.")

    hash_audio = str(get_hash(media_file))
    media_dir = os.path.dirname(media_file)

    outputs = []

    start_time = time.time()

    if stem == "vocal":
        try:
            _, _, _, _, vocal_audio = process_uvr_task(
                orig_song_path=media_file,
                song_id=hash_audio + "mdx",
                main_vocals=main,
                dereverb=dereverb,
                remove_files_output_dir=False,
            )

            if vocal_effects:
                suffix = '_effects'
                file_name, file_extension = os.path.splitext(vocal_audio)
                out_effects = file_name + suffix + file_extension
                out_effects_path = os.path.join(media_dir, out_effects)
                add_vocal_effects(vocal_audio, out_effects_path,
                                  reverb_room_size=vocal_reverb_room_size, reverb_damping=vocal_reverb_damping, reverb_wet_level=vocal_reverb_wet_level,
                                  delay_seconds=vocal_delay_seconds, delay_mix=vocal_delay_mix,
                                  compressor_threshold_db=vocal_compressor_threshold_db, compressor_ratio=vocal_compressor_ratio, compressor_attack_ms=vocal_compressor_attack_ms, compressor_release_ms=vocal_compressor_release_ms,
                                  gain_db=vocal_gain_db
                                  )
                vocal_audio = out_effects_path

            outputs.append(vocal_audio)
        except Exception as error:
            logger.error(str(error))
            traceback.print_exc()

    if stem == "background":
        background_audio, _ = process_uvr_task(
            orig_song_path=media_file,
            song_id=hash_audio + "voiceless",
            only_voiceless=True,
            remove_files_output_dir=False,
        )

        if background_effects:
            suffix = '_effects'
            file_name, file_extension = os.path.splitext(background_audio)
            out_effects = file_name + suffix + file_extension
            out_effects_path = os.path.join(media_dir, out_effects)
            add_instrumental_effects(background_audio, out_effects_path,
                                     highpass_freq=background_highpass_freq, lowpass_freq=background_lowpass_freq,
                                     reverb_room_size=background_reverb_room_size, reverb_damping=background_reverb_damping, reverb_wet_level=background_reverb_wet_level,
                                     compressor_threshold_db=background_compressor_threshold_db, compressor_ratio=background_compressor_ratio, compressor_attack_ms=background_compressor_attack_ms, compressor_release_ms=background_compressor_release_ms,
                                     gain_db=background_gain_db
                                     )
            background_audio = out_effects_path

        outputs.append(background_audio)

    end_time = time.time()
    execution_time = end_time - start_time
    logger.info(f"Execution time: {execution_time} seconds")

    if not outputs:
        raise Exception("Error in sound separation.")

    return outputs


def sound_separate(media_file, stem, main, dereverb, vocal_effects=True, background_effects=True,
                   vocal_reverb_room_size=0.6, vocal_reverb_damping=0.6, vocal_reverb_dryness=0.8 ,vocal_reverb_wet_level=0.35,
                   vocal_delay_seconds=0.4, vocal_delay_mix=0.25,
                   vocal_compressor_threshold_db=-25, vocal_compressor_ratio=3.5, vocal_compressor_attack_ms=10, vocal_compressor_release_ms=60,
                   vocal_gain_db=4,
                   background_highpass_freq=120, background_lowpass_freq=11000,
                   background_reverb_room_size=0.5, background_reverb_damping=0.5, background_reverb_wet_level=0.25,
                   background_compressor_threshold_db=-20, background_compressor_ratio=2.5, background_compressor_attack_ms=15, background_compressor_release_ms=80,
                   background_gain_db=3,
):
    if not media_file:
        raise ValueError("The audio path is missing.")

    if not stem:
        raise ValueError("Please select 'vocal' or 'background' stem.")

    hash_audio = str(get_hash(media_file))
    media_dir = os.path.dirname(media_file)

    outputs = []

    try:
        duration_base_ = librosa.get_duration(filename=media_file)
        print("Duration audio:", duration_base_)
    except Exception as e:
        print(e)
    
    start_time = time.time()

    if stem == "vocal":
        try:
            _, _, _, _, vocal_audio = process_uvr_task(
                orig_song_path=media_file,
                song_id=hash_audio + "mdx",
                main_vocals=main,
                dereverb=dereverb,
                remove_files_output_dir=False,
            )

            if vocal_effects:
                suffix = '_effects'
                file_name, file_extension = os.path.splitext(os.path.abspath(vocal_audio))
                out_effects = file_name + suffix + file_extension
                out_effects_path = os.path.join(media_dir, out_effects)
                add_vocal_effects(vocal_audio, out_effects_path,
                                  reverb_room_size=vocal_reverb_room_size, reverb_damping=vocal_reverb_damping, vocal_reverb_dryness=vocal_reverb_dryness, reverb_wet_level=vocal_reverb_wet_level,
                                  delay_seconds=vocal_delay_seconds, delay_mix=vocal_delay_mix,
                                  compressor_threshold_db=vocal_compressor_threshold_db, compressor_ratio=vocal_compressor_ratio, compressor_attack_ms=vocal_compressor_attack_ms, compressor_release_ms=vocal_compressor_release_ms,
                                  gain_db=vocal_gain_db
                                  )
                vocal_audio = out_effects_path

            outputs.append(vocal_audio)
        except Exception as error:
            gr.Info(str(error))
            logger.error(str(error))

    if stem == "background":
        background_audio, _ = process_uvr_task(
            orig_song_path=media_file,
            song_id=hash_audio + "voiceless",
            only_voiceless=True,
            remove_files_output_dir=False,
        )

        if background_effects:
            suffix = '_effects'
            file_name, file_extension = os.path.splitext(os.path.abspath(background_audio))
            out_effects = file_name + suffix + file_extension
            out_effects_path = os.path.join(media_dir, out_effects)
            print(file_name, file_extension, out_effects, out_effects_path)
            add_instrumental_effects(background_audio, out_effects_path,
                                     highpass_freq=background_highpass_freq, lowpass_freq=background_lowpass_freq,
                                     reverb_room_size=background_reverb_room_size, reverb_damping=background_reverb_damping, reverb_wet_level=background_reverb_wet_level,
                                     compressor_threshold_db=background_compressor_threshold_db, compressor_ratio=background_compressor_ratio, compressor_attack_ms=background_compressor_attack_ms, compressor_release_ms=background_compressor_release_ms,
                                     gain_db=background_gain_db
                                     )
            background_audio = out_effects_path

        outputs.append(background_audio)

    end_time = time.time()
    execution_time = end_time - start_time
    logger.info(f"Execution time: {execution_time} seconds")

    if not outputs:
        raise Exception("Error in sound separation.")

    return outputs


def audio_downloader(
    url_media,
):

    url_media = url_media.strip()

    if not url_media:
        return None

    print(url_media[:10])

    dir_output_downloads = "downloads"
    os.makedirs(dir_output_downloads, exist_ok=True)

    media_info = yt_dlp.YoutubeDL(
        {"quiet": True, "no_warnings": True, "noplaylist": True}
    ).extract_info(url_media, download=False)
    download_path = f"{os.path.join(dir_output_downloads, media_info['title'])}.m4a"

    ydl_opts = {
        'format': 'm4a/bestaudio/best',
        'postprocessors': [{  # Extract audio using ffmpeg
            'key': 'FFmpegExtractAudio',
            'preferredcodec': 'm4a',
        }],
        'force_overwrites': True,
        'noplaylist': True,
        'no_warnings': True,
        'quiet': True,
        'ignore_no_formats_error': True,
        'restrictfilenames': True,
        'outtmpl': download_path,
    }
    with yt_dlp.YoutubeDL(ydl_opts) as ydl_download:
        ydl_download.download([url_media])

    return download_path


def downloader_conf():
    return gr.Checkbox(
        False,
        label="URL-to-Audio",
        # info="",
        container=False,
    )


def url_media_conf():
    return gr.Textbox(
        value="",
        label="Enter URL",
        placeholder="www.youtube.com/watch?v=g_9rPvbENUw",
        visible=False,
        lines=1,
    )


def url_button_conf():
    return gr.Button(
        "Go",
        variant="secondary",
        visible=False,
    )


def show_components_downloader(value_active):
    return gr.update(
        visible=value_active
    ), gr.update(
        visible=value_active
    )


def audio_conf():
    return gr.File(
        label="Audio file",
        # file_count="multiple",
        type="filepath",
        container=True,
    )


def stem_conf():
    return gr.Radio(
        choices=["vocal", "background"],
        value="vocal",
        label="Stem",
        # info="",
    )


def main_conf():
    return gr.Checkbox(
        False,
        label="Main",
        # info="",
    )


def dereverb_conf():
    return gr.Checkbox(
        False,
        label="Dereverb",
        # info="",
        visible=True,
    )


def vocal_effects_conf():
    return gr.Checkbox(
        False,
        label="Vocal Effects",
        # info="",
        visible=True,
    )


def background_effects_conf():
    return gr.Checkbox(
        False,
        label="Background Effects",
        # info="",
        visible=False,
    )


def vocal_reverb_room_size_conf():
    return gr.Number(
        0.15,
        label="Vocal Reverb Room Size",
        minimum=0.0,
        maximum=1.0,
        step=0.05,
        visible=True,
    )


def vocal_reverb_damping_conf():
    return gr.Number(
        0.7,
        label="Vocal Reverb Damping",
        minimum=0.0,
        maximum=1.0,
        step=0.01,
        visible=True,
    )


def vocal_reverb_wet_level_conf():
    return gr.Number(
        0.2,
        label="Vocal Reverb Wet Level",
        minimum=0.0,
        maximum=1.0,
        step=0.05,
        visible=True,
    )


def vocal_reverb_dryness_level_conf():
    return gr.Number(
        0.8,
        label="Vocal Reverb Dryness Level",
        minimum=0.0,
        maximum=1.0,
        step=0.05,
        visible=True,
    )


def vocal_delay_seconds_conf():
    return gr.Number(
        0.,
        label="Vocal Delay Seconds",
        minimum=0.0,
        maximum=1.0,
        step=0.01,
        visible=True,
    )


def vocal_delay_mix_conf():
    return gr.Number(
        0.,
        label="Vocal Delay Mix",
        minimum=0.0,
        maximum=1.0,
        step=0.01,
        visible=True,
    )


def vocal_compressor_threshold_db_conf():
    return gr.Number(
        -15,
        label="Vocal Compressor Threshold (dB)",
        minimum=-60,
        maximum=0,
        step=1,
        visible=True,
    )


def vocal_compressor_ratio_conf():
    return gr.Number(
        4.,
        label="Vocal Compressor Ratio",
        minimum=0,
        maximum=20,
        step=0.1,
        visible=True,
    )


def vocal_compressor_attack_ms_conf():
    return gr.Number(
        1.0,
        label="Vocal Compressor Attack (ms)",
        minimum=0,
        maximum=1000,
        step=1,
        visible=True,
    )


def vocal_compressor_release_ms_conf():
    return gr.Number(
        100,
        label="Vocal Compressor Release (ms)",
        minimum=0,
        maximum=3000,
        step=1,
        visible=True,
    )


def vocal_gain_db_conf():
    return gr.Number(
        0,
        label="Vocal Gain (dB)",
        minimum=-40,
        maximum=40,
        step=1,
        visible=True,
    )


def background_highpass_freq_conf():
    return gr.Number(
        120,
        label="Background Highpass Frequency (Hz)",
        minimum=0,
        maximum=1000,
        step=1,
        visible=True,
    )


def background_lowpass_freq_conf():
    return gr.Number(
        11000,
        label="Background Lowpass Frequency (Hz)",
        minimum=0,
        maximum=20000,
        step=1,
        visible=True,
    )


def background_reverb_room_size_conf():
    return gr.Number(
        0.1,
        label="Background Reverb Room Size",
        minimum=0.0,
        maximum=1.0,
        step=0.1,
        visible=True,
    )


def background_reverb_damping_conf():
    return gr.Number(
        0.5,
        label="Background Reverb Damping",
        minimum=0.0,
        maximum=1.0,
        step=0.1,
        visible=True,
    )


def background_reverb_wet_level_conf():
    return gr.Number(
        0.25,
        label="Background Reverb Wet Level",
        minimum=0.0,
        maximum=1.0,
        step=0.05,
        visible=True,
    )


def background_compressor_threshold_db_conf():
    return gr.Number(
        -15,
        label="Background Compressor Threshold (dB)",
        minimum=-60,
        maximum=0,
        step=1,
        visible=True,
    )


def background_compressor_ratio_conf():
    return gr.Number(
        4.,
        label="Background Compressor Ratio",
        minimum=0,
        maximum=20,
        step=0.1,
        visible=True,
    )


def background_compressor_attack_ms_conf():
    return gr.Number(
        15,
        label="Background Compressor Attack (ms)",
        minimum=0,
        maximum=1000,
        step=1,
        visible=True,
    )


def background_compressor_release_ms_conf():
    return gr.Number(
        60,
        label="Background Compressor Release (ms)",
        minimum=0,
        maximum=3000,
        step=1,
        visible=True,
    )


def background_gain_db_conf():
    return gr.Number(
        0,
        label="Background Gain (dB)",
        minimum=-40,
        maximum=40,
        step=1,
        visible=True,
    )


def button_conf():
    return gr.Button(
        "Inference",
        variant="primary",
    )


def output_conf():
    return gr.File(
        label="Result",
        file_count="multiple",
        interactive=False,
    )


def show_vocal_components(value_name):

    if value_name == "vocal":
        return gr.update(visible=True), gr.update(
            visible=True
        ), gr.update(visible=True), gr.update(
            visible=False
        )
    else:
        return gr.update(visible=False), gr.update(
            visible=False
        ), gr.update(visible=False), gr.update(
            visible=True
        )


def get_gui(theme):
    with gr.Blocks(theme=theme) as app:
        gr.Markdown(title)
        gr.Markdown(description)

        downloader_gui = downloader_conf()
        with gr.Row():
            with gr.Column(scale=2):
                url_media_gui = url_media_conf()
            with gr.Column(scale=1):
                url_button_gui = url_button_conf()

        downloader_gui.change(
            show_components_downloader,
            [downloader_gui],
            [url_media_gui, url_button_gui]
        )

        aud = audio_conf()

        url_button_gui.click(
            audio_downloader,
            [url_media_gui],
            [aud]
        )

        with gr.Column():
            with gr.Row():
                stem_gui = stem_conf()

        with gr.Column():
            with gr.Row():
                main_gui = main_conf()
                dereverb_gui = dereverb_conf()
                vocal_effects_gui = vocal_effects_conf()
                background_effects_gui = background_effects_conf()

            # with gr.Column():
            with gr.Accordion("Vocal Effects Parameters", open=False): # with gr.Row():
                # gr.Label("Vocal Effects Parameters")
                with gr.Row():
                    vocal_reverb_room_size_gui = vocal_reverb_room_size_conf()
                    vocal_reverb_damping_gui = vocal_reverb_damping_conf()
                    vocal_reverb_dryness_gui = vocal_reverb_dryness_level_conf()
                    vocal_reverb_wet_level_gui = vocal_reverb_wet_level_conf()
                    vocal_delay_seconds_gui = vocal_delay_seconds_conf()
                    vocal_delay_mix_gui = vocal_delay_mix_conf()
                    vocal_compressor_threshold_db_gui = vocal_compressor_threshold_db_conf()
                    vocal_compressor_ratio_gui = vocal_compressor_ratio_conf()
                    vocal_compressor_attack_ms_gui = vocal_compressor_attack_ms_conf()
                    vocal_compressor_release_ms_gui = vocal_compressor_release_ms_conf()
                    vocal_gain_db_gui = vocal_gain_db_conf()

            with gr.Accordion("Background Effects Parameters", open=False): # with gr.Row():
                # gr.Label("Background Effects Parameters")
                with gr.Row():
                    background_highpass_freq_gui = background_highpass_freq_conf()
                    background_lowpass_freq_gui = background_lowpass_freq_conf()
                    background_reverb_room_size_gui = background_reverb_room_size_conf()
                    background_reverb_damping_gui = background_reverb_damping_conf()
                    background_reverb_wet_level_gui = background_reverb_wet_level_conf()
                    background_compressor_threshold_db_gui = background_compressor_threshold_db_conf()
                    background_compressor_ratio_gui = background_compressor_ratio_conf()
                    background_compressor_attack_ms_gui = background_compressor_attack_ms_conf()
                    background_compressor_release_ms_gui = background_compressor_release_ms_conf()
                    background_gain_db_gui = background_gain_db_conf()

            stem_gui.change(
                show_vocal_components,
                [stem_gui],
                [main_gui, dereverb_gui, vocal_effects_gui, background_effects_gui],
            )

        button_base = button_conf()
        output_base = output_conf()

        button_base.click(
            sound_separate,
            inputs=[
                aud,
                stem_gui,
                main_gui,
                dereverb_gui,
                vocal_effects_gui,
                background_effects_gui,
                vocal_reverb_room_size_gui, vocal_reverb_damping_gui, vocal_reverb_dryness_gui, vocal_reverb_wet_level_gui,
                vocal_delay_seconds_gui, vocal_delay_mix_gui, vocal_compressor_threshold_db_gui, vocal_compressor_ratio_gui,
                vocal_compressor_attack_ms_gui, vocal_compressor_release_ms_gui, vocal_gain_db_gui,
                background_highpass_freq_gui, background_lowpass_freq_gui, background_reverb_room_size_gui,
                background_reverb_damping_gui, background_reverb_wet_level_gui, background_compressor_threshold_db_gui,
                background_compressor_ratio_gui, background_compressor_attack_ms_gui, background_compressor_release_ms_gui,
                background_gain_db_gui,
            ],
            outputs=[output_base],
        )

        gr.Examples(
            examples=[
                [
                    "./test.mp3",
                    "vocal",
                    False,
                    False,
                    False,
                    False,
                    0.15, 0.7, 0.8, 0.2,
                    0., 0., -15, 4., 1, 100, 0,
                    120, 11000, 0.5, 0.1, 0.25, -15, 4., 15, 60, 0,
                ],
            ],
            fn=sound_separate,
            inputs=[
                aud,
                stem_gui,
                main_gui,
                dereverb_gui,
                vocal_effects_gui,
                background_effects_gui,
                vocal_reverb_room_size_gui, vocal_reverb_damping_gui, vocal_reverb_dryness_gui, vocal_reverb_wet_level_gui,
                vocal_delay_seconds_gui, vocal_delay_mix_gui, vocal_compressor_threshold_db_gui, vocal_compressor_ratio_gui,
                vocal_compressor_attack_ms_gui, vocal_compressor_release_ms_gui, vocal_gain_db_gui,
                background_highpass_freq_gui, background_lowpass_freq_gui, background_reverb_room_size_gui,
                background_reverb_damping_gui, background_reverb_wet_level_gui, background_compressor_threshold_db_gui,
                background_compressor_ratio_gui, background_compressor_attack_ms_gui, background_compressor_release_ms_gui,
                background_gain_db_gui,
            ],
            outputs=[output_base],
            cache_examples=False,
        )

    return app


if __name__ == "__main__":

    for id_model in UVR_MODELS:
        download_manager(
            os.path.join(MDX_DOWNLOAD_LINK, id_model), mdxnet_models_dir
        )

    app = get_gui(theme)

    app.queue(default_concurrency_limit=40)

    app.launch(
        max_threads=40,
        share=False,
        show_error=True,
        quiet=False,
        debug=False,
    )