-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcore.py
More file actions
1590 lines (1426 loc) · 53.5 KB
/
core.py
File metadata and controls
1590 lines (1426 loc) · 53.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Core audio processing module for Hyper-RVC.
Provides functions for:
- Model and music downloading
- Audio separation (vocals, instrumentals, karaoke)
- RVC voice conversion
- Audio effects (reverb, denoise, deecho)
- Audio merging and post-processing
"""
import sys
import os
import subprocess
import torch
from functools import lru_cache
import shutil
from typing import Optional, Dict, Any, List, Tuple
from pedalboard import Pedalboard, Reverb
from pedalboard.io import AudioFile
from pydub import AudioSegment
from audio_separator.separator import Separator
import logging
import yaml
import gc
now_dir = os.getcwd()
sys.path.append(now_dir)
from programs.applio_code.rvc.infer.infer import VoiceConverter
from programs.applio_code.rvc.lib.tools.model_download import model_download_pipeline
from programs.music_separation_code.inference import proc_file
from programs.variable import (
models_vocals,
karaoke_models,
denoise_models,
deecho_models,
dereverb_models,
check_fp16_support
)
from programs.tools.logger import get_logger
logger = get_logger(__name__)
@lru_cache(maxsize=None)
def import_voice_converter() -> VoiceConverter:
"""
Import and cache the VoiceConverter instance.
Returns:
VoiceConverter instance for RVC inference
"""
from programs.applio_code.rvc.infer.infer import VoiceConverter
return VoiceConverter()
@lru_cache(maxsize=1)
def get_config():
"""
Get and cache the RVC configuration.
Returns:
RVC Config instance
"""
from programs.applio_code.rvc.configs.config import Config
return Config()
def download_file(url: str, path: str, filename: str) -> Optional[str]:
"""
Download a file from a URL to a specified path.
Args:
url: URL to download from
path: Directory path to save the file
filename: Name of the file to save
Returns:
Path to downloaded file if successful, None otherwise
"""
os.makedirs(path, exist_ok=True)
file_path = os.path.join(path, filename)
if os.path.exists(file_path):
logger.info(f"File '{filename}' already exists at '{path}'.")
return file_path
try:
torch.hub.download_url_to_file(url, file_path)
logger.info(f"File '{filename}' downloaded successfully")
return file_path
except Exception as e:
logger.error(f"Error downloading file '{filename}' from '{url}': {e}")
return None
def get_model_info_by_name(model_name: str) -> Optional[Dict[str, Any]]:
"""
Get model information by model name.
Args:
model_name: Name of the model to search for
Returns:
Dictionary containing model information, or None if not found
"""
all_models = (
models_vocals
+ karaoke_models
+ dereverb_models
+ deecho_models
+ denoise_models
)
for model in all_models:
if model["name"] == model_name:
return model
return None
def get_last_modified_file(pasta: str) -> Optional[str]:
"""
Get the most recently modified file in a directory.
Args:
pasta: Directory path to search
Returns:
Name of the most recently modified file, or None if directory is empty
Raises:
NotADirectoryError: If the path is not a valid directory
"""
if not os.path.isdir(pasta):
raise NotADirectoryError(f"{pasta} is not a valid directory.")
arquivos = [f for f in os.listdir(pasta) if os.path.isfile(os.path.join(pasta, f))]
if not arquivos:
return None
return max(arquivos, key=lambda x: os.path.getmtime(os.path.join(pasta, x)))
def search_with_word(folder: str, word: str) -> Optional[str]:
"""
Search for the most recent file containing a specific word in its name.
Args:
folder: Directory to search in
word: Word to search for in filenames
Returns:
Name of the most recent file containing the word, or None if not found
Raises:
NotADirectoryError: If the path is not a valid directory
"""
if not os.path.isdir(folder):
raise NotADirectoryError(f"{folder} is not a valid directory.")
file_with_word = [file for file in os.listdir(folder) if word in file]
if not file_with_word:
return None
most_recent_file = max(
file_with_word, key=lambda file: os.path.getmtime(os.path.join(folder, file))
)
return most_recent_file
def search_with_two_words(folder: str, word1: str, word2: str) -> Optional[str]:
"""
Search for the most recent file containing two specific words in its name.
Args:
folder: Directory to search in
word1: First word to search for
word2: Second word to search for
Returns:
Name of the most recent file containing both words, or None if not found
Raises:
NotADirectoryError: If the path is not a valid directory
"""
if not os.path.isdir(folder):
raise NotADirectoryError(f"{folder} is not a valid directory.")
file_with_words = [
file for file in os.listdir(folder) if word1 in file and word2 in file
]
if not file_with_words:
return None
most_recent_file = max(
file_with_words, key=lambda file: os.path.getmtime(os.path.join(folder, file))
)
return most_recent_file
def get_last_modified_folder(path: str) -> Optional[str]:
"""
Get the most recently modified subdirectory.
Args:
path: Parent directory path
Returns:
Path to the most recently modified subdirectory, or None if none exist
"""
directories = [
os.path.join(path, d)
for d in os.listdir(path)
if os.path.isdir(os.path.join(path, d))
]
if not directories:
return None
last_modified_folder = max(directories, key=os.path.getmtime)
return last_modified_folder
def download_model(link: str) -> str:
"""
Download an RVC model from a link.
Args:
link: URL or link to download the model from
Returns:
Success or error message
"""
try:
model_download_pipeline(link)
logger.info("Model downloaded successfully")
return "Model downloaded with success"
except Exception as e:
logger.error(f"Error downloading model: {e}")
return f"Error downloading model: {e}"
def download_music(link: str) -> str:
"""
Download music from a URL (YouTube, etc.).
Args:
link: URL to download music from
Returns:
Success or error message
"""
try:
os.makedirs(os.path.join(now_dir, "audio_files", "original_files"), exist_ok=True)
command = [
"yt-dlp",
"-x",
"--output",
os.path.join(now_dir, "audio_files", "original_files", "%(title)s.%(ext)s"),
link,
]
subprocess.run(command, check=True)
logger.info("Music downloaded successfully")
return "Music downloaded with success"
except subprocess.CalledProcessError as e:
logger.error(f"Error downloading music: {e}")
return f"Error downloading music: {e}"
except Exception as e:
logger.error(f"Unexpected error downloading music: {e}")
return f"Error downloading music: {e}"
def whisper_process(
model_size: str,
input_audio: str,
configs: Dict[str, Any],
device: str,
out_queue,
word_timestamps: bool = True
) -> None:
"""
Process audio with Whisper for transcription/speaker diarization.
Args:
model_size: Size of the Whisper model to use
input_audio: Path to input audio file
configs: Configuration dictionary
device: Device to run inference on
out_queue: Queue to put results in
word_timestamps: Whether to extract word-level timestamps
"""
from programs.speaker_diarization.whisper import load_model
try:
segments = load_model(
model_size,
device=device
).transcribe(
input_audio,
fp16=check_fp16_support(device),
word_timestamps=word_timestamps
)
out_queue.put(segments["segments"])
except Exception as e:
out_queue.put(e)
finally:
del segments
gc.collect()
def add_audio_effects(
audio_path: str,
reverb_size: float,
reverb_wet: float,
reverb_dry: float,
reverb_damping: float,
reverb_width: float,
output_path: str,
) -> str:
"""
Add reverb effects to an audio file using Pedalboard.
Args:
audio_path: Path to input audio file
reverb_size: Room size (0-1)
reverb_wet: Wet level (0-1)
reverb_dry: Dry level (0-1)
reverb_damping: Damping (0-1)
reverb_width: Stereo width (0-1)
output_path: Path to save the output file
Returns:
Path to the output file
"""
try:
board = Pedalboard([])
board.append(
Reverb(
room_size=reverb_size,
dry_level=reverb_dry,
wet_level=reverb_wet,
damping=reverb_damping,
width=reverb_width,
)
)
with AudioFile(audio_path) as f:
with AudioFile(output_path, "w", f.samplerate, f.num_channels) as o:
while f.tell() < f.frames:
chunk = f.read(int(f.samplerate))
effected = board(chunk, f.samplerate, reset=False)
o.write(effected)
logger.info(f"Audio effects applied successfully: {output_path}")
return output_path
except Exception as e:
logger.error(f"Error applying audio effects: {e}")
raise
def merge_audios(
vocals_path: str,
inst_path: str,
backing_path: str,
output_path: str,
main_gain: float,
inst_gain: float,
backing_Vol: float,
output_format: str,
) -> str:
"""
Merge multiple audio files (vocals, instrumentals, backing vocals).
Args:
vocals_path: Path to vocals audio file
inst_path: Path to instrumental audio file
backing_path: Path to backing vocals audio file
output_path: Path to save the merged output
main_gain: Volume gain for main vocals (dB)
inst_gain: Volume gain for instrumentals (dB)
backing_Vol: Volume gain for backing vocals (dB)
output_format: Output format (e.g., 'mp3', 'flac', 'wav')
Returns:
Path to the merged output file
"""
try:
main_vocal_audio = AudioSegment.from_file(vocals_path, format="flac") + main_gain
instrumental_audio = AudioSegment.from_file(inst_path, format="flac") + inst_gain
backing_vocal_audio = (
AudioSegment.from_file(backing_path, format="flac") + backing_Vol
)
combined_audio = main_vocal_audio.overlay(
instrumental_audio.overlay(backing_vocal_audio)
)
combined_audio.export(output_path, format=output_format)
logger.info(f"Audio files merged successfully: {output_path}")
return output_path
except Exception as e:
logger.error(f"Error merging audio files: {e}")
raise
def update_model_config_for_fp16(model_info: Dict[str, Any], use_fp16: bool) -> None:
"""
Update model config file based on FP16 support.
Args:
model_info: Dictionary containing model information
use_fp16: Whether FP16 is supported
"""
if not use_fp16 and os.path.exists(model_info["config"]):
try:
with open(model_info["config"], "r") as file:
config = yaml.safe_load(file)
if "training" in config and "use_amp" in config["training"]:
config["training"]["use_amp"] = False
with open(model_info["config"], "w") as file:
yaml.safe_dump(config, file)
logger.info(f"Disabled FP16/AMP in config for {model_info['name']}")
except Exception as e:
logger.error(f"Error updating config for {model_info['name']}: {e}")
def full_inference_program(
model_path: str,
index_path: str,
input_audio_path: str,
output_path: str,
export_format_rvc: str,
split_audio: bool,
autotune: bool,
vocal_model: str,
karaoke_model: str,
dereverb_model: str,
deecho: bool,
deecho_model: str,
denoise: bool,
denoise_model: str,
reverb: bool,
vocals_volume: float,
instrumentals_volume: float,
backing_vocals_volume: float,
export_format_final: str,
devices: str,
pitch: int,
filter_radius: int,
index_rate: float,
rms_mix_rate: float,
protect: float,
pitch_extract: str,
hop_lenght: int,
reverb_room_size: float,
reverb_damping: float,
reverb_wet_gain: float,
reverb_dry_gain: float,
reverb_width: float,
embedder_model: str,
delete_audios: bool,
use_tta: bool,
batch_size: int,
infer_backing_vocals: bool,
infer_backing_vocals_model: str,
infer_backing_vocals_index: str,
change_inst_pitch: int,
pitch_back: int,
filter_radius_back: int,
index_rate_back: float,
rms_mix_rate_back: float,
protect_back: float,
pitch_extract_back: str,
hop_length_back: int,
export_format_rvc_back: str,
split_audio_back: bool,
autotune_back: bool,
embedder_model_back: str,
) -> Tuple[str, str]:
"""
Run the full RVC inference pipeline on an audio file.
This function performs:
1. Vocal separation from the input audio
2. Karaoke/backing vocal separation
3. Dereverb processing (optional)
4. Deecho processing (optional)
5. Denoise processing (optional)
6. RVC voice conversion
7. Backing vocals inference (optional)
8. Reverb effects (optional)
9. Pitch adjustment for instrumentals (optional)
10. Final audio merging
Args:
model_path: Path to the RVC model file
index_path: Path to the RVC index file
input_audio_path: Path to the input audio file
output_path: Directory path for output
export_format_rvc: Export format for RVC output
split_audio: Whether to split audio for processing
autotune: Whether to apply autotune
vocal_model: Name of the vocal separation model
karaoke_model: Name of the karaoke separation model
dereverb_model: Name of the dereverb model
deecho: Whether to apply deecho processing
deecho_model: Name of the deecho model
denoise: Whether to apply denoise processing
denoise_model: Name of the denoise model
reverb: Whether to apply reverb effect
vocals_volume: Volume adjustment for vocals (dB)
instrumentals_volume: Volume adjustment for instrumentals (dB)
backing_vocals_volume: Volume adjustment for backing vocals (dB)
export_format_final: Final export format
devices: GPU devices to use (e.g., "0" or "0 1")
pitch: Pitch adjustment in semitones
filter_radius: Filter radius for pitch extraction
index_rate: Index rate for voice conversion
rms_mix_rate: RMS mix rate for volume envelope
protect: Protect value for conversion
pitch_extract: Pitch extraction method
hop_lenght: Hop length for pitch extraction
reverb_room_size: Reverb room size (0-1)
reverb_damping: Reverb damping (0-1)
reverb_wet_gain: Reverb wet gain (0-1)
reverb_dry_gain: Reverb dry gain (0-1)
reverb_width: Reverb width (0-1)
embedder_model: Embedder model to use
delete_audios: Whether to delete intermediate audio files
use_tta: Whether to use test-time augmentation
batch_size: Batch size for separation models
infer_backing_vocals: Whether to infer backing vocals separately
infer_backing_vocals_model: Model for backing vocals inference
infer_backing_vocals_index: Index for backing vocals inference
change_inst_pitch: Change instrumental pitch (semitones)
pitch_back: Pitch for backing vocals
filter_radius_back: Filter radius for backing vocals
index_rate_back: Index rate for backing vocals
rms_mix_rate_back: RMS mix rate for backing vocals
protect_back: Protect value for backing vocals
pitch_extract_back: Pitch extraction for backing vocals
hop_length_back: Hop length for backing vocals
export_format_rvc_back: Export format for backing vocals
split_audio_back: Whether to split audio for backing vocals
autotune_back: Whether to apply autotune to backing vocals
embedder_model_back: Embedder model for backing vocals
Returns:
Tuple of (success message, output file path)
Raises:
Exception: If any step in the pipeline fails
"""
# Initialize configuration
configs = {}
# Determine device and FP16 support
if torch.cuda.is_available() and devices != "cpu":
n_gpu = torch.cuda.device_count()
devices = devices.replace("-", " ")
logger.info(f"Number of GPUs available: {n_gpu}")
first_device = devices.split()[0] if devices.split() else "cuda:0"
# Check config for FP16 setting, fallback to hardware check
use_fp16 = configs.get("fp16", check_fp16_support(first_device))
logger.info(f"FP16 inference: {'Enabled' if use_fp16 else 'Disabled'}")
else:
devices = "cpu"
logger.info("Using CPU")
use_fp16 = False
music_folder = os.path.splitext(os.path.basename(input_audio_path))[0]
# Vocals Separation
model_info = get_model_info_by_name(vocal_model)
model_ckpt_path = os.path.join(model_info["path"], "model.ckpt")
if not os.path.exists(model_ckpt_path):
download_file(
model_info["model_url"],
model_info["path"],
"model.ckpt",
)
config_json_path = os.path.join(model_info["path"], "config.yaml")
if not os.path.exists(config_json_path):
download_file(
model_info["config_url"],
model_info["path"],
"config.yaml",
)
# Update model config based on FP16 support
update_model_config_for_fp16(model_info, use_fp16)
store_dir = os.path.join(now_dir, "audio_files", music_folder, "vocals")
inst_dir = os.path.join(now_dir, "audio_files", music_folder, "instrumentals")
os.makedirs(store_dir, exist_ok=True)
os.makedirs(inst_dir, exist_ok=True)
input_audio_basename = os.path.splitext(os.path.basename(input_audio_path))[0]
search_result = search_with_word(store_dir, "vocals")
if search_result:
logger.info("Vocals already separated")
else:
logger.info("Separating vocals")
command = [
"python",
os.path.join(now_dir, "programs", "music_separation_code", "inference.py"),
"--model_type",
model_info["type"],
"--config_path",
model_info["config"],
"--start_check_point",
model_info["model"],
"--input_file",
input_audio_path,
"--store_dir",
store_dir,
"--flac_file",
"--pcm_type",
"PCM_16",
"--extract_instrumental",
]
if devices == "cpu":
command.append("--force_cpu")
else:
device_ids = [str(int(device)) for device in devices.split()]
command.extend(["--device_ids"] + device_ids)
# Add FP16 flag if supported
if use_fp16:
command.append("--fp16")
subprocess.run(command)
os.rename(
os.path.join(
store_dir,
search_with_two_words(
store_dir,
os.path.basename(input_audio_path).split(".")[0],
"instrumental",
),
),
os.path.join(
inst_dir,
f"{os.path.basename(input_audio_path).split('.')[0]}_instrumentals.flac",
),
)
inst_file = os.path.join(
inst_dir,
search_with_two_words(
inst_dir, os.path.basename(input_audio_path).split(".")[0], "instrumentals"
),
)
# karaoke separation
model_info = get_model_info_by_name(karaoke_model)
store_dir = os.path.join(now_dir, "audio_files", music_folder, "karaoke")
os.makedirs(store_dir, exist_ok=True)
vocals_path = os.path.join(now_dir, "audio_files", music_folder, "vocals")
input_file = search_with_word(vocals_path, "vocals")
karaoke_exists = search_with_word(store_dir, "karaoke") is not None
if karaoke_exists:
logger.info("Backing vocals already separated")
else:
if input_file:
input_file = os.path.join(vocals_path, input_file)
logger.info("Separating backing vocals")
if model_info["name"] == "Mel-Roformer Karaoke by aufr33 and viperx":
model_ckpt_path = os.path.join(model_info["path"], "model.ckpt")
if not os.path.exists(model_ckpt_path):
download_file(
model_info["model_url"],
model_info["path"],
"model.ckpt",
)
config_json_path = os.path.join(model_info["path"], "config.yaml")
if not os.path.exists(config_json_path):
download_file(
model_info["config_url"],
model_info["path"],
"config.yaml",
)
# Update model config based on FP16 support
update_model_config_for_fp16(model_info, use_fp16)
command = [
"python",
os.path.join(
now_dir, "programs", "music_separation_code", "inference.py"
),
"--model_type",
model_info["type"],
"--config_path",
model_info["config"],
"--start_check_point",
model_info["model"],
"--input_file",
input_file,
"--store_dir",
store_dir,
"--flac_file",
"--pcm_type",
"PCM_16",
"--extract_instrumental",
]
if devices == "cpu":
command.append("--force_cpu")
else:
device_ids = [str(int(device)) for device in devices.split()]
command.extend(["--device_ids"] + device_ids)
# Add FP16 flag if supported
if use_fp16:
command.append("--fp16")
subprocess.run(command)
else:
vr_params = {
"batch_size": batch_size,
"enable_tta": use_tta,
}
if use_fp16:
vr_params["fp16"] = True
separator = Separator(
model_file_dir=os.path.join(now_dir, "models", "karaoke"),
log_level=logging.WARNING,
normalization_threshold=1.0,
output_format="flac",
output_dir=store_dir,
vr_params=vr_params,
)
separator.load_model(model_filename=model_info["full_name"])
separator.separate(input_file)
karaoke_path = os.path.join(now_dir, "audio_files", music_folder, "karaoke")
vocals_result = search_with_two_words(
karaoke_path,
os.path.basename(input_audio_path).split(".")[0],
"Vocals",
)
instrumental_result = search_with_two_words(
karaoke_path,
os.path.basename(input_audio_path).split(".")[0],
"Instrumental",
)
if "UVR-BVE-4B_SN-44100-1" in os.path.basename(vocals_result):
os.rename(
os.path.join(karaoke_path, vocals_result),
os.path.join(
karaoke_path,
f"{os.path.basename(input_audio_path).split('.')[0]}_karaoke.flac",
),
)
if "UVR-BVE-4B_SN-44100-1" in os.path.basename(instrumental_result):
os.rename(
os.path.join(karaoke_path, instrumental_result),
os.path.join(
karaoke_path,
f"{os.path.basename(input_audio_path).split('.')[0]}_instrumental.flac",
),
)
# dereverb
model_info = get_model_info_by_name(dereverb_model)
store_dir = os.path.join(now_dir, "audio_files", music_folder, "dereverb")
os.makedirs(store_dir, exist_ok=True)
karaoke_path = os.path.join(now_dir, "audio_files", music_folder, "karaoke")
input_file = search_with_word(karaoke_path, "karaoke")
noreverb_exists = search_with_word(store_dir, "noreverb") is not None
if noreverb_exists:
logger.info("Reverb already removed")
else:
if input_file:
input_file = os.path.join(karaoke_path, input_file)
logger.info("Removing reverb")
if (
model_info["name"] == "BS-Roformer Dereverb by anvuew"
or model_info["name"] == "MDX23C DeReverb by aufr33 and jarredou"
):
model_ckpt_path = os.path.join(model_info["path"], "model.ckpt")
if not os.path.exists(model_ckpt_path):
download_file(
model_info["model_url"],
model_info["path"],
"model.ckpt",
)
config_json_path = os.path.join(model_info["path"], "config.yaml")
if not os.path.exists(config_json_path):
download_file(
model_info["config_url"],
model_info["path"],
"config.yaml",
)
# Update model config based on FP16 support
update_model_config_for_fp16(model_info, use_fp16)
command = [
"python",
os.path.join(
now_dir, "programs", "music_separation_code", "inference.py"
),
"--model_type",
model_info["type"],
"--config_path",
model_info["config"],
"--start_check_point",
model_info["model"],
"--input_file",
input_file,
"--store_dir",
store_dir,
"--flac_file",
"--pcm_type",
"PCM_16",
]
if devices == "cpu":
command.append("--force_cpu")
else:
device_ids = [str(int(device)) for device in devices.split()]
command.extend(["--device_ids"] + device_ids)
# Add FP16 flag if supported
if use_fp16:
command.append("--fp16")
subprocess.run(command)
else:
if model_info["arch"] == "vr":
vr_params = {
"batch_size": batch_size,
"enable_tta": use_tta,
}
if use_fp16:
vr_params["fp16"] = True
separator = Separator(
model_file_dir=os.path.join(now_dir, "models", "dereverb"),
log_level=logging.WARNING,
normalization_threshold=1.0,
output_format="flac",
output_dir=store_dir,
output_single_stem="No Reverb",
vr_params=vr_params,
)
else:
separator = Separator(
model_file_dir=os.path.join(now_dir, "models", "dereverb"),
log_level=logging.WARNING,
normalization_threshold=1.0,
output_format="flac",
output_dir=store_dir,
output_single_stem="No Reverb",
)
separator.load_model(model_filename=model_info["full_name"])
separator.separate(input_file)
dereverb_path = os.path.join(
now_dir, "audio_files", music_folder, "dereverb"
)
search_result = search_with_two_words(
dereverb_path,
os.path.basename(input_audio_path).split(".")[0],
"No Reverb",
)
if "UVR-DeEcho-DeReverb" in os.path.basename(
search_result
) or "MDX Reverb HQ by FoxJoy" in os.path.basename(search_result):
os.rename(
os.path.join(dereverb_path, search_result),
os.path.join(
dereverb_path,
f"{os.path.basename(input_audio_path).split('.')[0]}_noreverb.flac",
),
)
# deecho
store_dir = os.path.join(now_dir, "audio_files", music_folder, "deecho")
os.makedirs(store_dir, exist_ok=True)
if deecho:
no_echo_exists = search_with_word(store_dir, "noecho") is not None
if no_echo_exists:
logger.info("Echo already removed")
else:
logger.info("Removing echo")
model_info = get_model_info_by_name(deecho_model)
dereverb_path = os.path.join(
now_dir, "audio_files", music_folder, "dereverb"
)
noreverb_file = search_with_word(dereverb_path, "noreverb")
input_file = os.path.join(dereverb_path, noreverb_file)
vr_params = {
"batch_size": batch_size,
"enable_tta": use_tta,
}
if use_fp16:
vr_params["fp16"] = True
separator = Separator(
model_file_dir=os.path.join(now_dir, "models", "deecho"),
log_level=logging.WARNING,
normalization_threshold=1.0,
output_format="flac",
output_dir=store_dir,
output_single_stem="No Echo",
vr_params=vr_params,
)
separator.load_model(model_filename=model_info["full_name"])
separator.separate(input_file)
deecho_path = os.path.join(now_dir, "audio_files", music_folder, "deecho")
search_result = search_with_two_words(
deecho_path,
os.path.basename(input_audio_path).split(".")[0],
"No Echo",
)
if "UVR-De-Echo-Normal" in os.path.basename(
search_result
) or "UVR-Deecho-Agggressive" in os.path.basename(search_result):
os.rename(
os.path.join(deecho_path, search_result),
os.path.join(
deecho_path,
f"{os.path.basename(input_audio_path).split('.')[0]}_noecho.flac",
),
)
# denoise
store_dir = os.path.join(now_dir, "audio_files", music_folder, "denoise")
os.makedirs(store_dir, exist_ok=True)
if denoise:
no_noise_exists = search_with_word(store_dir, "dry") is not None
if no_noise_exists:
logger.info("Noise already removed")
else:
model_info = get_model_info_by_name(denoise_model)
logger.info("Removing noise")
input_file = (
os.path.join(
now_dir,
"audio_files",
music_folder,
"deecho",
search_with_word(
os.path.join(now_dir, "audio_files", music_folder, "deecho"),
"noecho",
),
)
if deecho
else os.path.join(
now_dir,
"audio_files",
music_folder,
"dereverb",
search_with_word(
os.path.join(now_dir, "audio_files", music_folder, "dereverb"),
"noreverb",
),
)
)
if (
model_info["name"] == "Mel-Roformer Denoise Normal by aufr33"
or model_info["name"] == "Mel-Roformer Denoise Aggressive by aufr33"
):
model_ckpt_path = os.path.join(model_info["path"], "model.ckpt")
if not os.path.exists(model_ckpt_path):
download_file(
model_info["model_url"],
model_info["path"],
"model.ckpt",
)
config_json_path = os.path.join(model_info["path"], "config.yaml")
if not os.path.exists(config_json_path):
download_file(
model_info["config_url"], model_info["path"], "config.yaml"
)
# Update model config based on FP16 support
update_model_config_for_fp16(model_info, use_fp16)
command = [
"python",
os.path.join(
now_dir, "programs", "music_separation_code", "inference.py"
),
"--model_type",
model_info["type"],
"--config_path",
model_info["config"],
"--start_check_point",
model_info["model"],
"--input_file",
input_file,
"--store_dir",
store_dir,
"--flac_file",
"--pcm_type",
"PCM_16",
]
if devices == "cpu":
command.append("--force_cpu")
else:
device_ids = [str(int(device)) for device in devices.split()]