Spaces:
Running
Running
File size: 55,190 Bytes
c8be32d |
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 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 |
"""
This module contains functions to generate song covers using RVC-based voice models.
"""
from typing import Any
from typings.extra import F0Method, InputAudioExt, InputType, OutputAudioExt
import gc
import glob
import os
import shlex
import shutil
import subprocess
from contextlib import suppress
from logging import WARNING
from pathlib import Path, PurePath
from urllib.parse import parse_qs, urlparse
import yt_dlp
import gradio as gr
import soundfile as sf
import sox
from audio_separator.separator import Separator
from pedalboard import Compressor, HighpassFilter, Reverb
from pedalboard._pedalboard import Pedalboard
from pedalboard.io import AudioFile
from pydub import AudioSegment
from pydub import utils as pydub_utils
from vc.rvc import Config, get_vc, load_hubert, rvc_infer
from backend.common import (
INTERMEDIATE_AUDIO_DIR,
OUTPUT_AUDIO_DIR,
display_progress,
get_file_hash,
get_hash,
get_path_stem,
get_rvc_model,
json_dump,
json_load,
)
from backend.exceptions import InputMissingError, InvalidPathError, PathNotFoundError
from common import RVC_MODELS_DIR, SEPARATOR_MODELS_DIR
SEPARATOR = Separator(
log_level=WARNING,
model_file_dir=SEPARATOR_MODELS_DIR,
output_dir=INTERMEDIATE_AUDIO_DIR,
mdx_params={
"hop_length": 1024,
"segment_size": 256,
"overlap": 0.001,
"batch_size": 1,
"enable_denoise": False,
},
mdxc_params={"segment_size": 256, "batch_size": 1, "overlap": 2},
)
def _get_youtube_video_id(url: str, ignore_playlist: bool = True) -> str | None:
"""
Get video id from a YouTube URL.
Parameters
----------
url : str
The YouTube URL.
ignore_playlist : bool, default=True
Whether to get id of first video in playlist or the playlist id itself.
Returns
-------
str
The video id.
"""
query = urlparse(url)
if query.hostname == "youtu.be":
if query.path[1:] == "watch":
return query.query[2:]
return query.path[1:]
if query.hostname in {"www.youtube.com", "youtube.com", "music.youtube.com"}:
if not ignore_playlist:
# use case: get playlist id not current video in playlist
with suppress(KeyError):
return parse_qs(query.query)["list"][0]
if query.path == "/watch":
return parse_qs(query.query)["v"][0]
if query.path[:7] == "/watch/":
return query.path.split("/")[1]
if query.path[:7] == "/embed/":
return query.path.split("/")[2]
if query.path[:3] == "/v/":
return query.path.split("/")[2]
return None
def _yt_download(link: str, song_dir: str) -> str:
"""
Download audio from a YouTube link.
Parameters
----------
link : str
The YouTube link.
song_dir : str
The directory to save the downloaded audio to.
Returns
-------
str
The path to the downloaded audio file.
"""
outtmpl = os.path.join(song_dir, "0_%(title)s_Original")
ydl_opts = {
"quiet": True,
"no_warnings": True,
"format": "bestaudio",
"outtmpl": outtmpl,
"ignoreerrors": True,
"nocheckcertificate": True,
"postprocessors": [
{
"key": "FFmpegExtractAudio",
"preferredcodec": "wav",
"preferredquality": 0,
}
],
}
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
result = ydl.extract_info(link, download=True)
if not result:
raise PathNotFoundError("No audio found in the provided YouTube link!")
download_path = ydl.prepare_filename(result, outtmpl=f"{outtmpl}.wav")
return download_path
def _get_input_audio_paths() -> list[str]:
"""
Get the paths of all cached input audio files.
Returns
-------
list[str]
The paths of all cached input audio files
"""
# TODO if we later add .json file for input then we need to exclude those here
return glob.glob(os.path.join(INTERMEDIATE_AUDIO_DIR, "*", "0_*_Original*"))
def _get_input_audio_path(song_dir: str) -> str | None:
"""
Get the path of the cached input audio file in a given song directory.
Parameters
----------
song_dir : str
The path to a song directory.
Returns
-------
str
The path of the cached input audio file, if it exists.
"""
# NOTE orig_song_paths should never contain more than one element
return next(iter(glob.glob(os.path.join(song_dir, "0_*_Original*"))), None)
def _pitch_shift(audio_path: str, output_path: str, n_semi_tones: int) -> None:
"""
Pitch-shift an audio file.
Parameters
----------
audio_path : str
The path of the audio file to pitch-shift.
output_path : str
The path to save the pitch-shifted audio file to.
n_semi_tones : int
The number of semi-tones to pitch-shift the audio by.
"""
y, sr = sf.read(audio_path)
tfm = sox.Transformer()
tfm.pitch(n_semi_tones)
y_shifted = tfm.build_array(input_array=y, sample_rate_in=sr)
sf.write(output_path, y_shifted, sr)
# TODO consider increasing hash_size to 16
# otherwise we might have problems with hash collisions
# when using app as CLI
def _get_unique_base_path(
song_dir: str,
prefix: str,
arg_dict: dict[str, Any],
progress_bar: gr.Progress | None = None,
percentage: float = 0.0,
hash_size: int = 5,
) -> str:
"""
Get a unique base path for an audio file in a song directory
by hashing the arguments used to generate the audio.
Parameters
----------
song_dir : str
The path to a song directory.
prefix : str
The prefix to use for the base path.
arg_dict : dict
The dictionary of arguments used to generate the audio in the given file.
progress_bar : gr.Progress, optional
Gradio progress bar to update.
percentage : float, default=0.0
Percentage to display in the progress bar.
hash_size : int, default=5
The size (in bytes) of the hash to use for the base path.
Returns
-------
str
The unique base path for the audio file.
"""
dict_hash = get_hash(arg_dict, size=hash_size)
while True:
base_path = os.path.join(song_dir, f"{prefix}_{dict_hash}")
json_path = f"{base_path}.json"
if os.path.exists(json_path):
file_dict = json_load(json_path)
if file_dict == arg_dict:
return base_path
display_progress("[~] Rehashing...", percentage, progress_bar)
dict_hash = get_hash(dict_hash, size=hash_size)
else:
return base_path
def _convert_voice(
voice_model: str,
voice_path: str,
output_path: str,
pitch_change: int,
f0_method: F0Method,
index_rate: float,
filter_radius: int,
rms_mix_rate: float,
protect: float,
crepe_hop_length: int,
output_sr: int,
) -> None:
"""
Convert a voice track using a voice model.
Parameters
----------
voice_model : str
The name of the voice model to use.
voice_path : str
The path to the voice track to convert.
output_path : str
The path to save the converted voice to.
pitch_change : int
The number of semi-tones to pitch-shift the converted voice by.
f0_method : F0Method
The method to use for pitch extraction.
index_rate : float
The influence of index file on voice conversion.
filter_radius : int
The filter radius to use for the voice conversion.
rms_mix_rate : float
The blending rate of the volume envelope of converted voice.
protect : float
The protection rate for consonants and breathing sounds.
crepe_hop_length : int
The hop length to use for Crepe pitch extraction method.
output_sr : int
The sample rate to use for the output audio.
"""
rvc_model_path, rvc_index_path = get_rvc_model(voice_model)
device = "cuda:0"
config = Config(device, True)
hubert_model = load_hubert(
device, config.is_half, os.path.join(RVC_MODELS_DIR, "hubert_base.pt")
)
cpt, version, net_g, tgt_sr, vc = get_vc(
device, config.is_half, config, rvc_model_path
)
# convert main vocals
rvc_infer(
rvc_index_path,
index_rate,
voice_path,
output_path,
pitch_change,
f0_method,
cpt,
version,
net_g,
filter_radius,
tgt_sr,
rms_mix_rate,
protect,
crepe_hop_length,
vc,
hubert_model,
output_sr,
)
del hubert_model, cpt
gc.collect()
def _add_audio_effects(
audio_path: str,
output_path: str,
reverb_rm_size: float,
reverb_wet: float,
reverb_dry: float,
reverb_damping: float,
) -> None:
"""
Add high-pass filter, compressor and reverb effects to an audio file.
Parameters
----------
audio_path : str
The path of the audio file to add effects to.
output_path : str
The path to save the effected audio file to.
reverb_rm_size : float
The room size of the reverb effect.
reverb_wet : float
The wet level of the reverb effect.
reverb_dry : float
The dry level of the reverb effect.
reverb_damping : float
The damping of the reverb effect.
"""
board = Pedalboard(
[
HighpassFilter(),
Compressor(ratio=4, threshold_db=-15),
Reverb(
room_size=reverb_rm_size,
dry_level=reverb_dry,
wet_level=reverb_wet,
damping=reverb_damping,
),
]
)
with AudioFile(audio_path) as f:
with AudioFile(output_path, "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 _map_audio_ext(input_audio_ext: InputAudioExt) -> OutputAudioExt:
"""
Map an input audio extension to an output audio extension.
Parameters
----------
input_audio_ext : InputAudioExt
The input audio extension.
Returns
-------
OutputAudioExt
The output audio extension.
"""
match input_audio_ext:
case "m4a":
return "ipod"
case "aac":
return "adts"
case _:
return input_audio_ext
def _mix_audio(
main_vocal_path: str,
backup_vocal_path: str,
instrumental_path: str,
main_gain: int,
backup_gain: int,
inst_gain: int,
output_format: InputAudioExt,
output_sr: int,
output_path: str,
) -> None:
"""
Mix main vocals, backup vocals and instrumentals.
Parameters
----------
main_vocal_path : str
The path of an audio file containing main vocals.
backup_vocal_path : str
The path of an audio file containing backup vocals.
instrumental_path : str
The path of an audio file containing instrumentals.
main_gain : int
The gain to apply to the main vocals.
backup_gain : int
The gain to apply to the backup vocals.
inst_gain : int
The gain to apply to the instrumental.
output_format : InputAudioExt
The format to save the mixed audio file in.
output_sr : int
The sample rate to use for the mixed audio file.
output_path : str
The path to save the mixed audio file to.
"""
main_vocal_audio = AudioSegment.from_wav(main_vocal_path) + main_gain
backup_vocal_audio = AudioSegment.from_wav(backup_vocal_path) + backup_gain
instrumental_audio = AudioSegment.from_wav(instrumental_path) + inst_gain
combined_audio = main_vocal_audio.overlay(backup_vocal_audio).overlay(
instrumental_audio
)
combined_audio_resampled = combined_audio.set_frame_rate(output_sr)
mapped_output_format = _map_audio_ext(output_format)
combined_audio_resampled.export(output_path, format=mapped_output_format)
def get_named_song_dirs() -> list[tuple[str, str]]:
"""
Get the names and paths of all song directories.
Returns
-------
list[tuple[str, str]]
A list of tuples containing the name and path of each song directory.
"""
input_paths = _get_input_audio_paths()
named_song_dirs: list[tuple[str, str]] = []
for path in input_paths:
song_dir, song_basename = os.path.split(path)
song_name = (
os.path.splitext(song_basename)[0]
.removeprefix("0_")
.removesuffix("_Original")
)
named_song_dirs.append((song_name, song_dir))
return sorted(named_song_dirs, key=lambda x: x[0])
def convert_to_stereo(
song_path: str,
song_dir: str,
progress_bar: gr.Progress | None = None,
percentage: float = 0.0,
) -> str:
"""
Converts an audio file to stereo.
Parameters
----------
song_path : str
The path to the audio file to convert.
song_dir : str
The path to the directory where the stereo audio file will be saved.
progress_bar : gr.Progress, optional
Gradio progress bar to update.
percentage : float, default=0.0
Percentage to display in the progress bar.
Returns
-------
str
The path to the stereo audio file.
Raises
------
InputMissingError
If no audio file or song directory path is provided.
PathNotFoundError
If the provided audio file or song directory path does not point
to an existing file or directory.
"""
if not song_path:
raise InputMissingError("Input song missing!")
if not os.path.isfile(song_path):
raise PathNotFoundError("Input song does not exist!")
if not song_dir:
raise InputMissingError("Song directory missing!")
if not os.path.isdir(song_dir):
raise PathNotFoundError("Song directory does not exist!")
stereo_path = song_path
song_info = pydub_utils.mediainfo(song_path)
if song_info["channels"] == "1":
arg_dict = {
"input-files": [
{"name": os.path.basename(song_path), "hash": get_file_hash(song_path)}
],
}
stereo_path_base = _get_unique_base_path(
song_dir, "0_Stereo", arg_dict, progress_bar, percentage
)
stereo_path = f"{stereo_path_base}.wav"
stereo_json_path = f"{stereo_path_base}.json"
if not (os.path.exists(stereo_path) and os.path.exists(stereo_json_path)):
display_progress(
"[~] Converting song to stereo...", percentage, progress_bar
)
command = shlex.split(
f'ffmpeg -y -loglevel error -i "{song_path}" -ac 2 -f wav'
f' "{stereo_path}"'
)
subprocess.run(command)
json_dump(arg_dict, stereo_json_path)
return stereo_path
def _make_song_dir(
song_input: str, progress_bar: gr.Progress | None = None, percentage: float = 0.0
) -> tuple[str, InputType]:
"""
Create a song directory for a given song input.
* If the song input is a YouTube URL,
the song directory will be named after the video id.
* If the song input is a local audio file,
the song directory will be named after the file hash.
* if the song input is a song directory,
the song directory will be used as is.
Parameters
----------
song_input : str
The song input to create a directory for.
progress_bar : gr.Progress, optional
Gradio progress bar to update.
percentage : float, default=0.0
Percentage to display in the progress bar.
Returns
-------
song_dir : str
The path to the created song directory.
input_type : InputType
The type of input provided.
Raises
------
InputMissingError
If no song input is provided.
InvalidPathError
If the provided YouTube URL is invalid or if the provided song directory
is not located in the root of the intermediate audio directory.
PathNotFoundError
If the provided song input is neither a valid HTTPS-based URL
nor the path of an existing song directory or audio file.
"""
# if song directory
if os.path.isdir(song_input):
if not PurePath(song_input).parent == PurePath(INTERMEDIATE_AUDIO_DIR):
raise InvalidPathError(
"Song directory not located in the root of the intermediate audio"
" directory."
)
display_progress(
"[~] Using existing song directory...", percentage, progress_bar
)
input_type = "local"
return song_input, input_type
display_progress("[~] Creating song directory...", percentage, progress_bar)
# if youtube url
if urlparse(song_input).scheme == "https":
input_type = "yt"
song_id = _get_youtube_video_id(song_input)
if song_id is None:
raise InvalidPathError("Invalid YouTube url!")
# if local audio file
elif os.path.isfile(song_input):
input_type = "local"
song_id = get_file_hash(song_input)
else:
raise PathNotFoundError(f"Song input {song_input} does not exist.")
song_dir = os.path.join(INTERMEDIATE_AUDIO_DIR, song_id)
Path(song_dir).mkdir(parents=True, exist_ok=True)
return song_dir, input_type
def retrieve_song(
song_input: str,
progress_bar: gr.Progress | None = None,
percentages: tuple[float, float, float] = (0, 0.33, 0.67),
) -> tuple[str, str]:
"""
Retrieve a song from a YouTube URL, local audio file or a song directory.
Parameters
----------
song_input : str
A Youtube URL, the path of a local audio file
or the path of a song directory.
progress_bar : gr.Progress, optional
Gradio progress bar to update.
percentages : tuple[float,float,float], default=(0, 0.33, 0.67)
Percentages to display in the progress bar.
Returns
-------
song_path : str
The path to the retrieved audio file
song_dir : str
The path to the song directory containing it.
Raises
------
InputMissingError
If no song input is provided.
InvalidPathError
If the provided Youtube URL is invalid or if the provided song directory
is not located in the root of the intermediate audio directory.
PathNotFoundError
If the provided song input is neither a valid HTTPS-based URL
nor the path of an existing song directory or audio file.
"""
if not song_input:
raise InputMissingError(
"Song input missing! Please provide a valid YouTube url, local audio file"
" path or cached song directory path."
)
song_dir, input_type = _make_song_dir(song_input, progress_bar, percentages[0])
orig_song_path = _get_input_audio_path(song_dir)
if not orig_song_path:
if input_type == "yt":
display_progress("[~] Downloading song...", percentages[1], progress_bar)
song_link = song_input.split("&")[0]
orig_song_path = _yt_download(song_link, song_dir)
else:
display_progress("[~] Copying song...", percentages[1], progress_bar)
song_input_base = os.path.basename(song_input)
song_input_name, song_input_ext = os.path.splitext(song_input_base)
orig_song_name = f"0_{song_input_name}_Original"
orig_song_path = os.path.join(song_dir, orig_song_name + song_input_ext)
shutil.copyfile(song_input, orig_song_path)
stereo_path = convert_to_stereo(
orig_song_path, song_dir, progress_bar, percentages[2]
)
return stereo_path, song_dir
def separate_vocals(
song_path: str,
song_dir: str,
stereofy: bool = True,
progress_bar: gr.Progress | None = None,
percentages: tuple[float, float] = (0.0, 0.5),
) -> tuple[str, str]:
"""
Separate a song into vocals and instrumentals.
Parameters
----------
song_path : str
The path to the song to separate.
song_dir : str
The path to the song directory where the
separated vocals and instrumentals will be saved.
stereofy : bool, default=True
Whether to convert the song to stereo
before separating its vocals and instrumentals.
progress_bar : gr.Progress, optional
Gradio progress bar to update.
percentages : tuple[float,float], default=(0.0, 0.5)
Percentages to display in the progress bar.
Returns
-------
vocals_path : str
The path to the separated vocals.
instrumentals_path : str
The path to the separated instrumentals.
Raises
------
InputMissingError
If no song path or song directory path is provided.
PathNotFoundError
If the provided song path or song directory path does not point
to an existing file or directory.
"""
if not song_path:
raise InputMissingError("Input song missing!")
if not os.path.isfile(song_path):
raise PathNotFoundError("Input song does not exist!")
if not song_dir:
raise InputMissingError("Song directory missing!")
if not os.path.isdir(song_dir):
raise PathNotFoundError("Song directory does not exist!")
song_path = (
convert_to_stereo(song_path, song_dir, progress_bar, percentages[0])
if stereofy
else song_path
)
arg_dict = {
"input-files": [
{"name": os.path.basename(song_path), "hash": get_file_hash(song_path)}
],
}
vocals_path_base = _get_unique_base_path(
song_dir, "1_Vocals", arg_dict, progress_bar, percentages[1]
)
instrumentals_path_base = _get_unique_base_path(
song_dir, "1_Instrumental", arg_dict, progress_bar, percentages[1]
)
vocals_path = f"{vocals_path_base}.wav"
vocals_json_path = f"{vocals_path_base}.json"
instrumentals_path = f"{instrumentals_path_base}.wav"
instrumentals_json_path = f"{instrumentals_path_base}.json"
if not (
os.path.exists(vocals_path)
and os.path.exists(vocals_json_path)
and os.path.exists(instrumentals_path)
and os.path.exists(instrumentals_json_path)
):
display_progress(
"[~] Separating vocals from instrumentals...", percentages[1], progress_bar
)
SEPARATOR.arch_specific_params["MDX"]["segment_size"] = 512
SEPARATOR.load_model("UVR-MDX-NET-Voc_FT.onnx")
temp_instrumentals_name, temp_vocals_name = SEPARATOR.separate(song_path)
shutil.move(
os.path.join(INTERMEDIATE_AUDIO_DIR, temp_instrumentals_name),
instrumentals_path,
)
shutil.move(os.path.join(INTERMEDIATE_AUDIO_DIR, temp_vocals_name), vocals_path)
json_dump(arg_dict, vocals_json_path)
json_dump(arg_dict, instrumentals_json_path)
return vocals_path, instrumentals_path
def separate_main_vocals(
vocals_path: str,
song_dir: str,
stereofy: bool = True,
progress_bar: gr.Progress | None = None,
percentages: tuple[float, float] = (0.0, 0.5),
) -> tuple[str, str]:
"""
Separate a vocals track into main vocals and backup vocals.
Parameters
----------
vocals_path : str
The path to the vocals track to separate.
song_dir : str
The path to the directory where the separated main vocals
and backup vocals will be saved.
stereofy : bool, default=True
Whether to convert the vocals track to stereo
before separating its main vocals and backup vocals.
progress_bar : gr.Progress, optional
Gradio progress bar to update.
percentages : tuple[float,float], default=(0.0, 0.5)
Percentages to display in the progress bar.
Returns
-------
main_vocals_path : str
The path to the separated main vocals.
backup_vocals_path : str
The path to the separated backup vocals.
Raises
------
InputMissingError
If no vocals track path or song directory path is provided.
PathNotFoundError
If the provided vocals path or song directory path does not point
to an existing file or directory.
"""
if not vocals_path:
raise InputMissingError("Vocals missing!")
if not os.path.isfile(vocals_path):
raise PathNotFoundError("Vocals do not exist!")
if not song_dir:
raise InputMissingError("Song directory missing!")
if not os.path.isdir(song_dir):
raise PathNotFoundError("song directory does not exist!")
vocals_path = (
convert_to_stereo(vocals_path, song_dir, progress_bar, percentages[0])
if stereofy
else vocals_path
)
arg_dict = {
"input-files": [
{"name": os.path.basename(vocals_path), "hash": get_file_hash(vocals_path)}
],
}
main_vocals_path_base = _get_unique_base_path(
song_dir, "2_Vocals_Main", arg_dict, progress_bar, percentages[1]
)
backup_vocals_path_base = _get_unique_base_path(
song_dir, "2_Vocals_Backup", arg_dict, progress_bar, percentages[1]
)
main_vocals_path = f"{main_vocals_path_base}.wav"
main_vocals_json_path = f"{main_vocals_path_base}.json"
backup_vocals_path = f"{backup_vocals_path_base}.wav"
backup_vocals_json_path = f"{backup_vocals_path_base}.json"
if not (
os.path.exists(main_vocals_path)
and os.path.exists(main_vocals_json_path)
and os.path.exists(backup_vocals_path)
and os.path.exists(backup_vocals_json_path)
):
display_progress(
"[~] Separating main vocals from backup vocals...",
percentages[1],
progress_bar,
)
SEPARATOR.arch_specific_params["MDX"]["segment_size"] = 512
SEPARATOR.load_model("UVR_MDXNET_KARA_2.onnx")
temp_main_vocals_name, temp_backup_vocals_name = SEPARATOR.separate(vocals_path)
shutil.move(
os.path.join(INTERMEDIATE_AUDIO_DIR, temp_main_vocals_name),
main_vocals_path,
)
shutil.move(
os.path.join(INTERMEDIATE_AUDIO_DIR, temp_backup_vocals_name),
backup_vocals_path,
)
json_dump(arg_dict, main_vocals_json_path)
json_dump(arg_dict, backup_vocals_json_path)
return main_vocals_path, backup_vocals_path
def dereverb_vocals(
vocals_path: str,
song_dir: str,
stereofy: bool = True,
progress_bar: gr.Progress | None = None,
percentages: tuple[float, float] = (0.0, 0.5),
) -> tuple[str, str]:
"""
De-reverb a vocals track.
Parameters
----------
vocals_path : str
The path to the vocals track to de-reverb.
song_dir : str
The path to the directory where the de-reverbed vocals will be saved.
stereofy : bool, default=True
Whether to convert the vocals track to stereo before de-reverbing it.
progress_bar : gr.Progress, optional
Gradio progress bar to update.
percentages : tuple[float,float], default=(0.0, 0.5)
Percentages to display in the progress bar.
Returns
-------
vocals_dereverb_path : str
The path to the de-reverbed vocals.
vocals_reverb_path : str
The path to the reverb of the vocals.
Raises
------
InputMissingError
If no vocals track path or song directory path is provided.
PathNotFoundError
If the provided vocals path or song directory path does not point
to an existing file or directory.
"""
if not vocals_path:
raise InputMissingError("Vocals missing!")
if not os.path.isfile(vocals_path):
raise PathNotFoundError("Vocals do not exist!")
if not song_dir:
raise InputMissingError("Song directory missing!")
if not os.path.isdir(song_dir):
raise PathNotFoundError("song directory does not exist!")
vocals_path = (
convert_to_stereo(vocals_path, song_dir, progress_bar, percentages[0])
if stereofy
else vocals_path
)
arg_dict = {
"input-files": [
{"name": os.path.basename(vocals_path), "hash": get_file_hash(vocals_path)}
],
}
vocals_dereverb_path_base = _get_unique_base_path(
song_dir, "3_Vocals_DeReverb", arg_dict, progress_bar, percentages[1]
)
vocals_reverb_path_base = _get_unique_base_path(
song_dir, "3_Vocals_Reverb", arg_dict, progress_bar, percentages[1]
)
vocals_dereverb_path = f"{vocals_dereverb_path_base}.wav"
vocals_dereverb_json_path = f"{vocals_dereverb_path_base}.json"
vocals_reverb_path = f"{vocals_reverb_path_base}.wav"
vocals_reverb_json_path = f"{vocals_reverb_path_base}.json"
if not (
os.path.exists(vocals_dereverb_path)
and os.path.exists(vocals_dereverb_json_path)
and os.path.exists(vocals_reverb_path)
and os.path.exists(vocals_reverb_json_path)
):
display_progress("[~] De-reverbing vocals...", percentages[1], progress_bar)
SEPARATOR.arch_specific_params["MDX"]["segment_size"] = 256
SEPARATOR.load_model("Reverb_HQ_By_FoxJoy.onnx")
temp_vocals_dereverb_name, temp_vocals_reverb_name = SEPARATOR.separate(
vocals_path
)
shutil.move(
os.path.join(INTERMEDIATE_AUDIO_DIR, temp_vocals_dereverb_name),
vocals_dereverb_path,
)
shutil.move(
os.path.join(INTERMEDIATE_AUDIO_DIR, temp_vocals_reverb_name),
vocals_reverb_path,
)
json_dump(arg_dict, vocals_dereverb_json_path)
json_dump(arg_dict, vocals_reverb_json_path)
return vocals_dereverb_path, vocals_reverb_path
def convert_vocals(
vocals_path: str,
song_dir: str,
voice_model: str,
pitch_change_octaves: int = 0,
pitch_change_semi_tones: int = 0,
index_rate: float = 0.5,
filter_radius: int = 3,
rms_mix_rate: float = 0.25,
protect: float = 0.33,
f0_method: F0Method = "rmvpe",
crepe_hop_length: int = 128,
progress_bar: gr.Progress | None = None,
percentage: float = 0.0,
) -> str:
"""
Convert a vocals track using a voice model.
Parameters
----------
vocals_path : str
The path to the vocals track to convert.
song_dir : str
The path to the directory where the converted vocals will be saved.
voice_model : str
The name of the voice model to use.
pitch_change_octaves : int, default=0
The number of octaves to pitch-shift the converted vocals by.
pitch_change_semi_tones : int, default=0
The number of semi-tones to pitch-shift the converted vocals by.
index_rate : float, default=0.5
The influence of the index file on the vocal conversion.
filter_radius : int, default=3
The filter radius to use for the vocal conversion.
rms_mix_rate : float, default=0.25
The blending rate of the volume envelope of the converted vocals.
protect : float, default=0.33
The protection rate for consonants and breathing sounds.
f0_method : F0Method, default="rmvpe"
The method to use for pitch extraction.
crepe_hop_length : int, default=128
The hop length to use for crepe-based pitch extraction.
progress_bar : gr.Progress, optional
Gradio progress bar to update.
percentage : float, default=0.0
Percentage to display in the progress bar.
Returns
-------
str
The path to the converted vocals.
Raises
------
InputMissingError
If no vocals track path, song directory path or voice model name is provided.
PathNotFoundError
If the provided vocals path, song directory path or voice model name
does not point to an existing file or directory.
"""
if not vocals_path:
raise InputMissingError("Vocals missing!")
if not os.path.isfile(vocals_path):
raise PathNotFoundError("Vocals do not exist!")
if not song_dir:
raise InputMissingError("Song directory missing!")
if not os.path.isdir(song_dir):
raise PathNotFoundError("song directory does not exist!")
if not voice_model:
raise InputMissingError("Voice model missing!")
if not os.path.isdir(os.path.join(RVC_MODELS_DIR, voice_model)):
raise PathNotFoundError("Voice model does not exist!")
pitch_change = pitch_change_octaves * 12 + pitch_change_semi_tones
hop_length_suffix = "" if f0_method != "mangio-crepe" else f"_{crepe_hop_length}"
arg_dict = {
"input-files": [
{"name": os.path.basename(vocals_path), "hash": get_file_hash(vocals_path)}
],
"voice-model": voice_model,
"pitch-shift": pitch_change,
"index-rate": index_rate,
"filter-radius": filter_radius,
"rms-mix-rate": rms_mix_rate,
"protect": protect,
"f0-method": f"{f0_method}{hop_length_suffix}",
}
converted_vocals_path_base = _get_unique_base_path(
song_dir, "4_Vocals_Converted", arg_dict, progress_bar, percentage
)
converted_vocals_path = f"{converted_vocals_path_base}.wav"
converted_vocals_json_path = f"{converted_vocals_path_base}.json"
if not (
os.path.exists(converted_vocals_path)
and os.path.exists(converted_vocals_json_path)
):
display_progress("[~] Converting vocals using RVC...", percentage, progress_bar)
_convert_voice(
voice_model,
vocals_path,
converted_vocals_path,
pitch_change,
f0_method,
index_rate,
filter_radius,
rms_mix_rate,
protect,
crepe_hop_length,
44100,
)
json_dump(arg_dict, converted_vocals_json_path)
return converted_vocals_path
def postprocess_vocals(
vocals_path: str,
song_dir: str,
reverb_rm_size: float = 0.15,
reverb_wet: float = 0.2,
reverb_dry: float = 0.8,
reverb_damping: float = 0.7,
progress_bar: gr.Progress | None = None,
percentage: float = 0.0,
) -> str:
"""
Apply high-pass filter, compressor and reverb effects to a vocals track.
Parameters
----------
vocals_path : str
The path to the vocals track to add effects to.
song_dir : str
The path to the directory where the effected vocals will be saved.
reverb_rm_size : float, default=0.15
The room size of the reverb effect.
reverb_wet : float, default=0.2
The wet level of the reverb effect.
reverb_dry : float, default=0.8
The dry level of the reverb effect.
reverb_damping : float, default=0.7
The damping of the reverb effect.
progress_bar : gr.Progress, optional
Gradio progress bar to update.
percentage : float, default=0.0
Percentage to display in the progress bar.
Returns
-------
str
The path to the effected vocals.
Raises
------
InputMissingError
If no vocals track path or song directory path is provided.
PathNotFoundError
If the provided vocals path or song directory path does not point
to an existing file or directory.
"""
if not vocals_path:
raise InputMissingError("Vocals missing!")
if not os.path.isfile(vocals_path):
raise PathNotFoundError("Vocals do not exist!")
if not song_dir:
raise InputMissingError("Song directory missing!")
if not os.path.isdir(song_dir):
raise PathNotFoundError("song directory does not exist!")
arg_dict = {
"input-files": [
{"name": os.path.basename(vocals_path), "hash": get_file_hash(vocals_path)}
],
"reverb-room-size": reverb_rm_size,
"reverb-wet": reverb_wet,
"reverb-dry": reverb_dry,
"reverb-damping": reverb_damping,
}
vocals_mixed_path_base = _get_unique_base_path(
song_dir, "5_Vocals_Postprocessed", arg_dict, progress_bar, percentage
)
vocals_mixed_path = f"{vocals_mixed_path_base}.wav"
vocals_mixed_json_path = f"{vocals_mixed_path_base}.json"
if not (
os.path.exists(vocals_mixed_path) and os.path.exists(vocals_mixed_json_path)
):
display_progress(
"[~] Applying audio effects to vocals...", percentage, progress_bar
)
_add_audio_effects(
vocals_path,
vocals_mixed_path,
reverb_rm_size,
reverb_wet,
reverb_dry,
reverb_damping,
)
json_dump(arg_dict, vocals_mixed_json_path)
return vocals_mixed_path
def pitch_shift_background(
instrumentals_path: str,
backup_vocals_path: str,
song_dir: str,
pitch_change: int = 0,
progress_bar: gr.Progress | None = None,
percentages: tuple[float, float] = (0.0, 0.5),
) -> tuple[str, str]:
"""
Pitch shift instrumentals and backup vocals by a given number of semi-tones.
Parameters
----------
instrumentals_path : str
The path to the instrumentals to pitch shift.
backup_vocals_path : str
The path to the backup vocals to pitch shift.
song_dir : str
The path to the directory where the pitch-shifted instrumentals
and backup vocals will be saved.
pitch_change : int, default=0
The number of semi-tones to pitch-shift the instrumentals
and backup vocals by.
progress_bar : gr.Progress, optional
Gradio progress bar to update.
percentages : tuple[float,float], default=(0.0, 0.5)
Percentages to display in the progress bar.
Returns
-------
instrumentals_shifted_path : str
The path to the pitch-shifted instrumentals.
backup_vocals_shifted_path : str
The path to the pitch-shifted backup vocals.
Raises
------
InputMissingError
If no instrumentals path, backup vocals path or song directory path is provided.
PathNotFoundError
If the provided instrumentals path, backup vocals path or song directory path
does not point to an existing file or directory.
"""
if not instrumentals_path:
raise InputMissingError("Instrumentals missing!")
if not os.path.isfile(instrumentals_path):
raise PathNotFoundError("Instrumentals do not exist!")
if not backup_vocals_path:
raise InputMissingError("Backup vocals missing!")
if not os.path.isfile(backup_vocals_path):
raise PathNotFoundError("Backup vocals do not exist!")
if not song_dir:
raise InputMissingError("Song directory missing!")
if not os.path.isdir(song_dir):
raise PathNotFoundError("song directory does not exist!")
instrumentals_shifted_path = instrumentals_path
backup_vocals_shifted_path = backup_vocals_path
if pitch_change != 0:
instrumentals_dict = {
"input-files": [
{
"name": os.path.basename(instrumentals_path),
"hash": get_file_hash(instrumentals_path),
}
],
"pitch-shift": pitch_change,
}
instrumentals_shifted_path_base = _get_unique_base_path(
song_dir,
"6_Instrumental_Shifted",
instrumentals_dict,
progress_bar,
percentages[0],
)
instrumentals_shifted_path = f"{instrumentals_shifted_path_base}.wav"
instrumentals_shifted_json_path = f"{instrumentals_shifted_path_base}.json"
if not (
os.path.exists(instrumentals_shifted_path)
and os.path.exists(instrumentals_shifted_json_path)
):
display_progress(
"[~] Applying pitch shift to instrumentals",
percentages[0],
progress_bar,
)
_pitch_shift(instrumentals_path, instrumentals_shifted_path, pitch_change)
json_dump(instrumentals_dict, instrumentals_shifted_json_path)
backup_vocals_dict = {
"input-files": [
{
"name": os.path.basename(backup_vocals_path),
"hash": get_file_hash(backup_vocals_path),
}
],
"pitch-shift": pitch_change,
}
backup_vocals_shifted_path_base = _get_unique_base_path(
song_dir,
"6_Vocals_Backup_Shifted",
backup_vocals_dict,
progress_bar,
percentages[1],
)
backup_vocals_shifted_path = f"{backup_vocals_shifted_path_base}.wav"
backup_vocals_shifted_json_path = f"{backup_vocals_shifted_path_base}.json"
if not (
os.path.exists(backup_vocals_shifted_path)
and os.path.exists(backup_vocals_shifted_json_path)
):
display_progress(
"[~] Applying pitch shift to backup vocals",
percentages[1],
progress_bar,
)
_pitch_shift(backup_vocals_path, backup_vocals_shifted_path, pitch_change)
json_dump(backup_vocals_dict, backup_vocals_shifted_json_path)
return instrumentals_shifted_path, backup_vocals_shifted_path
def _get_voice_model(
mixed_vocals_path: str | None = None, song_dir: str | None = None
) -> str:
"""
Infer the voice model used for vocal conversion from a
mixed vocals file in a given song directory.
If the voice model cannot be inferred, "Unknown" is returned.
Parameters
----------
mixed_vocals_path : str, optional
The path to a mixed vocals file.
song_dir : str, optional
The path to a song directory.
Returns
-------
str
The voice model used for vocal conversion.
"""
voice_model = "Unknown"
if not (mixed_vocals_path and song_dir):
return voice_model
mixed_vocals_stem = get_path_stem(mixed_vocals_path)
mixed_vocals_json_path = os.path.join(song_dir, f"{mixed_vocals_stem}.json")
if not os.path.isfile(mixed_vocals_json_path):
return voice_model
mixed_vocals_json_dict = json_load(mixed_vocals_json_path)
input_files = mixed_vocals_json_dict.get("input-files")
input_path = input_files[0].get("name") if input_files else None
if not input_path:
return voice_model
input_stem = get_path_stem(input_path)
converted_vocals_json_path = os.path.join(song_dir, f"{input_stem}.json")
if not os.path.isfile(converted_vocals_json_path):
return voice_model
converted_vocals_dict = json_load(converted_vocals_json_path)
return converted_vocals_dict.get("voice-model", voice_model)
def get_song_cover_name(
mixed_vocals_path: str | None = None,
song_dir: str | None = None,
voice_model: str | None = None,
progress_bar: gr.Progress | None = None,
percentage: float = 0.0,
) -> str:
"""
Generates a suitable name for a cover of a song based on that song's
original name and the voice model used for vocal conversion.
If the path of an existing song directory is provided, the original song
name is inferred from that directory. If a voice model is not provided but
the path of an existing song directory and the path of a mixed
vocals file in that directory are provided, then the voice model is
inferred from the mixed vocals file.
Parameters
----------
mixed_vocals_path : str, optional
The path to a mixed vocals file.
song_dir : str, optional
The path to a song directory.
voice_model : str, optional
A voice model name.
progress_bar : gr.Progress, optional
Gradio progress bar to update.
percentage : float, default=0.0
Percentage to display in the progress bar.
Returns
-------
str
The song cover name
"""
display_progress("[~] Getting song cover name...", percentage, progress_bar)
orig_song_path = _get_input_audio_path(song_dir) if song_dir else None
orig_song_name = (
(get_path_stem(orig_song_path).removeprefix("0_").removesuffix("_Original"))
if orig_song_path
else "Unknown"
)
voice_model = voice_model or _get_voice_model(mixed_vocals_path, song_dir)
return f"{orig_song_name} ({voice_model} Ver)"
def mix_song_cover(
main_vocals_path: str,
instrumentals_path: str,
backup_vocals_path: str,
song_dir: str,
main_gain: int = 0,
inst_gain: int = 0,
backup_gain: int = 0,
output_sr: int = 44100,
output_format: InputAudioExt = "mp3",
output_name: str | None = None,
progress_bar: gr.Progress | None = None,
percentages: tuple[float, float] = (0.0, 0.5),
) -> str:
"""
Mix main vocals, instrumentals, and backup vocals to create a song cover.
Parameters
----------
main_vocals_path : str
The path to the main vocals to mix.
instrumentals_path : str
The path to the instrumentals to mix.
backup_vocals_path : str
The path to the backup vocals to mix.
song_dir : str
The path to the song directory where the song cover will be saved.
main_gain : int, default=0
The gain to apply to the main vocals.
inst_gain : int, default=0
The gain to apply to the instrumentals.
backup_gain : int, default=0
The gain to apply to the backup vocals.
output_sr : int, default=44100
The sample rate of the song cover.
output_format : InputAudioExt, default="mp3"
The audio format of the song cover.
output_name : str, optional
The name of the song cover.
progress_bar : gr.Progress, optional
Gradio progress bar to update.
percentages : tuple[float,float], default=(0.0, 0.5)
Percentages to display in the progress bar.
Returns
-------
str
The path to the song cover.
Raises
------
InputMissingError
If no main vocals, instrumentals, backup vocals or song directory path is provided.
PathNotFoundError
If the provided main vocals, instrumentals, backup vocals or song directory path
does not point to an existing file or directory.
"""
if not main_vocals_path:
raise InputMissingError("Main vocals missing!")
if not os.path.isfile(main_vocals_path):
raise PathNotFoundError("Main vocals do not exist!")
if not instrumentals_path:
raise InputMissingError("Instrumentals missing!")
if not os.path.isfile(instrumentals_path):
raise PathNotFoundError("Instrumentals do not exist!")
if not backup_vocals_path:
raise InputMissingError("Backup vocals missing!")
if not os.path.isfile(backup_vocals_path):
raise PathNotFoundError("Backup vocals do not exist!")
if not song_dir:
raise InputMissingError("Song directory missing!")
if not os.path.isdir(song_dir):
raise PathNotFoundError("song directory does not exist!")
arg_dict = {
"input-files": [
{
"name": os.path.basename(main_vocals_path),
"hash": get_file_hash(main_vocals_path),
},
{
"name": os.path.basename(instrumentals_path),
"hash": get_file_hash(instrumentals_path),
},
{
"name": os.path.basename(backup_vocals_path),
"hash": get_file_hash(backup_vocals_path),
},
],
"main-gain": main_gain,
"instrument-gain": inst_gain,
"backup-gain": backup_gain,
"sample-rate": output_sr,
}
mixdown_path_base = _get_unique_base_path(
song_dir, "7_Mixdown", arg_dict, progress_bar, percentages[0]
)
mixdown_path = f"{mixdown_path_base}.{output_format}"
mixdown_json_path = f"{mixdown_path_base}.json"
if not (os.path.exists(mixdown_path) and os.path.exists(mixdown_json_path)):
display_progress(
"[~] Mixing main vocals, instrumentals, and backup vocals...",
percentages[0],
progress_bar,
)
_mix_audio(
main_vocals_path,
backup_vocals_path,
instrumentals_path,
main_gain,
backup_gain,
inst_gain,
output_format,
output_sr,
mixdown_path,
)
json_dump(arg_dict, mixdown_json_path)
output_name = output_name or get_song_cover_name(
main_vocals_path, song_dir, None, progress_bar, percentages[1]
)
song_cover_path = os.path.join(OUTPUT_AUDIO_DIR, f"{output_name}.{output_format}")
os.makedirs(OUTPUT_AUDIO_DIR, exist_ok=True)
shutil.copyfile(mixdown_path, song_cover_path)
return song_cover_path
def run_pipeline(
song_input: str,
voice_model: str,
pitch_change_vocals: int = 0,
pitch_change_all: int = 0,
index_rate: float = 0.5,
filter_radius: int = 3,
rms_mix_rate: float = 0.25,
protect: float = 0.33,
f0_method: F0Method = "rmvpe",
crepe_hop_length: int = 128,
reverb_rm_size: float = 0.15,
reverb_wet: float = 0.2,
reverb_dry: float = 0.8,
reverb_damping: float = 0.7,
main_gain: int = 0,
inst_gain: int = 0,
backup_gain: int = 0,
output_sr: int = 44100,
output_format: InputAudioExt = "mp3",
output_name: str | None = None,
return_files: bool = False,
progress_bar: gr.Progress | None = None,
) -> str | tuple[str, ...]:
"""
Run the song cover generation pipeline.
Parameters
----------
song_input : str
A Youtube URL, the path of a local audio file or the path of a song directory.
voice_model : str
The name of the voice model to use for vocal conversion.
pitch_change_vocals : int, default=0
The number of octaves to pitch-shift the converted vocals by.
pitch_change_all : int, default=0
The number of semi-tones to pitch-shift the converted vocals,
instrumentals, and backup vocals by.
index_rate : float, default=0.5
The influence of the index file on the vocal conversion.
filter_radius : int, default=3
The filter radius to use for the vocal conversion.
rms_mix_rate : float, default=0.25
The blending rate of the volume envelope of the converted vocals.
protect : float, default=0.33
The protection rate for consonants and breathing sounds in the vocal conversion.
f0_method : F0Method, default="rmvpe"
The method to use for pitch extraction in the vocal conversion.
crepe_hop_length : int, default=128
The hop length to use for crepe-based pitch extraction.
reverb_rm_size : float, default=0.15
The room size of the reverb effect to apply to the converted vocals.
reverb_wet : float, default=0.2
The wet level of the reverb effect to apply to the converted vocals.
reverb_dry : float, default=0.8
The dry level of the reverb effect to apply to the converted vocals.
reverb_damping : float, default=0.7
The damping of the reverb effect to apply to the converted vocals.
main_gain : int, default=0
The gain to apply to the post-processed vocals.
inst_gain : int, default=0
The gain to apply to the pitch-shifted instrumentals.
backup_gain : int, default=0
The gain to apply to the pitch-shifted backup vocals.
output_sr : int, default=44100
The sample rate of the song cover.
output_format : InputAudioExt, default="mp3"
The audio format of the song cover.
output_name : str, optional
The name of the song cover.
return_files : bool, default=False
Whether to return the paths of the generated intermediate audio files.
progress_bar : gr.Progress, optional
Gradio progress bar to update.
Returns
-------
str | tuple[str,...]
The path to the generated song cover and, if `return_files=True`,
also the paths of any generated intermediate audio files.
"""
if not song_input:
raise InputMissingError(
"Song input missing! Please provide a valid YouTube url, local audio file"
" path or cached song directory path."
)
if not voice_model:
raise InputMissingError("Voice model missing!")
if not os.path.isdir(os.path.join(RVC_MODELS_DIR, voice_model)):
raise PathNotFoundError("Voice model does not exist!")
display_progress("[~] Starting song cover generation pipeline...", 0, progress_bar)
orig_song_path, song_dir = retrieve_song(
song_input, progress_bar, (0 / 15, 1 / 15, 2 / 15)
)
vocals_path, instrumentals_path = separate_vocals(
orig_song_path, song_dir, False, progress_bar, (3 / 15, 4 / 15)
)
main_vocals_path, backup_vocals_path = separate_main_vocals(
vocals_path, song_dir, False, progress_bar, (5 / 15, 6 / 15)
)
vocals_dereverb_path, reverb_path = dereverb_vocals(
main_vocals_path, song_dir, False, progress_bar, (7 / 15, 8 / 15)
)
converted_vocals_path = convert_vocals(
vocals_dereverb_path,
song_dir,
voice_model,
pitch_change_vocals,
pitch_change_all,
index_rate,
filter_radius,
rms_mix_rate,
protect,
f0_method,
crepe_hop_length,
progress_bar,
9 / 15,
)
vocals_mixed_path = postprocess_vocals(
converted_vocals_path,
song_dir,
reverb_rm_size,
reverb_wet,
reverb_dry,
reverb_damping,
progress_bar,
10 / 15,
)
instrumentals_shifted_path, backup_vocals_shifted_path = pitch_shift_background(
instrumentals_path,
backup_vocals_path,
song_dir,
pitch_change_all,
progress_bar,
(11 / 15, 12 / 15),
)
song_cover_path = mix_song_cover(
vocals_mixed_path,
instrumentals_shifted_path or instrumentals_path,
backup_vocals_shifted_path or backup_vocals_path,
song_dir,
main_gain,
inst_gain,
backup_gain,
output_sr,
output_format,
output_name,
progress_bar,
(13 / 15, 14 / 15),
)
if return_files:
return (
orig_song_path,
vocals_path,
instrumentals_path,
main_vocals_path,
backup_vocals_path,
vocals_dereverb_path,
reverb_path,
converted_vocals_path,
vocals_mixed_path,
instrumentals_shifted_path,
backup_vocals_shifted_path,
song_cover_path,
)
else:
return song_cover_path
|