Spaces:
Runtime error
Runtime error
Upload 6 files
Browse filesFiles changed (6)
- LICENSEAdded+21
- config.pyAdded+96
- infer.pyAdded+942
- requirements.txtAdded+25
- rmvpe.pyAdded+432
- vc_infer_pipeline.pyAdded+443
123456789101112131415161718192021MIT License
Copyright (c) 2023 arkandash
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596import argparseimport sysimport torchfrom multiprocessing import cpu_count
class Config: def __init__(self): self.device = "cuda:0" self.is_half = True self.n_cpu = 0 self.gpu_name = None self.gpu_mem = None ( self.colab, self.api, ) = self.arg_parse() self.x_pad, self.x_query, self.x_center, self.x_max = self.device_config()
@staticmethod def arg_parse() -> tuple: parser = argparse.ArgumentParser() parser.add_argument("--colab", action="store_true", help="Launch in colab") parser.add_argument("--api", action="store_true", help="Launch with api") cmd_opts = parser.parse_args()
return ( cmd_opts.colab, cmd_opts.api )
# has_mps is only available in nightly pytorch (for now) and MasOS 12.3+. # check `getattr` and try it for compatibility @staticmethod def has_mps() -> bool: if not torch.backends.mps.is_available(): return False try: torch.zeros(1).to(torch.device("mps")) return True except Exception: return False
def device_config(self) -> tuple: if torch.cuda.is_available(): i_device = int(self.device.split(":")[-1]) self.gpu_name = torch.cuda.get_device_name(i_device) if ( ("16" in self.gpu_name and "V100" not in self.gpu_name.upper()) or "P40" in self.gpu_name.upper() or "1060" in self.gpu_name or "1070" in self.gpu_name or "1080" in self.gpu_name ): print("INFO: Found GPU", self.gpu_name, ", force to fp32") self.is_half = False else: print("INFO: Found GPU", self.gpu_name) self.gpu_mem = int( torch.cuda.get_device_properties(i_device).total_memory / 1024 / 1024 / 1024 + 0.4 ) elif self.has_mps(): print("INFO: No supported Nvidia GPU found, use MPS instead") self.device = "mps" self.is_half = False else: print("INFO: No supported Nvidia GPU found, use CPU instead") self.device = "cpu" self.is_half = False
if self.n_cpu == 0: self.n_cpu = cpu_count()
if self.is_half: # 6G显存配置 x_pad = 3 x_query = 10 x_center = 60 x_max = 65 else: # 5G显存配置 x_pad = 1 x_query = 6 x_center = 38 x_max = 41
if self.gpu_mem != None and self.gpu_mem <= 4: x_pad = 1 x_query = 5 x_center = 30 x_max = 32
return x_pad, x_query, x_center, x_max123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942import torch, os, traceback, sys, warnings, shutil, numpy as npimport gradio as grimport librosaimport asyncioimport rarfileimport edge_ttsimport yt_dlpimport ffmpegimport gdownimport subprocessimport waveimport soundfile as sffrom scipy.io import wavfilefrom datetime import datetimefrom urllib.parse import urlparsefrom mega import Mega
now_dir = os.getcwd()tmp = os.path.join(now_dir, "TEMP")shutil.rmtree(tmp, ignore_errors=True)os.makedirs(tmp, exist_ok=True)os.environ["TEMP"] = tmpfrom lib.infer_pack.models import ( SynthesizerTrnMs256NSFsid, SynthesizerTrnMs256NSFsid_nono, SynthesizerTrnMs768NSFsid, SynthesizerTrnMs768NSFsid_nono,)from fairseq import checkpoint_utilsfrom vc_infer_pipeline import VCfrom config import Configconfig = Config()
tts_voice_list = asyncio.get_event_loop().run_until_complete(edge_tts.list_voices())voices = [f"{v['ShortName']}-{v['Gender']}" for v in tts_voice_list]
hubert_model = None
f0method_mode = ["pm", "harvest", "crepe"]f0method_info = "PM is fast, Harvest is good but extremely slow, and Crepe effect is good but requires GPU (Default: PM)"
if os.path.isfile("rmvpe.pt"): f0method_mode.insert(2, "rmvpe") f0method_info = "PM is fast, Harvest is good but extremely slow, Rvmpe is alternative to harvest (might be better), and Crepe effect is good but requires GPU (Default: PM)"
def load_hubert(): global hubert_model models, _, _ = checkpoint_utils.load_model_ensemble_and_task( ["hubert_base.pt"], suffix="", ) hubert_model = models[0] hubert_model = hubert_model.to(config.device) if config.is_half: hubert_model = hubert_model.half() else: hubert_model = hubert_model.float() hubert_model.eval()
load_hubert()
weight_root = "weights"index_root = "weights/index"weights_model = []weights_index = []for _, _, model_files in os.walk(weight_root): for file in model_files: if file.endswith(".pth"): weights_model.append(file)for _, _, index_files in os.walk(index_root): for file in index_files: if file.endswith('.index') and "trained" not in file: weights_index.append(os.path.join(index_root, file))
def check_models(): weights_model = [] weights_index = [] for _, _, model_files in os.walk(weight_root): for file in model_files: if file.endswith(".pth"): weights_model.append(file) for _, _, index_files in os.walk(index_root): for file in index_files: if file.endswith('.index') and "trained" not in file: weights_index.append(os.path.join(index_root, file)) return ( gr.Dropdown.update(choices=sorted(weights_model), value=weights_model[0]), gr.Dropdown.update(choices=sorted(weights_index)) )
def clean(): return ( gr.Dropdown.update(value=""), gr.Slider.update(visible=False) )
def vc_single( sid, vc_audio_mode, input_audio_path, input_upload_audio, vocal_audio, tts_text, tts_voice, f0_up_key, f0_file, f0_method, file_index, index_rate, filter_radius, resample_sr, rms_mix_rate, protect): # spk_item, input_audio0, vc_transform0,f0_file,f0method0 global tgt_sr, net_g, vc, hubert_model, version, cpt try: logs = [] print(f"Converting...") logs.append(f"Converting...") yield "\n".join(logs), None if vc_audio_mode == "Input path" or "Youtube" and input_audio_path != "": audio, sr = librosa.load(input_audio_path, sr=16000, mono=True) elif vc_audio_mode == "Upload audio": selected_audio = input_upload_audio if vocal_audio: selected_audio = vocal_audio elif input_upload_audio: selected_audio = input_upload_audio sampling_rate, audio = selected_audio duration = audio.shape[0] / sampling_rate audio = (audio / np.iinfo(audio.dtype).max).astype(np.float32) if len(audio.shape) > 1: audio = librosa.to_mono(audio.transpose(1, 0)) if sampling_rate != 16000: audio = librosa.resample(audio, orig_sr=sampling_rate, target_sr=16000) elif vc_audio_mode == "TTS Audio": if tts_text is None or tts_voice is None: return "You need to enter text and select a voice", None asyncio.run(edge_tts.Communicate(tts_text, "-".join(tts_voice.split('-')[:-1])).save("tts.mp3")) audio, sr = librosa.load("tts.mp3", sr=16000, mono=True) input_audio_path = "tts.mp3" f0_up_key = int(f0_up_key) times = [0, 0, 0] if hubert_model == None: load_hubert() if_f0 = cpt.get("f0", 1) audio_opt = vc.pipeline( hubert_model, net_g, sid, audio, input_audio_path, times, f0_up_key, f0_method, file_index, # file_big_npy, index_rate, if_f0, filter_radius, tgt_sr, resample_sr, rms_mix_rate, version, protect, f0_file=f0_file ) if resample_sr >= 16000 and tgt_sr != resample_sr: tgt_sr = resample_sr index_info = ( "Using index:%s." % file_index if os.path.exists(file_index) else "Index not used." ) print("Success.\n %s\nTime:\n npy:%ss, f0:%ss, infer:%ss" % ( index_info, times[0], times[1], times[2], )) info = f"{index_info}\n[{datetime.now().strftime('%Y-%m-%d %H:%M')}]: npy: {times[0]}, f0: {times[1]}s, infer: {times[2]}s" logs.append(info) yield "\n".join(logs), (tgt_sr, audio_opt) except: info = traceback.format_exc() print(info) logs.append(info) yield "\n".join(logs), None
def get_vc(sid, to_return_protect0): global n_spk, tgt_sr, net_g, vc, cpt, version, weights_index if sid == "" or sid == []: global hubert_model if hubert_model is not None: # 考虑到轮询, 需要加个判断看是否 sid 是由有模型切换到无模型的 print("clean_empty_cache") del net_g, n_spk, vc, hubert_model, tgt_sr # ,cpt hubert_model = net_g = n_spk = vc = hubert_model = tgt_sr = None if torch.cuda.is_available(): torch.cuda.empty_cache() ###楼下不这么折腾清理不干净 if_f0 = cpt.get("f0", 1) version = cpt.get("version", "v1") if version == "v1": if if_f0 == 1: net_g = SynthesizerTrnMs256NSFsid( *cpt["config"], is_half=config.is_half ) else: net_g = SynthesizerTrnMs256NSFsid_nono(*cpt["config"]) elif version == "v2": if if_f0 == 1: net_g = SynthesizerTrnMs768NSFsid( *cpt["config"], is_half=config.is_half ) else: net_g = SynthesizerTrnMs768NSFsid_nono(*cpt["config"]) del net_g, cpt if torch.cuda.is_available(): torch.cuda.empty_cache() cpt = None return ( gr.Slider.update(maximum=2333, visible=False), gr.Slider.update(visible=True), gr.Dropdown.update(choices=sorted(weights_index), value=""), gr.Markdown.update(value="# <center> No model selected") ) print(f"Loading {sid} model...") selected_model = sid[:-4] cpt = torch.load(os.path.join(weight_root, sid), map_location="cpu") tgt_sr = cpt["config"][-1] cpt["config"][-3] = cpt["weight"]["emb_g.weight"].shape[0] if_f0 = cpt.get("f0", 1) if if_f0 == 0: to_return_protect0 = { "visible": False, "value": 0.5, "__type__": "update", } else: to_return_protect0 = { "visible": True, "value": to_return_protect0, "__type__": "update", } version = cpt.get("version", "v1") if version == "v1": if if_f0 == 1: net_g = SynthesizerTrnMs256NSFsid(*cpt["config"], is_half=config.is_half) else: net_g = SynthesizerTrnMs256NSFsid_nono(*cpt["config"]) elif version == "v2": if if_f0 == 1: net_g = SynthesizerTrnMs768NSFsid(*cpt["config"], is_half=config.is_half) else: net_g = SynthesizerTrnMs768NSFsid_nono(*cpt["config"]) del net_g.enc_q print(net_g.load_state_dict(cpt["weight"], strict=False)) net_g.eval().to(config.device) if config.is_half: net_g = net_g.half() else: net_g = net_g.float() vc = VC(tgt_sr, config) n_spk = cpt["config"][-3] weights_index = [] for _, _, index_files in os.walk(index_root): for file in index_files: if file.endswith('.index') and "trained" not in file: weights_index.append(os.path.join(index_root, file)) if weights_index == []: selected_index = gr.Dropdown.update(value="") else selected_index = gr.Dropdown.update(value=weights_index[0]) for index, model_index in enumerate(weights_index): if selected_model in model_index: selected_index = gr.Dropdown.update(value=weights_index[index]) break return ( gr.Slider.update(maximum=n_spk, visible=True), to_return_protect0, selected_index, gr.Markdown.update( f'## <center> {selected_model}\n'+ f'### <center> RVC {version} Model' ) )
def find_audio_files(folder_path, extensions): audio_files = [] for root, dirs, files in os.walk(folder_path): for file in files: if any(file.endswith(ext) for ext in extensions): audio_files.append(file) return audio_files
def vc_multi( spk_item, vc_input, vc_output, vc_transform0, f0method0, file_index, index_rate, filter_radius, resample_sr, rms_mix_rate, protect,): global tgt_sr, net_g, vc, hubert_model, version, cpt logs = [] logs.append("Converting...") yield "\n".join(logs) print() try: if os.path.exists(vc_input): folder_path = vc_input extensions = [".mp3", ".wav", ".flac", ".ogg"] audio_files = find_audio_files(folder_path, extensions) for index, file in enumerate(audio_files, start=1): audio, sr = librosa.load(os.path.join(folder_path, file), sr=16000, mono=True) input_audio_path = folder_path, file f0_up_key = int(vc_transform0) times = [0, 0, 0] if hubert_model == None: load_hubert() if_f0 = cpt.get("f0", 1) audio_opt = vc.pipeline( hubert_model, net_g, spk_item, audio, input_audio_path, times, f0_up_key, f0method0, file_index, index_rate, if_f0, filter_radius, tgt_sr, resample_sr, rms_mix_rate, version, protect, f0_file=None ) if resample_sr >= 16000 and tgt_sr != resample_sr: tgt_sr = resample_sr output_path = f"{os.path.join(vc_output, file)}" os.makedirs(os.path.join(vc_output), exist_ok=True) sf.write( output_path, audio_opt, tgt_sr, ) info = f"{index} / {len(audio_files)} | {file}" print(info) logs.append(info) yield "\n".join(logs) else: logs.append("Folder not found or path doesn't exist.") yield "\n".join(logs) except: info = traceback.format_exc() print(info) logs.append(info) yield "\n".join(logs)
def download_audio(url, audio_provider): logs = [] os.makedirs("dl_audio", exist_ok=True) if url == "": logs.append("URL required!") yield None, "\n".join(logs) return None, "\n".join(logs) if audio_provider == "Youtube": logs.append("Downloading the audio...") yield None, "\n".join(logs) ydl_opts = { 'noplaylist': True, 'format': 'bestaudio/best', 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'wav', }], "outtmpl": 'result/dl_audio/audio', } audio_path = "result/dl_audio/audio.wav" with yt_dlp.YoutubeDL(ydl_opts) as ydl: ydl.download([url]) logs.append("Download Complete.") yield audio_path, "\n".join(logs)
def cut_vocal_and_inst_yt(split_model): logs = [] logs.append("Starting the audio splitting process...") yield "\n".join(logs), None, None, None command = f"demucs --two-stems=vocals -n {split_model} result/dl_audio/audio.wav -o output" result = subprocess.Popen(command.split(), stdout=subprocess.PIPE, text=True) for line in result.stdout: logs.append(line) yield "\n".join(logs), None, None, None print(result.stdout) vocal = f"output/{split_model}/audio/vocals.wav" inst = f"output/{split_model}/audio/no_vocals.wav" logs.append("Audio splitting complete.") yield "\n".join(logs), vocal, inst, vocal
def cut_vocal_and_inst(split_model, audio_data): logs = [] vocal_path = "output/result/audio.wav" os.makedirs("output/result", exist_ok=True) wavfile.write(vocal_path, audio_data[0], audio_data[1]) logs.append("Starting the audio splitting process...") yield "\n".join(logs), None, None command = f"demucs --two-stems=vocals -n {split_model} {vocal_path} -o output" result = subprocess.Popen(command.split(), stdout=subprocess.PIPE, text=True) for line in result.stdout: logs.append(line) yield "\n".join(logs), None, None print(result.stdout) vocal = f"output/{split_model}/audio/vocals.wav" inst = f"output/{split_model}/audio/no_vocals.wav" logs.append("Audio splitting complete.") yield "\n".join(logs), vocal, inst def combine_vocal_and_inst(audio_data, vocal_volume, inst_volume, split_model): os.makedirs("output/result", exist_ok=True) vocal_path = "output/result/output.wav" output_path = "output/result/combine.mp3" inst_path = f"output/{split_model}/audio/no_vocals.wav" wavfile.write(vocal_path, audio_data[0], audio_data[1]) command = f'ffmpeg -y -i {inst_path} -i {vocal_path} -filter_complex [0:a]volume={inst_volume}[i];[1:a]volume={vocal_volume}[v];[i][v]amix=inputs=2:duration=longest[a] -map [a] -b:a 320k -c:a libmp3lame {output_path}' result = subprocess.run(command.split(), stdout=subprocess.PIPE) print(result.stdout.decode()) return output_path
def download_and_extract_models(urls): logs = [] os.makedirs("zips", exist_ok=True) os.makedirs(os.path.join("zips", "extract"), exist_ok=True) os.makedirs(os.path.join(weight_root), exist_ok=True) os.makedirs(os.path.join(index_root), exist_ok=True) for link in urls.splitlines(): url = link.strip() if not url: raise gr.Error("URL Required!") return "No URLs provided." model_zip = urlparse(url).path.split('/')[-2] + '.zip' model_zip_path = os.path.join('zips', model_zip) logs.append(f"Downloading...") yield "\n".join(logs) if "drive.google.com" in url: gdown.download(url, os.path.join("zips", "extract"), quiet=False) elif "mega.nz" in url: m = Mega() m.download_url(url, 'zips') else: os.system(f"wget {url} -O {model_zip_path}") logs.append(f"Extracting...") yield "\n".join(logs) for filename in os.listdir("zips"): archived_file = os.path.join("zips", filename) if filename.endswith(".zip"): shutil.unpack_archive(archived_file, os.path.join("zips", "extract"), 'zip') elif filename.endswith(".rar"): with rarfile.RarFile(archived_file, 'r') as rar: rar.extractall(os.path.join("zips", "extract")) for _, dirs, files in os.walk(os.path.join("zips", "extract")): logs.append(f"Searching Model and Index...") yield "\n".join(logs) model = False index = False if files: for file in files: if file.endswith(".pth"): basename = file[:-4] shutil.move(os.path.join("zips", "extract", file), os.path.join(weight_root, file)) model = True if file.endswith('.index') and "trained" not in file: shutil.move(os.path.join("zips", "extract", file), os.path.join(index_root, file)) index = True else: logs.append("No model in main folder.") yield "\n".join(logs) logs.append("Searching in subfolders...") yield "\n".join(logs) for sub_dir in dirs: for _, _, sub_files in os.walk(os.path.join("zips", "extract", sub_dir)): for file in sub_files: if file.endswith(".pth"): basename = file[:-4] shutil.move(os.path.join("zips", "extract", sub_dir, file), os.path.join(weight_root, file)) model = True if file.endswith('.index') and "trained" not in file: shutil.move(os.path.join("zips", "extract", sub_dir, file), os.path.join(index_root, file)) index = True shutil.rmtree(os.path.join("zips", "extract", sub_dir)) if index is False: logs.append("Model only file, no Index file detected.") yield "\n".join(logs) logs.append("Download Completed!") yield "\n".join(logs) logs.append("Successfully download all models! Refresh your model list to load the model") yield "\n".join(logs)
def use_microphone(microphone): if microphone == True: return gr.Audio.update(source="microphone") else: return gr.Audio.update(source="upload")
def change_audio_mode(vc_audio_mode): if vc_audio_mode == "Input path": return ( # Input & Upload gr.Textbox.update(visible=True), gr.Checkbox.update(visible=False), gr.Audio.update(visible=False), # Youtube gr.Dropdown.update(visible=False), gr.Textbox.update(visible=False), gr.Textbox.update(visible=False), gr.Button.update(visible=False), # Splitter gr.Dropdown.update(visible=True), gr.Textbox.update(visible=True), gr.Button.update(visible=True), gr.Button.update(visible=False), gr.Audio.update(visible=False), gr.Audio.update(visible=True), gr.Audio.update(visible=True), gr.Slider.update(visible=True), gr.Slider.update(visible=True), gr.Audio.update(visible=True), gr.Button.update(visible=True), # TTS gr.Textbox.update(visible=False), gr.Dropdown.update(visible=False) ) elif vc_audio_mode == "Upload audio": return ( # Input & Upload gr.Textbox.update(visible=False), gr.Checkbox.update(visible=True), gr.Audio.update(visible=True), # Youtube gr.Dropdown.update(visible=False), gr.Textbox.update(visible=False), gr.Textbox.update(visible=False), gr.Button.update(visible=False), # Splitter gr.Dropdown.update(visible=True), gr.Textbox.update(visible=True), gr.Button.update(visible=False), gr.Button.update(visible=True), gr.Audio.update(visible=False), gr.Audio.update(visible=True), gr.Audio.update(visible=True), gr.Slider.update(visible=True), gr.Slider.update(visible=True), gr.Audio.update(visible=True), gr.Button.update(visible=True), # TTS gr.Textbox.update(visible=False), gr.Dropdown.update(visible=False) ) elif vc_audio_mode == "Youtube": return ( # Input & Upload gr.Textbox.update(visible=False), gr.Checkbox.update(visible=False), gr.Audio.update(visible=False), # Youtube gr.Dropdown.update(visible=True), gr.Textbox.update(visible=True), gr.Textbox.update(visible=True), gr.Button.update(visible=True), # Splitter gr.Dropdown.update(visible=True), gr.Textbox.update(visible=True), gr.Button.update(visible=True), gr.Button.update(visible=False), gr.Audio.update(visible=True), gr.Audio.update(visible=True), gr.Audio.update(visible=True), gr.Slider.update(visible=True), gr.Slider.update(visible=True), gr.Audio.update(visible=True), gr.Button.update(visible=True), # TTS gr.Textbox.update(visible=False), gr.Dropdown.update(visible=False) ) elif vc_audio_mode == "TTS Audio": return ( # Input & Upload gr.Textbox.update(visible=False), gr.Checkbox.update(visible=False), gr.Audio.update(visible=False), # Youtube gr.Dropdown.update(visible=False), gr.Textbox.update(visible=False), gr.Textbox.update(visible=False), gr.Button.update(visible=False), # Splitter gr.Dropdown.update(visible=False), gr.Textbox.update(visible=False), gr.Button.update(visible=False), gr.Button.update(visible=False), gr.Audio.update(visible=False), gr.Audio.update(visible=False), gr.Audio.update(visible=False), gr.Slider.update(visible=False), gr.Slider.update(visible=False), gr.Audio.update(visible=False), gr.Button.update(visible=False), # TTS gr.Textbox.update(visible=True), gr.Dropdown.update(visible=True) ) with gr.Blocks() as app: gr.Markdown( "# <center> Advanced RVC Inference\n" ) with gr.Row(): sid = gr.Dropdown( label="Weight", choices=sorted(weights_model), ) file_index = gr.Dropdown( label="List of index file", choices=sorted(weights_index), interactive=True, ) spk_item = gr.Slider( minimum=0, maximum=2333, step=1, label="Speaker ID", value=0, visible=False, interactive=True, ) refresh_model = gr.Button("Refresh model list", variant="primary") clean_button = gr.Button("Clear Model from memory", variant="primary") refresh_model.click( fn=check_models, inputs=[], outputs=[sid, file_index] ) clean_button.click(fn=clean, inputs=[], outputs=[sid, spk_item]) with gr.TabItem("Inference"): selected_model = gr.Markdown(value="# <center> No model selected") with gr.Row(): with gr.Column(): vc_audio_mode = gr.Dropdown(label="Input voice", choices=["Input path", "Upload audio", "Youtube", "TTS Audio"], allow_custom_value=False, value="Upload audio") # Input vc_input = gr.Textbox(label="Input audio path", visible=False) # Upload vc_microphone_mode = gr.Checkbox(label="Use Microphone", value=False, visible=True, interactive=True) vc_upload = gr.Audio(label="Upload audio file", source="upload", visible=True, interactive=True) # Youtube vc_download_audio = gr.Dropdown(label="Provider", choices=["Youtube"], allow_custom_value=False, visible=False, value="Youtube", info="Select provider (Default: Youtube)") vc_link = gr.Textbox(label="Youtube URL", visible=False, info="Example: https://www.youtube.com/watch?v=Nc0sB1Bmf-A", placeholder="https://www.youtube.com/watch?v=...") vc_log_yt = gr.Textbox(label="Output Information", visible=False, interactive=False) vc_download_button = gr.Button("Download Audio", variant="primary", visible=False) vc_audio_preview = gr.Audio(label="Downloaded Audio Preview", visible=False) # TTS tts_text = gr.Textbox(label="TTS text", info="Text to speech input", visible=False) tts_voice = gr.Dropdown(label="Edge-tts speaker", choices=voices, visible=False, allow_custom_value=False, value="en-US-AnaNeural-Female") # Splitter vc_split_model = gr.Dropdown(label="Splitter Model", choices=["hdemucs_mmi", "htdemucs", "htdemucs_ft", "mdx", "mdx_q", "mdx_extra_q"], allow_custom_value=False, visible=True, value="htdemucs", info="Select the splitter model (Default: htdemucs)") vc_split_log = gr.Textbox(label="Output Information", visible=True, interactive=False) vc_split_yt = gr.Button("Split Audio", variant="primary", visible=False) vc_split = gr.Button("Split Audio", variant="primary", visible=True) vc_vocal_preview = gr.Audio(label="Vocal Preview", interactive=False, visible=True) vc_inst_preview = gr.Audio(label="Instrumental Preview", interactive=False, visible=True) with gr.Column(): vc_transform0 = gr.Number( label="Transpose", info='Type "12" to change from male to female convertion or Type "-12" to change female to male convertion.', value=0 ) f0method0 = gr.Radio( label="Pitch extraction algorithm", info=f0method_info, choices=f0method_mode, value="pm", interactive=True, ) index_rate0 = gr.Slider( minimum=0, maximum=1, label="Retrieval feature ratio", value=0.7, interactive=True, ) filter_radius0 = gr.Slider( minimum=0, maximum=7, label="Apply Median Filtering", info="The value represents the filter radius and can reduce breathiness.", value=3, step=1, interactive=True, ) resample_sr0 = gr.Slider( minimum=0, maximum=48000, label="Resample the output audio", info="Resample the output audio in post-processing to the final sample rate. Set to 0 for no resampling", value=0, step=1, interactive=True, ) rms_mix_rate0 = gr.Slider( minimum=0, maximum=1, label="Volume Envelope", info="Use the volume envelope of the input to replace or mix with the volume envelope of the output. The closer the ratio is to 1, the more the output envelope is used", value=1, interactive=True, ) protect0 = gr.Slider( minimum=0, maximum=0.5, label="Voice Protection", info="Protect voiceless consonants and breath sounds to prevent artifacts such as tearing in electronic music. Set to 0.5 to disable. Decrease the value to increase protection, but it may reduce indexing accuracy", value=0.5, step=0.01, interactive=True, ) f0_file0 = gr.File( label="F0 curve file (Optional)", info="One pitch per line, Replace the default F0 and pitch modulation" ) with gr.Column(): vc_log = gr.Textbox(label="Output Information", interactive=False) vc_output = gr.Audio(label="Output Audio", interactive=False) vc_convert = gr.Button("Convert", variant="primary") vc_vocal_volume = gr.Slider( minimum=0, maximum=10, label="Vocal volume", value=1, interactive=True, step=1, info="Adjust vocal volume (Default: 1}", visible=True ) vc_inst_volume = gr.Slider( minimum=0, maximum=10, label="Instrument volume", value=1, interactive=True, step=1, info="Adjust instrument volume (Default: 1}", visible=True ) vc_combined_output = gr.Audio(label="Output Combined Audio", visible=True) vc_combine = gr.Button("Combine",variant="primary", visible=True) vc_convert.click( vc_single, [ spk_item, vc_audio_mode, vc_input, vc_upload, vc_vocal_preview, tts_text, tts_voice, vc_transform0, f0_file0, f0method0, file_index, index_rate0, filter_radius0, resample_sr0, rms_mix_rate0, protect0, ], [vc_log, vc_output], ) vc_download_button.click( fn=download_audio, inputs=[vc_link, vc_download_audio], outputs=[vc_audio_preview, vc_log_yt] ) vc_split_yt.click( fn=cut_vocal_and_inst_yt, inputs=[vc_split_model], outputs=[vc_split_log, vc_vocal_preview, vc_inst_preview, vc_input] ) vc_split.click( fn=cut_vocal_and_inst, inputs=[vc_split_model, vc_upload], outputs=[vc_split_log, vc_vocal_preview, vc_inst_preview] ) vc_combine.click( fn=combine_vocal_and_inst, inputs=[vc_output, vc_vocal_volume, vc_inst_volume, vc_split_model], outputs=[vc_combined_output] ) vc_microphone_mode.change( fn=use_microphone, inputs=vc_microphone_mode, outputs=vc_upload ) vc_audio_mode.change( fn=change_audio_mode, inputs=[vc_audio_mode], outputs=[ # Input & Upload vc_input, vc_microphone_mode, vc_upload, # Youtube vc_download_audio, vc_link, vc_log_yt, vc_download_button, # Splitter vc_split_model, vc_split_log, vc_split_yt, vc_split, vc_audio_preview, vc_vocal_preview, vc_inst_preview, vc_vocal_volume, vc_inst_volume, vc_combined_output, vc_combine, # TTS tts_text, tts_voice ] ) sid.change(fn=get_vc, inputs=[sid, protect0], outputs=[spk_item, protect0, file_index, selected_model]) with gr.TabItem("Batch Inference"): with gr.Row(): with gr.Column(): vc_input_bat = gr.Textbox(label="Input audio path (folder)", visible=True) vc_output_bat = gr.Textbox(label="Output audio path (folder)", value="result/batch", visible=True) with gr.Column(): vc_transform0_bat = gr.Number( label="Transpose", info='Type "12" to change from male to female convertion or Type "-12" to change female to male convertion.', value=0 ) f0method0_bat = gr.Radio( label="Pitch extraction algorithm", info=f0method_info, choices=f0method_mode, value="pm", interactive=True, ) index_rate0_bat = gr.Slider( minimum=0, maximum=1, label="Retrieval feature ratio", value=0.7, interactive=True, ) filter_radius0_bat = gr.Slider( minimum=0, maximum=7, label="Apply Median Filtering", info="The value represents the filter radius and can reduce breathiness.", value=3, step=1, interactive=True, ) resample_sr0_bat = gr.Slider( minimum=0, maximum=48000, label="Resample the output audio", info="Resample the output audio in post-processing to the final sample rate. Set to 0 for no resampling", value=0, step=1, interactive=True, ) rms_mix_rate0_bat = gr.Slider( minimum=0, maximum=1, label="Volume Envelope", info="Use the volume envelope of the input to replace or mix with the volume envelope of the output. The closer the ratio is to 1, the more the output envelope is used", value=1, interactive=True, ) protect0_bat = gr.Slider( minimum=0, maximum=0.5, label="Voice Protection", info="Protect voiceless consonants and breath sounds to prevent artifacts such as tearing in electronic music. Set to 0.5 to disable. Decrease the value to increase protection, but it may reduce indexing accuracy", value=0.5, step=0.01, interactive=True, ) with gr.Column(): vc_log_bat = gr.Textbox(label="Output Information", interactive=False) vc_convert_bat = gr.Button("Convert", variant="primary") vc_convert_bat.click( vc_multi, [ spk_item, vc_input_bat, vc_output_bat, vc_transform0_bat, f0method0_bat, file_index, index_rate0_bat, filter_radius0_bat, resample_sr0_bat, rms_mix_rate0_bat, protect0_bat, ], [vc_log_bat], ) with gr.TabItem("Model Downloader"): gr.Markdown( "# <center> Model Downloader (Beta)\n"+ "#### <center> To download multi link you have to put your link to the textbox and every link separated by space\n"+ "#### <center> Support Direct Link, Mega, Google Drive, etc" ) with gr.Column(): md_text = gr.Textbox(label="URL") with gr.Row(): md_download = gr.Button(label="Convert", variant="primary") md_download_logs = gr.Textbox(label="Output information", interactive=False) md_download.click( fn=download_and_extract_models, inputs=[md_text], outputs=[md_download_logs] ) with gr.TabItem("Settings"): gr.Markdown( "# <center> Settings\n"+ "#### <center> Work in progress" ) app.queue(concurrency_count=1, max_size=50, api_open=config.api).launch(share=config.colab)12345678910111213141516171819202122232425wheelsetuptoolsffmpegnumba==0.56.4numpy==1.23.5scipy==1.9.3librosa==0.9.1fairseq==0.12.2faiss-cpu==1.7.3gradio==3.40.1pyworld==0.3.2soundfile>=0.12.1praat-parselmouth>=0.4.2httpx==0.23.0tensorboardtensorboardXtorchcrepeonnxruntimeasynciodemucsedge-ttsyt_dlprarfilemega.pygdown123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432import sys, torch, numpy as np, traceback, pdbimport torch.nn as nnfrom time import time as ttimeimport torch.nn.functional as F
class BiGRU(nn.Module): def __init__(self, input_features, hidden_features, num_layers): super(BiGRU, self).__init__() self.gru = nn.GRU( input_features, hidden_features, num_layers=num_layers, batch_first=True, bidirectional=True, )
def forward(self, x): return self.gru(x)[0]
class ConvBlockRes(nn.Module): def __init__(self, in_channels, out_channels, momentum=0.01): super(ConvBlockRes, self).__init__() self.conv = nn.Sequential( nn.Conv2d( in_channels=in_channels, out_channels=out_channels, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False, ), nn.BatchNorm2d(out_channels, momentum=momentum), nn.ReLU(), nn.Conv2d( in_channels=out_channels, out_channels=out_channels, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False, ), nn.BatchNorm2d(out_channels, momentum=momentum), nn.ReLU(), ) if in_channels != out_channels: self.shortcut = nn.Conv2d(in_channels, out_channels, (1, 1)) self.is_shortcut = True else: self.is_shortcut = False
def forward(self, x): if self.is_shortcut: return self.conv(x) + self.shortcut(x) else: return self.conv(x) + x
class Encoder(nn.Module): def __init__( self, in_channels, in_size, n_encoders, kernel_size, n_blocks, out_channels=16, momentum=0.01, ): super(Encoder, self).__init__() self.n_encoders = n_encoders self.bn = nn.BatchNorm2d(in_channels, momentum=momentum) self.layers = nn.ModuleList() self.latent_channels = [] for i in range(self.n_encoders): self.layers.append( ResEncoderBlock( in_channels, out_channels, kernel_size, n_blocks, momentum=momentum ) ) self.latent_channels.append([out_channels, in_size]) in_channels = out_channels out_channels *= 2 in_size //= 2 self.out_size = in_size self.out_channel = out_channels
def forward(self, x): concat_tensors = [] x = self.bn(x) for i in range(self.n_encoders): _, x = self.layers[i](x) concat_tensors.append(_) return x, concat_tensors
class ResEncoderBlock(nn.Module): def __init__( self, in_channels, out_channels, kernel_size, n_blocks=1, momentum=0.01 ): super(ResEncoderBlock, self).__init__() self.n_blocks = n_blocks self.conv = nn.ModuleList() self.conv.append(ConvBlockRes(in_channels, out_channels, momentum)) for i in range(n_blocks - 1): self.conv.append(ConvBlockRes(out_channels, out_channels, momentum)) self.kernel_size = kernel_size if self.kernel_size is not None: self.pool = nn.AvgPool2d(kernel_size=kernel_size)
def forward(self, x): for i in range(self.n_blocks): x = self.conv[i](x) if self.kernel_size is not None: return x, self.pool(x) else: return x
class Intermediate(nn.Module): # def __init__(self, in_channels, out_channels, n_inters, n_blocks, momentum=0.01): super(Intermediate, self).__init__() self.n_inters = n_inters self.layers = nn.ModuleList() self.layers.append( ResEncoderBlock(in_channels, out_channels, None, n_blocks, momentum) ) for i in range(self.n_inters - 1): self.layers.append( ResEncoderBlock(out_channels, out_channels, None, n_blocks, momentum) )
def forward(self, x): for i in range(self.n_inters): x = self.layers[i](x) return x
class ResDecoderBlock(nn.Module): def __init__(self, in_channels, out_channels, stride, n_blocks=1, momentum=0.01): super(ResDecoderBlock, self).__init__() out_padding = (0, 1) if stride == (1, 2) else (1, 1) self.n_blocks = n_blocks self.conv1 = nn.Sequential( nn.ConvTranspose2d( in_channels=in_channels, out_channels=out_channels, kernel_size=(3, 3), stride=stride, padding=(1, 1), output_padding=out_padding, bias=False, ), nn.BatchNorm2d(out_channels, momentum=momentum), nn.ReLU(), ) self.conv2 = nn.ModuleList() self.conv2.append(ConvBlockRes(out_channels * 2, out_channels, momentum)) for i in range(n_blocks - 1): self.conv2.append(ConvBlockRes(out_channels, out_channels, momentum))
def forward(self, x, concat_tensor): x = self.conv1(x) x = torch.cat((x, concat_tensor), dim=1) for i in range(self.n_blocks): x = self.conv2[i](x) return x
class Decoder(nn.Module): def __init__(self, in_channels, n_decoders, stride, n_blocks, momentum=0.01): super(Decoder, self).__init__() self.layers = nn.ModuleList() self.n_decoders = n_decoders for i in range(self.n_decoders): out_channels = in_channels // 2 self.layers.append( ResDecoderBlock(in_channels, out_channels, stride, n_blocks, momentum) ) in_channels = out_channels
def forward(self, x, concat_tensors): for i in range(self.n_decoders): x = self.layers[i](x, concat_tensors[-1 - i]) return x
class DeepUnet(nn.Module): def __init__( self, kernel_size, n_blocks, en_de_layers=5, inter_layers=4, in_channels=1, en_out_channels=16, ): super(DeepUnet, self).__init__() self.encoder = Encoder( in_channels, 128, en_de_layers, kernel_size, n_blocks, en_out_channels ) self.intermediate = Intermediate( self.encoder.out_channel // 2, self.encoder.out_channel, inter_layers, n_blocks, ) self.decoder = Decoder( self.encoder.out_channel, en_de_layers, kernel_size, n_blocks )
def forward(self, x): x, concat_tensors = self.encoder(x) x = self.intermediate(x) x = self.decoder(x, concat_tensors) return x
class E2E(nn.Module): def __init__( self, n_blocks, n_gru, kernel_size, en_de_layers=5, inter_layers=4, in_channels=1, en_out_channels=16, ): super(E2E, self).__init__() self.unet = DeepUnet( kernel_size, n_blocks, en_de_layers, inter_layers, in_channels, en_out_channels, ) self.cnn = nn.Conv2d(en_out_channels, 3, (3, 3), padding=(1, 1)) if n_gru: self.fc = nn.Sequential( BiGRU(3 * 128, 256, n_gru), nn.Linear(512, 360), nn.Dropout(0.25), nn.Sigmoid(), ) else: self.fc = nn.Sequential( nn.Linear(3 * N_MELS, N_CLASS), nn.Dropout(0.25), nn.Sigmoid() )
def forward(self, mel): mel = mel.transpose(-1, -2).unsqueeze(1) x = self.cnn(self.unet(mel)).transpose(1, 2).flatten(-2) x = self.fc(x) return x
from librosa.filters import mel
class MelSpectrogram(torch.nn.Module): def __init__( self, is_half, n_mel_channels, sampling_rate, win_length, hop_length, n_fft=None, mel_fmin=0, mel_fmax=None, clamp=1e-5, ): super().__init__() n_fft = win_length if n_fft is None else n_fft self.hann_window = {} mel_basis = mel( sr=sampling_rate, n_fft=n_fft, n_mels=n_mel_channels, fmin=mel_fmin, fmax=mel_fmax, htk=True, ) mel_basis = torch.from_numpy(mel_basis).float() self.register_buffer("mel_basis", mel_basis) self.n_fft = win_length if n_fft is None else n_fft self.hop_length = hop_length self.win_length = win_length self.sampling_rate = sampling_rate self.n_mel_channels = n_mel_channels self.clamp = clamp self.is_half = is_half
def forward(self, audio, keyshift=0, speed=1, center=True): factor = 2 ** (keyshift / 12) n_fft_new = int(np.round(self.n_fft * factor)) win_length_new = int(np.round(self.win_length * factor)) hop_length_new = int(np.round(self.hop_length * speed)) keyshift_key = str(keyshift) + "_" + str(audio.device) if keyshift_key not in self.hann_window: self.hann_window[keyshift_key] = torch.hann_window(win_length_new).to( audio.device ) fft = torch.stft( audio, n_fft=n_fft_new, hop_length=hop_length_new, win_length=win_length_new, window=self.hann_window[keyshift_key], center=center, return_complex=True, ) magnitude = torch.sqrt(fft.real.pow(2) + fft.imag.pow(2)) if keyshift != 0: size = self.n_fft // 2 + 1 resize = magnitude.size(1) if resize < size: magnitude = F.pad(magnitude, (0, 0, 0, size - resize)) magnitude = magnitude[:, :size, :] * self.win_length / win_length_new mel_output = torch.matmul(self.mel_basis, magnitude) if self.is_half == True: mel_output = mel_output.half() log_mel_spec = torch.log(torch.clamp(mel_output, min=self.clamp)) return log_mel_spec
class RMVPE: def __init__(self, model_path, is_half, device=None): self.resample_kernel = {} model = E2E(4, 1, (2, 2)) ckpt = torch.load(model_path, map_location="cpu") model.load_state_dict(ckpt) model.eval() if is_half == True: model = model.half() self.model = model self.resample_kernel = {} self.is_half = is_half if device is None: device = "cuda" if torch.cuda.is_available() else "cpu" self.device = device self.mel_extractor = MelSpectrogram( is_half, 128, 16000, 1024, 160, None, 30, 8000 ).to(device) self.model = self.model.to(device) cents_mapping = 20 * np.arange(360) + 1997.3794084376191 self.cents_mapping = np.pad(cents_mapping, (4, 4)) # 368
def mel2hidden(self, mel): with torch.no_grad(): n_frames = mel.shape[-1] mel = F.pad( mel, (0, 32 * ((n_frames - 1) // 32 + 1) - n_frames), mode="reflect" ) hidden = self.model(mel) return hidden[:, :n_frames]
def decode(self, hidden, thred=0.03): cents_pred = self.to_local_average_cents(hidden, thred=thred) f0 = 10 * (2 ** (cents_pred / 1200)) f0[f0 == 10] = 0 # f0 = np.array([10 * (2 ** (cent_pred / 1200)) if cent_pred else 0 for cent_pred in cents_pred]) return f0
def infer_from_audio(self, audio, thred=0.03): audio = torch.from_numpy(audio).float().to(self.device).unsqueeze(0) # torch.cuda.synchronize() # t0=ttime() mel = self.mel_extractor(audio, center=True) # torch.cuda.synchronize() # t1=ttime() hidden = self.mel2hidden(mel) # torch.cuda.synchronize() # t2=ttime() hidden = hidden.squeeze(0).cpu().numpy() if self.is_half == True: hidden = hidden.astype("float32") f0 = self.decode(hidden, thred=thred) # torch.cuda.synchronize() # t3=ttime() # print("hmvpe:%s\t%s\t%s\t%s"%(t1-t0,t2-t1,t3-t2,t3-t0)) return f0
def to_local_average_cents(self, salience, thred=0.05): # t0 = ttime() center = np.argmax(salience, axis=1) # 帧长#index salience = np.pad(salience, ((0, 0), (4, 4))) # 帧长,368 # t1 = ttime() center += 4 todo_salience = [] todo_cents_mapping = [] starts = center - 4 ends = center + 5 for idx in range(salience.shape[0]): todo_salience.append(salience[:, starts[idx] : ends[idx]][idx]) todo_cents_mapping.append(self.cents_mapping[starts[idx] : ends[idx]]) # t2 = ttime() todo_salience = np.array(todo_salience) # 帧长,9 todo_cents_mapping = np.array(todo_cents_mapping) # 帧长,9 product_sum = np.sum(todo_salience * todo_cents_mapping, 1) weight_sum = np.sum(todo_salience, 1) # 帧长 devided = product_sum / weight_sum # 帧长 # t3 = ttime() maxx = np.max(salience, axis=1) # 帧长 devided[maxx <= thred] = 0 # t4 = ttime() # print("decode:%s\t%s\t%s\t%s" % (t1 - t0, t2 - t1, t3 - t2, t4 - t3)) return devided
# if __name__ == '__main__':# audio, sampling_rate = sf.read("卢本伟语录~1.wav")# if len(audio.shape) > 1:# audio = librosa.to_mono(audio.transpose(1, 0))# audio_bak = audio.copy()# if sampling_rate != 16000:# audio = librosa.resample(audio, orig_sr=sampling_rate, target_sr=16000)# model_path = "/bili-coeus/jupyter/jupyterhub-liujing04/vits_ch/test-RMVPE/weights/rmvpe_llc_half.pt"# thred = 0.03 # 0.01# device = 'cuda' if torch.cuda.is_available() else 'cpu'# rmvpe = RMVPE(model_path,is_half=False, device=device)# t0=ttime()# f0 = rmvpe.infer_from_audio(audio, thred=thred)# f0 = rmvpe.infer_from_audio(audio, thred=thred)# f0 = rmvpe.infer_from_audio(audio, thred=thred)# f0 = rmvpe.infer_from_audio(audio, thred=thred)# f0 = rmvpe.infer_from_audio(audio, thred=thred)# t1=ttime()# print(f0.shape,t1-t0)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443import numpy as np, parselmouth, torch, pdb, sys, osfrom time import time as ttimeimport torch.nn.functional as Fimport scipy.signal as signalimport pyworld, os, traceback, faiss, librosa, torchcrepefrom scipy import signalfrom functools import lru_cache
now_dir = os.getcwd()sys.path.append(now_dir)
bh, ah = signal.butter(N=5, Wn=48, btype="high", fs=16000)
input_audio_path2wav = {}
@lru_cachedef cache_harvest_f0(input_audio_path, fs, f0max, f0min, frame_period): audio = input_audio_path2wav[input_audio_path] f0, t = pyworld.harvest( audio, fs=fs, f0_ceil=f0max, f0_floor=f0min, frame_period=frame_period, ) f0 = pyworld.stonemask(audio, f0, t, fs) return f0
def change_rms(data1, sr1, data2, sr2, rate): # 1是输入音频,2是输出音频,rate是2的占比 # print(data1.max(),data2.max()) rms1 = librosa.feature.rms( y=data1, frame_length=sr1 // 2 * 2, hop_length=sr1 // 2 ) # 每半秒一个点 rms2 = librosa.feature.rms(y=data2, frame_length=sr2 // 2 * 2, hop_length=sr2 // 2) rms1 = torch.from_numpy(rms1) rms1 = F.interpolate( rms1.unsqueeze(0), size=data2.shape[0], mode="linear" ).squeeze() rms2 = torch.from_numpy(rms2) rms2 = F.interpolate( rms2.unsqueeze(0), size=data2.shape[0], mode="linear" ).squeeze() rms2 = torch.max(rms2, torch.zeros_like(rms2) + 1e-6) data2 *= ( torch.pow(rms1, torch.tensor(1 - rate)) * torch.pow(rms2, torch.tensor(rate - 1)) ).numpy() return data2
class VC(object): def __init__(self, tgt_sr, config): self.x_pad, self.x_query, self.x_center, self.x_max, self.is_half = ( config.x_pad, config.x_query, config.x_center, config.x_max, config.is_half, ) self.sr = 16000 # hubert输入采样率 self.window = 160 # 每帧点数 self.t_pad = self.sr * self.x_pad # 每条前后pad时间 self.t_pad_tgt = tgt_sr * self.x_pad self.t_pad2 = self.t_pad * 2 self.t_query = self.sr * self.x_query # 查询切点前后查询时间 self.t_center = self.sr * self.x_center # 查询切点位置 self.t_max = self.sr * self.x_max # 免查询时长阈值 self.device = config.device
def get_f0( self, input_audio_path, x, p_len, f0_up_key, f0_method, filter_radius, inp_f0=None, ): global input_audio_path2wav time_step = self.window / self.sr * 1000 f0_min = 50 f0_max = 1100 f0_mel_min = 1127 * np.log(1 + f0_min / 700) f0_mel_max = 1127 * np.log(1 + f0_max / 700) if f0_method == "pm": f0 = ( parselmouth.Sound(x, self.sr) .to_pitch_ac( time_step=time_step / 1000, voicing_threshold=0.6, pitch_floor=f0_min, pitch_ceiling=f0_max, ) .selected_array["frequency"] ) pad_size = (p_len - len(f0) + 1) // 2 if pad_size > 0 or p_len - len(f0) - pad_size > 0: f0 = np.pad( f0, [[pad_size, p_len - len(f0) - pad_size]], mode="constant" ) elif f0_method == "harvest": input_audio_path2wav[input_audio_path] = x.astype(np.double) f0 = cache_harvest_f0(input_audio_path, self.sr, f0_max, f0_min, 10) if filter_radius > 2: f0 = signal.medfilt(f0, 3) elif f0_method == "crepe": model = "full" # Pick a batch size that doesn't cause memory errors on your gpu batch_size = 512 # Compute pitch using first gpu audio = torch.tensor(np.copy(x))[None].float() f0, pd = torchcrepe.predict( audio, self.sr, self.window, f0_min, f0_max, model, batch_size=batch_size, device=self.device, return_periodicity=True, ) pd = torchcrepe.filter.median(pd, 3) f0 = torchcrepe.filter.mean(f0, 3) f0[pd < 0.1] = 0 f0 = f0[0].cpu().numpy() elif f0_method == "rmvpe": if hasattr(self, "model_rmvpe") == False: from rmvpe import RMVPE
print("loading rmvpe model") self.model_rmvpe = RMVPE( "rmvpe.pt", is_half=self.is_half, device=self.device ) f0 = self.model_rmvpe.infer_from_audio(x, thred=0.03) f0 *= pow(2, f0_up_key / 12) # with open("test.txt","w")as f:f.write("\n".join([str(i)for i in f0.tolist()])) tf0 = self.sr // self.window # 每秒f0点数 if inp_f0 is not None: delta_t = np.round( (inp_f0[:, 0].max() - inp_f0[:, 0].min()) * tf0 + 1 ).astype("int16") replace_f0 = np.interp( list(range(delta_t)), inp_f0[:, 0] * 100, inp_f0[:, 1] ) shape = f0[self.x_pad * tf0 : self.x_pad * tf0 + len(replace_f0)].shape[0] f0[self.x_pad * tf0 : self.x_pad * tf0 + len(replace_f0)] = replace_f0[ :shape ] # with open("test_opt.txt","w")as f:f.write("\n".join([str(i)for i in f0.tolist()])) f0bak = f0.copy() f0_mel = 1127 * np.log(1 + f0 / 700) f0_mel[f0_mel > 0] = (f0_mel[f0_mel > 0] - f0_mel_min) * 254 / ( f0_mel_max - f0_mel_min ) + 1 f0_mel[f0_mel <= 1] = 1 f0_mel[f0_mel > 255] = 255 f0_coarse = np.rint(f0_mel).astype(np.int) return f0_coarse, f0bak # 1-0
def vc( self, model, net_g, sid, audio0, pitch, pitchf, times, index, big_npy, index_rate, version, protect, ): # ,file_index,file_big_npy feats = torch.from_numpy(audio0) if self.is_half: feats = feats.half() else: feats = feats.float() if feats.dim() == 2: # double channels feats = feats.mean(-1) assert feats.dim() == 1, feats.dim() feats = feats.view(1, -1) padding_mask = torch.BoolTensor(feats.shape).to(self.device).fill_(False)
inputs = { "source": feats.to(self.device), "padding_mask": padding_mask, "output_layer": 9 if version == "v1" else 12, } t0 = ttime() with torch.no_grad(): logits = model.extract_features(**inputs) feats = model.final_proj(logits[0]) if version == "v1" else logits[0] if protect < 0.5 and pitch != None and pitchf != None: feats0 = feats.clone() if ( isinstance(index, type(None)) == False and isinstance(big_npy, type(None)) == False and index_rate != 0 ): npy = feats[0].cpu().numpy() if self.is_half: npy = npy.astype("float32")
# _, I = index.search(npy, 1) # npy = big_npy[I.squeeze()]
score, ix = index.search(npy, k=8) weight = np.square(1 / score) weight /= weight.sum(axis=1, keepdims=True) npy = np.sum(big_npy[ix] * np.expand_dims(weight, axis=2), axis=1)
if self.is_half: npy = npy.astype("float16") feats = ( torch.from_numpy(npy).unsqueeze(0).to(self.device) * index_rate + (1 - index_rate) * feats )
feats = F.interpolate(feats.permute(0, 2, 1), scale_factor=2).permute(0, 2, 1) if protect < 0.5 and pitch != None and pitchf != None: feats0 = F.interpolate(feats0.permute(0, 2, 1), scale_factor=2).permute( 0, 2, 1 ) t1 = ttime() p_len = audio0.shape[0] // self.window if feats.shape[1] < p_len: p_len = feats.shape[1] if pitch != None and pitchf != None: pitch = pitch[:, :p_len] pitchf = pitchf[:, :p_len]
if protect < 0.5 and pitch != None and pitchf != None: pitchff = pitchf.clone() pitchff[pitchf > 0] = 1 pitchff[pitchf < 1] = protect pitchff = pitchff.unsqueeze(-1) feats = feats * pitchff + feats0 * (1 - pitchff) feats = feats.to(feats0.dtype) p_len = torch.tensor([p_len], device=self.device).long() with torch.no_grad(): if pitch != None and pitchf != None: audio1 = ( (net_g.infer(feats, p_len, pitch, pitchf, sid)[0][0, 0]) .data.cpu() .float() .numpy() ) else: audio1 = ( (net_g.infer(feats, p_len, sid)[0][0, 0]).data.cpu().float().numpy() ) del feats, p_len, padding_mask if torch.cuda.is_available(): torch.cuda.empty_cache() t2 = ttime() times[0] += t1 - t0 times[2] += t2 - t1 return audio1
def pipeline( self, model, net_g, sid, audio, input_audio_path, times, f0_up_key, f0_method, file_index, # file_big_npy, index_rate, if_f0, filter_radius, tgt_sr, resample_sr, rms_mix_rate, version, protect, f0_file=None, ): if ( file_index != "" # and file_big_npy != "" # and os.path.exists(file_big_npy) == True and os.path.exists(file_index) == True and index_rate != 0 ): try: index = faiss.read_index(file_index) # big_npy = np.load(file_big_npy) big_npy = index.reconstruct_n(0, index.ntotal) except: traceback.print_exc() index = big_npy = None else: index = big_npy = None audio = signal.filtfilt(bh, ah, audio) audio_pad = np.pad(audio, (self.window // 2, self.window // 2), mode="reflect") opt_ts = [] if audio_pad.shape[0] > self.t_max: audio_sum = np.zeros_like(audio) for i in range(self.window): audio_sum += audio_pad[i : i - self.window] for t in range(self.t_center, audio.shape[0], self.t_center): opt_ts.append( t - self.t_query + np.where( np.abs(audio_sum[t - self.t_query : t + self.t_query]) == np.abs(audio_sum[t - self.t_query : t + self.t_query]).min() )[0][0] ) s = 0 audio_opt = [] t = None t1 = ttime() audio_pad = np.pad(audio, (self.t_pad, self.t_pad), mode="reflect") p_len = audio_pad.shape[0] // self.window inp_f0 = None if hasattr(f0_file, "name") == True: try: with open(f0_file.name, "r") as f: lines = f.read().strip("\n").split("\n") inp_f0 = [] for line in lines: inp_f0.append([float(i) for i in line.split(",")]) inp_f0 = np.array(inp_f0, dtype="float32") except: traceback.print_exc() sid = torch.tensor(sid, device=self.device).unsqueeze(0).long() pitch, pitchf = None, None if if_f0 == 1: pitch, pitchf = self.get_f0( input_audio_path, audio_pad, p_len, f0_up_key, f0_method, filter_radius, inp_f0, ) pitch = pitch[:p_len] pitchf = pitchf[:p_len] if self.device == "mps": pitchf = pitchf.astype(np.float32) pitch = torch.tensor(pitch, device=self.device).unsqueeze(0).long() pitchf = torch.tensor(pitchf, device=self.device).unsqueeze(0).float() t2 = ttime() times[1] += t2 - t1 for t in opt_ts: t = t // self.window * self.window if if_f0 == 1: audio_opt.append( self.vc( model, net_g, sid, audio_pad[s : t + self.t_pad2 + self.window], pitch[:, s // self.window : (t + self.t_pad2) // self.window], pitchf[:, s // self.window : (t + self.t_pad2) // self.window], times, index, big_npy, index_rate, version, protect, )[self.t_pad_tgt : -self.t_pad_tgt] ) else: audio_opt.append( self.vc( model, net_g, sid, audio_pad[s : t + self.t_pad2 + self.window], None, None, times, index, big_npy, index_rate, version, protect, )[self.t_pad_tgt : -self.t_pad_tgt] ) s = t if if_f0 == 1: audio_opt.append( self.vc( model, net_g, sid, audio_pad[t:], pitch[:, t // self.window :] if t is not None else pitch, pitchf[:, t // self.window :] if t is not None else pitchf, times, index, big_npy, index_rate, version, protect, )[self.t_pad_tgt : -self.t_pad_tgt] ) else: audio_opt.append( self.vc( model, net_g, sid, audio_pad[t:], None, None, times, index, big_npy, index_rate, version, protect, )[self.t_pad_tgt : -self.t_pad_tgt] ) audio_opt = np.concatenate(audio_opt) if rms_mix_rate != 1: audio_opt = change_rms(audio, 16000, audio_opt, tgt_sr, rms_mix_rate) if resample_sr >= 16000 and tgt_sr != resample_sr: audio_opt = librosa.resample( audio_opt, orig_sr=tgt_sr, target_sr=resample_sr ) audio_max = np.abs(audio_opt).max() / 0.99 max_int16 = 32768 if audio_max > 1: max_int16 /= audio_max audio_opt = (audio_opt * max_int16).astype(np.int16) del pitch, pitchf, sid if torch.cuda.is_available(): torch.cuda.empty_cache() return audio_optLICENSEAdded+21
config.pyAdded+96
infer.pyAdded+942
requirements.txtAdded+25
rmvpe.pyAdded+432
vc_infer_pipeline.pyAdded+443