vunhucuongit commited on
Commit
ebb199f
1 Parent(s): 5216cbf

Upload 12 files

Browse files
Files changed (12) hide show
  1. .gitattributes +3 -1
  2. README.md +12 -1
  3. app-full.py +503 -0
  4. app.py +504 -0
  5. config.py +117 -0
  6. gitattributes.txt +36 -0
  7. gitignore.txt +382 -0
  8. hubert_base.pt +3 -0
  9. requirements.txt +21 -0
  10. rmvpe.pt +3 -0
  11. rmvpe.py +432 -0
  12. vc_infer_pipeline.py +443 -0
.gitattributes CHANGED
@@ -25,7 +25,6 @@
25
  *.safetensors filter=lfs diff=lfs merge=lfs -text
26
  saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
  *.tar.* filter=lfs diff=lfs merge=lfs -text
28
- *.tar filter=lfs diff=lfs merge=lfs -text
29
  *.tflite filter=lfs diff=lfs merge=lfs -text
30
  *.tgz filter=lfs diff=lfs merge=lfs -text
31
  *.wasm filter=lfs diff=lfs merge=lfs -text
@@ -33,3 +32,6 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
25
  *.safetensors filter=lfs diff=lfs merge=lfs -text
26
  saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
  *.tar.* filter=lfs diff=lfs merge=lfs -text
 
28
  *.tflite filter=lfs diff=lfs merge=lfs -text
29
  *.tgz filter=lfs diff=lfs merge=lfs -text
30
  *.wasm filter=lfs diff=lfs merge=lfs -text
 
32
  *.zip filter=lfs diff=lfs merge=lfs -text
33
  *.zst filter=lfs diff=lfs merge=lfs -text
34
  *tfevents* filter=lfs diff=lfs merge=lfs -text
35
+ *.index filter=lfs diff=lfs merge=lfs -text
36
+ *.png filter=lfs diff=lfs merge=lfs -text
37
+ *.jpg filter=lfs diff=lfs merge=lfs -text
README.md CHANGED
@@ -1,3 +1,14 @@
1
  ---
2
- license: apache-2.0
 
 
 
 
 
 
 
 
 
3
  ---
 
 
 
1
  ---
2
+ title: Genshin Impact RVC Models (combined)
3
+ emoji: 🎤
4
+ colorFrom: purple
5
+ colorTo: red
6
+ sdk: gradio
7
+ sdk_version: 3.36.1
8
+ app_file: app.py
9
+ pinned: false
10
+ license: mit
11
+ duplicated_from: taishoushiki/combined-GI-RVC-models
12
  ---
13
+
14
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app-full.py ADDED
@@ -0,0 +1,503 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
36
+ if limitation is True:
37
+ audio_mode = ["Upload audio", "TTS Audio"]
38
+ f0method_mode = ["pm", "harvest"]
39
+ f0method_info = "PM is fast, Harvest is good but extremely slow, Rvmpe is alternative to harvest (might be better). (Default: PM)"
40
+ else:
41
+ audio_mode = ["Input path", "Upload audio", "Youtube", "TTS Audio"]
42
+ f0method_mode = ["pm", "harvest", "crepe"]
43
+ 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)"
44
+
45
+ if os.path.isfile("rmvpe.pt"):
46
+ f0method_mode.insert(2, "rmvpe")
47
+
48
+ def create_vc_fn(model_name, tgt_sr, net_g, vc, if_f0, version, file_index):
49
+ def vc_fn(
50
+ vc_audio_mode,
51
+ vc_input,
52
+ vc_upload,
53
+ tts_text,
54
+ tts_voice,
55
+ f0_up_key,
56
+ f0_method,
57
+ index_rate,
58
+ filter_radius,
59
+ resample_sr,
60
+ rms_mix_rate,
61
+ protect,
62
+ ):
63
+ try:
64
+ print(f"Converting using {model_name}...")
65
+ if vc_audio_mode == "Input path" or "Youtube" and vc_input != "":
66
+ audio, sr = librosa.load(vc_input, sr=16000, mono=True)
67
+ elif vc_audio_mode == "Upload audio":
68
+ if vc_upload is None:
69
+ return "You need to upload an audio", None
70
+ sampling_rate, audio = vc_upload
71
+ duration = audio.shape[0] / sampling_rate
72
+ if duration > 20 and limitation:
73
+ 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
74
+ audio = (audio / np.iinfo(audio.dtype).max).astype(np.float32)
75
+ if len(audio.shape) > 1:
76
+ audio = librosa.to_mono(audio.transpose(1, 0))
77
+ if sampling_rate != 16000:
78
+ audio = librosa.resample(audio, orig_sr=sampling_rate, target_sr=16000)
79
+ elif vc_audio_mode == "TTS Audio":
80
+ if len(tts_text) > 100 and limitation:
81
+ return "Text is too long", None
82
+ if tts_text is None or tts_voice is None:
83
+ return "You need to enter text and select a voice", None
84
+ asyncio.run(edge_tts.Communicate(tts_text, "-".join(tts_voice.split('-')[:-1])).save("tts.mp3"))
85
+ audio, sr = librosa.load("tts.mp3", sr=16000, mono=True)
86
+ vc_input = "tts.mp3"
87
+ times = [0, 0, 0]
88
+ f0_up_key = int(f0_up_key)
89
+ audio_opt = vc.pipeline(
90
+ hubert_model,
91
+ net_g,
92
+ 0,
93
+ audio,
94
+ vc_input,
95
+ times,
96
+ f0_up_key,
97
+ f0_method,
98
+ file_index,
99
+ # file_big_npy,
100
+ index_rate,
101
+ if_f0,
102
+ filter_radius,
103
+ tgt_sr,
104
+ resample_sr,
105
+ rms_mix_rate,
106
+ version,
107
+ protect,
108
+ f0_file=None,
109
+ )
110
+ info = f"[{datetime.now().strftime('%Y-%m-%d %H:%M')}]: npy: {times[0]}, f0: {times[1]}s, infer: {times[2]}s"
111
+ print(f"{model_name} | {info}")
112
+ return info, (tgt_sr, audio_opt)
113
+ except:
114
+ info = traceback.format_exc()
115
+ print(info)
116
+ return info, None
117
+ return vc_fn
118
+
119
+ def load_model():
120
+ models = []
121
+ with open(f"weights/model_info.json", "r", encoding="utf-8") as f:
122
+ models_info = json.load(f)
123
+ for character_name, info in models_info.items():
124
+ if not info['enable']:
125
+ continue
126
+ model_title = info['title']
127
+ model_name = info['model_path']
128
+ model_author = info.get("author", None)
129
+ model_cover = f"weights/{character_name}/{info['cover']}"
130
+ model_index = f"weights/{character_name}/{info['feature_retrieval_library']}"
131
+ cpt = torch.load(f"weights/{character_name}/{model_name}", map_location="cpu")
132
+ tgt_sr = cpt["config"][-1]
133
+ cpt["config"][-3] = cpt["weight"]["emb_g.weight"].shape[0] # n_spk
134
+ if_f0 = cpt.get("f0", 1)
135
+ version = cpt.get("version", "v1")
136
+ if version == "v1":
137
+ if if_f0 == 1:
138
+ net_g = SynthesizerTrnMs256NSFsid(*cpt["config"], is_half=config.is_half)
139
+ else:
140
+ net_g = SynthesizerTrnMs256NSFsid_nono(*cpt["config"])
141
+ model_version = "V1"
142
+ elif version == "v2":
143
+ if if_f0 == 1:
144
+ net_g = SynthesizerTrnMs768NSFsid(*cpt["config"], is_half=config.is_half)
145
+ else:
146
+ net_g = SynthesizerTrnMs768NSFsid_nono(*cpt["config"])
147
+ model_version = "V2"
148
+ del net_g.enc_q
149
+ print(net_g.load_state_dict(cpt["weight"], strict=False))
150
+ net_g.eval().to(config.device)
151
+ if config.is_half:
152
+ net_g = net_g.half()
153
+ else:
154
+ net_g = net_g.float()
155
+ vc = VC(tgt_sr, config)
156
+ print(f"Model loaded: {character_name} / {info['feature_retrieval_library']} | ({model_version})")
157
+ 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)))
158
+ return models
159
+
160
+ def cut_vocal_and_inst(url, audio_provider, split_model):
161
+ if url != "":
162
+ if not os.path.exists("dl_audio"):
163
+ os.mkdir("dl_audio")
164
+ if audio_provider == "Youtube":
165
+ ydl_opts = {
166
+ 'noplaylist': True,
167
+ 'format': 'bestaudio/best',
168
+ 'postprocessors': [{
169
+ 'key': 'FFmpegExtractAudio',
170
+ 'preferredcodec': 'wav',
171
+ }],
172
+ "outtmpl": 'dl_audio/youtube_audio',
173
+ }
174
+ with yt_dlp.YoutubeDL(ydl_opts) as ydl:
175
+ ydl.download([url])
176
+ audio_path = "dl_audio/youtube_audio.wav"
177
+ if split_model == "htdemucs":
178
+ command = f"demucs --two-stems=vocals {audio_path} -o output"
179
+ result = subprocess.run(command.split(), stdout=subprocess.PIPE)
180
+ print(result.stdout.decode())
181
+ return "output/htdemucs/youtube_audio/vocals.wav", "output/htdemucs/youtube_audio/no_vocals.wav", audio_path, "output/htdemucs/youtube_audio/vocals.wav"
182
+ else:
183
+ command = f"demucs --two-stems=vocals -n mdx_extra_q {audio_path} -o output"
184
+ result = subprocess.run(command.split(), stdout=subprocess.PIPE)
185
+ print(result.stdout.decode())
186
+ 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"
187
+ else:
188
+ raise gr.Error("URL Required!")
189
+ return None, None, None, None
190
+
191
+ def combine_vocal_and_inst(audio_data, audio_volume, split_model):
192
+ if not os.path.exists("output/result"):
193
+ os.mkdir("output/result")
194
+ vocal_path = "output/result/output.wav"
195
+ output_path = "output/result/combine.mp3"
196
+ if split_model == "htdemucs":
197
+ inst_path = "output/htdemucs/youtube_audio/no_vocals.wav"
198
+ else:
199
+ inst_path = "output/mdx_extra_q/youtube_audio/no_vocals.wav"
200
+ with wave.open(vocal_path, "w") as wave_file:
201
+ wave_file.setnchannels(1)
202
+ wave_file.setsampwidth(2)
203
+ wave_file.setframerate(audio_data[0])
204
+ wave_file.writeframes(audio_data[1].tobytes())
205
+ 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}'
206
+ result = subprocess.run(command.split(), stdout=subprocess.PIPE)
207
+ print(result.stdout.decode())
208
+ return output_path
209
+
210
+ def load_hubert():
211
+ global hubert_model
212
+ models, _, _ = checkpoint_utils.load_model_ensemble_and_task(
213
+ ["hubert_base.pt"],
214
+ suffix="",
215
+ )
216
+ hubert_model = models[0]
217
+ hubert_model = hubert_model.to(config.device)
218
+ if config.is_half:
219
+ hubert_model = hubert_model.half()
220
+ else:
221
+ hubert_model = hubert_model.float()
222
+ hubert_model.eval()
223
+
224
+ def change_audio_mode(vc_audio_mode):
225
+ if vc_audio_mode == "Input path":
226
+ return (
227
+ # Input & Upload
228
+ gr.Textbox.update(visible=True),
229
+ gr.Checkbox.update(visible=False),
230
+ gr.Audio.update(visible=False),
231
+ # Youtube
232
+ gr.Dropdown.update(visible=False),
233
+ gr.Textbox.update(visible=False),
234
+ gr.Dropdown.update(visible=False),
235
+ gr.Button.update(visible=False),
236
+ gr.Audio.update(visible=False),
237
+ gr.Audio.update(visible=False),
238
+ gr.Audio.update(visible=False),
239
+ gr.Slider.update(visible=False),
240
+ gr.Audio.update(visible=False),
241
+ gr.Button.update(visible=False),
242
+ # TTS
243
+ gr.Textbox.update(visible=False),
244
+ gr.Dropdown.update(visible=False)
245
+ )
246
+ elif vc_audio_mode == "Upload audio":
247
+ return (
248
+ # Input & Upload
249
+ gr.Textbox.update(visible=False),
250
+ gr.Checkbox.update(visible=True),
251
+ gr.Audio.update(visible=True),
252
+ # Youtube
253
+ gr.Dropdown.update(visible=False),
254
+ gr.Textbox.update(visible=False),
255
+ gr.Dropdown.update(visible=False),
256
+ gr.Button.update(visible=False),
257
+ gr.Audio.update(visible=False),
258
+ gr.Audio.update(visible=False),
259
+ gr.Audio.update(visible=False),
260
+ gr.Slider.update(visible=False),
261
+ gr.Audio.update(visible=False),
262
+ gr.Button.update(visible=False),
263
+ # TTS
264
+ gr.Textbox.update(visible=False),
265
+ gr.Dropdown.update(visible=False)
266
+ )
267
+ elif vc_audio_mode == "Youtube":
268
+ return (
269
+ # Input & Upload
270
+ gr.Textbox.update(visible=False),
271
+ gr.Checkbox.update(visible=False),
272
+ gr.Audio.update(visible=False),
273
+ # Youtube
274
+ gr.Dropdown.update(visible=True),
275
+ gr.Textbox.update(visible=True),
276
+ gr.Dropdown.update(visible=True),
277
+ gr.Button.update(visible=True),
278
+ gr.Audio.update(visible=True),
279
+ gr.Audio.update(visible=True),
280
+ gr.Audio.update(visible=True),
281
+ gr.Slider.update(visible=True),
282
+ gr.Audio.update(visible=True),
283
+ gr.Button.update(visible=True),
284
+ # TTS
285
+ gr.Textbox.update(visible=False),
286
+ gr.Dropdown.update(visible=False)
287
+ )
288
+ elif vc_audio_mode == "TTS Audio":
289
+ return (
290
+ # Input & Upload
291
+ gr.Textbox.update(visible=False),
292
+ gr.Checkbox.update(visible=False),
293
+ gr.Audio.update(visible=False),
294
+ # Youtube
295
+ gr.Dropdown.update(visible=False),
296
+ gr.Textbox.update(visible=False),
297
+ gr.Dropdown.update(visible=False),
298
+ gr.Button.update(visible=False),
299
+ gr.Audio.update(visible=False),
300
+ gr.Audio.update(visible=False),
301
+ gr.Audio.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=True),
307
+ gr.Dropdown.update(visible=True)
308
+ )
309
+ else:
310
+ return (
311
+ # Input & Upload
312
+ gr.Textbox.update(visible=False),
313
+ gr.Checkbox.update(visible=True),
314
+ gr.Audio.update(visible=True),
315
+ # Youtube
316
+ gr.Dropdown.update(visible=False),
317
+ gr.Textbox.update(visible=False),
318
+ gr.Dropdown.update(visible=False),
319
+ gr.Button.update(visible=False),
320
+ gr.Audio.update(visible=False),
321
+ gr.Audio.update(visible=False),
322
+ gr.Audio.update(visible=False),
323
+ gr.Slider.update(visible=False),
324
+ gr.Audio.update(visible=False),
325
+ gr.Button.update(visible=False),
326
+ # TTS
327
+ gr.Textbox.update(visible=False),
328
+ gr.Dropdown.update(visible=False)
329
+ )
330
+
331
+ def use_microphone(microphone):
332
+ if microphone == True:
333
+ return gr.Audio.update(source="microphone")
334
+ else:
335
+ return gr.Audio.update(source="upload")
336
+
337
+ if __name__ == '__main__':
338
+ load_hubert()
339
+ models = load_model()
340
+ tts_voice_list = asyncio.new_event_loop().run_until_complete(edge_tts.list_voices())
341
+ voices = [f"{v['ShortName']}-{v['Gender']}" for v in tts_voice_list]
342
+ with gr.Blocks() as app:
343
+ gr.Markdown(
344
+ "# <center> Combined Genshin Impact RVC Models\n"
345
+ "## <center> The input audio should be clean and pure voice without background music.\n"
346
+ "### <center> It is recommended to use google colab for more features. \n"
347
+ "[![image](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1Tgr6q9kKiB5P37rUitrB3CsNl8JP9iQZ?usp=sharing)\n\n"
348
+ "[![Original Repo](https://badgen.net/badge/icon/github?icon=github&label=Original%20Repo)](https://github.com/RVC-Project/Retrieval-based-Voice-Conversion-WebUI)"
349
+ )
350
+ with gr.Tabs():
351
+ for (name, title, author, cover, model_version, vc_fn) in models:
352
+ with gr.TabItem(name):
353
+ with gr.Row():
354
+ gr.Markdown(
355
+ '<div align="center">'
356
+ f'<div>{title}</div>\n'+
357
+ f'<div>RVC {model_version} Model</div>\n'+
358
+ (f'<div>Model author: {author}</div>' if author else "")+
359
+ (f'<img style="width:auto;height:300px;" src="file/{cover}">' if cover else "")+
360
+ '</div>'
361
+ )
362
+ with gr.Row():
363
+ with gr.Column():
364
+ vc_audio_mode = gr.Dropdown(label="Input voice", choices=audio_mode, allow_custom_value=False, value="Upload audio")
365
+ # Input
366
+ vc_input = gr.Textbox(label="Input audio path", visible=False)
367
+ # Upload
368
+ vc_microphone_mode = gr.Checkbox(label="Use Microphone", value=False, visible=True, interactive=True)
369
+ vc_upload = gr.Audio(label="Upload audio file", source="upload", visible=True, interactive=True)
370
+ # Youtube
371
+ vc_download_audio = gr.Dropdown(label="Provider", choices=["Youtube"], allow_custom_value=False, visible=False, value="Youtube", info="Select provider (Default: Youtube)")
372
+ 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=...")
373
+ 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)")
374
+ vc_split = gr.Button("Split Audio", variant="primary", visible=False)
375
+ vc_vocal_preview = gr.Audio(label="Vocal Preview", visible=False)
376
+ vc_inst_preview = gr.Audio(label="Instrumental Preview", visible=False)
377
+ vc_audio_preview = gr.Audio(label="Audio Preview", visible=False)
378
+ # TTS
379
+ tts_text = gr.Textbox(visible=False, label="TTS text", info="Text to speech input")
380
+ tts_voice = gr.Dropdown(label="Edge-tts speaker", choices=voices, visible=False, allow_custom_value=False, value="en-US-AnaNeural-Female")
381
+ with gr.Column():
382
+ 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')
383
+ f0method0 = gr.Radio(
384
+ label="Pitch extraction algorithm",
385
+ info=f0method_info,
386
+ choices=f0method_mode,
387
+ value="pm",
388
+ interactive=True
389
+ )
390
+ index_rate1 = gr.Slider(
391
+ minimum=0,
392
+ maximum=1,
393
+ label="Retrieval feature ratio",
394
+ info="(Default: 0.7)",
395
+ value=0.7,
396
+ interactive=True,
397
+ )
398
+ filter_radius0 = gr.Slider(
399
+ minimum=0,
400
+ maximum=7,
401
+ label="Apply Median Filtering",
402
+ info="The value represents the filter radius and can reduce breathiness.",
403
+ value=3,
404
+ step=1,
405
+ interactive=True,
406
+ )
407
+ resample_sr0 = gr.Slider(
408
+ minimum=0,
409
+ maximum=48000,
410
+ label="Resample the output audio",
411
+ info="Resample the output audio in post-processing to the final sample rate. Set to 0 for no resampling",
412
+ value=0,
413
+ step=1,
414
+ interactive=True,
415
+ )
416
+ rms_mix_rate0 = gr.Slider(
417
+ minimum=0,
418
+ maximum=1,
419
+ label="Volume Envelope",
420
+ 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",
421
+ value=1,
422
+ interactive=True,
423
+ )
424
+ protect0 = gr.Slider(
425
+ minimum=0,
426
+ maximum=0.5,
427
+ label="Voice Protection",
428
+ 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",
429
+ value=0.5,
430
+ step=0.01,
431
+ interactive=True,
432
+ )
433
+ with gr.Column():
434
+ vc_log = gr.Textbox(label="Output Information", interactive=False)
435
+ vc_output = gr.Audio(label="Output Audio", interactive=False)
436
+ vc_convert = gr.Button("Convert", variant="primary")
437
+ vc_volume = gr.Slider(
438
+ minimum=0,
439
+ maximum=10,
440
+ label="Vocal volume",
441
+ value=4,
442
+ interactive=True,
443
+ step=1,
444
+ info="Adjust vocal volume (Default: 4}",
445
+ visible=False
446
+ )
447
+ vc_combined_output = gr.Audio(label="Output Combined Audio", visible=False)
448
+ vc_combine = gr.Button("Combine",variant="primary", visible=False)
449
+ vc_convert.click(
450
+ fn=vc_fn,
451
+ inputs=[
452
+ vc_audio_mode,
453
+ vc_input,
454
+ vc_upload,
455
+ tts_text,
456
+ tts_voice,
457
+ vc_transform0,
458
+ f0method0,
459
+ index_rate1,
460
+ filter_radius0,
461
+ resample_sr0,
462
+ rms_mix_rate0,
463
+ protect0,
464
+ ],
465
+ outputs=[vc_log ,vc_output]
466
+ )
467
+ vc_split.click(
468
+ fn=cut_vocal_and_inst,
469
+ inputs=[vc_link, vc_download_audio, vc_split_model],
470
+ outputs=[vc_vocal_preview, vc_inst_preview, vc_audio_preview, vc_input]
471
+ )
472
+ vc_combine.click(
473
+ fn=combine_vocal_and_inst,
474
+ inputs=[vc_output, vc_volume, vc_split_model],
475
+ outputs=[vc_combined_output]
476
+ )
477
+ vc_microphone_mode.change(
478
+ fn=use_microphone,
479
+ inputs=vc_microphone_mode,
480
+ outputs=vc_upload
481
+ )
482
+ vc_audio_mode.change(
483
+ fn=change_audio_mode,
484
+ inputs=[vc_audio_mode],
485
+ outputs=[
486
+ vc_input,
487
+ vc_microphone_mode,
488
+ vc_upload,
489
+ vc_download_audio,
490
+ vc_link,
491
+ vc_split_model,
492
+ vc_split,
493
+ vc_vocal_preview,
494
+ vc_inst_preview,
495
+ vc_audio_preview,
496
+ vc_volume,
497
+ vc_combined_output,
498
+ vc_combine,
499
+ tts_text,
500
+ tts_voice
501
+ ]
502
+ )
503
+ app.queue(concurrency_count=1, max_size=20, api_open=config.api).launch(share=config.colab)
app.py ADDED
@@ -0,0 +1,504 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import glob
3
+ import json
4
+ import argparse
5
+ import traceback
6
+ import logging
7
+ import gradio as gr
8
+ import numpy as np
9
+ import librosa
10
+ import torch
11
+ import asyncio
12
+ import edge_tts
13
+ import yt_dlp
14
+ import ffmpeg
15
+ import subprocess
16
+ import sys
17
+ import io
18
+ import wave
19
+ from datetime import datetime
20
+ from fairseq import checkpoint_utils
21
+ from lib.infer_pack.models import (
22
+ SynthesizerTrnMs256NSFsid,
23
+ SynthesizerTrnMs256NSFsid_nono,
24
+ SynthesizerTrnMs768NSFsid,
25
+ SynthesizerTrnMs768NSFsid_nono,
26
+ )
27
+ from vc_infer_pipeline import VC
28
+ from config import Config
29
+ config = Config()
30
+ logging.getLogger("numba").setLevel(logging.WARNING)
31
+ limitation = os.getenv("SYSTEM") == "spaces" # limit audio length in huggingface spaces
32
+
33
+ audio_mode = []
34
+ f0method_mode = []
35
+ f0method_info = ""
36
+
37
+ if limitation is True:
38
+ audio_mode = ["Upload audio", "TTS Audio"]
39
+ f0method_mode = ["pm", "harvest"]
40
+ f0method_info = "PM is fast, Harvest is good but extremely slow, Rvmpe is alternative to harvest (might be better). (Default: PM)"
41
+ else:
42
+ audio_mode = ["Input path", "Upload audio", "Youtube", "TTS Audio"]
43
+ f0method_mode = ["pm", "harvest", "crepe"]
44
+ 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)"
45
+
46
+ if os.path.isfile("rmvpe.pt"):
47
+ f0method_mode.insert(2, "rmvpe")
48
+
49
+ def create_vc_fn(model_name, tgt_sr, net_g, vc, if_f0, version, file_index):
50
+ def vc_fn(
51
+ vc_audio_mode,
52
+ vc_input,
53
+ vc_upload,
54
+ tts_text,
55
+ tts_voice,
56
+ f0_up_key,
57
+ f0_method,
58
+ index_rate,
59
+ filter_radius,
60
+ resample_sr,
61
+ rms_mix_rate,
62
+ protect
63
+ ):
64
+ try:
65
+ print(f"Converting using {model_name}...")
66
+ if vc_audio_mode == "Input path" or "Youtube" and vc_input != "":
67
+ audio, sr = librosa.load(vc_input, sr=16000, mono=True)
68
+ elif vc_audio_mode == "Upload audio":
69
+ if vc_upload is None:
70
+ return "You need to upload an audio", None
71
+ sampling_rate, audio = vc_upload
72
+ duration = audio.shape[0] / sampling_rate
73
+ if duration > 20 and limitation:
74
+ 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
75
+ audio = (audio / np.iinfo(audio.dtype).max).astype(np.float32)
76
+ if len(audio.shape) > 1:
77
+ audio = librosa.to_mono(audio.transpose(1, 0))
78
+ if sampling_rate != 16000:
79
+ audio = librosa.resample(audio, orig_sr=sampling_rate, target_sr=16000)
80
+ elif vc_audio_mode == "TTS Audio":
81
+ if len(tts_text) > 100 and limitation:
82
+ return "Text is too long", None
83
+ if tts_text is None or tts_voice is None:
84
+ return "You need to enter text and select a voice", None
85
+ asyncio.run(edge_tts.Communicate(tts_text, "-".join(tts_voice.split('-')[:-1])).save("tts.mp3"))
86
+ audio, sr = librosa.load("tts.mp3", sr=16000, mono=True)
87
+ vc_input = "tts.mp3"
88
+ times = [0, 0, 0]
89
+ f0_up_key = int(f0_up_key)
90
+ audio_opt = vc.pipeline(
91
+ hubert_model,
92
+ net_g,
93
+ 0,
94
+ audio,
95
+ vc_input,
96
+ times,
97
+ f0_up_key,
98
+ f0_method,
99
+ file_index,
100
+ # file_big_npy,
101
+ index_rate,
102
+ if_f0,
103
+ filter_radius,
104
+ tgt_sr,
105
+ resample_sr,
106
+ rms_mix_rate,
107
+ version,
108
+ protect,
109
+ f0_file=None,
110
+ )
111
+ info = f"[{datetime.now().strftime('%Y-%m-%d %H:%M')}]: npy: {times[0]}, f0: {times[1]}s, infer: {times[2]}s"
112
+ print(info)
113
+ return info, (tgt_sr, audio_opt)
114
+ except:
115
+ info = traceback.format_exc()
116
+ print(f"{model_name} | {info}")
117
+ return info, (tgt_sr, audio_opt)
118
+ return vc_fn
119
+
120
+ def load_model():
121
+ models = []
122
+ with open(f"weights/model_info.json", "r", encoding="utf-8") as f:
123
+ models_info = json.load(f)
124
+ for character_name, info in models_info.items():
125
+ if not info['enable']:
126
+ continue
127
+ model_title = info['title']
128
+ model_name = info['model_path']
129
+ model_author = info.get("author", None)
130
+ model_cover = f"weights/{character_name}/{info['cover']}"
131
+ model_index = f"weights/{character_name}/{info['feature_retrieval_library']}"
132
+ cpt = torch.load(f"weights/{character_name}/{model_name}", map_location="cpu")
133
+ tgt_sr = cpt["config"][-1]
134
+ cpt["config"][-3] = cpt["weight"]["emb_g.weight"].shape[0] # n_spk
135
+ if_f0 = cpt.get("f0", 1)
136
+ version = cpt.get("version", "v1")
137
+ if version == "v1":
138
+ if if_f0 == 1:
139
+ net_g = SynthesizerTrnMs256NSFsid(*cpt["config"], is_half=config.is_half)
140
+ else:
141
+ net_g = SynthesizerTrnMs256NSFsid_nono(*cpt["config"])
142
+ model_version = "V1"
143
+ elif version == "v2":
144
+ if if_f0 == 1:
145
+ net_g = SynthesizerTrnMs768NSFsid(*cpt["config"], is_half=config.is_half)
146
+ else:
147
+ net_g = SynthesizerTrnMs768NSFsid_nono(*cpt["config"])
148
+ model_version = "V2"
149
+ del net_g.enc_q
150
+ print(net_g.load_state_dict(cpt["weight"], strict=False))
151
+ net_g.eval().to(config.device)
152
+ if config.is_half:
153
+ net_g = net_g.half()
154
+ else:
155
+ net_g = net_g.float()
156
+ vc = VC(tgt_sr, config)
157
+ print(f"Model loaded: {character_name} / {info['feature_retrieval_library']} | ({model_version})")
158
+ 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)))
159
+ return models
160
+
161
+ def cut_vocal_and_inst(url, audio_provider, split_model):
162
+ if url != "":
163
+ if not os.path.exists("dl_audio"):
164
+ os.mkdir("dl_audio")
165
+ if audio_provider == "Youtube":
166
+ ydl_opts = {
167
+ 'noplaylist': True,
168
+ 'format': 'bestaudio/best',
169
+ 'postprocessors': [{
170
+ 'key': 'FFmpegExtractAudio',
171
+ 'preferredcodec': 'wav',
172
+ }],
173
+ "outtmpl": 'dl_audio/youtube_audio',
174
+ }
175
+ with yt_dlp.YoutubeDL(ydl_opts) as ydl:
176
+ ydl.download([url])
177
+ audio_path = "dl_audio/youtube_audio.wav"
178
+ if split_model == "htdemucs":
179
+ command = f"demucs --two-stems=vocals {audio_path} -o output"
180
+ result = subprocess.run(command.split(), stdout=subprocess.PIPE)
181
+ print(result.stdout.decode())
182
+ return "output/htdemucs/youtube_audio/vocals.wav", "output/htdemucs/youtube_audio/no_vocals.wav", audio_path, "output/htdemucs/youtube_audio/vocals.wav"
183
+ else:
184
+ command = f"demucs --two-stems=vocals -n mdx_extra_q {audio_path} -o output"
185
+ result = subprocess.run(command.split(), stdout=subprocess.PIPE)
186
+ print(result.stdout.decode())
187
+ 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"
188
+ else:
189
+ raise gr.Error("URL Required!")
190
+ return None, None, None, None
191
+
192
+ def combine_vocal_and_inst(audio_data, audio_volume, split_model):
193
+ if not os.path.exists("output/result"):
194
+ os.mkdir("output/result")
195
+ vocal_path = "output/result/output.wav"
196
+ output_path = "output/result/combine.mp3"
197
+ if split_model == "htdemucs":
198
+ inst_path = "output/htdemucs/youtube_audio/no_vocals.wav"
199
+ else:
200
+ inst_path = "output/mdx_extra_q/youtube_audio/no_vocals.wav"
201
+ with wave.open(vocal_path, "w") as wave_file:
202
+ wave_file.setnchannels(1)
203
+ wave_file.setsampwidth(2)
204
+ wave_file.setframerate(audio_data[0])
205
+ wave_file.writeframes(audio_data[1].tobytes())
206
+ 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}'
207
+ result = subprocess.run(command.split(), stdout=subprocess.PIPE)
208
+ print(result.stdout.decode())
209
+ return output_path
210
+
211
+ def load_hubert():
212
+ global hubert_model
213
+ models, _, _ = checkpoint_utils.load_model_ensemble_and_task(
214
+ ["hubert_base.pt"],
215
+ suffix="",
216
+ )
217
+ hubert_model = models[0]
218
+ hubert_model = hubert_model.to(config.device)
219
+ if config.is_half:
220
+ hubert_model = hubert_model.half()
221
+ else:
222
+ hubert_model = hubert_model.float()
223
+ hubert_model.eval()
224
+
225
+ def change_audio_mode(vc_audio_mode):
226
+ if vc_audio_mode == "Input path":
227
+ return (
228
+ # Input & Upload
229
+ gr.Textbox.update(visible=True),
230
+ gr.Checkbox.update(visible=False),
231
+ gr.Audio.update(visible=False),
232
+ # Youtube
233
+ gr.Dropdown.update(visible=False),
234
+ gr.Textbox.update(visible=False),
235
+ gr.Dropdown.update(visible=False),
236
+ gr.Button.update(visible=False),
237
+ gr.Audio.update(visible=False),
238
+ gr.Audio.update(visible=False),
239
+ gr.Audio.update(visible=False),
240
+ gr.Slider.update(visible=False),
241
+ gr.Audio.update(visible=False),
242
+ gr.Button.update(visible=False),
243
+ # TTS
244
+ gr.Textbox.update(visible=False),
245
+ gr.Dropdown.update(visible=False)
246
+ )
247
+ elif vc_audio_mode == "Upload audio":
248
+ return (
249
+ # Input & Upload
250
+ gr.Textbox.update(visible=False),
251
+ gr.Checkbox.update(visible=True),
252
+ gr.Audio.update(visible=True),
253
+ # Youtube
254
+ gr.Dropdown.update(visible=False),
255
+ gr.Textbox.update(visible=False),
256
+ gr.Dropdown.update(visible=False),
257
+ gr.Button.update(visible=False),
258
+ gr.Audio.update(visible=False),
259
+ gr.Audio.update(visible=False),
260
+ gr.Audio.update(visible=False),
261
+ gr.Slider.update(visible=False),
262
+ gr.Audio.update(visible=False),
263
+ gr.Button.update(visible=False),
264
+ # TTS
265
+ gr.Textbox.update(visible=False),
266
+ gr.Dropdown.update(visible=False)
267
+ )
268
+ elif vc_audio_mode == "Youtube":
269
+ return (
270
+ # Input & Upload
271
+ gr.Textbox.update(visible=False),
272
+ gr.Checkbox.update(visible=False),
273
+ gr.Audio.update(visible=False),
274
+ # Youtube
275
+ gr.Dropdown.update(visible=True),
276
+ gr.Textbox.update(visible=True),
277
+ gr.Dropdown.update(visible=True),
278
+ gr.Button.update(visible=True),
279
+ gr.Audio.update(visible=True),
280
+ gr.Audio.update(visible=True),
281
+ gr.Audio.update(visible=True),
282
+ gr.Slider.update(visible=True),
283
+ gr.Audio.update(visible=True),
284
+ gr.Button.update(visible=True),
285
+ # TTS
286
+ gr.Textbox.update(visible=False),
287
+ gr.Dropdown.update(visible=False)
288
+ )
289
+ elif vc_audio_mode == "TTS Audio":
290
+ return (
291
+ # Input & Upload
292
+ gr.Textbox.update(visible=False),
293
+ gr.Checkbox.update(visible=False),
294
+ gr.Audio.update(visible=False),
295
+ # Youtube
296
+ gr.Dropdown.update(visible=False),
297
+ gr.Textbox.update(visible=False),
298
+ gr.Dropdown.update(visible=False),
299
+ gr.Button.update(visible=False),
300
+ gr.Audio.update(visible=False),
301
+ gr.Audio.update(visible=False),
302
+ gr.Audio.update(visible=False),
303
+ gr.Slider.update(visible=False),
304
+ gr.Audio.update(visible=False),
305
+ gr.Button.update(visible=False),
306
+ # TTS
307
+ gr.Textbox.update(visible=True),
308
+ gr.Dropdown.update(visible=True)
309
+ )
310
+ else:
311
+ return (
312
+ # Input & Upload
313
+ gr.Textbox.update(visible=False),
314
+ gr.Checkbox.update(visible=True),
315
+ gr.Audio.update(visible=True),
316
+ # Youtube
317
+ gr.Dropdown.update(visible=False),
318
+ gr.Textbox.update(visible=False),
319
+ gr.Dropdown.update(visible=False),
320
+ gr.Button.update(visible=False),
321
+ gr.Audio.update(visible=False),
322
+ gr.Audio.update(visible=False),
323
+ gr.Audio.update(visible=False),
324
+ gr.Slider.update(visible=False),
325
+ gr.Audio.update(visible=False),
326
+ gr.Button.update(visible=False),
327
+ # TTS
328
+ gr.Textbox.update(visible=False),
329
+ gr.Dropdown.update(visible=False)
330
+ )
331
+
332
+ def use_microphone(microphone):
333
+ if microphone == True:
334
+ return gr.Audio.update(source="microphone")
335
+ else:
336
+ return gr.Audio.update(source="upload")
337
+
338
+ if __name__ == '__main__':
339
+ load_hubert()
340
+ models = load_model()
341
+ tts_voice_list = asyncio.new_event_loop().run_until_complete(edge_tts.list_voices())
342
+ voices = [f"{v['ShortName']}-{v['Gender']}" for v in tts_voice_list]
343
+ with gr.Blocks() as app:
344
+ gr.Markdown(
345
+ "# <center> Combined Genshin Impact RVC Models\n"
346
+ "## <center> The input audio should be clean and pure voice without background music.\n"
347
+ "### <center> It is recommended to use google colab for more features. \n"
348
+ "[![image](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1Tgr6q9kKiB5P37rUitrB3CsNl8JP9iQZ?usp=sharing)\n\n"
349
+ "[![Original Repo](https://badgen.net/badge/icon/github?icon=github&label=Original%20Repo)](https://github.com/RVC-Project/Retrieval-based-Voice-Conversion-WebUI)"
350
+ )
351
+ with gr.Tabs():
352
+ for (name, title, author, cover, model_version, vc_fn) in models:
353
+ with gr.TabItem(name):
354
+ with gr.Row():
355
+ gr.Markdown(
356
+ '<div align="center">'
357
+ f'<div>{title}</div>\n'+
358
+ f'<div>RVC {model_version} Model</div>\n'+
359
+ (f'<div>Model author: {author}</div>' if author else "")+
360
+ (f'<img style="width:auto;height:300px;" src="file/{cover}">' if cover else "")+
361
+ '</div>'
362
+ )
363
+ with gr.Row():
364
+ with gr.Column():
365
+ vc_audio_mode = gr.Dropdown(label="Input voice", choices=audio_mode, allow_custom_value=False, value="Upload audio")
366
+ # Input
367
+ vc_input = gr.Textbox(label="Input audio path", visible=False)
368
+ # Upload
369
+ vc_microphone_mode = gr.Checkbox(label="Use Microphone", value=False, visible=True, interactive=True)
370
+ vc_upload = gr.Audio(label="Upload audio file", source="upload", visible=True, interactive=True)
371
+ # Youtube
372
+ vc_download_audio = gr.Dropdown(label="Provider", choices=["Youtube"], allow_custom_value=False, visible=False, value="Youtube", info="Select provider (Default: Youtube)")
373
+ 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=...")
374
+ 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)")
375
+ vc_split = gr.Button("Split Audio", variant="primary", visible=False)
376
+ vc_vocal_preview = gr.Audio(label="Vocal Preview", visible=False)
377
+ vc_inst_preview = gr.Audio(label="Instrumental Preview", visible=False)
378
+ vc_audio_preview = gr.Audio(label="Audio Preview", visible=False)
379
+ # TTS
380
+ tts_text = gr.Textbox(visible=False, label="TTS text", info="Text to speech input")
381
+ tts_voice = gr.Dropdown(label="Edge-tts speaker", choices=voices, visible=False, allow_custom_value=False, value="en-US-AnaNeural-Female")
382
+ with gr.Column():
383
+ 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')
384
+ f0method0 = gr.Radio(
385
+ label="Pitch extraction algorithm",
386
+ info=f0method_info,
387
+ choices=f0method_mode,
388
+ value="pm",
389
+ interactive=True
390
+ )
391
+ index_rate1 = gr.Slider(
392
+ minimum=0,
393
+ maximum=1,
394
+ label="Retrieval feature ratio",
395
+ info="(Default: 0.7)",
396
+ value=0.7,
397
+ interactive=True,
398
+ )
399
+ filter_radius0 = gr.Slider(
400
+ minimum=0,
401
+ maximum=7,
402
+ label="Apply Median Filtering",
403
+ info="The value represents the filter radius and can reduce breathiness.",
404
+ value=3,
405
+ step=1,
406
+ interactive=True,
407
+ )
408
+ resample_sr0 = gr.Slider(
409
+ minimum=0,
410
+ maximum=48000,
411
+ label="Resample the output audio",
412
+ info="Resample the output audio in post-processing to the final sample rate. Set to 0 for no resampling",
413
+ value=0,
414
+ step=1,
415
+ interactive=True,
416
+ )
417
+ rms_mix_rate0 = gr.Slider(
418
+ minimum=0,
419
+ maximum=1,
420
+ label="Volume Envelope",
421
+ 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",
422
+ value=1,
423
+ interactive=True,
424
+ )
425
+ protect0 = gr.Slider(
426
+ minimum=0,
427
+ maximum=0.5,
428
+ label="Voice Protection",
429
+ 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",
430
+ value=0.5,
431
+ step=0.01,
432
+ interactive=True,
433
+ )
434
+ with gr.Column():
435
+ vc_log = gr.Textbox(label="Output Information", interactive=False)
436
+ vc_output = gr.Audio(label="Output Audio", interactive=False)
437
+ vc_convert = gr.Button("Convert", variant="primary")
438
+ vc_volume = gr.Slider(
439
+ minimum=0,
440
+ maximum=10,
441
+ label="Vocal volume",
442
+ value=4,
443
+ interactive=True,
444
+ step=1,
445
+ info="Adjust vocal volume (Default: 4}",
446
+ visible=False
447
+ )
448
+ vc_combined_output = gr.Audio(label="Output Combined Audio", visible=False)
449
+ vc_combine = gr.Button("Combine",variant="primary", visible=False)
450
+ vc_convert.click(
451
+ fn=vc_fn,
452
+ inputs=[
453
+ vc_audio_mode,
454
+ vc_input,
455
+ vc_upload,
456
+ tts_text,
457
+ tts_voice,
458
+ vc_transform0,
459
+ f0method0,
460
+ index_rate1,
461
+ filter_radius0,
462
+ resample_sr0,
463
+ rms_mix_rate0,
464
+ protect0,
465
+ ],
466
+ outputs=[vc_log ,vc_output]
467
+ )
468
+ vc_split.click(
469
+ fn=cut_vocal_and_inst,
470
+ inputs=[vc_link, vc_download_audio, vc_split_model],
471
+ outputs=[vc_vocal_preview, vc_inst_preview, vc_audio_preview, vc_input]
472
+ )
473
+ vc_combine.click(
474
+ fn=combine_vocal_and_inst,
475
+ inputs=[vc_output, vc_volume, vc_split_model],
476
+ outputs=[vc_combined_output]
477
+ )
478
+ vc_microphone_mode.change(
479
+ fn=use_microphone,
480
+ inputs=vc_microphone_mode,
481
+ outputs=vc_upload
482
+ )
483
+ vc_audio_mode.change(
484
+ fn=change_audio_mode,
485
+ inputs=[vc_audio_mode],
486
+ outputs=[
487
+ vc_input,
488
+ vc_microphone_mode,
489
+ vc_upload,
490
+ vc_download_audio,
491
+ vc_link,
492
+ vc_split_model,
493
+ vc_split,
494
+ vc_vocal_preview,
495
+ vc_inst_preview,
496
+ vc_audio_preview,
497
+ vc_volume,
498
+ vc_combined_output,
499
+ vc_combine,
500
+ tts_text,
501
+ tts_voice
502
+ ]
503
+ )
504
+ app.queue(concurrency_count=1, max_size=20, api_open=config.api).launch(share=config.colab)
config.py ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import sys
3
+ import torch
4
+ from multiprocessing import cpu_count
5
+
6
+ class Config:
7
+ def __init__(self):
8
+ self.device = "cuda:0"
9
+ self.is_half = True
10
+ self.n_cpu = 0
11
+ self.gpu_name = None
12
+ self.gpu_mem = None
13
+ (
14
+ self.python_cmd,
15
+ self.listen_port,
16
+ self.colab,
17
+ self.noparallel,
18
+ self.noautoopen,
19
+ self.api
20
+ ) = self.arg_parse()
21
+ self.x_pad, self.x_query, self.x_center, self.x_max = self.device_config()
22
+
23
+ @staticmethod
24
+ def arg_parse() -> tuple:
25
+ exe = sys.executable or "python"
26
+ parser = argparse.ArgumentParser()
27
+ parser.add_argument("--port", type=int, default=7865, help="Listen port")
28
+ parser.add_argument("--pycmd", type=str, default=exe, help="Python command")
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
+ # has_mps is only available in nightly pytorch (for now) and MasOS 12.3+.
53
+ # check `getattr` and try it for compatibility
54
+ @staticmethod
55
+ def has_mps() -> bool:
56
+ if not torch.backends.mps.is_available():
57
+ return False
58
+ try:
59
+ torch.zeros(1).to(torch.device("mps"))
60
+ return True
61
+ except Exception:
62
+ return False
63
+
64
+ def device_config(self) -> tuple:
65
+ if torch.cuda.is_available():
66
+ i_device = int(self.device.split(":")[-1])
67
+ self.gpu_name = torch.cuda.get_device_name(i_device)
68
+ if (
69
+ ("16" in self.gpu_name and "V100" not in self.gpu_name.upper())
70
+ or "P40" in self.gpu_name.upper()
71
+ or "1060" in self.gpu_name
72
+ or "1070" in self.gpu_name
73
+ or "1080" in self.gpu_name
74
+ ):
75
+ print("Found GPU", self.gpu_name, ", force to fp32")
76
+ self.is_half = False
77
+ else:
78
+ print("Found GPU", self.gpu_name)
79
+ self.gpu_mem = int(
80
+ torch.cuda.get_device_properties(i_device).total_memory
81
+ / 1024
82
+ / 1024
83
+ / 1024
84
+ + 0.4
85
+ )
86
+ elif self.has_mps():
87
+ print("No supported Nvidia GPU found, use MPS instead")
88
+ self.device = "mps"
89
+ self.is_half = False
90
+ else:
91
+ print("No supported Nvidia GPU found, use CPU instead")
92
+ self.device = "cpu"
93
+ self.is_half = False
94
+
95
+ if self.n_cpu == 0:
96
+ self.n_cpu = cpu_count()
97
+
98
+ if self.is_half:
99
+ # 6G显存配置
100
+ x_pad = 3
101
+ x_query = 10
102
+ x_center = 60
103
+ x_max = 65
104
+ else:
105
+ # 5G显存配置
106
+ x_pad = 1
107
+ x_query = 6
108
+ x_center = 38
109
+ x_max = 41
110
+
111
+ if self.gpu_mem != None and self.gpu_mem <= 4:
112
+ x_pad = 1
113
+ x_query = 5
114
+ x_center = 30
115
+ x_max = 32
116
+
117
+ return x_pad, x_query, x_center, x_max
gitattributes.txt ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tflite filter=lfs diff=lfs merge=lfs -text
29
+ *.tgz filter=lfs diff=lfs merge=lfs -text
30
+ *.wasm filter=lfs diff=lfs merge=lfs -text
31
+ *.xz filter=lfs diff=lfs merge=lfs -text
32
+ *.zip filter=lfs diff=lfs merge=lfs -text
33
+ *.zst filter=lfs diff=lfs merge=lfs -text
34
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
35
+ *.index filter=lfs diff=lfs merge=lfs -text
36
+ *.png filter=lfs diff=lfs merge=lfs -text
gitignore.txt ADDED
@@ -0,0 +1,382 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ## Ignore Visual Studio temporary files, build results, and
2
+ ## files generated by popular Visual Studio add-ons.
3
+ ##
4
+ ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
5
+
6
+ # User-specific files
7
+ *.rsuser
8
+ *.suo
9
+ *.user
10
+ *.userosscache
11
+ *.sln.docstates
12
+
13
+ # User-specific files (MonoDevelop/Xamarin Studio)
14
+ *.userprefs
15
+
16
+ # Mono auto generated files
17
+ mono_crash.*
18
+
19
+ # Build results
20
+ [Dd]ebug/
21
+ [Dd]ebugPublic/
22
+ [Rr]elease/
23
+ [Rr]eleases/
24
+ x64/
25
+ x86/
26
+ [Ww][Ii][Nn]32/
27
+ [Aa][Rr][Mm]/
28
+ [Aa][Rr][Mm]64/
29
+ bld/
30
+ [Bb]in/
31
+ [Oo]bj/
32
+ [Oo]ut/
33
+ [Ll]og/
34
+ [Ll]ogs/
35
+ infer_pack\__pycache__
36
+ # Visual Studio 2015/2017 cache/options directory
37
+ .vs/
38
+ # Uncomment if you have tasks that create the project's static files in wwwroot
39
+ #wwwroot/
40
+
41
+ # Visual Studio 2017 auto generated files
42
+ Generated\ Files/
43
+
44
+ # MSTest test Results
45
+ [Tt]est[Rr]esult*/
46
+ [Bb]uild[Ll]og.*
47
+
48
+ # NUnit
49
+ *.VisualState.xml
50
+ TestResult.xml
51
+ nunit-*.xml
52
+
53
+ # Build Results of an ATL Project
54
+ [Dd]ebugPS/
55
+ [Rr]eleasePS/
56
+ dlldata.c
57
+
58
+ # Benchmark Results
59
+ BenchmarkDotNet.Artifacts/
60
+
61
+ # .NET Core
62
+ project.lock.json
63
+ project.fragment.lock.json
64
+ artifacts/
65
+
66
+ # ASP.NET Scaffolding
67
+ ScaffoldingReadMe.txt
68
+
69
+ # StyleCop
70
+ StyleCopReport.xml
71
+
72
+ # Files built by Visual Studio
73
+ *_i.c
74
+ *_p.c
75
+ *_h.h
76
+ *.ilk
77
+ *.meta
78
+ *.obj
79
+ *.iobj
80
+ *.pch
81
+ *.pdb
82
+ *.ipdb
83
+ *.pgc
84
+ *.pgd
85
+ *.rsp
86
+ *.sbr
87
+ *.tlb
88
+ *.tli
89
+ *.tlh
90
+ *.tmp
91
+ *.tmp_proj
92
+ *_wpftmp.csproj
93
+ *.log
94
+ *.vspscc
95
+ *.vssscc
96
+ .builds
97
+ *.pidb
98
+ *.svclog
99
+ *.scc
100
+
101
+ # Chutzpah Test files
102
+ _Chutzpah*
103
+
104
+ # Visual C++ cache files
105
+ ipch/
106
+ *.aps
107
+ *.ncb
108
+ *.opendb
109
+ *.opensdf
110
+ *.sdf
111
+ *.cachefile
112
+ *.VC.db
113
+ *.VC.VC.opendb
114
+
115
+ # Visual Studio profiler
116
+ *.psess
117
+ *.vsp
118
+ *.vspx
119
+ *.sap
120
+
121
+ # Visual Studio Trace Files
122
+ *.e2e
123
+
124
+ # TFS 2012 Local Workspace
125
+ $tf/
126
+
127
+ # Guidance Automation Toolkit
128
+ *.gpState
129
+
130
+ # ReSharper is a .NET coding add-in
131
+ _ReSharper*/
132
+ *.[Rr]e[Ss]harper
133
+ *.DotSettings.user
134
+
135
+ # TeamCity is a build add-in
136
+ _TeamCity*
137
+
138
+ # DotCover is a Code Coverage Tool
139
+ *.dotCover
140
+
141
+ # AxoCover is a Code Coverage Tool
142
+ .axoCover/*
143
+ !.axoCover/settings.json
144
+
145
+ # Coverlet is a free, cross platform Code Coverage Tool
146
+ coverage*.json
147
+ coverage*.xml
148
+ coverage*.info
149
+
150
+ # Visual Studio code coverage results
151
+ *.coverage
152
+ *.coveragexml
153
+
154
+ # NCrunch
155
+ _NCrunch_*
156
+ .*crunch*.local.xml
157
+ nCrunchTemp_*
158
+
159
+ # MightyMoose
160
+ *.mm.*
161
+ AutoTest.Net/
162
+
163
+ # Web workbench (sass)
164
+ .sass-cache/
165
+
166
+ # Installshield output folder
167
+ [Ee]xpress/
168
+
169
+ # DocProject is a documentation generator add-in
170
+ DocProject/buildhelp/
171
+ DocProject/Help/*.HxT
172
+ DocProject/Help/*.HxC
173
+ DocProject/Help/*.hhc
174
+ DocProject/Help/*.hhk
175
+ DocProject/Help/*.hhp
176
+ DocProject/Help/Html2
177
+ DocProject/Help/html
178
+
179
+ # Click-Once directory
180
+ publish/
181
+
182
+ # Publish Web Output
183
+ *.[Pp]ublish.xml
184
+ *.azurePubxml
185
+ # Note: Comment the next line if you want to checkin your web deploy settings,
186
+ # but database connection strings (with potential passwords) will be unencrypted
187
+ *.pubxml
188
+ *.publishproj
189
+
190
+ # Microsoft Azure Web App publish settings. Comment the next line if you want to
191
+ # checkin your Azure Web App publish settings, but sensitive information contained
192
+ # in these scripts will be unencrypted
193
+ PublishScripts/
194
+
195
+ # NuGet Packages
196
+ *.nupkg
197
+ # NuGet Symbol Packages
198
+ *.snupkg
199
+ # The packages folder can be ignored because of Package Restore
200
+ **/[Pp]ackages/*
201
+ # except build/, which is used as an MSBuild target.
202
+ !**/[Pp]ackages/build/
203
+ # Uncomment if necessary however generally it will be regenerated when needed
204
+ #!**/[Pp]ackages/repositories.config
205
+ # NuGet v3's project.json files produces more ignorable files
206
+ *.nuget.props
207
+ *.nuget.targets
208
+
209
+ # Microsoft Azure Build Output
210
+ csx/
211
+ *.build.csdef
212
+
213
+ # Microsoft Azure Emulator
214
+ ecf/
215
+ rcf/
216
+
217
+ # Windows Store app package directories and files
218
+ AppPackages/
219
+ BundleArtifacts/
220
+ Package.StoreAssociation.xml
221
+ _pkginfo.txt
222
+ *.appx
223
+ *.appxbundle
224
+ *.appxupload
225
+
226
+ # Visual Studio cache files
227
+ # files ending in .cache can be ignored
228
+ *.[Cc]ache
229
+ # but keep track of directories ending in .cache
230
+ !?*.[Cc]ache/
231
+
232
+ # Others
233
+ ClientBin/
234
+ ~$*
235
+ *~
236
+ *.dbmdl
237
+ *.dbproj.schemaview
238
+ *.jfm
239
+ *.pfx
240
+ *.publishsettings
241
+ orleans.codegen.cs
242
+
243
+ # Including strong name files can present a security risk
244
+ # (https://github.com/github/gitignore/pull/2483#issue-259490424)
245
+ #*.snk
246
+
247
+ # Since there are multiple workflows, uncomment next line to ignore bower_components
248
+ # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
249
+ #bower_components/
250
+
251
+ # RIA/Silverlight projects
252
+ Generated_Code/
253
+
254
+ # Backup & report files from converting an old project file
255
+ # to a newer Visual Studio version. Backup files are not needed,
256
+ # because we have git ;-)
257
+ _UpgradeReport_Files/
258
+ Backup*/
259
+ UpgradeLog*.XML
260
+ UpgradeLog*.htm
261
+ ServiceFabricBackup/
262
+ *.rptproj.bak
263
+
264
+ # SQL Server files
265
+ *.mdf
266
+ *.ldf
267
+ *.ndf
268
+
269
+ # Business Intelligence projects
270
+ *.rdl.data
271
+ *.bim.layout
272
+ *.bim_*.settings
273
+ *.rptproj.rsuser
274
+ *- [Bb]ackup.rdl
275
+ *- [Bb]ackup ([0-9]).rdl
276
+ *- [Bb]ackup ([0-9][0-9]).rdl
277
+
278
+ # Microsoft Fakes
279
+ FakesAssemblies/
280
+
281
+ # GhostDoc plugin setting file
282
+ *.GhostDoc.xml
283
+
284
+ # Node.js Tools for Visual Studio
285
+ .ntvs_analysis.dat
286
+ node_modules/
287
+
288
+ # Visual Studio 6 build log
289
+ *.plg
290
+
291
+ # Visual Studio 6 workspace options file
292
+ *.opt
293
+
294
+ # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
295
+ *.vbw
296
+
297
+ # Visual Studio LightSwitch build output
298
+ **/*.HTMLClient/GeneratedArtifacts
299
+ **/*.DesktopClient/GeneratedArtifacts
300
+ **/*.DesktopClient/ModelManifest.xml
301
+ **/*.Server/GeneratedArtifacts
302
+ **/*.Server/ModelManifest.xml
303
+ _Pvt_Extensions
304
+
305
+ # Paket dependency manager
306
+ .paket/paket.exe
307
+ paket-files/
308
+
309
+ # FAKE - F# Make
310
+ .fake/
311
+
312
+ # CodeRush personal settings
313
+ .cr/personal
314
+
315
+ # Python Tools for Visual Studio (PTVS)
316
+ __pycache__/
317
+
318
+
319
+ # Cake - Uncomment if you are using it
320
+ # tools/**
321
+ # !tools/packages.config
322
+
323
+ # Tabs Studio
324
+ *.tss
325
+
326
+ # Telerik's JustMock configuration file
327
+ *.jmconfig
328
+
329
+ # BizTalk build output
330
+ *.btp.cs
331
+ *.btm.cs
332
+ *.odx.cs
333
+ *.xsd.cs
334
+
335
+ # OpenCover UI analysis results
336
+ OpenCover/
337
+
338
+ # Azure Stream Analytics local run output
339
+ ASALocalRun/
340
+
341
+ # MSBuild Binary and Structured Log
342
+ *.binlog
343
+
344
+ # NVidia Nsight GPU debugger configuration file
345
+ *.nvuser
346
+
347
+ # MFractors (Xamarin productivity tool) working folder
348
+ .mfractor/
349
+
350
+ # Local History for Visual Studio
351
+ .localhistory/
352
+
353
+ # BeatPulse healthcheck temp database
354
+ healthchecksdb
355
+
356
+ # Backup folder for Package Reference Convert tool in Visual Studio 2017
357
+ MigrationBackup/
358
+
359
+ # Ionide (cross platform F# VS Code tools) working folder
360
+ .ionide/
361
+
362
+ # Fody - auto-generated XML schema
363
+ FodyWeavers.xsd
364
+
365
+ # build
366
+ build
367
+ monotonic_align/core.c
368
+ *.o
369
+ *.so
370
+ *.dll
371
+
372
+ # data
373
+ /config.json
374
+ /*.pth
375
+ *.wav
376
+ /monotonic_align/monotonic_align
377
+ /resources
378
+ /MoeGoe.spec
379
+ /dist/MoeGoe
380
+ /dist
381
+
382
+ .idea
hubert_base.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f54b40fd2802423a5643779c4861af1e9ee9c1564dc9d32f54f20b5ffba7db96
3
+ size 189507909
requirements.txt ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ wheel
2
+ setuptools
3
+ ffmpeg
4
+ numba==0.56.4
5
+ numpy==1.23.5
6
+ scipy==1.9.3
7
+ librosa==0.9.1
8
+ fairseq==0.12.2
9
+ faiss-cpu==1.7.3
10
+ gradio==3.36.1
11
+ pyworld==0.3.2
12
+ soundfile>=0.12.1
13
+ praat-parselmouth>=0.4.2
14
+ httpx==0.23.0
15
+ tensorboard
16
+ tensorboardX
17
+ torchcrepe
18
+ onnxruntime
19
+ demucs
20
+ edge-tts
21
+ yt_dlp
rmvpe.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a5ed4719f59085d1affc5d81354c70828c740584f2d24e782523345a6a278962
3
+ size 181189687
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 ADDED
@@ -0,0 +1,443 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
5
+ import pyworld, os, traceback, faiss, librosa, torchcrepe
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 = {}
15
+
16
+
17
+ @lru_cache
18
+ def cache_harvest_f0(input_audio_path, fs, f0max, f0min, frame_period):
19
+ audio = input_audio_path2wav[input_audio_path]
20
+ f0, t = pyworld.harvest(
21
+ audio,
22
+ fs=fs,
23
+ f0_ceil=f0max,
24
+ f0_floor=f0min,
25
+ frame_period=frame_period,
26
+ )
27
+ f0 = pyworld.stonemask(audio, f0, t, fs)
28
+ return f0
29
+
30
+
31
+ def change_rms(data1, sr1, data2, sr2, rate): # 1是输入音频,2是输出音频,rate是2的占比
32
+ # print(data1.max(),data2.max())
33
+ rms1 = librosa.feature.rms(
34
+ y=data1, frame_length=sr1 // 2 * 2, hop_length=sr1 // 2
35
+ ) # 每半秒一个点
36
+ rms2 = librosa.feature.rms(y=data2, frame_length=sr2 // 2 * 2, hop_length=sr2 // 2)
37
+ rms1 = torch.from_numpy(rms1)
38
+ rms1 = F.interpolate(
39
+ rms1.unsqueeze(0), size=data2.shape[0], mode="linear"
40
+ ).squeeze()
41
+ rms2 = torch.from_numpy(rms2)
42
+ rms2 = F.interpolate(
43
+ rms2.unsqueeze(0), size=data2.shape[0], mode="linear"
44
+ ).squeeze()
45
+ rms2 = torch.max(rms2, torch.zeros_like(rms2) + 1e-6)
46
+ data2 *= (
47
+ torch.pow(rms1, torch.tensor(1 - rate))
48
+ * torch.pow(rms2, torch.tensor(rate - 1))
49
+ ).numpy()
50
+ return data2
51
+
52
+
53
+ class VC(object):
54
+ def __init__(self, tgt_sr, config):
55
+ self.x_pad, self.x_query, self.x_center, self.x_max, self.is_half = (
56
+ config.x_pad,
57
+ config.x_query,
58
+ config.x_center,
59
+ config.x_max,
60
+ config.is_half,
61
+ )
62
+ self.sr = 16000 # hubert输入采样率
63
+ self.window = 160 # 每帧点数
64
+ self.t_pad = self.sr * self.x_pad # 每条前后pad时间
65
+ self.t_pad_tgt = tgt_sr * self.x_pad
66
+ self.t_pad2 = self.t_pad * 2
67
+ self.t_query = self.sr * self.x_query # 查询切点前后查询时间
68
+ self.t_center = self.sr * self.x_center # 查询切点位置
69
+ self.t_max = self.sr * self.x_max # 免查询时长阈值
70
+ self.device = config.device
71
+
72
+ def get_f0(
73
+ self,
74
+ input_audio_path,
75
+ x,
76
+ p_len,
77
+ f0_up_key,
78
+ f0_method,
79
+ filter_radius,
80
+ inp_f0=None,
81
+ ):
82
+ global input_audio_path2wav
83
+ time_step = self.window / self.sr * 1000
84
+ f0_min = 50
85
+ f0_max = 1100
86
+ f0_mel_min = 1127 * np.log(1 + f0_min / 700)
87
+ f0_mel_max = 1127 * np.log(1 + f0_max / 700)
88
+ if f0_method == "pm":
89
+ f0 = (
90
+ parselmouth.Sound(x, self.sr)
91
+ .to_pitch_ac(
92
+ time_step=time_step / 1000,
93
+ voicing_threshold=0.6,
94
+ pitch_floor=f0_min,
95
+ pitch_ceiling=f0_max,
96
+ )
97
+ .selected_array["frequency"]
98
+ )
99
+ pad_size = (p_len - len(f0) + 1) // 2
100
+ if pad_size > 0 or p_len - len(f0) - pad_size > 0:
101
+ f0 = np.pad(
102
+ f0, [[pad_size, p_len - len(f0) - pad_size]], mode="constant"
103
+ )
104
+ elif f0_method == "harvest":
105
+ input_audio_path2wav[input_audio_path] = x.astype(np.double)
106
+ f0 = cache_harvest_f0(input_audio_path, self.sr, f0_max, f0_min, 10)
107
+ if filter_radius > 2:
108
+ f0 = signal.medfilt(f0, 3)
109
+ elif f0_method == "crepe":
110
+ model = "full"
111
+ # Pick a batch size that doesn't cause memory errors on your gpu
112
+ batch_size = 512
113
+ # Compute pitch using first gpu
114
+ audio = torch.tensor(np.copy(x))[None].float()
115
+ f0, pd = torchcrepe.predict(
116
+ audio,
117
+ self.sr,
118
+ self.window,
119
+ f0_min,
120
+ f0_max,
121
+ model,
122
+ batch_size=batch_size,
123
+ device=self.device,
124
+ return_periodicity=True,
125
+ )
126
+ pd = torchcrepe.filter.median(pd, 3)
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点数
142
+ if inp_f0 is not None:
143
+ delta_t = np.round(
144
+ (inp_f0[:, 0].max() - inp_f0[:, 0].min()) * tf0 + 1
145
+ ).astype("int16")
146
+ replace_f0 = np.interp(
147
+ list(range(delta_t)), inp_f0[:, 0] * 100, inp_f0[:, 1]
148
+ )
149
+ shape = f0[self.x_pad * tf0 : self.x_pad * tf0 + len(replace_f0)].shape[0]
150
+ f0[self.x_pad * tf0 : self.x_pad * tf0 + len(replace_f0)] = replace_f0[
151
+ :shape
152
+ ]
153
+ # with open("test_opt.txt","w")as f:f.write("\n".join([str(i)for i in f0.tolist()]))
154
+ f0bak = f0.copy()
155
+ f0_mel = 1127 * np.log(1 + f0 / 700)
156
+ f0_mel[f0_mel > 0] = (f0_mel[f0_mel > 0] - f0_mel_min) * 254 / (
157
+ f0_mel_max - f0_mel_min
158
+ ) + 1
159
+ f0_mel[f0_mel <= 1] = 1
160
+ f0_mel[f0_mel > 255] = 255
161
+ f0_coarse = np.rint(f0_mel).astype(np.int)
162
+ return f0_coarse, f0bak # 1-0
163
+
164
+ def vc(
165
+ self,
166
+ model,
167
+ net_g,
168
+ sid,
169
+ audio0,
170
+ pitch,
171
+ pitchf,
172
+ times,
173
+ index,
174
+ big_npy,
175
+ index_rate,
176
+ version,
177
+ protect,
178
+ ): # ,file_index,file_big_npy
179
+ feats = torch.from_numpy(audio0)
180
+ if self.is_half:
181
+ feats = feats.half()
182
+ else:
183
+ feats = feats.float()
184
+ if feats.dim() == 2: # double channels
185
+ feats = feats.mean(-1)
186
+ assert feats.dim() == 1, feats.dim()
187
+ feats = feats.view(1, -1)
188
+ padding_mask = torch.BoolTensor(feats.shape).to(self.device).fill_(False)
189
+
190
+ inputs = {
191
+ "source": feats.to(self.device),
192
+ "padding_mask": padding_mask,
193
+ "output_layer": 9 if version == "v1" else 12,
194
+ }
195
+ t0 = ttime()
196
+ with torch.no_grad():
197
+ logits = model.extract_features(**inputs)
198
+ feats = model.final_proj(logits[0]) if version == "v1" else logits[0]
199
+ if protect < 0.5 and pitch != None and pitchf != None:
200
+ feats0 = feats.clone()
201
+ if (
202
+ isinstance(index, type(None)) == False
203
+ and isinstance(big_npy, type(None)) == False
204
+ and index_rate != 0
205
+ ):
206
+ npy = feats[0].cpu().numpy()
207
+ if self.is_half:
208
+ npy = npy.astype("float32")
209
+
210
+ # _, I = index.search(npy, 1)
211
+ # npy = big_npy[I.squeeze()]
212
+
213
+ score, ix = index.search(npy, k=8)
214
+ weight = np.square(1 / score)
215
+ weight /= weight.sum(axis=1, keepdims=True)
216
+ npy = np.sum(big_npy[ix] * np.expand_dims(weight, axis=2), axis=1)
217
+
218
+ if self.is_half:
219
+ npy = npy.astype("float16")
220
+ feats = (
221
+ torch.from_numpy(npy).unsqueeze(0).to(self.device) * index_rate
222
+ + (1 - index_rate) * feats
223
+ )
224
+
225
+ feats = F.interpolate(feats.permute(0, 2, 1), scale_factor=2).permute(0, 2, 1)
226
+ if protect < 0.5 and pitch != None and pitchf != None:
227
+ feats0 = F.interpolate(feats0.permute(0, 2, 1), scale_factor=2).permute(
228
+ 0, 2, 1
229
+ )
230
+ t1 = ttime()
231
+ p_len = audio0.shape[0] // self.window
232
+ if feats.shape[1] < p_len:
233
+ p_len = feats.shape[1]
234
+ if pitch != None and pitchf != None:
235
+ pitch = pitch[:, :p_len]
236
+ pitchf = pitchf[:, :p_len]
237
+
238
+ if protect < 0.5 and pitch != None and pitchf != None:
239
+ pitchff = pitchf.clone()
240
+ pitchff[pitchf > 0] = 1
241
+ pitchff[pitchf < 1] = protect
242
+ pitchff = pitchff.unsqueeze(-1)
243
+ feats = feats * pitchff + feats0 * (1 - pitchff)
244
+ feats = feats.to(feats0.dtype)
245
+ p_len = torch.tensor([p_len], device=self.device).long()
246
+ with torch.no_grad():
247
+ if pitch != None and pitchf != None:
248
+ audio1 = (
249
+ (net_g.infer(feats, p_len, pitch, pitchf, sid)[0][0, 0])
250
+ .data.cpu()
251
+ .float()
252
+ .numpy()
253
+ )
254
+ else:
255
+ audio1 = (
256
+ (net_g.infer(feats, p_len, sid)[0][0, 0]).data.cpu().float().numpy()
257
+ )
258
+ del feats, p_len, padding_mask
259
+ if torch.cuda.is_available():
260
+ torch.cuda.empty_cache()
261
+ t2 = ttime()
262
+ times[0] += t1 - t0
263
+ times[2] += t2 - t1
264
+ return audio1
265
+
266
+ def pipeline(
267
+ self,
268
+ model,
269
+ net_g,
270
+ sid,
271
+ audio,
272
+ input_audio_path,
273
+ times,
274
+ f0_up_key,
275
+ f0_method,
276
+ file_index,
277
+ # file_big_npy,
278
+ index_rate,
279
+ if_f0,
280
+ filter_radius,
281
+ tgt_sr,
282
+ resample_sr,
283
+ rms_mix_rate,
284
+ version,
285
+ protect,
286
+ f0_file=None,
287
+ ):
288
+ if (
289
+ file_index != ""
290
+ # and file_big_npy != ""
291
+ # and os.path.exists(file_big_npy) == True
292
+ and os.path.exists(file_index) == True
293
+ and index_rate != 0
294
+ ):
295
+ try:
296
+ index = faiss.read_index(file_index)
297
+ # big_npy = np.load(file_big_npy)
298
+ big_npy = index.reconstruct_n(0, index.ntotal)
299
+ except:
300
+ traceback.print_exc()
301
+ index = big_npy = None
302
+ else:
303
+ index = big_npy = None
304
+ audio = signal.filtfilt(bh, ah, audio)
305
+ audio_pad = np.pad(audio, (self.window // 2, self.window // 2), mode="reflect")
306
+ opt_ts = []
307
+ if audio_pad.shape[0] > self.t_max:
308
+ audio_sum = np.zeros_like(audio)
309
+ for i in range(self.window):
310
+ audio_sum += audio_pad[i : i - self.window]
311
+ for t in range(self.t_center, audio.shape[0], self.t_center):
312
+ opt_ts.append(
313
+ t
314
+ - self.t_query
315
+ + np.where(
316
+ np.abs(audio_sum[t - self.t_query : t + self.t_query])
317
+ == np.abs(audio_sum[t - self.t_query : t + self.t_query]).min()
318
+ )[0][0]
319
+ )
320
+ s = 0
321
+ audio_opt = []
322
+ t = None
323
+ t1 = ttime()
324
+ audio_pad = np.pad(audio, (self.t_pad, self.t_pad), mode="reflect")
325
+ p_len = audio_pad.shape[0] // self.window
326
+ inp_f0 = None
327
+ if hasattr(f0_file, "name") == True:
328
+ try:
329
+ with open(f0_file.name, "r") as f:
330
+ lines = f.read().strip("\n").split("\n")
331
+ inp_f0 = []
332
+ for line in lines:
333
+ inp_f0.append([float(i) for i in line.split(",")])
334
+ inp_f0 = np.array(inp_f0, dtype="float32")
335
+ except:
336
+ traceback.print_exc()
337
+ sid = torch.tensor(sid, device=self.device).unsqueeze(0).long()
338
+ pitch, pitchf = None, None
339
+ if if_f0 == 1:
340
+ pitch, pitchf = self.get_f0(
341
+ input_audio_path,
342
+ audio_pad,
343
+ p_len,
344
+ f0_up_key,
345
+ f0_method,
346
+ filter_radius,
347
+ inp_f0,
348
+ )
349
+ pitch = pitch[:p_len]
350
+ pitchf = pitchf[:p_len]
351
+ if self.device == "mps":
352
+ pitchf = pitchf.astype(np.float32)
353
+ pitch = torch.tensor(pitch, device=self.device).unsqueeze(0).long()
354
+ pitchf = torch.tensor(pitchf, device=self.device).unsqueeze(0).float()
355
+ t2 = ttime()
356
+ times[1] += t2 - t1
357
+ for t in opt_ts:
358
+ t = t // self.window * self.window
359
+ if if_f0 == 1:
360
+ audio_opt.append(
361
+ self.vc(
362
+ model,
363
+ net_g,
364
+ sid,
365
+ audio_pad[s : t + self.t_pad2 + self.window],
366
+ pitch[:, s // self.window : (t + self.t_pad2) // self.window],
367
+ pitchf[:, s // self.window : (t + self.t_pad2) // self.window],
368
+ times,
369
+ index,
370
+ big_npy,
371
+ index_rate,
372
+ version,
373
+ protect,
374
+ )[self.t_pad_tgt : -self.t_pad_tgt]
375
+ )
376
+ else:
377
+ audio_opt.append(
378
+ self.vc(
379
+ model,
380
+ net_g,
381
+ sid,
382
+ audio_pad[s : t + self.t_pad2 + self.window],
383
+ None,
384
+ None,
385
+ times,
386
+ index,
387
+ big_npy,
388
+ index_rate,
389
+ version,
390
+ protect,
391
+ )[self.t_pad_tgt : -self.t_pad_tgt]
392
+ )
393
+ s = t
394
+ if if_f0 == 1:
395
+ audio_opt.append(
396
+ self.vc(
397
+ model,
398
+ net_g,
399
+ sid,
400
+ audio_pad[t:],
401
+ pitch[:, t // self.window :] if t is not None else pitch,
402
+ pitchf[:, t // self.window :] if t is not None else pitchf,
403
+ times,
404
+ index,
405
+ big_npy,
406
+ index_rate,
407
+ version,
408
+ protect,
409
+ )[self.t_pad_tgt : -self.t_pad_tgt]
410
+ )
411
+ else:
412
+ audio_opt.append(
413
+ self.vc(
414
+ model,
415
+ net_g,
416
+ sid,
417
+ audio_pad[t:],
418
+ None,
419
+ None,
420
+ times,
421
+ index,
422
+ big_npy,
423
+ index_rate,
424
+ version,
425
+ protect,
426
+ )[self.t_pad_tgt : -self.t_pad_tgt]
427
+ )
428
+ audio_opt = np.concatenate(audio_opt)
429
+ if rms_mix_rate != 1:
430
+ audio_opt = change_rms(audio, 16000, audio_opt, tgt_sr, rms_mix_rate)
431
+ if resample_sr >= 16000 and tgt_sr != resample_sr:
432
+ audio_opt = librosa.resample(
433
+ audio_opt, orig_sr=tgt_sr, target_sr=resample_sr
434
+ )
435
+ audio_max = np.abs(audio_opt).max() / 0.99
436
+ max_int16 = 32768
437
+ if audio_max > 1:
438
+ max_int16 /= audio_max
439
+ audio_opt = (audio_opt * max_int16).astype(np.int16)
440
+ del pitch, pitchf, sid
441
+ if torch.cuda.is_available():
442
+ torch.cuda.empty_cache()
443
+ return audio_opt