MrMocci commited on
Commit
12896c9
1 Parent(s): 62c0766

Upload 4 files

Browse files
Files changed (4) hide show
  1. app.py +676 -0
  2. config.py +23 -30
  3. rmvpe.py +432 -0
  4. vc_infer_pipeline.py +13 -1
app.py ADDED
@@ -0,0 +1,676 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import glob
3
+ import json
4
+ import traceback
5
+ import logging
6
+ import gradio as gr
7
+ import numpy as np
8
+ import librosa
9
+ import torch
10
+ import asyncio
11
+ import edge_tts
12
+ import yt_dlp
13
+ import ffmpeg
14
+ import subprocess
15
+ import sys
16
+ import io
17
+ import wave
18
+ from datetime import datetime
19
+ from fairseq import checkpoint_utils
20
+ from lib.infer_pack.models import (
21
+ SynthesizerTrnMs256NSFsid,
22
+ SynthesizerTrnMs256NSFsid_nono,
23
+ SynthesizerTrnMs768NSFsid,
24
+ SynthesizerTrnMs768NSFsid_nono,
25
+ )
26
+ from vc_infer_pipeline import VC
27
+ from config import Config
28
+ config = Config()
29
+ logging.getLogger("numba").setLevel(logging.WARNING)
30
+ spaces = os.getenv("SYSTEM") == "spaces"
31
+ force_support = None
32
+ if config.unsupported is False:
33
+ if config.device == "mps" or config.device == "cpu":
34
+ force_support = False
35
+ else:
36
+ force_support = True
37
+
38
+ audio_mode = []
39
+ f0method_mode = []
40
+ f0method_info = ""
41
+
42
+ if force_support is False or spaces is True:
43
+ if spaces is True:
44
+ audio_mode = ["Upload audio", "TTS Audio"]
45
+ else:
46
+ audio_mode = ["Input path", "Upload audio", "TTS Audio"]
47
+ f0method_mode = ["pm", "harvest"]
48
+ f0method_info = "PM is fast, Harvest is good but extremely slow, Rvmpe is alternative to harvest (might be better). (Default: PM)"
49
+ else:
50
+ audio_mode = ["Input path", "Upload audio", "Youtube", "TTS Audio"]
51
+ f0method_mode = ["pm", "harvest", "crepe"]
52
+ 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)"
53
+
54
+ if os.path.isfile("rmvpe.pt"):
55
+ f0method_mode.insert(2, "rmvpe")
56
+
57
+ def create_vc_fn(model_name, tgt_sr, net_g, vc, if_f0, version, file_index):
58
+ def vc_fn(
59
+ vc_audio_mode,
60
+ vc_input,
61
+ vc_upload,
62
+ tts_text,
63
+ tts_voice,
64
+ f0_up_key,
65
+ f0_method,
66
+ index_rate,
67
+ filter_radius,
68
+ resample_sr,
69
+ rms_mix_rate,
70
+ protect,
71
+ ):
72
+ try:
73
+ logs = []
74
+ print(f"Converting using {model_name}...")
75
+ logs.append(f"Converting using {model_name}...")
76
+ yield "\n".join(logs), None
77
+ if vc_audio_mode == "Input path" or "Youtube" and vc_input != "":
78
+ audio, sr = librosa.load(vc_input, sr=16000, mono=True)
79
+ elif vc_audio_mode == "Upload audio":
80
+ if vc_upload is None:
81
+ return "You need to upload an audio", None
82
+ sampling_rate, audio = vc_upload
83
+ duration = audio.shape[0] / sampling_rate
84
+ if duration > 20 and spaces:
85
+ return "Please upload an audio file that is less than 20 seconds. If you need to generate a longer audio file, please use Colab.", None
86
+ audio = (audio / np.iinfo(audio.dtype).max).astype(np.float32)
87
+ if len(audio.shape) > 1:
88
+ audio = librosa.to_mono(audio.transpose(1, 0))
89
+ if sampling_rate != 16000:
90
+ audio = librosa.resample(audio, orig_sr=sampling_rate, target_sr=16000)
91
+ elif vc_audio_mode == "TTS Audio":
92
+ if len(tts_text) > 100 and spaces:
93
+ return "Text is too long", None
94
+ if tts_text is None or tts_voice is None:
95
+ return "You need to enter text and select a voice", None
96
+ asyncio.run(edge_tts.Communicate(tts_text, "-".join(tts_voice.split('-')[:-1])).save("tts.mp3"))
97
+ audio, sr = librosa.load("tts.mp3", sr=16000, mono=True)
98
+ vc_input = "tts.mp3"
99
+ times = [0, 0, 0]
100
+ f0_up_key = int(f0_up_key)
101
+ audio_opt = vc.pipeline(
102
+ hubert_model,
103
+ net_g,
104
+ 0,
105
+ audio,
106
+ vc_input,
107
+ times,
108
+ f0_up_key,
109
+ f0_method,
110
+ file_index,
111
+ # file_big_npy,
112
+ index_rate,
113
+ if_f0,
114
+ filter_radius,
115
+ tgt_sr,
116
+ resample_sr,
117
+ rms_mix_rate,
118
+ version,
119
+ protect,
120
+ f0_file=None,
121
+ )
122
+ info = f"[{datetime.now().strftime('%Y-%m-%d %H:%M')}]: npy: {times[0]}, f0: {times[1]}s, infer: {times[2]}s"
123
+ print(f"{model_name} | {info}")
124
+ logs.append(f"Successfully Convert {model_name}\n{info}")
125
+ yield "\n".join(logs), (tgt_sr, audio_opt)
126
+ except:
127
+ info = traceback.format_exc()
128
+ print(info)
129
+ yield info, None
130
+ return vc_fn
131
+
132
+ def load_model():
133
+ categories = []
134
+ if os.path.isfile("weights/folder_info.json"):
135
+ with open("weights/folder_info.json", "r", encoding="utf-8") as f:
136
+ folder_info = json.load(f)
137
+ for category_name, category_info in folder_info.items():
138
+ if not category_info['enable']:
139
+ continue
140
+ category_title = category_info['title']
141
+ category_folder = category_info['folder_path']
142
+ description = category_info['description']
143
+ models = []
144
+ with open(f"weights/{category_folder}/model_info.json", "r", encoding="utf-8") as f:
145
+ models_info = json.load(f)
146
+ for character_name, info in models_info.items():
147
+ if not info['enable']:
148
+ continue
149
+ model_title = info['title']
150
+ model_name = info['model_path']
151
+ model_author = info.get("author", None)
152
+ model_cover = f"weights/{category_folder}/{character_name}/{info['cover']}"
153
+ model_index = f"weights/{category_folder}/{character_name}/{info['feature_retrieval_library']}"
154
+ cpt = torch.load(f"weights/{category_folder}/{character_name}/{model_name}", map_location="cpu")
155
+ tgt_sr = cpt["config"][-1]
156
+ cpt["config"][-3] = cpt["weight"]["emb_g.weight"].shape[0] # n_spk
157
+ if_f0 = cpt.get("f0", 1)
158
+ version = cpt.get("version", "v1")
159
+ if version == "v1":
160
+ if if_f0 == 1:
161
+ net_g = SynthesizerTrnMs256NSFsid(*cpt["config"], is_half=config.is_half)
162
+ else:
163
+ net_g = SynthesizerTrnMs256NSFsid_nono(*cpt["config"])
164
+ model_version = "V1"
165
+ elif version == "v2":
166
+ if if_f0 == 1:
167
+ net_g = SynthesizerTrnMs768NSFsid(*cpt["config"], is_half=config.is_half)
168
+ else:
169
+ net_g = SynthesizerTrnMs768NSFsid_nono(*cpt["config"])
170
+ model_version = "V2"
171
+ del net_g.enc_q
172
+ print(net_g.load_state_dict(cpt["weight"], strict=False))
173
+ net_g.eval().to(config.device)
174
+ if config.is_half:
175
+ net_g = net_g.half()
176
+ else:
177
+ net_g = net_g.float()
178
+ vc = VC(tgt_sr, config)
179
+ print(f"Model loaded: {character_name} / {info['feature_retrieval_library']} | ({model_version})")
180
+ models.append((character_name, model_title, model_author, model_cover, model_version, create_vc_fn(model_name, tgt_sr, net_g, vc, if_f0, version, model_index)))
181
+ categories.append([category_title, category_folder, description, models])
182
+ else:
183
+ categories = []
184
+ return categories
185
+
186
+ def download_audio(url, audio_provider):
187
+ logs = []
188
+ if url == "":
189
+ raise gr.Error("URL Required!")
190
+ return "URL Required"
191
+ if not os.path.exists("dl_audio"):
192
+ os.mkdir("dl_audio")
193
+ if audio_provider == "Youtube":
194
+ logs.append("Downloading the audio...")
195
+ yield None, "\n".join(logs)
196
+ ydl_opts = {
197
+ 'noplaylist': True,
198
+ 'format': 'bestaudio/best',
199
+ 'postprocessors': [{
200
+ 'key': 'FFmpegExtractAudio',
201
+ 'preferredcodec': 'wav',
202
+ }],
203
+ "outtmpl": 'dl_audio/audio',
204
+ }
205
+ audio_path = "dl_audio/audio.wav"
206
+ with yt_dlp.YoutubeDL(ydl_opts) as ydl:
207
+ ydl.download([url])
208
+ logs.append("Download Complete.")
209
+ yield audio_path, "\n".join(logs)
210
+
211
+ def cut_vocal_and_inst(split_model):
212
+ logs = []
213
+ logs.append("Starting the audio splitting process...")
214
+ yield "\n".join(logs), None, None, None, None
215
+ command = f"demucs --two-stems=vocals -n {split_model} dl_audio/audio.wav -o output"
216
+ result = subprocess.Popen(command.split(), stdout=subprocess.PIPE, text=True)
217
+ for line in result.stdout:
218
+ logs.append(line)
219
+ yield "\n".join(logs), None, None, None, None
220
+ print(result.stdout)
221
+ vocal = f"output/{split_model}/audio/vocals.wav"
222
+ inst = f"output/{split_model}/audio/no_vocals.wav"
223
+ logs.append("Audio splitting complete.")
224
+ yield "\n".join(logs), vocal, inst, vocal
225
+
226
+ def combine_vocal_and_inst(audio_data, vocal_volume, inst_volume, split_model):
227
+ if not os.path.exists("output/result"):
228
+ os.mkdir("output/result")
229
+ vocal_path = "output/result/output.wav"
230
+ output_path = "output/result/combine.mp3"
231
+ inst_path = f"output/{split_model}/audio/no_vocals.wav"
232
+ with wave.open(vocal_path, "w") as wave_file:
233
+ wave_file.setnchannels(1)
234
+ wave_file.setsampwidth(2)
235
+ wave_file.setframerate(audio_data[0])
236
+ wave_file.writeframes(audio_data[1].tobytes())
237
+ 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}'
238
+ result = subprocess.run(command.split(), stdout=subprocess.PIPE)
239
+ print(result.stdout.decode())
240
+ return output_path
241
+
242
+ def load_hubert():
243
+ global hubert_model
244
+ models, _, _ = checkpoint_utils.load_model_ensemble_and_task(
245
+ ["hubert_base.pt"],
246
+ suffix="",
247
+ )
248
+ hubert_model = models[0]
249
+ hubert_model = hubert_model.to(config.device)
250
+ if config.is_half:
251
+ hubert_model = hubert_model.half()
252
+ else:
253
+ hubert_model = hubert_model.float()
254
+ hubert_model.eval()
255
+
256
+ def change_audio_mode(vc_audio_mode):
257
+ if vc_audio_mode == "Input path":
258
+ return (
259
+ # Input & Upload
260
+ gr.Textbox.update(visible=True),
261
+ gr.Checkbox.update(visible=False),
262
+ gr.Audio.update(visible=False),
263
+ # Youtube
264
+ gr.Dropdown.update(visible=False),
265
+ gr.Textbox.update(visible=False),
266
+ gr.Textbox.update(visible=False),
267
+ gr.Button.update(visible=False),
268
+ # Splitter
269
+ gr.Dropdown.update(visible=False),
270
+ gr.Textbox.update(visible=False),
271
+ gr.Button.update(visible=False),
272
+ gr.Audio.update(visible=False),
273
+ gr.Audio.update(visible=False),
274
+ gr.Audio.update(visible=False),
275
+ gr.Slider.update(visible=False),
276
+ gr.Slider.update(visible=False),
277
+ gr.Audio.update(visible=False),
278
+ gr.Button.update(visible=False),
279
+ # TTS
280
+ gr.Textbox.update(visible=False),
281
+ gr.Dropdown.update(visible=False)
282
+ )
283
+ elif vc_audio_mode == "Upload audio":
284
+ return (
285
+ # Input & Upload
286
+ gr.Textbox.update(visible=False),
287
+ gr.Checkbox.update(visible=True),
288
+ gr.Audio.update(visible=True),
289
+ # Youtube
290
+ gr.Dropdown.update(visible=False),
291
+ gr.Textbox.update(visible=False),
292
+ gr.Textbox.update(visible=False),
293
+ gr.Button.update(visible=False),
294
+ # Splitter
295
+ gr.Dropdown.update(visible=False),
296
+ gr.Textbox.update(visible=False),
297
+ gr.Button.update(visible=False),
298
+ gr.Audio.update(visible=False),
299
+ gr.Audio.update(visible=False),
300
+ gr.Audio.update(visible=False),
301
+ gr.Slider.update(visible=False),
302
+ gr.Slider.update(visible=False),
303
+ gr.Audio.update(visible=False),
304
+ gr.Button.update(visible=False),
305
+ # TTS
306
+ gr.Textbox.update(visible=False),
307
+ gr.Dropdown.update(visible=False)
308
+ )
309
+ elif vc_audio_mode == "Youtube":
310
+ return (
311
+ # Input & Upload
312
+ gr.Textbox.update(visible=False),
313
+ gr.Checkbox.update(visible=False),
314
+ gr.Audio.update(visible=False),
315
+ # Youtube
316
+ gr.Dropdown.update(visible=True),
317
+ gr.Textbox.update(visible=True),
318
+ gr.Textbox.update(visible=True),
319
+ gr.Button.update(visible=True),
320
+ # Splitter
321
+ gr.Dropdown.update(visible=True),
322
+ gr.Textbox.update(visible=True),
323
+ gr.Button.update(visible=True),
324
+ gr.Audio.update(visible=True),
325
+ gr.Audio.update(visible=True),
326
+ gr.Audio.update(visible=True),
327
+ gr.Slider.update(visible=True),
328
+ gr.Slider.update(visible=True),
329
+ gr.Audio.update(visible=True),
330
+ gr.Button.update(visible=True),
331
+ # TTS
332
+ gr.Textbox.update(visible=False),
333
+ gr.Dropdown.update(visible=False)
334
+ )
335
+ elif vc_audio_mode == "TTS Audio":
336
+ return (
337
+ # Input & Upload
338
+ gr.Textbox.update(visible=False),
339
+ gr.Checkbox.update(visible=False),
340
+ gr.Audio.update(visible=False),
341
+ # Youtube
342
+ gr.Dropdown.update(visible=False),
343
+ gr.Textbox.update(visible=False),
344
+ gr.Textbox.update(visible=False),
345
+ gr.Button.update(visible=False),
346
+ # Splitter
347
+ gr.Dropdown.update(visible=False),
348
+ gr.Textbox.update(visible=False),
349
+ gr.Button.update(visible=False),
350
+ gr.Audio.update(visible=False),
351
+ gr.Audio.update(visible=False),
352
+ gr.Audio.update(visible=False),
353
+ gr.Slider.update(visible=False),
354
+ gr.Slider.update(visible=False),
355
+ gr.Audio.update(visible=False),
356
+ gr.Button.update(visible=False),
357
+ # TTS
358
+ gr.Textbox.update(visible=True),
359
+ gr.Dropdown.update(visible=True)
360
+ )
361
+
362
+ def use_microphone(microphone):
363
+ if microphone == True:
364
+ return gr.Audio.update(source="microphone")
365
+ else:
366
+ return gr.Audio.update(source="upload")
367
+
368
+ if __name__ == '__main__':
369
+ load_hubert()
370
+ categories = load_model()
371
+ tts_voice_list = asyncio.new_event_loop().run_until_complete(edge_tts.list_voices())
372
+ voices = [f"{v['ShortName']}-{v['Gender']}" for v in tts_voice_list]
373
+ with gr.Blocks() as app:
374
+ gr.Markdown(
375
+ "<div align='center'>\n\n"+
376
+ "# Multi Model RVC Inference\n\n"+
377
+ "[![Repository](https://img.shields.io/badge/Github-Multi%20Model%20RVC%20Inference-blue?style=for-the-badge&logo=github)](https://github.com/ArkanDash/Multi-Model-RVC-Inference)\n\n"+
378
+ "</div>"
379
+ )
380
+ if categories == []:
381
+ gr.Markdown(
382
+ "<div align='center'>\n\n"+
383
+ "## No model found, please add the model into weights folder\n\n"+
384
+ "</div>"
385
+ )
386
+ for (folder_title, folder, description, models) in categories:
387
+ with gr.TabItem(folder_title):
388
+ if description:
389
+ gr.Markdown(f"### <center> {description}")
390
+ with gr.Tabs():
391
+ if not models:
392
+ gr.Markdown("# <center> No Model Loaded.")
393
+ gr.Markdown("## <center> Please add the model or fix your model path.")
394
+ continue
395
+ for (name, title, author, cover, model_version, vc_fn) in models:
396
+ with gr.TabItem(name):
397
+ with gr.Row():
398
+ gr.Markdown(
399
+ '<div align="center">'
400
+ f'<div>{title}</div>\n'+
401
+ f'<div>RVC {model_version} Model</div>\n'+
402
+ (f'<div>Model author: {author}</div>' if author else "")+
403
+ (f'<img style="width:auto;height:300px;" src="file/{cover}">' if cover else "")+
404
+ '</div>'
405
+ )
406
+ with gr.Row():
407
+ if spaces is False:
408
+ with gr.TabItem("Input"):
409
+ with gr.Row():
410
+ with gr.Column():
411
+ vc_audio_mode = gr.Dropdown(label="Input voice", choices=audio_mode, allow_custom_value=False, value="Upload audio")
412
+ # Input
413
+ vc_input = gr.Textbox(label="Input audio path", visible=False)
414
+ # Upload
415
+ vc_microphone_mode = gr.Checkbox(label="Use Microphone", value=False, visible=True, interactive=True)
416
+ vc_upload = gr.Audio(label="Upload audio file", source="upload", visible=True, interactive=True)
417
+ # Youtube
418
+ vc_download_audio = gr.Dropdown(label="Provider", choices=["Youtube"], allow_custom_value=False, visible=False, value="Youtube", info="Select provider (Default: Youtube)")
419
+ 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=...")
420
+ vc_log_yt = gr.Textbox(label="Output Information", visible=False, interactive=False)
421
+ vc_download_button = gr.Button("Download Audio", variant="primary", visible=False)
422
+ vc_audio_preview = gr.Audio(label="Audio Preview", visible=False)
423
+ # TTS
424
+ tts_text = gr.Textbox(label="TTS text", info="Text to speech input", visible=False)
425
+ tts_voice = gr.Dropdown(label="Edge-tts speaker", choices=voices, visible=False, allow_custom_value=False, value="en-US-AnaNeural-Female")
426
+ with gr.Column():
427
+ 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=False, value="htdemucs", info="Select the splitter model (Default: htdemucs)")
428
+ vc_split_log = gr.Textbox(label="Output Information", visible=False, interactive=False)
429
+ vc_split = gr.Button("Split Audio", variant="primary", visible=False)
430
+ vc_vocal_preview = gr.Audio(label="Vocal Preview", visible=False)
431
+ vc_inst_preview = gr.Audio(label="Instrumental Preview", visible=False)
432
+ with gr.TabItem("Convert"):
433
+ with gr.Row():
434
+ with gr.Column():
435
+ vc_transform0 = gr.Number(label="Transpose", value=0, info='Type "12" to change from male to female voice. Type "-12" to change female to male voice')
436
+ f0method0 = gr.Radio(
437
+ label="Pitch extraction algorithm",
438
+ info=f0method_info,
439
+ choices=f0method_mode,
440
+ value="pm",
441
+ interactive=True
442
+ )
443
+ index_rate1 = gr.Slider(
444
+ minimum=0,
445
+ maximum=1,
446
+ label="Retrieval feature ratio",
447
+ info="(Default: 0.7)",
448
+ value=0.7,
449
+ interactive=True,
450
+ )
451
+ filter_radius0 = gr.Slider(
452
+ minimum=0,
453
+ maximum=7,
454
+ label="Apply Median Filtering",
455
+ info="The value represents the filter radius and can reduce breathiness.",
456
+ value=3,
457
+ step=1,
458
+ interactive=True,
459
+ )
460
+ resample_sr0 = gr.Slider(
461
+ minimum=0,
462
+ maximum=48000,
463
+ label="Resample the output audio",
464
+ info="Resample the output audio in post-processing to the final sample rate. Set to 0 for no resampling",
465
+ value=0,
466
+ step=1,
467
+ interactive=True,
468
+ )
469
+ rms_mix_rate0 = gr.Slider(
470
+ minimum=0,
471
+ maximum=1,
472
+ label="Volume Envelope",
473
+ 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",
474
+ value=1,
475
+ interactive=True,
476
+ )
477
+ protect0 = gr.Slider(
478
+ minimum=0,
479
+ maximum=0.5,
480
+ label="Voice Protection",
481
+ 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",
482
+ value=0.5,
483
+ step=0.01,
484
+ interactive=True,
485
+ )
486
+ with gr.Column():
487
+ vc_log = gr.Textbox(label="Output Information", interactive=False)
488
+ vc_output = gr.Audio(label="Output Audio", interactive=False)
489
+ vc_convert = gr.Button("Convert", variant="primary")
490
+ vc_vocal_volume = gr.Slider(
491
+ minimum=0,
492
+ maximum=10,
493
+ label="Vocal volume",
494
+ value=1,
495
+ interactive=True,
496
+ step=1,
497
+ info="Adjust vocal volume (Default: 1}",
498
+ visible=False
499
+ )
500
+ vc_inst_volume = gr.Slider(
501
+ minimum=0,
502
+ maximum=10,
503
+ label="Instrument volume",
504
+ value=1,
505
+ interactive=True,
506
+ step=1,
507
+ info="Adjust instrument volume (Default: 1}",
508
+ visible=False
509
+ )
510
+ vc_combined_output = gr.Audio(label="Output Combined Audio", visible=False)
511
+ vc_combine = gr.Button("Combine",variant="primary", visible=False)
512
+ else:
513
+ with gr.Column():
514
+ vc_audio_mode = gr.Dropdown(label="Input voice", choices=audio_mode, allow_custom_value=False, value="Upload audio")
515
+ # Input
516
+ vc_input = gr.Textbox(label="Input audio path", visible=False)
517
+ # Upload
518
+ vc_microphone_mode = gr.Checkbox(label="Use Microphone", value=False, visible=True, interactive=True)
519
+ vc_upload = gr.Audio(label="Upload audio file", source="upload", visible=True, interactive=True)
520
+ # Youtube
521
+ vc_download_audio = gr.Dropdown(label="Provider", choices=["Youtube"], allow_custom_value=False, visible=False, value="Youtube", info="Select provider (Default: Youtube)")
522
+ 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=...")
523
+ vc_log_yt = gr.Textbox(label="Output Information", visible=False, interactive=False)
524
+ vc_download_button = gr.Button("Download Audio", variant="primary", visible=False)
525
+ vc_audio_preview = gr.Audio(label="Audio Preview", visible=False)
526
+ # Splitter
527
+ 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=False, value="htdemucs", info="Select the splitter model (Default: htdemucs)")
528
+ vc_split_log = gr.Textbox(label="Output Information", visible=False, interactive=False)
529
+ vc_split = gr.Button("Split Audio", variant="primary", visible=False)
530
+ vc_vocal_preview = gr.Audio(label="Vocal Preview", visible=False)
531
+ vc_inst_preview = gr.Audio(label="Instrumental Preview", visible=False)
532
+ # TTS
533
+ tts_text = gr.Textbox(label="TTS text", info="Text to speech input", visible=False)
534
+ tts_voice = gr.Dropdown(label="Edge-tts speaker", choices=voices, visible=False, allow_custom_value=False, value="en-US-AnaNeural-Female")
535
+ with gr.Column():
536
+ vc_transform0 = gr.Number(label="Transpose", value=0, info='Type "12" to change from male to female voice. Type "-12" to change female to male voice')
537
+ f0method0 = gr.Radio(
538
+ label="Pitch extraction algorithm",
539
+ info=f0method_info,
540
+ choices=f0method_mode,
541
+ value="pm",
542
+ interactive=True
543
+ )
544
+ index_rate1 = gr.Slider(
545
+ minimum=0,
546
+ maximum=1,
547
+ label="Retrieval feature ratio",
548
+ info="(Default: 0.7)",
549
+ value=0.7,
550
+ interactive=True,
551
+ )
552
+ filter_radius0 = gr.Slider(
553
+ minimum=0,
554
+ maximum=7,
555
+ label="Apply Median Filtering",
556
+ info="The value represents the filter radius and can reduce breathiness.",
557
+ value=3,
558
+ step=1,
559
+ interactive=True,
560
+ )
561
+ resample_sr0 = gr.Slider(
562
+ minimum=0,
563
+ maximum=48000,
564
+ label="Resample the output audio",
565
+ info="Resample the output audio in post-processing to the final sample rate. Set to 0 for no resampling",
566
+ value=0,
567
+ step=1,
568
+ interactive=True,
569
+ )
570
+ rms_mix_rate0 = gr.Slider(
571
+ minimum=0,
572
+ maximum=1,
573
+ label="Volume Envelope",
574
+ 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",
575
+ value=1,
576
+ interactive=True,
577
+ )
578
+ protect0 = gr.Slider(
579
+ minimum=0,
580
+ maximum=0.5,
581
+ label="Voice Protection",
582
+ 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",
583
+ value=0.5,
584
+ step=0.01,
585
+ interactive=True,
586
+ )
587
+ with gr.Column():
588
+ vc_log = gr.Textbox(label="Output Information", interactive=False)
589
+ vc_output = gr.Audio(label="Output Audio", interactive=False)
590
+ vc_convert = gr.Button("Convert", variant="primary")
591
+ vc_vocal_volume = gr.Slider(
592
+ minimum=0,
593
+ maximum=10,
594
+ label="Vocal volume",
595
+ value=1,
596
+ interactive=True,
597
+ step=1,
598
+ info="Adjust vocal volume (Default: 1}",
599
+ visible=False
600
+ )
601
+ vc_inst_volume = gr.Slider(
602
+ minimum=0,
603
+ maximum=10,
604
+ label="Instrument volume",
605
+ value=1,
606
+ interactive=True,
607
+ step=1,
608
+ info="Adjust instrument volume (Default: 1}",
609
+ visible=False
610
+ )
611
+ vc_combined_output = gr.Audio(label="Output Combined Audio", visible=False)
612
+ vc_combine = gr.Button("Combine",variant="primary", visible=False)
613
+ vc_convert.click(
614
+ fn=vc_fn,
615
+ inputs=[
616
+ vc_audio_mode,
617
+ vc_input,
618
+ vc_upload,
619
+ tts_text,
620
+ tts_voice,
621
+ vc_transform0,
622
+ f0method0,
623
+ index_rate1,
624
+ filter_radius0,
625
+ resample_sr0,
626
+ rms_mix_rate0,
627
+ protect0,
628
+ ],
629
+ outputs=[vc_log ,vc_output]
630
+ )
631
+ vc_download_button.click(
632
+ fn=download_audio,
633
+ inputs=[vc_link, vc_download_audio],
634
+ outputs=[vc_audio_preview, vc_log_yt]
635
+ )
636
+ vc_split.click(
637
+ fn=cut_vocal_and_inst,
638
+ inputs=[vc_split_model],
639
+ outputs=[vc_split_log, vc_vocal_preview, vc_inst_preview, vc_input]
640
+ )
641
+ vc_combine.click(
642
+ fn=combine_vocal_and_inst,
643
+ inputs=[vc_output, vc_vocal_volume, vc_inst_volume, vc_split_model],
644
+ outputs=[vc_combined_output]
645
+ )
646
+ vc_microphone_mode.change(
647
+ fn=use_microphone,
648
+ inputs=vc_microphone_mode,
649
+ outputs=vc_upload
650
+ )
651
+ vc_audio_mode.change(
652
+ fn=change_audio_mode,
653
+ inputs=[vc_audio_mode],
654
+ outputs=[
655
+ vc_input,
656
+ vc_microphone_mode,
657
+ vc_upload,
658
+ vc_download_audio,
659
+ vc_link,
660
+ vc_log_yt,
661
+ vc_download_button,
662
+ vc_split_model,
663
+ vc_split_log,
664
+ vc_split,
665
+ vc_audio_preview,
666
+ vc_vocal_preview,
667
+ vc_inst_preview,
668
+ vc_vocal_volume,
669
+ vc_inst_volume,
670
+ vc_combined_output,
671
+ vc_combine,
672
+ tts_text,
673
+ tts_voice
674
+ ]
675
+ )
676
+ app.queue(concurrency_count=1, max_size=20, api_open=config.api).launch(share=config.colab)
config.py CHANGED
@@ -1,4 +1,5 @@
1
  import argparse
 
2
  import torch
3
  from multiprocessing import cpu_count
4
 
@@ -10,45 +11,38 @@ class Config:
10
  self.gpu_name = None
11
  self.gpu_mem = None
12
  (
13
- self.python_cmd,
14
- self.listen_port,
15
  self.colab,
16
- self.noparallel,
17
- self.noautoopen,
18
- self.api
19
  ) = self.arg_parse()
20
  self.x_pad, self.x_query, self.x_center, self.x_max = self.device_config()
21
 
22
  @staticmethod
23
  def arg_parse() -> tuple:
24
  parser = argparse.ArgumentParser()
25
- parser.add_argument("--port", type=int, default=7865, help="Listen port")
26
- parser.add_argument(
27
- "--pycmd", type=str, default="python", help="Python command"
28
- )
29
  parser.add_argument("--colab", action="store_true", help="Launch in colab")
30
- parser.add_argument(
31
- "--noparallel", action="store_true", help="Disable parallel processing"
32
- )
33
- parser.add_argument(
34
- "--noautoopen",
35
- action="store_true",
36
- help="Do not open in browser automatically",
37
- )
38
  parser.add_argument("--api", action="store_true", help="Launch with api")
 
39
  cmd_opts = parser.parse_args()
40
 
41
- cmd_opts.port = cmd_opts.port if 0 <= cmd_opts.port <= 65535 else 7865
42
-
43
  return (
44
- cmd_opts.pycmd,
45
- cmd_opts.port,
46
  cmd_opts.colab,
47
- cmd_opts.noparallel,
48
- cmd_opts.noautoopen,
49
- cmd_opts.api
50
  )
51
 
 
 
 
 
 
 
 
 
 
 
 
 
52
  def device_config(self) -> tuple:
53
  if torch.cuda.is_available():
54
  i_device = int(self.device.split(":")[-1])
@@ -60,11 +54,10 @@ class Config:
60
  or "1070" in self.gpu_name
61
  or "1080" in self.gpu_name
62
  ):
63
- print("16系/10系显卡和P40强制单精度")
64
  self.is_half = False
65
-
66
  else:
67
- self.gpu_name = None
68
  self.gpu_mem = int(
69
  torch.cuda.get_device_properties(i_device).total_memory
70
  / 1024
@@ -72,12 +65,12 @@ class Config:
72
  / 1024
73
  + 0.4
74
  )
75
- elif torch.backends.mps.is_available():
76
- print("没有发现支持的N卡, 使用MPS进行推理")
77
  self.device = "mps"
78
  self.is_half = False
79
  else:
80
- print("没有发现支持的N卡, 使用CPU进行推理")
81
  self.device = "cpu"
82
  self.is_half = False
83
 
 
1
  import argparse
2
+ import sys
3
  import torch
4
  from multiprocessing import cpu_count
5
 
 
11
  self.gpu_name = None
12
  self.gpu_mem = None
13
  (
 
 
14
  self.colab,
15
+ self.api,
16
+ self.unsupported
 
17
  ) = self.arg_parse()
18
  self.x_pad, self.x_query, self.x_center, self.x_max = self.device_config()
19
 
20
  @staticmethod
21
  def arg_parse() -> tuple:
22
  parser = argparse.ArgumentParser()
 
 
 
 
23
  parser.add_argument("--colab", action="store_true", help="Launch in colab")
 
 
 
 
 
 
 
 
24
  parser.add_argument("--api", action="store_true", help="Launch with api")
25
+ parser.add_argument("--unsupported", action="store_true", help="Enable unsupported feature")
26
  cmd_opts = parser.parse_args()
27
 
 
 
28
  return (
 
 
29
  cmd_opts.colab,
30
+ cmd_opts.api,
31
+ cmd_opts.unsupported
 
32
  )
33
 
34
+ # has_mps is only available in nightly pytorch (for now) and MasOS 12.3+.
35
+ # check `getattr` and try it for compatibility
36
+ @staticmethod
37
+ def has_mps() -> bool:
38
+ if not torch.backends.mps.is_available():
39
+ return False
40
+ try:
41
+ torch.zeros(1).to(torch.device("mps"))
42
+ return True
43
+ except Exception:
44
+ return False
45
+
46
  def device_config(self) -> tuple:
47
  if torch.cuda.is_available():
48
  i_device = int(self.device.split(":")[-1])
 
54
  or "1070" in self.gpu_name
55
  or "1080" in self.gpu_name
56
  ):
57
+ print("INFO: Found GPU", self.gpu_name, ", force to fp32")
58
  self.is_half = False
 
59
  else:
60
+ print("INFO: Found GPU", self.gpu_name)
61
  self.gpu_mem = int(
62
  torch.cuda.get_device_properties(i_device).total_memory
63
  / 1024
 
65
  / 1024
66
  + 0.4
67
  )
68
+ elif self.has_mps():
69
+ print("INFO: No supported Nvidia GPU found, use MPS instead")
70
  self.device = "mps"
71
  self.is_half = False
72
  else:
73
+ print("INFO: No supported Nvidia GPU found, use CPU instead")
74
  self.device = "cpu"
75
  self.is_half = False
76
 
rmvpe.py ADDED
@@ -0,0 +1,432 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys, torch, numpy as np, traceback, pdb
2
+ import torch.nn as nn
3
+ from time import time as ttime
4
+ import torch.nn.functional as F
5
+
6
+
7
+ class BiGRU(nn.Module):
8
+ def __init__(self, input_features, hidden_features, num_layers):
9
+ super(BiGRU, self).__init__()
10
+ self.gru = nn.GRU(
11
+ input_features,
12
+ hidden_features,
13
+ num_layers=num_layers,
14
+ batch_first=True,
15
+ bidirectional=True,
16
+ )
17
+
18
+ def forward(self, x):
19
+ return self.gru(x)[0]
20
+
21
+
22
+ class ConvBlockRes(nn.Module):
23
+ def __init__(self, in_channels, out_channels, momentum=0.01):
24
+ super(ConvBlockRes, self).__init__()
25
+ self.conv = nn.Sequential(
26
+ nn.Conv2d(
27
+ in_channels=in_channels,
28
+ out_channels=out_channels,
29
+ kernel_size=(3, 3),
30
+ stride=(1, 1),
31
+ padding=(1, 1),
32
+ bias=False,
33
+ ),
34
+ nn.BatchNorm2d(out_channels, momentum=momentum),
35
+ nn.ReLU(),
36
+ nn.Conv2d(
37
+ in_channels=out_channels,
38
+ out_channels=out_channels,
39
+ kernel_size=(3, 3),
40
+ stride=(1, 1),
41
+ padding=(1, 1),
42
+ bias=False,
43
+ ),
44
+ nn.BatchNorm2d(out_channels, momentum=momentum),
45
+ nn.ReLU(),
46
+ )
47
+ if in_channels != out_channels:
48
+ self.shortcut = nn.Conv2d(in_channels, out_channels, (1, 1))
49
+ self.is_shortcut = True
50
+ else:
51
+ self.is_shortcut = False
52
+
53
+ def forward(self, x):
54
+ if self.is_shortcut:
55
+ return self.conv(x) + self.shortcut(x)
56
+ else:
57
+ return self.conv(x) + x
58
+
59
+
60
+ class Encoder(nn.Module):
61
+ def __init__(
62
+ self,
63
+ in_channels,
64
+ in_size,
65
+ n_encoders,
66
+ kernel_size,
67
+ n_blocks,
68
+ out_channels=16,
69
+ momentum=0.01,
70
+ ):
71
+ super(Encoder, self).__init__()
72
+ self.n_encoders = n_encoders
73
+ self.bn = nn.BatchNorm2d(in_channels, momentum=momentum)
74
+ self.layers = nn.ModuleList()
75
+ self.latent_channels = []
76
+ for i in range(self.n_encoders):
77
+ self.layers.append(
78
+ ResEncoderBlock(
79
+ in_channels, out_channels, kernel_size, n_blocks, momentum=momentum
80
+ )
81
+ )
82
+ self.latent_channels.append([out_channels, in_size])
83
+ in_channels = out_channels
84
+ out_channels *= 2
85
+ in_size //= 2
86
+ self.out_size = in_size
87
+ self.out_channel = out_channels
88
+
89
+ def forward(self, x):
90
+ concat_tensors = []
91
+ x = self.bn(x)
92
+ for i in range(self.n_encoders):
93
+ _, x = self.layers[i](x)
94
+ concat_tensors.append(_)
95
+ return x, concat_tensors
96
+
97
+
98
+ class ResEncoderBlock(nn.Module):
99
+ def __init__(
100
+ self, in_channels, out_channels, kernel_size, n_blocks=1, momentum=0.01
101
+ ):
102
+ super(ResEncoderBlock, self).__init__()
103
+ self.n_blocks = n_blocks
104
+ self.conv = nn.ModuleList()
105
+ self.conv.append(ConvBlockRes(in_channels, out_channels, momentum))
106
+ for i in range(n_blocks - 1):
107
+ self.conv.append(ConvBlockRes(out_channels, out_channels, momentum))
108
+ self.kernel_size = kernel_size
109
+ if self.kernel_size is not None:
110
+ self.pool = nn.AvgPool2d(kernel_size=kernel_size)
111
+
112
+ def forward(self, x):
113
+ for i in range(self.n_blocks):
114
+ x = self.conv[i](x)
115
+ if self.kernel_size is not None:
116
+ return x, self.pool(x)
117
+ else:
118
+ return x
119
+
120
+
121
+ class Intermediate(nn.Module): #
122
+ def __init__(self, in_channels, out_channels, n_inters, n_blocks, momentum=0.01):
123
+ super(Intermediate, self).__init__()
124
+ self.n_inters = n_inters
125
+ self.layers = nn.ModuleList()
126
+ self.layers.append(
127
+ ResEncoderBlock(in_channels, out_channels, None, n_blocks, momentum)
128
+ )
129
+ for i in range(self.n_inters - 1):
130
+ self.layers.append(
131
+ ResEncoderBlock(out_channels, out_channels, None, n_blocks, momentum)
132
+ )
133
+
134
+ def forward(self, x):
135
+ for i in range(self.n_inters):
136
+ x = self.layers[i](x)
137
+ return x
138
+
139
+
140
+ class ResDecoderBlock(nn.Module):
141
+ def __init__(self, in_channels, out_channels, stride, n_blocks=1, momentum=0.01):
142
+ super(ResDecoderBlock, self).__init__()
143
+ out_padding = (0, 1) if stride == (1, 2) else (1, 1)
144
+ self.n_blocks = n_blocks
145
+ self.conv1 = nn.Sequential(
146
+ nn.ConvTranspose2d(
147
+ in_channels=in_channels,
148
+ out_channels=out_channels,
149
+ kernel_size=(3, 3),
150
+ stride=stride,
151
+ padding=(1, 1),
152
+ output_padding=out_padding,
153
+ bias=False,
154
+ ),
155
+ nn.BatchNorm2d(out_channels, momentum=momentum),
156
+ nn.ReLU(),
157
+ )
158
+ self.conv2 = nn.ModuleList()
159
+ self.conv2.append(ConvBlockRes(out_channels * 2, out_channels, momentum))
160
+ for i in range(n_blocks - 1):
161
+ self.conv2.append(ConvBlockRes(out_channels, out_channels, momentum))
162
+
163
+ def forward(self, x, concat_tensor):
164
+ x = self.conv1(x)
165
+ x = torch.cat((x, concat_tensor), dim=1)
166
+ for i in range(self.n_blocks):
167
+ x = self.conv2[i](x)
168
+ return x
169
+
170
+
171
+ class Decoder(nn.Module):
172
+ def __init__(self, in_channels, n_decoders, stride, n_blocks, momentum=0.01):
173
+ super(Decoder, self).__init__()
174
+ self.layers = nn.ModuleList()
175
+ self.n_decoders = n_decoders
176
+ for i in range(self.n_decoders):
177
+ out_channels = in_channels // 2
178
+ self.layers.append(
179
+ ResDecoderBlock(in_channels, out_channels, stride, n_blocks, momentum)
180
+ )
181
+ in_channels = out_channels
182
+
183
+ def forward(self, x, concat_tensors):
184
+ for i in range(self.n_decoders):
185
+ x = self.layers[i](x, concat_tensors[-1 - i])
186
+ return x
187
+
188
+
189
+ class DeepUnet(nn.Module):
190
+ def __init__(
191
+ self,
192
+ kernel_size,
193
+ n_blocks,
194
+ en_de_layers=5,
195
+ inter_layers=4,
196
+ in_channels=1,
197
+ en_out_channels=16,
198
+ ):
199
+ super(DeepUnet, self).__init__()
200
+ self.encoder = Encoder(
201
+ in_channels, 128, en_de_layers, kernel_size, n_blocks, en_out_channels
202
+ )
203
+ self.intermediate = Intermediate(
204
+ self.encoder.out_channel // 2,
205
+ self.encoder.out_channel,
206
+ inter_layers,
207
+ n_blocks,
208
+ )
209
+ self.decoder = Decoder(
210
+ self.encoder.out_channel, en_de_layers, kernel_size, n_blocks
211
+ )
212
+
213
+ def forward(self, x):
214
+ x, concat_tensors = self.encoder(x)
215
+ x = self.intermediate(x)
216
+ x = self.decoder(x, concat_tensors)
217
+ return x
218
+
219
+
220
+ class E2E(nn.Module):
221
+ def __init__(
222
+ self,
223
+ n_blocks,
224
+ n_gru,
225
+ kernel_size,
226
+ en_de_layers=5,
227
+ inter_layers=4,
228
+ in_channels=1,
229
+ en_out_channels=16,
230
+ ):
231
+ super(E2E, self).__init__()
232
+ self.unet = DeepUnet(
233
+ kernel_size,
234
+ n_blocks,
235
+ en_de_layers,
236
+ inter_layers,
237
+ in_channels,
238
+ en_out_channels,
239
+ )
240
+ self.cnn = nn.Conv2d(en_out_channels, 3, (3, 3), padding=(1, 1))
241
+ if n_gru:
242
+ self.fc = nn.Sequential(
243
+ BiGRU(3 * 128, 256, n_gru),
244
+ nn.Linear(512, 360),
245
+ nn.Dropout(0.25),
246
+ nn.Sigmoid(),
247
+ )
248
+ else:
249
+ self.fc = nn.Sequential(
250
+ nn.Linear(3 * N_MELS, N_CLASS), nn.Dropout(0.25), nn.Sigmoid()
251
+ )
252
+
253
+ def forward(self, mel):
254
+ mel = mel.transpose(-1, -2).unsqueeze(1)
255
+ x = self.cnn(self.unet(mel)).transpose(1, 2).flatten(-2)
256
+ x = self.fc(x)
257
+ return x
258
+
259
+
260
+ from librosa.filters import mel
261
+
262
+
263
+ class MelSpectrogram(torch.nn.Module):
264
+ def __init__(
265
+ self,
266
+ is_half,
267
+ n_mel_channels,
268
+ sampling_rate,
269
+ win_length,
270
+ hop_length,
271
+ n_fft=None,
272
+ mel_fmin=0,
273
+ mel_fmax=None,
274
+ clamp=1e-5,
275
+ ):
276
+ super().__init__()
277
+ n_fft = win_length if n_fft is None else n_fft
278
+ self.hann_window = {}
279
+ mel_basis = mel(
280
+ sr=sampling_rate,
281
+ n_fft=n_fft,
282
+ n_mels=n_mel_channels,
283
+ fmin=mel_fmin,
284
+ fmax=mel_fmax,
285
+ htk=True,
286
+ )
287
+ mel_basis = torch.from_numpy(mel_basis).float()
288
+ self.register_buffer("mel_basis", mel_basis)
289
+ self.n_fft = win_length if n_fft is None else n_fft
290
+ self.hop_length = hop_length
291
+ self.win_length = win_length
292
+ self.sampling_rate = sampling_rate
293
+ self.n_mel_channels = n_mel_channels
294
+ self.clamp = clamp
295
+ self.is_half = is_half
296
+
297
+ def forward(self, audio, keyshift=0, speed=1, center=True):
298
+ factor = 2 ** (keyshift / 12)
299
+ n_fft_new = int(np.round(self.n_fft * factor))
300
+ win_length_new = int(np.round(self.win_length * factor))
301
+ hop_length_new = int(np.round(self.hop_length * speed))
302
+ keyshift_key = str(keyshift) + "_" + str(audio.device)
303
+ if keyshift_key not in self.hann_window:
304
+ self.hann_window[keyshift_key] = torch.hann_window(win_length_new).to(
305
+ audio.device
306
+ )
307
+ fft = torch.stft(
308
+ audio,
309
+ n_fft=n_fft_new,
310
+ hop_length=hop_length_new,
311
+ win_length=win_length_new,
312
+ window=self.hann_window[keyshift_key],
313
+ center=center,
314
+ return_complex=True,
315
+ )
316
+ magnitude = torch.sqrt(fft.real.pow(2) + fft.imag.pow(2))
317
+ if keyshift != 0:
318
+ size = self.n_fft // 2 + 1
319
+ resize = magnitude.size(1)
320
+ if resize < size:
321
+ magnitude = F.pad(magnitude, (0, 0, 0, size - resize))
322
+ magnitude = magnitude[:, :size, :] * self.win_length / win_length_new
323
+ mel_output = torch.matmul(self.mel_basis, magnitude)
324
+ if self.is_half == True:
325
+ mel_output = mel_output.half()
326
+ log_mel_spec = torch.log(torch.clamp(mel_output, min=self.clamp))
327
+ return log_mel_spec
328
+
329
+
330
+ class RMVPE:
331
+ def __init__(self, model_path, is_half, device=None):
332
+ self.resample_kernel = {}
333
+ model = E2E(4, 1, (2, 2))
334
+ ckpt = torch.load(model_path, map_location="cpu")
335
+ model.load_state_dict(ckpt)
336
+ model.eval()
337
+ if is_half == True:
338
+ model = model.half()
339
+ self.model = model
340
+ self.resample_kernel = {}
341
+ self.is_half = is_half
342
+ if device is None:
343
+ device = "cuda" if torch.cuda.is_available() else "cpu"
344
+ self.device = device
345
+ self.mel_extractor = MelSpectrogram(
346
+ is_half, 128, 16000, 1024, 160, None, 30, 8000
347
+ ).to(device)
348
+ self.model = self.model.to(device)
349
+ cents_mapping = 20 * np.arange(360) + 1997.3794084376191
350
+ self.cents_mapping = np.pad(cents_mapping, (4, 4)) # 368
351
+
352
+ def mel2hidden(self, mel):
353
+ with torch.no_grad():
354
+ n_frames = mel.shape[-1]
355
+ mel = F.pad(
356
+ mel, (0, 32 * ((n_frames - 1) // 32 + 1) - n_frames), mode="reflect"
357
+ )
358
+ hidden = self.model(mel)
359
+ return hidden[:, :n_frames]
360
+
361
+ def decode(self, hidden, thred=0.03):
362
+ cents_pred = self.to_local_average_cents(hidden, thred=thred)
363
+ f0 = 10 * (2 ** (cents_pred / 1200))
364
+ f0[f0 == 10] = 0
365
+ # f0 = np.array([10 * (2 ** (cent_pred / 1200)) if cent_pred else 0 for cent_pred in cents_pred])
366
+ return f0
367
+
368
+ def infer_from_audio(self, audio, thred=0.03):
369
+ audio = torch.from_numpy(audio).float().to(self.device).unsqueeze(0)
370
+ # torch.cuda.synchronize()
371
+ # t0=ttime()
372
+ mel = self.mel_extractor(audio, center=True)
373
+ # torch.cuda.synchronize()
374
+ # t1=ttime()
375
+ hidden = self.mel2hidden(mel)
376
+ # torch.cuda.synchronize()
377
+ # t2=ttime()
378
+ hidden = hidden.squeeze(0).cpu().numpy()
379
+ if self.is_half == True:
380
+ hidden = hidden.astype("float32")
381
+ f0 = self.decode(hidden, thred=thred)
382
+ # torch.cuda.synchronize()
383
+ # t3=ttime()
384
+ # print("hmvpe:%s\t%s\t%s\t%s"%(t1-t0,t2-t1,t3-t2,t3-t0))
385
+ return f0
386
+
387
+ def to_local_average_cents(self, salience, thred=0.05):
388
+ # t0 = ttime()
389
+ center = np.argmax(salience, axis=1) # 帧长#index
390
+ salience = np.pad(salience, ((0, 0), (4, 4))) # 帧长,368
391
+ # t1 = ttime()
392
+ center += 4
393
+ todo_salience = []
394
+ todo_cents_mapping = []
395
+ starts = center - 4
396
+ ends = center + 5
397
+ for idx in range(salience.shape[0]):
398
+ todo_salience.append(salience[:, starts[idx] : ends[idx]][idx])
399
+ todo_cents_mapping.append(self.cents_mapping[starts[idx] : ends[idx]])
400
+ # t2 = ttime()
401
+ todo_salience = np.array(todo_salience) # 帧长,9
402
+ todo_cents_mapping = np.array(todo_cents_mapping) # 帧长,9
403
+ product_sum = np.sum(todo_salience * todo_cents_mapping, 1)
404
+ weight_sum = np.sum(todo_salience, 1) # 帧长
405
+ devided = product_sum / weight_sum # 帧长
406
+ # t3 = ttime()
407
+ maxx = np.max(salience, axis=1) # 帧长
408
+ devided[maxx <= thred] = 0
409
+ # t4 = ttime()
410
+ # print("decode:%s\t%s\t%s\t%s" % (t1 - t0, t2 - t1, t3 - t2, t4 - t3))
411
+ return devided
412
+
413
+
414
+ # if __name__ == '__main__':
415
+ # audio, sampling_rate = sf.read("卢本伟语录~1.wav")
416
+ # if len(audio.shape) > 1:
417
+ # audio = librosa.to_mono(audio.transpose(1, 0))
418
+ # audio_bak = audio.copy()
419
+ # if sampling_rate != 16000:
420
+ # audio = librosa.resample(audio, orig_sr=sampling_rate, target_sr=16000)
421
+ # model_path = "/bili-coeus/jupyter/jupyterhub-liujing04/vits_ch/test-RMVPE/weights/rmvpe_llc_half.pt"
422
+ # thred = 0.03 # 0.01
423
+ # device = 'cuda' if torch.cuda.is_available() else 'cpu'
424
+ # rmvpe = RMVPE(model_path,is_half=False, device=device)
425
+ # t0=ttime()
426
+ # f0 = rmvpe.infer_from_audio(audio, thred=thred)
427
+ # f0 = rmvpe.infer_from_audio(audio, thred=thred)
428
+ # f0 = rmvpe.infer_from_audio(audio, thred=thred)
429
+ # f0 = rmvpe.infer_from_audio(audio, thred=thred)
430
+ # f0 = rmvpe.infer_from_audio(audio, thred=thred)
431
+ # t1=ttime()
432
+ # print(f0.shape,t1-t0)
vc_infer_pipeline.py CHANGED
@@ -1,4 +1,4 @@
1
- import numpy as np, parselmouth, torch, pdb
2
  from time import time as ttime
3
  import torch.nn.functional as F
4
  import scipy.signal as signal
@@ -6,6 +6,9 @@ import pyworld, os, traceback, faiss, librosa, torchcrepe
6
  from scipy import signal
7
  from functools import lru_cache
8
 
 
 
 
9
  bh, ah = signal.butter(N=5, Wn=48, btype="high", fs=16000)
10
 
11
  input_audio_path2wav = {}
@@ -124,6 +127,15 @@ class VC(object):
124
  f0 = torchcrepe.filter.mean(f0, 3)
125
  f0[pd < 0.1] = 0
126
  f0 = f0[0].cpu().numpy()
 
 
 
 
 
 
 
 
 
127
  f0 *= pow(2, f0_up_key / 12)
128
  # with open("test.txt","w")as f:f.write("\n".join([str(i)for i in f0.tolist()]))
129
  tf0 = self.sr // self.window # 每秒f0点数
 
1
+ import numpy as np, parselmouth, torch, pdb, sys, os
2
  from time import time as ttime
3
  import torch.nn.functional as F
4
  import scipy.signal as signal
 
6
  from scipy import signal
7
  from functools import lru_cache
8
 
9
+ now_dir = os.getcwd()
10
+ sys.path.append(now_dir)
11
+
12
  bh, ah = signal.butter(N=5, Wn=48, btype="high", fs=16000)
13
 
14
  input_audio_path2wav = {}
 
127
  f0 = torchcrepe.filter.mean(f0, 3)
128
  f0[pd < 0.1] = 0
129
  f0 = f0[0].cpu().numpy()
130
+ elif f0_method == "rmvpe":
131
+ if hasattr(self, "model_rmvpe") == False:
132
+ from rmvpe import RMVPE
133
+
134
+ print("loading rmvpe model")
135
+ self.model_rmvpe = RMVPE(
136
+ "rmvpe.pt", is_half=self.is_half, device=self.device
137
+ )
138
+ f0 = self.model_rmvpe.infer_from_audio(x, thred=0.03)
139
  f0 *= pow(2, f0_up_key / 12)
140
  # with open("test.txt","w")as f:f.write("\n".join([str(i)for i in f0.tolist()]))
141
  tf0 = self.sr // self.window # 每秒f0点数