Spaces:
Running on Zero
Running on Zero
Upload 10 files
Browse filesFiles changed (10)
- README.md+12-12
- app.py+4-7
- pre-requirements.txt+2-1
- requirements.txt+7-5
- src/download_models.py+12-5
- src/infer_pack/models.py+4-4
- src/main.py+112-27
- src/mdx.py+7-3
- src/rvc.py+15-4
- src/webui.py+82-27
12345678910111213---title: AICoverGenemoji: 🚀colorFrom: redcolorTo: pinksdk: gradiosdk_version: 5.35.0app_file: app.pypinned: falselicense: mit---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference12345678910111213---title: AICoverGenemoji: 🚀colorFrom: redcolorTo: pinksdk: gradiosdk_version: 5.44.0app_file: app.pypinned: falselicense: mit---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
123456789101112import oscmd = """pip install onnxruntime-gpu[cuda,cudnn]==1.22.0find / -name 'libcudnn.so*' 2>/dev/nullpython src/download_models.pypython src/webui.py"""os.system(cmd)123456789import osimport sysos.system("python src/download_models.py")args = " ".join(sys.argv[1:])cmd = f"python src/webui.py {args}"os.system(cmd)
1pip<=23.1.212pip==23.0.1Setuptools<=80.6.0
12341 unmodified line6789101112131415163 unmodified lines2021222324--extra-index-url=https://download.pytorch.org/whl/cu121torch==2.5.1torchvision==0.20.1torchaudio==2.5.11 unmodified linefairseq==0.12.2faiss-cpu==1.7.3ffmpeg-python>=0.2.0# gradio==3.39.0lib==4.0.0librosa==0.9.1numpy==1.23.5# onnxruntime #onnxruntime_gpupraat-parselmouth>=0.4.2pedalboard==0.7.7pydub==0.25.13 unmodified linessoundfile==0.12.1torchcrepe==0.0.20tqdm==4.65.0yt_dlp==2023.7.6sox==1.4.11231 unmodified line567891011121314153 unmodified lines1920212223242526torch==2.5.1torchvision==0.20.1torchaudio==2.5.11 unmodified linefairseq==0.12.2faiss-cpu==1.7.3ffmpeg-python>=0.2.0gradio==5.44.0lib==4.0.0librosa==0.9.1numpy==1.23.5onnxruntime-gpu==1.22.0 # onnxruntime #onnxruntime_gpupraat-parselmouth>=0.4.2pedalboard==0.7.7pydub==0.25.13 unmodified linessoundfile==0.12.1torchcrepe==0.0.20tqdm==4.65.0yt_dlpsox==1.4.1noisereducespacesmatplotlib-inline
7 unmodified lines891011121314151617181 unmodified line2021222324252627282930317 unmodified linesmdxnet_models_dir = BASE_DIR / 'mdxnet_models'rvc_models_dir = BASE_DIR / 'rvc_models'def dl_model(link, model_name, dir_name):with requests.get(f'{link}{model_name}') as r:r.raise_for_status()with open(dir_name / model_name, 'wb') as f:for chunk in r.iter_content(chunk_size=8192):f.write(chunk)1 unmodified lineif __name__ == '__main__':mdx_model_names = ['UVR-MDX-NET-Inst_HQ_4.onnx', 'UVR-MDX-NET-Voc_FT.onnx', 'UVR_MDXNET_KARA_2.onnx', 'Reverb_HQ_By_FoxJoy.onnx']for model in mdx_model_names:print(f'Downloading {model}...')dl_model(MDX_DOWNLOAD_LINK, model, mdxnet_models_dir)rvc_model_names = ['hubert_base.pt', 'rmvpe.pt']for model in rvc_model_names:print(f'Downloading {model}...')dl_model(RVC_DOWNLOAD_LINK, model, rvc_models_dir)print('All models downloaded!')7 unmodified lines891011121314151617181920212223242526271 unmodified line293031323334353637387 unmodified linesmdxnet_models_dir = BASE_DIR / 'mdxnet_models'rvc_models_dir = BASE_DIR / 'rvc_models'mdxnet_models_dir.mkdir(parents=True, exist_ok=True)rvc_models_dir.mkdir(parents=True, exist_ok=True)def dl_model(link, model_name, dir_name):model_path = dir_name / model_nameif model_path.exists():# print(f"{model_name} already exists, skipping download.")returnprint(f"Downloading {model_name}...")with requests.get(f'{link}{model_name}', stream=True) as r:r.raise_for_status()with open(model_path, 'wb') as f:for chunk in r.iter_content(chunk_size=8192):f.write(chunk)1 unmodified lineif __name__ == '__main__':mdx_model_names = ['UVR-MDX-NET-Inst_HQ_4.onnx', 'UVR-MDX-NET-Voc_FT.onnx', 'UVR_MDXNET_KARA_2.onnx', 'Reverb_HQ_By_FoxJoy.onnx']for model in mdx_model_names:dl_model(MDX_DOWNLOAD_LINK, model, mdxnet_models_dir)rvc_model_names = ['hubert_base.pt', 'rmvpe.pt']for model in rvc_model_names:dl_model(RVC_DOWNLOAD_LINK, model, rvc_models_dir)print('All models ready!')
606 unmodified lines607608609610611612613104 unmodified lines718719720721722723724101 unmodified lines82682782882983083183295 unmodified lines928929930931932933934606 unmodified linesinter_channels, hidden_channels, 5, 1, 3, gin_channels=gin_channels)self.emb_g = nn.Embedding(self.spk_embed_dim, gin_channels)print("gin_channels:", gin_channels, "self.spk_embed_dim:", self.spk_embed_dim)def remove_weight_norm(self):self.dec.remove_weight_norm()104 unmodified linesinter_channels, hidden_channels, 5, 1, 3, gin_channels=gin_channels)self.emb_g = nn.Embedding(self.spk_embed_dim, gin_channels)print("gin_channels:", gin_channels, "self.spk_embed_dim:", self.spk_embed_dim)def remove_weight_norm(self):self.dec.remove_weight_norm()101 unmodified linesinter_channels, hidden_channels, 5, 1, 3, gin_channels=gin_channels)self.emb_g = nn.Embedding(self.spk_embed_dim, gin_channels)print("gin_channels:", gin_channels, "self.spk_embed_dim:", self.spk_embed_dim)def remove_weight_norm(self):self.dec.remove_weight_norm()95 unmodified linesinter_channels, hidden_channels, 5, 1, 3, gin_channels=gin_channels)self.emb_g = nn.Embedding(self.spk_embed_dim, gin_channels)print("gin_channels:", gin_channels, "self.spk_embed_dim:", self.spk_embed_dim)def remove_weight_norm(self):self.dec.remove_weight_norm()606 unmodified lines607608609610611612613104 unmodified lines718719720721722723724101 unmodified lines82682782882983083183295 unmodified lines928929930931932933934606 unmodified linesinter_channels, hidden_channels, 5, 1, 3, gin_channels=gin_channels)self.emb_g = nn.Embedding(self.spk_embed_dim, gin_channels)# print("gin_channels:", gin_channels, "self.spk_embed_dim:", self.spk_embed_dim)def remove_weight_norm(self):self.dec.remove_weight_norm()104 unmodified linesinter_channels, hidden_channels, 5, 1, 3, gin_channels=gin_channels)self.emb_g = nn.Embedding(self.spk_embed_dim, gin_channels)# print("gin_channels:", gin_channels, "self.spk_embed_dim:", self.spk_embed_dim)def remove_weight_norm(self):self.dec.remove_weight_norm()101 unmodified linesinter_channels, hidden_channels, 5, 1, 3, gin_channels=gin_channels)self.emb_g = nn.Embedding(self.spk_embed_dim, gin_channels)# print("gin_channels:", gin_channels, "self.spk_embed_dim:", self.spk_embed_dim)def remove_weight_norm(self):self.dec.remove_weight_norm()95 unmodified linesinter_channels, hidden_channels, 5, 1, 3, gin_channels=gin_channels)self.emb_g = nn.Embedding(self.spk_embed_dim, gin_channels)# print("gin_channels:", gin_channels, "self.spk_embed_dim:", self.spk_embed_dim)def remove_weight_norm(self):self.dec.remove_weight_norm()
8 unmodified lines910111213144 unmodified lines1920212223242 unmodified lines27282930313233343536373829 unmodified lines68697071727321 unmodified lines959697989910010110210310410510629 unmodified lines13613713813914014114214314471 unmodified lines2162172182192202212224 unmodified lines22722822923023123223323432 unmodified lines2672682692702712722732742752 unmodified lines27827928028128228328428528628728828929029129229329429529629729829930030130230330430530627 unmodified lines33433533633733833934034134222 unmodified lines3653663673683693703 unmodified lines3743753763773783793803813823833843853863873883893903913923935 unmodified lines3994004014024034044058 unmodified linesimport subprocessfrom contextlib import suppressfrom urllib.parse import urlparse, parse_qsimport gradio as grimport librosa4 unmodified linesfrom pedalboard import Pedalboard, Reverb, Compressor, HighpassFilterfrom pedalboard.io import AudioFilefrom pydub import AudioSegmentfrom mdx import run_mdxfrom rvc import Config, load_hubert, get_vc, rvc_infer2 unmodified lineslogging.getLogger("httpx").setLevel(logging.WARNING)BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))mdxnet_models_dir = os.path.join(BASE_DIR, 'mdxnet_models')rvc_models_dir = os.path.join(BASE_DIR, 'rvc_models')output_dir = os.path.join(BASE_DIR, 'song_output')def get_youtube_video_id(url, ignore_playlist=True):"""Examples:29 unmodified linesdef yt_download(link):ydl_opts = {'format': 'bestaudio','outtmpl': '%(title)s',21 unmodified linesdef get_rvc_model(voice_model, is_webui):rvc_model_filename, rvc_index_filename = None, Nonemodel_dir = os.path.join(rvc_models_dir, voice_model)print(model_dir)for file in os.listdir(model_dir):print(file)if os.path.isdir(file):for ff in os.listdir(file):print("subfile", ff)ext = os.path.splitext(ff)[1]if ext == '.pth':rvc_model_filename = ff29 unmodified lineselif file.endswith('_Vocals_Backup.wav'):backup_vocals_path = os.path.join(song_dir, file)return orig_song_path, instrumentals_path, main_vocals_dereverb_path, backup_vocals_pathdef convert_to_stereo(audio_path):wave, sr = librosa.load(audio_path, mono=False, sr=44100)71 unmodified linesprint(device, "half>>", config.is_half)# @spaces.GPU(enable_queue=True)def voice_change(voice_model, vocals_path, output_path, pitch_change, f0_method, index_rate, filter_radius, rms_mix_rate, protect, crepe_hop_length, is_webui):rvc_model_path, rvc_index_path = get_rvc_model(voice_model, is_webui)device = "cuda:0" if torch.cuda.is_available() else "cpu"4 unmodified lines# convert main vocalsglobal hubert_modelrvc_infer(rvc_index_path, index_rate, vocals_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)del hubert_model, cptgc.collect()32 unmodified linesdef process_song(song_dir, song_input, mdx_model_params, song_id, is_webui, input_type, progress,keep_files, pitch_change, pitch_change_all, voice_model, index_rate, filter_radius,rms_mix_rate, protect, f0_method, crepe_hop_length, output_format, keep_orig, orig_song_path):if not os.path.exists(song_dir):os.makedirs(song_dir)orig_song_path, vocals_path, instrumentals_path, main_vocals_path, backup_vocals_path, main_vocals_dereverb_path = preprocess_song(song_input, mdx_model_params, song_id, is_webui, input_type, progress, keep_orig, orig_song_path)2 unmodified linespaths = get_audio_paths(song_dir)# if any of the audio files aren't available or keep intermediate files, rerun preprocessif any(path is None for path in paths) or keep_files:orig_song_path, vocals_path, instrumentals_path, main_vocals_path, backup_vocals_path, main_vocals_dereverb_path = preprocess_song(song_input, mdx_model_params, song_id, is_webui, input_type, progress, keep_orig, orig_song_path)else:orig_song_path, instrumentals_path, main_vocals_dereverb_path, backup_vocals_path = pathspitch_change = pitch_change * 12 + pitch_change_allai_vocals_path = os.path.join(song_dir, f'{os.path.splitext(os.path.basename(orig_song_path))[0]}_{voice_model}_p{pitch_change}_i{index_rate}_fr{filter_radius}_rms{rms_mix_rate}_pro{protect}_{f0_method}{"" if f0_method != "mangio-crepe" else f"_{crepe_hop_length}"}.wav')ai_cover_path = os.path.join(song_dir, f'{os.path.splitext(os.path.basename(orig_song_path))[0]} ({voice_model} Ver).{output_format}')if not os.path.exists(ai_vocals_path):display_progress('[~] Converting voice using RVC...', 0.5, is_webui, progress)voice_change(voice_model, main_vocals_dereverb_path, ai_vocals_path, pitch_change, f0_method, index_rate, filter_radius, rms_mix_rate, protect, crepe_hop_length, is_webui)return ai_vocals_path, ai_cover_path, instrumentals_path, backup_vocals_path, vocals_path, main_vocals_path# process_song.zerogpu = True# @spaces.GPU(duration=140)def song_cover_pipeline(song_input, voice_model, pitch_change, keep_files,is_webui=0, main_gain=0, backup_gain=0, inst_gain=0, index_rate=0.5, filter_radius=3,rms_mix_rate=0.25, f0_method='rmvpe', crepe_hop_length=128, protect=0.33, pitch_change_all=0,reverb_rm_size=0.15, reverb_wet=0.2, reverb_dry=0.8, reverb_damping=0.7, output_format='mp3',progress=gr.Progress()):try:if not song_input or not voice_model:raise_exception('Ensure that the song input field and voice model field is filled.', is_webui)27 unmodified lineskeep_orig, orig_song_path = get_audio_file(song_input, is_webui, input_type, progress)orig_song_path = convert_to_stereo(orig_song_path)import timestart = time.time()(ai_vocals_path,ai_cover_path,22 unmodified linesoutput_format,keep_orig,orig_song_path,)end = time.time()3 unmodified linesprint(f"Audio duration: {duration__:.2f} seconds")display_progress('[~] Applying audio effects to Vocals...', 0.8, is_webui, progress)ai_vocals_mixed_path = add_audio_effects(ai_vocals_path, reverb_rm_size, reverb_wet, reverb_dry, reverb_damping)instrumentals_path, _ = run_mdx(mdx_model_params,os.path.join(output_dir, song_id),os.path.join(mdxnet_models_dir, "UVR-MDX-NET-Inst_HQ_4.onnx"),instrumentals_path,# exclude_main=False,exclude_inversion=True,suffix="Voiceless",denoise=False,keep_orig=True,base_device="")if pitch_change_all != 0:display_progress('[~] Applying overall pitch change', 0.85, is_webui, progress)5 unmodified linesif not keep_files:display_progress('[~] Removing intermediate audio files...', 0.95, is_webui, progress)intermediate_files = [vocals_path, main_vocals_path, ai_vocals_mixed_path]if pitch_change_all != 0:intermediate_files += [instrumentals_path, backup_vocals_path]for file in intermediate_files:8 unmodified lines9101112131415164 unmodified lines212223242526272 unmodified lines303132333435363738394041424344454647484950515253545556575829 unmodified lines88899091929394959621 unmodified lines11811912012112212312412512612712812929 unmodified lines15916016116216316416516616716816917017117217317417517617717817971 unmodified lines2512522532542552562574 unmodified lines26226326426526626726826932 unmodified lines3023033043053063073083093102 unmodified lines31331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338427 unmodified lines41241341441541641741841922 unmodified lines4424434444454464474483 unmodified lines4524534544554564574584594604614624634644654664674684694704714724734744754764774785 unmodified lines4844854864874884894908 unmodified linesimport subprocessfrom contextlib import suppressfrom urllib.parse import urlparse, parse_qsimport timeimport shutilimport gradio as grimport librosa4 unmodified linesfrom pedalboard import Pedalboard, Reverb, Compressor, HighpassFilterfrom pedalboard.io import AudioFilefrom pydub import AudioSegmentimport noisereduce as nrfrom mdx import run_mdxfrom rvc import Config, load_hubert, get_vc, rvc_infer2 unmodified lineslogging.getLogger("httpx").setLevel(logging.WARNING)BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))IS_ZERO_GPU = os.getenv("SPACES_ZERO_GPU")mdxnet_models_dir = os.path.join(BASE_DIR, 'mdxnet_models')rvc_models_dir = os.path.join(BASE_DIR, 'rvc_models')output_dir = os.path.join(BASE_DIR, 'song_output')def clean_old_folders(base_path: str, max_age_seconds: int = 10800):if not os.path.isdir(base_path):print(f"Error: {base_path} is not a valid directory.")returnnow = time.time()for folder_name in os.listdir(base_path):folder_path = os.path.join(base_path, folder_name)if os.path.isdir(folder_path):last_modified = os.path.getmtime(folder_path)if now - last_modified > max_age_seconds:# print(f"Deleting folder: {folder_path}")shutil.rmtree(folder_path)def get_youtube_video_id(url, ignore_playlist=True):"""Examples:29 unmodified linesdef yt_download(link):if not link.strip():gr.Info("You need to provide a download link.")return Noneydl_opts = {'format': 'bestaudio','outtmpl': '%(title)s',21 unmodified linesdef get_rvc_model(voice_model, is_webui):rvc_model_filename, rvc_index_filename = None, Nonemodel_dir = os.path.join(rvc_models_dir, voice_model)# print(model_dir)for file in os.listdir(model_dir):# print(file)if os.path.isdir(file):for ff in os.listdir(file):# print("subfile", ff)ext = os.path.splitext(ff)[1]if ext == '.pth':rvc_model_filename = ff29 unmodified lineselif file.endswith('_Vocals_Backup.wav'):backup_vocals_path = os.path.join(song_dir, file)# print(orig_song_path, instrumentals_path, main_vocals_dereverb_path, backup_vocals_path)return orig_song_path, instrumentals_path, main_vocals_dereverb_path, backup_vocals_pathdef get_audio_with_suffix(song_dir, suffix="_mysuffix.wav"):target_path = Nonefor file in os.listdir(song_dir):if file.endswith(suffix):target_path = os.path.join(song_dir, file)breakreturn target_pathdef convert_to_stereo(audio_path):wave, sr = librosa.load(audio_path, mono=False, sr=44100)71 unmodified linesprint(device, "half>>", config.is_half)# @spaces.GPU(enable_queue=True)def voice_change(voice_model, vocals_path, output_path, pitch_change, f0_method, index_rate, filter_radius, rms_mix_rate, protect, crepe_hop_length, is_webui, steps):rvc_model_path, rvc_index_path = get_rvc_model(voice_model, is_webui)device = "cuda:0" if torch.cuda.is_available() else "cpu"4 unmodified lines# convert main vocalsglobal hubert_modelrvc_infer(rvc_index_path, index_rate, vocals_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, steps)del cptgc.collect()32 unmodified linesdef process_song(song_dir, song_input, mdx_model_params, song_id, is_webui, input_type, progress,keep_files, pitch_change, pitch_change_all, voice_model, index_rate, filter_radius,rms_mix_rate, protect, f0_method, crepe_hop_length, output_format, keep_orig, orig_song_path, steps):if not os.path.exists(song_dir):os.makedirs(song_dir)orig_song_path, vocals_path, instrumentals_path, main_vocals_path, backup_vocals_path, main_vocals_dereverb_path = preprocess_song(song_input, mdx_model_params, song_id, is_webui, input_type, progress, keep_orig, orig_song_path)2 unmodified linespaths = get_audio_paths(song_dir)# if any of the audio files aren't available or keep intermediate files, rerun preprocessif any(path is None for path in paths):orig_song_path, vocals_path, instrumentals_path, main_vocals_path, backup_vocals_path, main_vocals_dereverb_path = preprocess_song(song_input, mdx_model_params, song_id, is_webui, input_type, progress, keep_orig, orig_song_path)else:orig_song_path, instrumentals_path, main_vocals_dereverb_path, backup_vocals_path = pathspitch_change = pitch_change * 12 + pitch_change_allai_vocals_path = os.path.join(song_dir, f'{os.path.splitext(os.path.basename(orig_song_path))[0]}_{voice_model}_p{pitch_change}_i{index_rate}_fr{filter_radius}_rms{rms_mix_rate}_pro{protect}_{f0_method}{"" if f0_method != "mangio-crepe" else f"_{crepe_hop_length}"}_s{steps}.wav')ai_cover_path = os.path.join(song_dir, f'{os.path.splitext(os.path.basename(orig_song_path))[0]} ({voice_model} Ver).{output_format}')if not os.path.exists(ai_vocals_path):display_progress('[~] Converting voice using RVC...', 0.5, is_webui, progress)voice_change(voice_model, main_vocals_dereverb_path, ai_vocals_path, pitch_change, f0_method, index_rate, filter_radius, rms_mix_rate, protect, crepe_hop_length, is_webui, steps)return ai_vocals_path, ai_cover_path, instrumentals_path, backup_vocals_path, vocals_path, main_vocals_pathdef apply_noisereduce(audio_list, type_output="wav"):# https://github.com/sa-if/Audio-Denoiserprint("Noice reduce")result = []for audio_path in audio_list:out_path = f"{os.path.splitext(audio_path)[0]}_nr.{type_output}"try:# Load audio fileaudio = AudioSegment.from_file(audio_path)# Convert audio to numpy arraysamples = np.array(audio.get_array_of_samples())# Reduce noisereduced_noise = nr.reduce_noise(samples, sr=audio.frame_rate, prop_decrease=0.6)# Convert reduced noise signal back to audioreduced_audio = AudioSegment(reduced_noise.tobytes(),frame_rate=audio.frame_rate,sample_width=audio.sample_width,channels=audio.channels)# Save reduced audio to filereduced_audio.export(out_path, format=type_output)result.append(out_path)except Exception as e:print(f"Error noisereduce: {str(e)}")result.append(audio_path)return result# @spaces.GPU(duration=140)def song_cover_pipeline(song_input, voice_model, pitch_change, keep_files,is_webui=0, main_gain=0, backup_gain=0, inst_gain=0, index_rate=0.5, filter_radius=3,rms_mix_rate=0.25, f0_method='rmvpe', crepe_hop_length=128, protect=0.33, pitch_change_all=0,reverb_rm_size=0.15, reverb_wet=0.2, reverb_dry=0.8, reverb_damping=0.7, output_format='mp3',extra_denoise=False, steps=1,progress=gr.Progress()):if not keep_files or IS_ZERO_GPU:clean_old_folders("./song_output", 14400)if IS_ZERO_GPU:clean_old_folders("./rvc_models", 10800)try:if not song_input or not voice_model:raise_exception('Ensure that the song input field and voice model field is filled.', is_webui)27 unmodified lineskeep_orig, orig_song_path = get_audio_file(song_input, is_webui, input_type, progress)orig_song_path = convert_to_stereo(orig_song_path)start = time.time()(ai_vocals_path,ai_cover_path,22 unmodified linesoutput_format,keep_orig,orig_song_path,steps,)end = time.time()3 unmodified linesprint(f"Audio duration: {duration__:.2f} seconds")display_progress('[~] Applying audio effects to Vocals...', 0.8, is_webui, progress)nr_path = ai_vocals_path # get_audio_with_suffix(song_dir, "_nr.wav")if extra_denoise:ai_vocals_path = apply_noisereduce([ai_vocals_path])[0]ai_vocals_mixed_path = add_audio_effects(ai_vocals_path, reverb_rm_size, reverb_wet, reverb_dry, reverb_damping)ins_path = get_audio_with_suffix(song_dir, "_Voiceless.wav")if not ins_path:instrumentals_path, _ = run_mdx(mdx_model_params,os.path.join(output_dir, song_id),os.path.join(mdxnet_models_dir, "UVR-MDX-NET-Inst_HQ_4.onnx"),instrumentals_path,# exclude_main=False,exclude_inversion=True,suffix="Voiceless",denoise=False,keep_orig=True,base_device=("" if IS_ZERO_GPU else "cuda"))if pitch_change_all != 0:display_progress('[~] Applying overall pitch change', 0.85, is_webui, progress)5 unmodified linesif not keep_files:display_progress('[~] Removing intermediate audio files...', 0.95, is_webui, progress)intermediate_files = [vocals_path, main_vocals_path, ai_vocals_mixed_path, ins_path, nr_path]if pitch_change_all != 0:intermediate_files += [instrumentals_path, backup_vocals_path]for file in intermediate_files:
245 unmodified lines2462472482492502512522532542552562572582592602612622632642659 unmodified lines275276277278279280245 unmodified linesdef 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, base_device="cuda"):if base_device == "cuda" and torch.cuda.is_available():device = torch.device("cuda:0")device_properties = torch.cuda.get_device_properties(device)vram_gb = device_properties.total_memory / 1024**3m_threads = 1 if vram_gb < 8 else (8 if vram_gb > 32 else 2)print(f"threads: {m_threads} vram: {vram_gb}")processor_num = 0else:device = torch.device("cpu")m_threads = 2if torch.cuda.is_available():m_threads = 8print(f"threads: {m_threads}")processor_num = -1model_hash = MDX.get_hash(model_path)9 unmodified linesmdx_sess = MDX(model_path, model, processor=processor_num)wave, sr = librosa.load(filename, mono=False, sr=44100)# normalizing input wave gives better outputpeak = max(np.max(wave), abs(np.min(wave)))wave /= peak245 unmodified lines2462472482492502512522532542552562572582592602612622632649 unmodified lines274275276277278279280281282283284245 unmodified linesdef 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, base_device="cuda"):vram_gb = 0if base_device == "cuda" and torch.cuda.is_available():device = torch.device("cuda:0")device_properties = torch.cuda.get_device_properties(device)vram_gb = device_properties.total_memory / 1024**3m_threads = 1 if vram_gb < 8 else (8 if vram_gb > 32 else 2)processor_num = 0else:device = torch.device("cpu")m_threads = 2if torch.cuda.is_available():m_threads = 8processor_num = -1model_hash = MDX.get_hash(model_path)9 unmodified linesmdx_sess = MDX(model_path, model, processor=processor_num)wave, sr = librosa.load(filename, mono=False, sr=44100)duration = librosa.get_duration(y=wave, sr=sr)if duration < 60:m_threads = 1print(f"threads: {m_threads} vram: {vram_gb}")# normalizing input wave gives better outputpeak = max(np.max(wave), abs(np.min(wave)))wave /= peak
156 unmodified lines157158159160161162163164165156 unmodified linesreturn cpt, version, net_g, tgt_sr, vcdef rvc_infer(index_path, index_rate, input_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):audio = load_audio(input_path, 16000)times = [0, 0, 0]if_f0 = cpt.get('f0', 1)audio_opt = vc.pipeline(hubert_model, net_g, 0, audio, input_path, times, pitch_change, f0_method, index_path, index_rate, if_f0, filter_radius, tgt_sr, 0, rms_mix_rate, version, protect, crepe_hop_length)wavfile.write(output_path, tgt_sr, audio_opt)156 unmodified lines157158159160161162163164165166167168169170171172173174175176156 unmodified linesreturn cpt, version, net_g, tgt_sr, vcdef rvc_infer(index_path, index_rate, input_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, steps):times = [0, 0, 0]if_f0 = cpt.get('f0', 1)working_path = input_pathfor step in range(steps):audio = load_audio(working_path, 16000)audio_opt = vc.pipeline(hubert_model, net_g, step, audio, working_path, times, pitch_change,f0_method, index_path, index_rate, if_f0, filter_radius, tgt_sr,0, rms_mix_rate, version, protect, crepe_hop_length)wavfile.write(output_path, tgt_sr, audio_opt)working_path = output_path
5 unmodified lines678910111213141562 unmodified lines7879808182838485868769 unmodified lines1571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891 unmodified line19119219319419519619719819920020120214 unmodified lines21721821922022122222315 unmodified lines2392402412422432442451 unmodified line24724824925025125225325425525625725812 unmodified lines27127227327427527652 unmodified lines3293303313323333343355 unmodified linesfrom argparse import ArgumentParserimport spacesimport gradio as grfrom main import song_cover_pipelineBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))mdxnet_models_dir = os.path.join(BASE_DIR, 'mdxnet_models')rvc_models_dir = os.path.join(BASE_DIR, 'rvc_models')62 unmodified linesif 'pixeldrain.com' in url:url = f'https://pixeldrain.com/api/file/{zip_name}'urllib.request.urlretrieve(url, zip_name)progress(0.5, desc='[~] Extracting zip...')extract_zip(extraction_folder, zip_name)return f'[+] {dir_name} Model successfully downloaded!'except Exception as e:69 unmodified linesif __name__ == '__main__':parser = ArgumentParser(description='Generate a AI cover song in the song_output/id directory.', add_help=True)parser.add_argument("--share", action="store_true", dest="share_enabled", default=False, help="Enable sharing")parser.add_argument("--listen", action="store_true", default=False, help="Make the WebUI reachable from your local network.")parser.add_argument('--listen-host', type=str, help='The hostname that the server will use.')parser.add_argument('--listen-port', type=int, help='The listening port that the server will use.')args = parser.parse_args()voice_models = get_current_models(rvc_models_dir)with open(os.path.join(rvc_models_dir, 'public_models.json'), encoding='utf8') as infile:public_models = json.load(infile)with gr.Blocks(title='AICoverGenWebUI') as app:gr.Label('AICoverGen WebUI ZeroGPU mode created with ❤️', show_label=False)gr.Markdown("""<details><summary style="font-size: 1.5em;">⚠️ Important (click to expand)</summary><ul><li>🚀 This demo use a Zero GPU, which is available only for a limited time. It's recommended to use audio files that are no longer than 5 minutes. If you want to use it without time restrictions, you can duplicate the 'old CPU space'. ⏳</li></ul></details>""")gr.Markdown("Duplicate the old CPU space for use in private: [](https://huggingface.co/spaces/r3gm/AICoverGen_old_stable_cpu?duplicate=true)\n\n")# main tabwith gr.Tab("Generate"):with gr.Accordion('Main Options'):with gr.Row():with gr.Column():1 unmodified lineref_btn = gr.Button('Refresh Models 🔁', variant='primary')with gr.Column(visible=False) as yt_link_col:song_input = gr.Text(label='Song input', info='Link to a song on YouTube or full path to a local file. For file upload, click the button below. Example: https://www.youtube.com/watch?v=M-mtdN6R3bQ')show_file_upload_button = gr.Button('Upload file instead')with gr.Column(visible=True) as file_upload_col:audio_extensions = ['.mp3', '.m4a', '.flac', '.wav', '.aac', '.ogg', '.wma', '.alac', '.aiff', '.opus', 'amr']local_file = gr.File(label='Audio file', interactive=True, type="filepath", file_types=audio_extensions)song_input_file = gr.UploadButton('Upload 📂', file_types=['audio'], variant='primary', visible=False)show_yt_link_button = gr.Button('Paste YouTube link/Path to local file instead', visible=False)song_input_file.upload(process_file_upload, inputs=[song_input_file], outputs=[local_file, song_input])14 unmodified linesf0_method = gr.Dropdown(['rmvpe+', 'rmvpe', 'mangio-crepe'], value='rmvpe+', label='Pitch detection algorithm', info='Best option is rmvpe (clarity in vocals), then mangio-crepe (smoother vocals), rmvpe+ use a minimum and maximum allowed pitch values.')crepe_hop_length = gr.Slider(32, 320, value=128, step=1, visible=False, label='Crepe hop length', info='Lower values leads to longer conversions and higher risk of voice cracks, but better pitch accuracy.')f0_method.change(show_hop_slider, inputs=f0_method, outputs=crepe_hop_length)keep_files = gr.Checkbox(True, label='Keep intermediate files', info='Keep all audio files generated in the song_output/id directory, e.g. Isolated Vocals/Instrumentals. Leave unchecked to save space')with gr.Accordion('Audio mixing options', open=False):gr.Markdown('### Volume Change (decibels)')15 unmodified lineswith gr.Row():clear_btn = gr.ClearButton(value='Clear', components=[song_input, rvc_model, keep_files, local_file])generate_btn = gr.Button("Generate", variant='primary')ai_cover = gr.Audio(label='AI Cover', show_share_button=False)ref_btn.click(update_models_list, None, outputs=rvc_model)is_webui = gr.Number(value=1, visible=False)1 unmodified lineinputs=[local_file, rvc_model, pitch, keep_files, is_webui, main_gain, backup_gain,inst_gain, index_rate, filter_radius, rms_mix_rate, f0_method, crepe_hop_length,protect, pitch_all, reverb_rm_size, reverb_wet, reverb_dry, reverb_damping,output_format],outputs=[ai_cover])clear_btn.click(lambda: [0, 0, 0, 0, 0.5, 3, 0.25, 0.33, 'rmvpe+', 128, 0, 0.15, 0.2, 0.8, 0.7, 'mp3', None],outputs=[pitch, main_gain, backup_gain, inst_gain, index_rate, filter_radius, rms_mix_rate,protect, f0_method, crepe_hop_length, pitch_all, reverb_rm_size, reverb_wet,reverb_dry, reverb_damping, output_format, ai_cover])# Download tabwith gr.Tab('Download model'):12 unmodified linesgr.Markdown('## Input Examples')gr.Examples([['https://huggingface.co/phant0m4r/LiSA/resolve/main/LiSA.zip', 'Lisa'],['https://pixeldrain.com/u/3tJmABXA', 'Gura'],['https://huggingface.co/Kit-Lemonfoot/kitlemonfoot_rvc_models/resolve/main/AZKi%20(Hybrid).zip', 'Azki']52 unmodified linesapp.launch(share=args.share_enabled,# enable_queue=True,server_name=None if not args.listen else (args.listen_host or '0.0.0.0'),server_port=args.listen_port,)5 unmodified lines678910111213141516171819202122232425262728293031323362 unmodified lines9697989910010110210310410510610710810911011111211311411511669 unmodified lines1861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212221 unmodified line22422522622722822923023123223323423523623723823924024124214 unmodified lines25725825926026126226326426526626726815 unmodified lines2842852862872882892902912922932942951 unmodified line29729829930030130230330430530630730812 unmodified lines32132232332432532632732852 unmodified lines3813823833843853863873883893905 unmodified linesfrom argparse import ArgumentParserimport spacesimport gradio as grimport loggingdef configure_logging_libs(debug=False):modules = ["numba","httpx","markdown_it","fairseq","faiss",]try:for module in modules:logging.getLogger(module).setLevel(logging.WARNING)os.environ['TF_CPP_MIN_LOG_LEVEL'] = "3" if not debug else "1"except Exception as error:passconfigure_logging_libs()from main import song_cover_pipeline, yt_downloadBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))IS_ZERO_GPU = os.getenv("SPACES_ZERO_GPU")mdxnet_models_dir = os.path.join(BASE_DIR, 'mdxnet_models')rvc_models_dir = os.path.join(BASE_DIR, 'rvc_models')62 unmodified linesif 'pixeldrain.com' in url:url = f'https://pixeldrain.com/api/file/{zip_name}'if "," in url:urls = [u.strip() for u in url.split(",") if u.strip()]os.makedirs(extraction_folder, exist_ok=True)for u in urls:u = u.replace("?download=true", "")file_name = u.split('/')[-1]file_path = os.path.join(extraction_folder, file_name)if not os.path.exists(file_path): # avoid re-downloadingurllib.request.urlretrieve(u, file_path)else:urllib.request.urlretrieve(url, zip_name)progress(0.5, desc='[~] Extracting zip...')extract_zip(extraction_folder, zip_name)return f'[+] {dir_name} Model successfully downloaded!'except Exception as e:69 unmodified linesif __name__ == '__main__':parser = ArgumentParser(description='Generate a AI cover song in the song_output/id directory.', add_help=True)parser.add_argument("--share", action="store_true", dest="share_enabled", default=False, help="Enable sharing")parser.add_argument("--builtin-player", action="store_true", default=False, help="Use the builtin audio player")parser.add_argument("--listen", action="store_true", default=False, help="Make the WebUI reachable from your local network.")parser.add_argument('--listen-host', type=str, help='The hostname that the server will use.')parser.add_argument('--listen-port', type=int, help='The listening port that the server will use.')parser.add_argument('--theme', type=str, default="NoCrypt/miku", help='Set the theme (default: NoCrypt/miku)')parser.add_argument("--ssr", action="store_true", help="Enable SSR (Server-Side Rendering)")args = parser.parse_args()voice_models = get_current_models(rvc_models_dir)with open(os.path.join(rvc_models_dir, 'public_models.json'), encoding='utf8') as infile:public_models = json.load(infile)with gr.Blocks(title='AICoverGenWebUI', theme=args.theme, fill_width=True, fill_height=False) as app:gr.Label(f'AICoverGen WebUI {"ZeroGPU mode" if IS_ZERO_GPU else ""} created with ❤️', show_label=False)if IS_ZERO_GPU:gr.Markdown("""<details><summary style="font-size: 1.5em;">⚠️ Important (click to expand)</summary><ul><li>🚀 This demo use a Zero GPU, which is available only for a limited time. It's recommended to use audio files that are no longer than 5 minutes. If you want to use it without time restrictions, you can duplicate the 'old CPU space'. ⏳</li></ul></details>""")gr.Markdown("Duplicate the old CPU space for use in private: [](https://huggingface.co/spaces/r3gm/AICoverGen_old_stable_cpu?duplicate=true)\n\n")# main tabwith gr.Tab("Generate"):with gr.Accordion('Main Options'):with gr.Row():with gr.Column():1 unmodified lineref_btn = gr.Button('Refresh Models 🔁', variant='primary')with gr.Column(visible=False) as yt_link_col:song_input = gr.Text(label='Song input', info='Link to a song on YouTube or full path to a local file. For file upload, click the button below.')show_file_upload_button = gr.Button('Upload file instead')with gr.Column(visible=True) as file_upload_col:audio_extensions = ['.mp3', '.m4a', '.flac', '.wav', '.aac', '.ogg', '.wma', '.alac', '.aiff', '.opus', 'amr']local_file = gr.File(label='Audio file', interactive=True, type="filepath", file_types=audio_extensions, height=150)if not IS_ZERO_GPU:with gr.Row():with gr.Row(scale=2):url_media_gui = gr.Textbox(value="", label="Enter URL", placeholder="www.youtube.com/watch?v=g_9rPvbENUw", lines=1)with gr.Row(scale=1):url_button_gui = gr.Button("Process URL", variant="secondary")url_button_gui.click(yt_download, [url_media_gui], [local_file])song_input_file = gr.UploadButton('Upload 📂', file_types=['audio'], variant='primary', visible=False)show_yt_link_button = gr.Button('Paste YouTube link/Path to local file instead', visible=False)song_input_file.upload(process_file_upload, inputs=[song_input_file], outputs=[local_file, song_input])14 unmodified linesf0_method = gr.Dropdown(['rmvpe+', 'rmvpe', 'mangio-crepe'], value='rmvpe+', label='Pitch detection algorithm', info='Best option is rmvpe (clarity in vocals), then mangio-crepe (smoother vocals), rmvpe+ use a minimum and maximum allowed pitch values.')crepe_hop_length = gr.Slider(32, 320, value=128, step=1, visible=False, label='Crepe hop length', info='Lower values leads to longer conversions and higher risk of voice cracks, but better pitch accuracy.')f0_method.change(show_hop_slider, inputs=f0_method, outputs=crepe_hop_length)with gr.Row():with gr.Row():steps = gr.Slider(minimum=1, maximum=3, label="Steps", value=1, step=1, interactive=True)with gr.Row():extra_denoise = gr.Checkbox(True, label='Denoise', info='Apply an additional noise reduction step to clean up the audio further.')keep_files = gr.Checkbox((False if IS_ZERO_GPU else True), label='Keep intermediate files', info='Keep all audio files generated in the song_output/id directory, e.g. Isolated Vocals/Instrumentals. Leave unchecked to save space', interactive=(False if IS_ZERO_GPU else True))with gr.Accordion('Audio mixing options', open=False):gr.Markdown('### Volume Change (decibels)')15 unmodified lineswith gr.Row():clear_btn = gr.ClearButton(value='Clear', components=[song_input, rvc_model, keep_files, local_file])generate_btn = gr.Button("Generate", variant='primary')ai_cover = (gr.Audio(label='AI Cover', show_share_button=True)if args.builtin_player elsegr.File(label="AI Cover", interactive=False))gr.Markdown("- You can also try `AICoverGen❤️` in Colab’s free tier, which provides free GPU [link](https://github.com/R3gm/AICoverGen?tab=readme-ov-file#aicovergen).")ref_btn.click(update_models_list, None, outputs=rvc_model)is_webui = gr.Number(value=1, visible=False)1 unmodified lineinputs=[local_file, rvc_model, pitch, keep_files, is_webui, main_gain, backup_gain,inst_gain, index_rate, filter_radius, rms_mix_rate, f0_method, crepe_hop_length,protect, pitch_all, reverb_rm_size, reverb_wet, reverb_dry, reverb_damping,output_format, extra_denoise, steps],outputs=[ai_cover])clear_btn.click(lambda: [0, 0, 0, 0, 0.5, 3, 0.25, 0.33, 'rmvpe+', 128, 0, 0.15, 0.2, 0.8, 0.7, 'mp3', None, True, 1],outputs=[pitch, main_gain, backup_gain, inst_gain, index_rate, filter_radius, rms_mix_rate,protect, f0_method, crepe_hop_length, pitch_all, reverb_rm_size, reverb_wet,reverb_dry, reverb_damping, output_format, ai_cover, extra_denoise, steps])# Download tabwith gr.Tab('Download model'):12 unmodified linesgr.Markdown('## Input Examples')gr.Examples([['https://huggingface.co/MrDawg/ToothBrushing/resolve/main/ToothBrushing.zip?download=true', 'ToothBrushing'],['https://huggingface.co/sail-rvc/Aldeano_Minecraft__RVC_V2_-_500_Epochs_/resolve/main/model.pth?download=true, https://huggingface.co/sail-rvc/Aldeano_Minecraft__RVC_V2_-_500_Epochs_/resolve/main/model.index?download=true', 'Minecraft_Villager'],['https://huggingface.co/phant0m4r/LiSA/resolve/main/LiSA.zip', 'Lisa'],['https://pixeldrain.com/u/3tJmABXA', 'Gura'],['https://huggingface.co/Kit-Lemonfoot/kitlemonfoot_rvc_models/resolve/main/AZKi%20(Hybrid).zip', 'Azki']52 unmodified linesapp.launch(share=args.share_enabled,debug=args.share_enabled,show_error=True,# enable_queue=True,server_name=None if not args.listen else (args.listen_host or '0.0.0.0'),server_port=args.listen_port,ssr_mode=args.ssr)
README.md+12-12
app.py+4-7
pre-requirements.txt+2-1
requirements.txt+7-5
src/download_models.py+12-5
src/infer_pack/models.py+4-4
src/main.py+112-27
src/mdx.py+7-3
src/rvc.py+15-4
src/webui.py+82-27