Faridmaruf commited on
Commit
73ebe1a
1 Parent(s): f94322b

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +513 -0
  2. vc_infer_pipeline.py +431 -0
app.py ADDED
@@ -0,0 +1,513 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ limitation = os.getenv("SYSTEM") == "spaces"
31
+
32
+ audio_mode = []
33
+ f0method_mode = []
34
+ f0method_info = ""
35
+ if limitation is True:
36
+ audio_mode = ["Upload audio", "TTS Audio"]
37
+ f0method_mode = ["pm", "harvest"]
38
+ f0method_info = "PM is fast, Harvest is good but extremely slow. (Default: PM)"
39
+ else:
40
+ audio_mode = ["Input path", "Upload audio", "Youtube", "TTS Audio"]
41
+ f0method_mode = ["pm", "harvest", "crepe"]
42
+ f0method_info = "PM is fast, Harvest is good but extremely slow, and Crepe effect is good but requires GPU (Default: PM)"
43
+
44
+ def create_vc_fn(model_title, tgt_sr, net_g, vc, if_f0, version, file_index):
45
+ def vc_fn(
46
+ vc_audio_mode,
47
+ vc_input,
48
+ vc_upload,
49
+ tts_text,
50
+ tts_voice,
51
+ f0_up_key,
52
+ f0_method,
53
+ index_rate,
54
+ filter_radius,
55
+ resample_sr,
56
+ rms_mix_rate,
57
+ protect,
58
+ ):
59
+ try:
60
+ if vc_audio_mode == "Input path" or "Youtube" and vc_input != "":
61
+ audio, sr = librosa.load(vc_input, sr=16000, mono=True)
62
+ elif vc_audio_mode == "Upload audio":
63
+ if vc_upload is None:
64
+ return "You need to upload an audio", None
65
+ sampling_rate, audio = vc_upload
66
+ duration = audio.shape[0] / sampling_rate
67
+ if duration > 20 and limitation:
68
+ 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
69
+ audio = (audio / np.iinfo(audio.dtype).max).astype(np.float32)
70
+ if len(audio.shape) > 1:
71
+ audio = librosa.to_mono(audio.transpose(1, 0))
72
+ if sampling_rate != 16000:
73
+ audio = librosa.resample(audio, orig_sr=sampling_rate, target_sr=16000)
74
+ elif vc_audio_mode == "TTS Audio":
75
+ if len(tts_text) > 100 and limitation:
76
+ return "Text is too long", None
77
+ if tts_text is None or tts_voice is None:
78
+ return "You need to enter text and select a voice", None
79
+ asyncio.run(edge_tts.Communicate(tts_text, "-".join(tts_voice.split('-')[:-1])).save("tts.mp3"))
80
+ audio, sr = librosa.load("tts.mp3", sr=16000, mono=True)
81
+ vc_input = "tts.mp3"
82
+ times = [0, 0, 0]
83
+ f0_up_key = int(f0_up_key)
84
+ audio_opt = vc.pipeline(
85
+ hubert_model,
86
+ net_g,
87
+ 0,
88
+ audio,
89
+ vc_input,
90
+ times,
91
+ f0_up_key,
92
+ f0_method,
93
+ file_index,
94
+ # file_big_npy,
95
+ index_rate,
96
+ if_f0,
97
+ filter_radius,
98
+ tgt_sr,
99
+ resample_sr,
100
+ rms_mix_rate,
101
+ version,
102
+ protect,
103
+ f0_file=None,
104
+ )
105
+ info = f"[{datetime.now().strftime('%Y-%m-%d %H:%M')}]: npy: {times[0]}, f0: {times[1]}s, infer: {times[2]}s"
106
+ print(f"{model_title} | {info}")
107
+ return info, (tgt_sr, audio_opt)
108
+ except:
109
+ info = traceback.format_exc()
110
+ print(info)
111
+ return info, (None, None)
112
+ return vc_fn
113
+
114
+ def load_model():
115
+ categories = []
116
+ with open("weights/folder_info.json", "r", encoding="utf-8") as f:
117
+ folder_info = json.load(f)
118
+ for category_name, category_info in folder_info.items():
119
+ if not category_info['enable']:
120
+ continue
121
+ category_title = category_info['title']
122
+ category_folder = category_info['folder_path']
123
+ description = category_info['description']
124
+ models = []
125
+ with open(f"weights/{category_folder}/model_info.json", "r", encoding="utf-8") as f:
126
+ models_info = json.load(f)
127
+ for character_name, info in models_info.items():
128
+ if not info['enable']:
129
+ continue
130
+ model_title = info['title']
131
+ model_name = info['model_path']
132
+ model_author = info.get("author", None)
133
+ model_cover = f"weights/{category_folder}/{character_name}/{info['cover']}"
134
+ model_index = f"weights/{category_folder}/{character_name}/{info['feature_retrieval_library']}"
135
+ cpt = torch.load(f"weights/{category_folder}/{character_name}/{model_name}", map_location="cpu")
136
+ tgt_sr = cpt["config"][-1]
137
+ cpt["config"][-3] = cpt["weight"]["emb_g.weight"].shape[0] # n_spk
138
+ if_f0 = cpt.get("f0", 1)
139
+ version = cpt.get("version", "v1")
140
+ if version == "v1":
141
+ if if_f0 == 1:
142
+ net_g = SynthesizerTrnMs256NSFsid(*cpt["config"], is_half=config.is_half)
143
+ else:
144
+ net_g = SynthesizerTrnMs256NSFsid_nono(*cpt["config"])
145
+ model_version = "V1"
146
+ elif version == "v2":
147
+ if if_f0 == 1:
148
+ net_g = SynthesizerTrnMs768NSFsid(*cpt["config"], is_half=config.is_half)
149
+ else:
150
+ net_g = SynthesizerTrnMs768NSFsid_nono(*cpt["config"])
151
+ model_version = "V2"
152
+ del net_g.enc_q
153
+ print(net_g.load_state_dict(cpt["weight"], strict=False))
154
+ net_g.eval().to(config.device)
155
+ if config.is_half:
156
+ net_g = net_g.half()
157
+ else:
158
+ net_g = net_g.float()
159
+ vc = VC(tgt_sr, config)
160
+ print(f"Model loaded: {character_name} / {info['feature_retrieval_library']} | ({model_version})")
161
+ models.append((character_name, model_title, model_author, model_cover, model_version, create_vc_fn(model_title, tgt_sr, net_g, vc, if_f0, version, model_index)))
162
+ categories.append([category_title, category_folder, description, models])
163
+ return categories
164
+
165
+ def cut_vocal_and_inst(url, audio_provider, split_model):
166
+ if url != "":
167
+ if not os.path.exists("dl_audio"):
168
+ os.mkdir("dl_audio")
169
+ if audio_provider == "Youtube":
170
+ ydl_opts = {
171
+ 'format': 'bestaudio/best',
172
+ 'postprocessors': [{
173
+ 'key': 'FFmpegExtractAudio',
174
+ 'preferredcodec': 'wav',
175
+ }],
176
+ "outtmpl": 'dl_audio/youtube_audio',
177
+ }
178
+ with yt_dlp.YoutubeDL(ydl_opts) as ydl:
179
+ ydl.download([url])
180
+ audio_path = "dl_audio/youtube_audio.wav"
181
+ else:
182
+ # Spotify doesnt work.
183
+ # Need to find other solution soon.
184
+ '''
185
+ command = f"spotdl download {url} --output dl_audio/.wav"
186
+ result = subprocess.run(command.split(), stdout=subprocess.PIPE)
187
+ print(result.stdout.decode())
188
+ audio_path = "dl_audio/spotify_audio.wav"
189
+ '''
190
+ if split_model == "htdemucs":
191
+ command = f"demucs --two-stems=vocals {audio_path} -o output"
192
+ result = subprocess.run(command.split(), stdout=subprocess.PIPE)
193
+ print(result.stdout.decode())
194
+ return "output/htdemucs/youtube_audio/vocals.wav", "output/htdemucs/youtube_audio/no_vocals.wav", audio_path, "output/htdemucs/youtube_audio/vocals.wav"
195
+ else:
196
+ command = f"demucs --two-stems=vocals -n mdx_extra_q {audio_path} -o output"
197
+ result = subprocess.run(command.split(), stdout=subprocess.PIPE)
198
+ print(result.stdout.decode())
199
+ return "output/mdx_extra_q/youtube_audio/vocals.wav", "output/mdx_extra_q/youtube_audio/no_vocals.wav", audio_path, "output/mdx_extra_q/youtube_audio/vocals.wav"
200
+ else:
201
+ raise gr.Error("URL Required!")
202
+ return None, None, None, None
203
+
204
+ def combine_vocal_and_inst(audio_data, audio_volume, split_model):
205
+ if not os.path.exists("output/result"):
206
+ os.mkdir("output/result")
207
+ vocal_path = "output/result/output.wav"
208
+ output_path = "output/result/combine.mp3"
209
+ if split_model == "htdemucs":
210
+ inst_path = "output/htdemucs/youtube_audio/no_vocals.wav"
211
+ else:
212
+ inst_path = "output/mdx_extra_q/youtube_audio/no_vocals.wav"
213
+ with wave.open(vocal_path, "w") as wave_file:
214
+ wave_file.setnchannels(1)
215
+ wave_file.setsampwidth(2)
216
+ wave_file.setframerate(audio_data[0])
217
+ wave_file.writeframes(audio_data[1].tobytes())
218
+ command = f'ffmpeg -y -i {inst_path} -i {vocal_path} -filter_complex [1:a]volume={audio_volume}dB[v];[0:a][v]amix=inputs=2:duration=longest -b:a 320k -c:a libmp3lame {output_path}'
219
+ result = subprocess.run(command.split(), stdout=subprocess.PIPE)
220
+ print(result.stdout.decode())
221
+ return output_path
222
+
223
+ def load_hubert():
224
+ global hubert_model
225
+ models, _, _ = checkpoint_utils.load_model_ensemble_and_task(
226
+ ["hubert_base.pt"],
227
+ suffix="",
228
+ )
229
+ hubert_model = models[0]
230
+ hubert_model = hubert_model.to(config.device)
231
+ if config.is_half:
232
+ hubert_model = hubert_model.half()
233
+ else:
234
+ hubert_model = hubert_model.float()
235
+ hubert_model.eval()
236
+
237
+ def change_audio_mode(vc_audio_mode):
238
+ if vc_audio_mode == "Input path":
239
+ return (
240
+ # Input & Upload
241
+ gr.Textbox.update(visible=True),
242
+ gr.Audio.update(visible=False),
243
+ # Youtube
244
+ gr.Dropdown.update(visible=False),
245
+ gr.Textbox.update(visible=False),
246
+ gr.Dropdown.update(visible=False),
247
+ gr.Button.update(visible=False),
248
+ gr.Audio.update(visible=False),
249
+ gr.Audio.update(visible=False),
250
+ gr.Audio.update(visible=False),
251
+ gr.Slider.update(visible=False),
252
+ gr.Audio.update(visible=False),
253
+ gr.Button.update(visible=False),
254
+ # TTS
255
+ gr.Textbox.update(visible=False),
256
+ gr.Dropdown.update(visible=False)
257
+ )
258
+ elif vc_audio_mode == "Upload audio":
259
+ return (
260
+ # Input & Upload
261
+ gr.Textbox.update(visible=False),
262
+ gr.Audio.update(visible=True),
263
+ # Youtube
264
+ gr.Dropdown.update(visible=False),
265
+ gr.Textbox.update(visible=False),
266
+ gr.Dropdown.update(visible=False),
267
+ gr.Button.update(visible=False),
268
+ gr.Audio.update(visible=False),
269
+ gr.Audio.update(visible=False),
270
+ gr.Audio.update(visible=False),
271
+ gr.Slider.update(visible=False),
272
+ gr.Audio.update(visible=False),
273
+ gr.Button.update(visible=False),
274
+ # TTS
275
+ gr.Textbox.update(visible=False),
276
+ gr.Dropdown.update(visible=False)
277
+ )
278
+ elif vc_audio_mode == "Youtube":
279
+ return (
280
+ # Input & Upload
281
+ gr.Textbox.update(visible=False),
282
+ gr.Audio.update(visible=False),
283
+ # Youtube
284
+ gr.Dropdown.update(visible=True),
285
+ gr.Textbox.update(visible=True),
286
+ gr.Dropdown.update(visible=True),
287
+ gr.Button.update(visible=True),
288
+ gr.Audio.update(visible=True),
289
+ gr.Audio.update(visible=True),
290
+ gr.Audio.update(visible=True),
291
+ gr.Slider.update(visible=True),
292
+ gr.Audio.update(visible=True),
293
+ gr.Button.update(visible=True),
294
+ # TTS
295
+ gr.Textbox.update(visible=False),
296
+ gr.Dropdown.update(visible=False)
297
+ )
298
+ elif vc_audio_mode == "TTS Audio":
299
+ return (
300
+ # Input & Upload
301
+ gr.Textbox.update(visible=False),
302
+ gr.Audio.update(visible=False),
303
+ # Youtube
304
+ gr.Dropdown.update(visible=False),
305
+ gr.Textbox.update(visible=False),
306
+ gr.Dropdown.update(visible=False),
307
+ gr.Button.update(visible=False),
308
+ gr.Audio.update(visible=False),
309
+ gr.Audio.update(visible=False),
310
+ gr.Audio.update(visible=False),
311
+ gr.Slider.update(visible=False),
312
+ gr.Audio.update(visible=False),
313
+ gr.Button.update(visible=False),
314
+ # TTS
315
+ gr.Textbox.update(visible=True),
316
+ gr.Dropdown.update(visible=True)
317
+ )
318
+ else:
319
+ return (
320
+ # Input & Upload
321
+ gr.Textbox.update(visible=False),
322
+ gr.Audio.update(visible=True),
323
+ # Youtube
324
+ gr.Dropdown.update(visible=False),
325
+ gr.Textbox.update(visible=False),
326
+ gr.Dropdown.update(visible=False),
327
+ gr.Button.update(visible=False),
328
+ gr.Audio.update(visible=False),
329
+ gr.Audio.update(visible=False),
330
+ gr.Audio.update(visible=False),
331
+ gr.Slider.update(visible=False),
332
+ gr.Audio.update(visible=False),
333
+ gr.Button.update(visible=False),
334
+ # TTS
335
+ gr.Textbox.update(visible=False),
336
+ gr.Dropdown.update(visible=False)
337
+ )
338
+
339
+ if __name__ == '__main__':
340
+ load_hubert()
341
+ categories = load_model()
342
+ tts_voice_list = asyncio.get_event_loop().run_until_complete(edge_tts.list_voices())
343
+ voices = [f"{v['ShortName']}-{v['Gender']}" for v in tts_voice_list]
344
+ with gr.Blocks() as app:
345
+ gr.Markdown(
346
+ "# <center> Multi Model RVC Inference\n"
347
+ "### <center> Support v2 Model\n"
348
+ "#### From [Retrieval-based-Voice-Conversion](https://github.com/RVC-Project/Retrieval-based-Voice-Conversion-WebUI)\n"
349
+ "[![Original Repo](https://badgen.net/badge/icon/github?icon=github&label=Original%20Repo)](https://github.com/ArkanDash/Multi-Model-RVC-Inference)"
350
+ )
351
+ for (folder_title, folder, description, models) in categories:
352
+ with gr.TabItem(folder_title):
353
+ if description:
354
+ gr.Markdown(f"### <center> {description}")
355
+ with gr.Tabs():
356
+ if not models:
357
+ gr.Markdown("# <center> No Model Loaded.")
358
+ gr.Markdown("## <center> Please add model or fix your model path.")
359
+ continue
360
+ for (name, title, author, cover, model_version, vc_fn) in models:
361
+ with gr.TabItem(name):
362
+ with gr.Row():
363
+ gr.Markdown(
364
+ '<div align="center">'
365
+ f'<div>{title}</div>\n'+
366
+ f'<div>RVC {model_version} Model</div>\n'+
367
+ (f'<div>Model author: {author}</div>' if author else "")+
368
+ (f'<img style="width:auto;height:300px;" src="file/{cover}">' if cover else "")+
369
+ '</div>'
370
+ )
371
+ with gr.Row():
372
+ with gr.Column():
373
+ vc_audio_mode = gr.Dropdown(label="Input voice", choices=audio_mode, allow_custom_value=False, value="Upload audio")
374
+ # Input and Upload
375
+ vc_input = gr.Textbox(label="Input audio path", visible=False)
376
+ vc_upload = gr.Audio(label="Upload audio file", visible=True, interactive=True)
377
+ # Youtube
378
+ vc_download_audio = gr.Dropdown(label="Provider", choices=["Youtube"], allow_custom_value=False, visible=False, value="Youtube", info="Select provider (Default: Youtube)")
379
+ 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=...")
380
+ vc_split_model = gr.Dropdown(label="Splitter Model", choices=["htdemucs", "mdx_extra_q"], allow_custom_value=False, visible=False, value="htdemucs", info="Select the splitter model (Default: htdemucs)")
381
+ vc_split = gr.Button("Split Audio", variant="primary", visible=False)
382
+ vc_vocal_preview = gr.Audio(label="Vocal Preview", visible=False)
383
+ vc_inst_preview = gr.Audio(label="Instrumental Preview", visible=False)
384
+ vc_audio_preview = gr.Audio(label="Audio Preview", visible=False)
385
+ # TTS
386
+ tts_text = gr.Textbox(visible=False, label="TTS text", info="Text to speech input")
387
+ tts_voice = gr.Dropdown(label="Edge-tts speaker", choices=voices, visible=False, allow_custom_value=False, value="en-US-AnaNeural-Female")
388
+ with gr.Column():
389
+ 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')
390
+ f0method0 = gr.Radio(
391
+ label="Pitch extraction algorithm",
392
+ info=f0method_info,
393
+ choices=f0method_mode,
394
+ value="pm",
395
+ interactive=True
396
+ )
397
+ index_rate1 = gr.Slider(
398
+ minimum=0,
399
+ maximum=1,
400
+ label="Retrieval feature ratio",
401
+ info="(Default: 0.6)",
402
+ value=0.6,
403
+ interactive=True,
404
+ )
405
+ filter_radius0 = gr.Slider(
406
+ minimum=0,
407
+ maximum=7,
408
+ label="Apply Median Filtering",
409
+ info="The value represents the filter radius and can reduce breathiness.",
410
+ value=3,
411
+ step=1,
412
+ interactive=True,
413
+ )
414
+ resample_sr0 = gr.Slider(
415
+ minimum=0,
416
+ maximum=48000,
417
+ label="Resample the output audio",
418
+ info="Resample the output audio in post-processing to the final sample rate. Set to 0 for no resampling",
419
+ value=0,
420
+ step=1,
421
+ interactive=True,
422
+ )
423
+ rms_mix_rate0 = gr.Slider(
424
+ minimum=0,
425
+ maximum=1,
426
+ label="Volume Envelope",
427
+ 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",
428
+ value=1,
429
+ interactive=True,
430
+ )
431
+ protect0 = gr.Slider(
432
+ minimum=0,
433
+ maximum=0.5,
434
+ label="Voice Protection",
435
+ 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",
436
+ value=0.4,
437
+ step=0.01,
438
+ interactive=True,
439
+ )
440
+ protect0 = gr.Slider(
441
+ minimum=0,
442
+ maximum=0.5,
443
+ label="Voice Protection",
444
+ 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",
445
+ value=0.5,
446
+ step=0.01,
447
+ interactive=True,
448
+ )
449
+ with gr.Column():
450
+ vc_log = gr.Textbox(label="Output Information", interactive=False)
451
+ vc_output = gr.Audio(label="Output Audio", interactive=False)
452
+ vc_convert = gr.Button("Convert", variant="primary")
453
+ vc_volume = gr.Slider(
454
+ minimum=0,
455
+ maximum=10,
456
+ label="Vocal volume",
457
+ value=4,
458
+ interactive=True,
459
+ step=1,
460
+ info="Adjust vocal volume (Default: 4}",
461
+ visible=False
462
+ )
463
+ vc_combined_output = gr.Audio(label="Output Combined Audio", visible=False)
464
+ vc_combine = gr.Button("Combine",variant="primary", visible=False)
465
+ vc_convert.click(
466
+ fn=vc_fn,
467
+ inputs=[
468
+ vc_audio_mode,
469
+ vc_input,
470
+ vc_upload,
471
+ tts_text,
472
+ tts_voice,
473
+ vc_transform0,
474
+ f0method0,
475
+ index_rate1,
476
+ filter_radius0,
477
+ resample_sr0,
478
+ rms_mix_rate0,
479
+ protect0,
480
+ ],
481
+ outputs=[vc_log ,vc_output]
482
+ )
483
+ vc_split.click(
484
+ fn=cut_vocal_and_inst,
485
+ inputs=[vc_link, vc_download_audio, vc_split_model],
486
+ outputs=[vc_vocal_preview, vc_inst_preview, vc_audio_preview, vc_input]
487
+ )
488
+ vc_combine.click(
489
+ fn=combine_vocal_and_inst,
490
+ inputs=[vc_output, vc_volume, vc_split_model],
491
+ outputs=[vc_combined_output]
492
+ )
493
+ vc_audio_mode.change(
494
+ fn=change_audio_mode,
495
+ inputs=[vc_audio_mode],
496
+ outputs=[
497
+ vc_input,
498
+ vc_upload,
499
+ vc_download_audio,
500
+ vc_link,
501
+ vc_split_model,
502
+ vc_split,
503
+ vc_vocal_preview,
504
+ vc_inst_preview,
505
+ vc_audio_preview,
506
+ vc_volume,
507
+ vc_combined_output,
508
+ vc_combine,
509
+ tts_text,
510
+ tts_voice
511
+ ]
512
+ )
513
+ app.queue(concurrency_count=1, max_size=20, api_open=config.api).launch(share=config.colab)
vc_infer_pipeline.py ADDED
@@ -0,0 +1,431 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
5
+ 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 = {}
12
+
13
+
14
+ @lru_cache
15
+ def cache_harvest_f0(input_audio_path, fs, f0max, f0min, frame_period):
16
+ audio = input_audio_path2wav[input_audio_path]
17
+ f0, t = pyworld.harvest(
18
+ audio,
19
+ fs=fs,
20
+ f0_ceil=f0max,
21
+ f0_floor=f0min,
22
+ frame_period=frame_period,
23
+ )
24
+ f0 = pyworld.stonemask(audio, f0, t, fs)
25
+ return f0
26
+
27
+
28
+ def change_rms(data1, sr1, data2, sr2, rate): # 1是输入音频,2是输出音频,rate是2的占比
29
+ # print(data1.max(),data2.max())
30
+ rms1 = librosa.feature.rms(
31
+ y=data1, frame_length=sr1 // 2 * 2, hop_length=sr1 // 2
32
+ ) # 每半秒一个点
33
+ rms2 = librosa.feature.rms(y=data2, frame_length=sr2 // 2 * 2, hop_length=sr2 // 2)
34
+ rms1 = torch.from_numpy(rms1)
35
+ rms1 = F.interpolate(
36
+ rms1.unsqueeze(0), size=data2.shape[0], mode="linear"
37
+ ).squeeze()
38
+ rms2 = torch.from_numpy(rms2)
39
+ rms2 = F.interpolate(
40
+ rms2.unsqueeze(0), size=data2.shape[0], mode="linear"
41
+ ).squeeze()
42
+ rms2 = torch.max(rms2, torch.zeros_like(rms2) + 1e-6)
43
+ data2 *= (
44
+ torch.pow(rms1, torch.tensor(1 - rate))
45
+ * torch.pow(rms2, torch.tensor(rate - 1))
46
+ ).numpy()
47
+ return data2
48
+
49
+
50
+ class VC(object):
51
+ def __init__(self, tgt_sr, config):
52
+ self.x_pad, self.x_query, self.x_center, self.x_max, self.is_half = (
53
+ config.x_pad,
54
+ config.x_query,
55
+ config.x_center,
56
+ config.x_max,
57
+ config.is_half,
58
+ )
59
+ self.sr = 16000 # hubert输入采样率
60
+ self.window = 160 # 每帧点数
61
+ self.t_pad = self.sr * self.x_pad # 每条前后pad时间
62
+ self.t_pad_tgt = tgt_sr * self.x_pad
63
+ self.t_pad2 = self.t_pad * 2
64
+ self.t_query = self.sr * self.x_query # 查询切点前后查询时间
65
+ self.t_center = self.sr * self.x_center # 查询切点位置
66
+ self.t_max = self.sr * self.x_max # 免查询时长阈值
67
+ self.device = config.device
68
+
69
+ def get_f0(
70
+ self,
71
+ input_audio_path,
72
+ x,
73
+ p_len,
74
+ f0_up_key,
75
+ f0_method,
76
+ filter_radius,
77
+ inp_f0=None,
78
+ ):
79
+ global input_audio_path2wav
80
+ time_step = self.window / self.sr * 1000
81
+ f0_min = 50
82
+ f0_max = 1100
83
+ f0_mel_min = 1127 * np.log(1 + f0_min / 700)
84
+ f0_mel_max = 1127 * np.log(1 + f0_max / 700)
85
+ if f0_method == "pm":
86
+ f0 = (
87
+ parselmouth.Sound(x, self.sr)
88
+ .to_pitch_ac(
89
+ time_step=time_step / 1000,
90
+ voicing_threshold=0.6,
91
+ pitch_floor=f0_min,
92
+ pitch_ceiling=f0_max,
93
+ )
94
+ .selected_array["frequency"]
95
+ )
96
+ pad_size = (p_len - len(f0) + 1) // 2
97
+ if pad_size > 0 or p_len - len(f0) - pad_size > 0:
98
+ f0 = np.pad(
99
+ f0, [[pad_size, p_len - len(f0) - pad_size]], mode="constant"
100
+ )
101
+ elif f0_method == "harvest":
102
+ input_audio_path2wav[input_audio_path] = x.astype(np.double)
103
+ f0 = cache_harvest_f0(input_audio_path, self.sr, f0_max, f0_min, 10)
104
+ if filter_radius > 2:
105
+ f0 = signal.medfilt(f0, 3)
106
+ elif f0_method == "crepe":
107
+ model = "full"
108
+ # Pick a batch size that doesn't cause memory errors on your gpu
109
+ batch_size = 512
110
+ # Compute pitch using first gpu
111
+ audio = torch.tensor(np.copy(x))[None].float()
112
+ f0, pd = torchcrepe.predict(
113
+ audio,
114
+ self.sr,
115
+ self.window,
116
+ f0_min,
117
+ f0_max,
118
+ model,
119
+ batch_size=batch_size,
120
+ device=self.device,
121
+ return_periodicity=True,
122
+ )
123
+ pd = torchcrepe.filter.median(pd, 3)
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点数
130
+ if inp_f0 is not None:
131
+ delta_t = np.round(
132
+ (inp_f0[:, 0].max() - inp_f0[:, 0].min()) * tf0 + 1
133
+ ).astype("int16")
134
+ replace_f0 = np.interp(
135
+ list(range(delta_t)), inp_f0[:, 0] * 100, inp_f0[:, 1]
136
+ )
137
+ shape = f0[self.x_pad * tf0 : self.x_pad * tf0 + len(replace_f0)].shape[0]
138
+ f0[self.x_pad * tf0 : self.x_pad * tf0 + len(replace_f0)] = replace_f0[
139
+ :shape
140
+ ]
141
+ # with open("test_opt.txt","w")as f:f.write("\n".join([str(i)for i in f0.tolist()]))
142
+ f0bak = f0.copy()
143
+ f0_mel = 1127 * np.log(1 + f0 / 700)
144
+ f0_mel[f0_mel > 0] = (f0_mel[f0_mel > 0] - f0_mel_min) * 254 / (
145
+ f0_mel_max - f0_mel_min
146
+ ) + 1
147
+ f0_mel[f0_mel <= 1] = 1
148
+ f0_mel[f0_mel > 255] = 255
149
+ f0_coarse = np.rint(f0_mel).astype(np.int)
150
+ return f0_coarse, f0bak # 1-0
151
+
152
+ def vc(
153
+ self,
154
+ model,
155
+ net_g,
156
+ sid,
157
+ audio0,
158
+ pitch,
159
+ pitchf,
160
+ times,
161
+ index,
162
+ big_npy,
163
+ index_rate,
164
+ version,
165
+ protect,
166
+ ): # ,file_index,file_big_npy
167
+ feats = torch.from_numpy(audio0)
168
+ if self.is_half:
169
+ feats = feats.half()
170
+ else:
171
+ feats = feats.float()
172
+ if feats.dim() == 2: # double channels
173
+ feats = feats.mean(-1)
174
+ assert feats.dim() == 1, feats.dim()
175
+ feats = feats.view(1, -1)
176
+ padding_mask = torch.BoolTensor(feats.shape).to(self.device).fill_(False)
177
+
178
+ inputs = {
179
+ "source": feats.to(self.device),
180
+ "padding_mask": padding_mask,
181
+ "output_layer": 9 if version == "v1" else 12,
182
+ }
183
+ t0 = ttime()
184
+ with torch.no_grad():
185
+ logits = model.extract_features(**inputs)
186
+ feats = model.final_proj(logits[0]) if version == "v1" else logits[0]
187
+ if protect < 0.5 and pitch != None and pitchf != None:
188
+ feats0 = feats.clone()
189
+ if (
190
+ isinstance(index, type(None)) == False
191
+ and isinstance(big_npy, type(None)) == False
192
+ and index_rate != 0
193
+ ):
194
+ npy = feats[0].cpu().numpy()
195
+ if self.is_half:
196
+ npy = npy.astype("float32")
197
+
198
+ # _, I = index.search(npy, 1)
199
+ # npy = big_npy[I.squeeze()]
200
+
201
+ score, ix = index.search(npy, k=8)
202
+ weight = np.square(1 / score)
203
+ weight /= weight.sum(axis=1, keepdims=True)
204
+ npy = np.sum(big_npy[ix] * np.expand_dims(weight, axis=2), axis=1)
205
+
206
+ if self.is_half:
207
+ npy = npy.astype("float16")
208
+ feats = (
209
+ torch.from_numpy(npy).unsqueeze(0).to(self.device) * index_rate
210
+ + (1 - index_rate) * feats
211
+ )
212
+
213
+ feats = F.interpolate(feats.permute(0, 2, 1), scale_factor=2).permute(0, 2, 1)
214
+ if protect < 0.5 and pitch != None and pitchf != None:
215
+ feats0 = F.interpolate(feats0.permute(0, 2, 1), scale_factor=2).permute(
216
+ 0, 2, 1
217
+ )
218
+ t1 = ttime()
219
+ p_len = audio0.shape[0] // self.window
220
+ if feats.shape[1] < p_len:
221
+ p_len = feats.shape[1]
222
+ if pitch != None and pitchf != None:
223
+ pitch = pitch[:, :p_len]
224
+ pitchf = pitchf[:, :p_len]
225
+
226
+ if protect < 0.5 and pitch != None and pitchf != None:
227
+ pitchff = pitchf.clone()
228
+ pitchff[pitchf > 0] = 1
229
+ pitchff[pitchf < 1] = protect
230
+ pitchff = pitchff.unsqueeze(-1)
231
+ feats = feats * pitchff + feats0 * (1 - pitchff)
232
+ feats = feats.to(feats0.dtype)
233
+ p_len = torch.tensor([p_len], device=self.device).long()
234
+ with torch.no_grad():
235
+ if pitch != None and pitchf != None:
236
+ audio1 = (
237
+ (net_g.infer(feats, p_len, pitch, pitchf, sid)[0][0, 0])
238
+ .data.cpu()
239
+ .float()
240
+ .numpy()
241
+ )
242
+ else:
243
+ audio1 = (
244
+ (net_g.infer(feats, p_len, sid)[0][0, 0]).data.cpu().float().numpy()
245
+ )
246
+ del feats, p_len, padding_mask
247
+ if torch.cuda.is_available():
248
+ torch.cuda.empty_cache()
249
+ t2 = ttime()
250
+ times[0] += t1 - t0
251
+ times[2] += t2 - t1
252
+ return audio1
253
+
254
+ def pipeline(
255
+ self,
256
+ model,
257
+ net_g,
258
+ sid,
259
+ audio,
260
+ input_audio_path,
261
+ times,
262
+ f0_up_key,
263
+ f0_method,
264
+ file_index,
265
+ # file_big_npy,
266
+ index_rate,
267
+ if_f0,
268
+ filter_radius,
269
+ tgt_sr,
270
+ resample_sr,
271
+ rms_mix_rate,
272
+ version,
273
+ protect,
274
+ f0_file=None,
275
+ ):
276
+ if (
277
+ file_index != ""
278
+ # and file_big_npy != ""
279
+ # and os.path.exists(file_big_npy) == True
280
+ and os.path.exists(file_index) == True
281
+ and index_rate != 0
282
+ ):
283
+ try:
284
+ index = faiss.read_index(file_index)
285
+ # big_npy = np.load(file_big_npy)
286
+ big_npy = index.reconstruct_n(0, index.ntotal)
287
+ except:
288
+ traceback.print_exc()
289
+ index = big_npy = None
290
+ else:
291
+ index = big_npy = None
292
+ audio = signal.filtfilt(bh, ah, audio)
293
+ audio_pad = np.pad(audio, (self.window // 2, self.window // 2), mode="reflect")
294
+ opt_ts = []
295
+ if audio_pad.shape[0] > self.t_max:
296
+ audio_sum = np.zeros_like(audio)
297
+ for i in range(self.window):
298
+ audio_sum += audio_pad[i : i - self.window]
299
+ for t in range(self.t_center, audio.shape[0], self.t_center):
300
+ opt_ts.append(
301
+ t
302
+ - self.t_query
303
+ + np.where(
304
+ np.abs(audio_sum[t - self.t_query : t + self.t_query])
305
+ == np.abs(audio_sum[t - self.t_query : t + self.t_query]).min()
306
+ )[0][0]
307
+ )
308
+ s = 0
309
+ audio_opt = []
310
+ t = None
311
+ t1 = ttime()
312
+ audio_pad = np.pad(audio, (self.t_pad, self.t_pad), mode="reflect")
313
+ p_len = audio_pad.shape[0] // self.window
314
+ inp_f0 = None
315
+ if hasattr(f0_file, "name") == True:
316
+ try:
317
+ with open(f0_file.name, "r") as f:
318
+ lines = f.read().strip("\n").split("\n")
319
+ inp_f0 = []
320
+ for line in lines:
321
+ inp_f0.append([float(i) for i in line.split(",")])
322
+ inp_f0 = np.array(inp_f0, dtype="float32")
323
+ except:
324
+ traceback.print_exc()
325
+ sid = torch.tensor(sid, device=self.device).unsqueeze(0).long()
326
+ pitch, pitchf = None, None
327
+ if if_f0 == 1:
328
+ pitch, pitchf = self.get_f0(
329
+ input_audio_path,
330
+ audio_pad,
331
+ p_len,
332
+ f0_up_key,
333
+ f0_method,
334
+ filter_radius,
335
+ inp_f0,
336
+ )
337
+ pitch = pitch[:p_len]
338
+ pitchf = pitchf[:p_len]
339
+ if self.device == "mps":
340
+ pitchf = pitchf.astype(np.float32)
341
+ pitch = torch.tensor(pitch, device=self.device).unsqueeze(0).long()
342
+ pitchf = torch.tensor(pitchf, device=self.device).unsqueeze(0).float()
343
+ t2 = ttime()
344
+ times[1] += t2 - t1
345
+ for t in opt_ts:
346
+ t = t // self.window * self.window
347
+ if if_f0 == 1:
348
+ audio_opt.append(
349
+ self.vc(
350
+ model,
351
+ net_g,
352
+ sid,
353
+ audio_pad[s : t + self.t_pad2 + self.window],
354
+ pitch[:, s // self.window : (t + self.t_pad2) // self.window],
355
+ pitchf[:, s // self.window : (t + self.t_pad2) // self.window],
356
+ times,
357
+ index,
358
+ big_npy,
359
+ index_rate,
360
+ version,
361
+ protect,
362
+ )[self.t_pad_tgt : -self.t_pad_tgt]
363
+ )
364
+ else:
365
+ audio_opt.append(
366
+ self.vc(
367
+ model,
368
+ net_g,
369
+ sid,
370
+ audio_pad[s : t + self.t_pad2 + self.window],
371
+ None,
372
+ None,
373
+ times,
374
+ index,
375
+ big_npy,
376
+ index_rate,
377
+ version,
378
+ protect,
379
+ )[self.t_pad_tgt : -self.t_pad_tgt]
380
+ )
381
+ s = t
382
+ if if_f0 == 1:
383
+ audio_opt.append(
384
+ self.vc(
385
+ model,
386
+ net_g,
387
+ sid,
388
+ audio_pad[t:],
389
+ pitch[:, t // self.window :] if t is not None else pitch,
390
+ pitchf[:, t // self.window :] if t is not None else pitchf,
391
+ times,
392
+ index,
393
+ big_npy,
394
+ index_rate,
395
+ version,
396
+ protect,
397
+ )[self.t_pad_tgt : -self.t_pad_tgt]
398
+ )
399
+ else:
400
+ audio_opt.append(
401
+ self.vc(
402
+ model,
403
+ net_g,
404
+ sid,
405
+ audio_pad[t:],
406
+ None,
407
+ None,
408
+ times,
409
+ index,
410
+ big_npy,
411
+ index_rate,
412
+ version,
413
+ protect,
414
+ )[self.t_pad_tgt : -self.t_pad_tgt]
415
+ )
416
+ audio_opt = np.concatenate(audio_opt)
417
+ if rms_mix_rate != 1:
418
+ audio_opt = change_rms(audio, 16000, audio_opt, tgt_sr, rms_mix_rate)
419
+ if resample_sr >= 16000 and tgt_sr != resample_sr:
420
+ audio_opt = librosa.resample(
421
+ audio_opt, orig_sr=tgt_sr, target_sr=resample_sr
422
+ )
423
+ audio_max = np.abs(audio_opt).max() / 0.99
424
+ max_int16 = 32768
425
+ if audio_max > 1:
426
+ max_int16 /= audio_max
427
+ audio_opt = (audio_opt * max_int16).astype(np.int16)
428
+ del pitch, pitchf, sid
429
+ if torch.cuda.is_available():
430
+ torch.cuda.empty_cache()
431
+ return audio_opt