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

Delete app-spaces.py

Browse files
Files changed (1) hide show
  1. app-spaces.py +0 -496
app-spaces.py DELETED
@@ -1,496 +0,0 @@
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 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
- def create_vc_fn(tgt_sr, net_g, vc, if_f0, file_index):
33
- def vc_fn(
34
- vc_audio_mode,
35
- vc_input,
36
- vc_upload,
37
- tts_text,
38
- tts_voice,
39
- spk_item,
40
- f0_up_key,
41
- f0_method,
42
- index_rate,
43
- filter_radius,
44
- resample_sr,
45
- rms_mix_rate,
46
- protect,
47
- ):
48
- try:
49
- if vc_audio_mode == "Input path" or "Youtube" and vc_input != "":
50
- audio, sr = librosa.load(vc_input, sr=16000, mono=True)
51
- elif vc_audio_mode == "Upload audio":
52
- if vc_upload is None:
53
- return "You need to upload an audio", None
54
- sampling_rate, audio = vc_upload
55
- duration = audio.shape[0] / sampling_rate
56
- if duration > 20 and limitation:
57
- 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
58
- audio = (audio / np.iinfo(audio.dtype).max).astype(np.float32)
59
- if len(audio.shape) > 1:
60
- audio = librosa.to_mono(audio.transpose(1, 0))
61
- if sampling_rate != 16000:
62
- audio = librosa.resample(audio, orig_sr=sampling_rate, target_sr=16000)
63
- elif vc_audio_mode == "TTS Audio":
64
- if len(tts_text) > 100 and limitation:
65
- return "Text is too long", None
66
- if tts_text is None or tts_voice is None:
67
- return "You need to enter text and select a voice", None
68
- asyncio.run(edge_tts.Communicate(tts_text, "-".join(tts_voice.split('-')[:-1])).save("tts.mp3"))
69
- audio, sr = librosa.load("tts.mp3", sr=16000, mono=True)
70
- vc_input = "tts.mp3"
71
- times = [0, 0, 0]
72
- f0_up_key = int(f0_up_key)
73
- audio_opt = vc.pipeline(
74
- hubert_model,
75
- net_g,
76
- spk_item,
77
- audio,
78
- vc_input,
79
- times,
80
- f0_up_key,
81
- f0_method,
82
- file_index,
83
- index_rate,
84
- if_f0,
85
- filter_radius,
86
- tgt_sr,
87
- resample_sr,
88
- rms_mix_rate,
89
- version,
90
- protect,
91
- f0_file=None,
92
- )
93
- info = f"[{datetime.now().strftime('%Y-%m-%d %H:%M')}]: npy: {times[0]}, f0: {times[1]}s, infer: {times[2]}s"
94
- print(info)
95
- return info, (tgt_sr, audio_opt)
96
- except:
97
- info = traceback.format_exc()
98
- print(info)
99
- return info, (None, None)
100
- return vc_fn
101
-
102
- def cut_vocal_and_inst(url, audio_provider, split_model):
103
- if url != "":
104
- if not os.path.exists("dl_audio"):
105
- os.mkdir("dl_audio")
106
- if audio_provider == "Youtube":
107
- ydl_opts = {
108
- 'format': 'bestaudio/best',
109
- 'postprocessors': [{
110
- 'key': 'FFmpegExtractAudio',
111
- 'preferredcodec': 'wav',
112
- }],
113
- "outtmpl": 'dl_audio/youtube_audio',
114
- }
115
- with yt_dlp.YoutubeDL(ydl_opts) as ydl:
116
- ydl.download([url])
117
- audio_path = "dl_audio/youtube_audio.wav"
118
- else:
119
- # Spotify doesnt work.
120
- # Need to find other solution soon.
121
- '''
122
- command = f"spotdl download {url} --output dl_audio/.wav"
123
- result = subprocess.run(command.split(), stdout=subprocess.PIPE)
124
- print(result.stdout.decode())
125
- audio_path = "dl_audio/spotify_audio.wav"
126
- '''
127
- if split_model == "htdemucs":
128
- command = f"demucs --two-stems=vocals {audio_path} -o output"
129
- result = subprocess.run(command.split(), stdout=subprocess.PIPE)
130
- print(result.stdout.decode())
131
- return "output/htdemucs/youtube_audio/vocals.wav", "output/htdemucs/youtube_audio/no_vocals.wav", audio_path, "output/htdemucs/youtube_audio/vocals.wav"
132
- else:
133
- command = f"demucs --two-stems=vocals -n mdx_extra_q {audio_path} -o output"
134
- result = subprocess.run(command.split(), stdout=subprocess.PIPE)
135
- print(result.stdout.decode())
136
- 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"
137
- else:
138
- raise gr.Error("URL Required!")
139
- return None, None, None, None
140
-
141
- def combine_vocal_and_inst(audio_data, audio_volume, split_model):
142
- if not os.path.exists("output/result"):
143
- os.mkdir("output/result")
144
- vocal_path = "output/result/output.wav"
145
- output_path = "output/result/combine.mp3"
146
- if split_model == "htdemucs":
147
- inst_path = "output/htdemucs/youtube_audio/no_vocals.wav"
148
- else:
149
- inst_path = "output/mdx_extra_q/youtube_audio/no_vocals.wav"
150
- with wave.open(vocal_path, "w") as wave_file:
151
- wave_file.setnchannels(1)
152
- wave_file.setsampwidth(2)
153
- wave_file.setframerate(audio_data[0])
154
- wave_file.writeframes(audio_data[1].tobytes())
155
- 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}'
156
- result = subprocess.run(command.split(), stdout=subprocess.PIPE)
157
- print(result.stdout.decode())
158
- return output_path
159
-
160
- def load_hubert():
161
- global hubert_model
162
- models, _, _ = checkpoint_utils.load_model_ensemble_and_task(
163
- ["hubert_base.pt"],
164
- suffix="",
165
- )
166
- hubert_model = models[0]
167
- hubert_model = hubert_model.to(config.device)
168
- if config.is_half:
169
- hubert_model = hubert_model.half()
170
- else:
171
- hubert_model = hubert_model.float()
172
- hubert_model.eval()
173
-
174
- def change_audio_mode(vc_audio_mode):
175
- if vc_audio_mode == "Input path":
176
- return (
177
- # Input & Upload
178
- gr.Textbox.update(visible=True),
179
- gr.Audio.update(visible=False),
180
- # Youtube
181
- gr.Dropdown.update(visible=False),
182
- gr.Textbox.update(visible=False),
183
- gr.Dropdown.update(visible=False),
184
- gr.Button.update(visible=False),
185
- gr.Audio.update(visible=False),
186
- gr.Audio.update(visible=False),
187
- gr.Audio.update(visible=False),
188
- gr.Slider.update(visible=False),
189
- gr.Audio.update(visible=False),
190
- gr.Button.update(visible=False),
191
- # TTS
192
- gr.Textbox.update(visible=False),
193
- gr.Dropdown.update(visible=False)
194
- )
195
- elif vc_audio_mode == "Upload audio":
196
- return (
197
- # Input & Upload
198
- gr.Textbox.update(visible=False),
199
- gr.Audio.update(visible=True),
200
- # Youtube
201
- gr.Dropdown.update(visible=False),
202
- gr.Textbox.update(visible=False),
203
- gr.Dropdown.update(visible=False),
204
- gr.Button.update(visible=False),
205
- gr.Audio.update(visible=False),
206
- gr.Audio.update(visible=False),
207
- gr.Audio.update(visible=False),
208
- gr.Slider.update(visible=False),
209
- gr.Audio.update(visible=False),
210
- gr.Button.update(visible=False),
211
- # TTS
212
- gr.Textbox.update(visible=False),
213
- gr.Dropdown.update(visible=False)
214
- )
215
- elif vc_audio_mode == "Youtube":
216
- return (
217
- # Input & Upload
218
- gr.Textbox.update(visible=False),
219
- gr.Audio.update(visible=False),
220
- # Youtube
221
- gr.Dropdown.update(visible=True),
222
- gr.Textbox.update(visible=True),
223
- gr.Dropdown.update(visible=True),
224
- gr.Button.update(visible=True),
225
- gr.Audio.update(visible=True),
226
- gr.Audio.update(visible=True),
227
- gr.Audio.update(visible=True),
228
- gr.Slider.update(visible=True),
229
- gr.Audio.update(visible=True),
230
- gr.Button.update(visible=True),
231
- # TTS
232
- gr.Textbox.update(visible=False),
233
- gr.Dropdown.update(visible=False)
234
- )
235
- elif vc_audio_mode == "TTS Audio":
236
- return (
237
- # Input & Upload
238
- gr.Textbox.update(visible=False),
239
- gr.Audio.update(visible=False),
240
- # Youtube
241
- gr.Dropdown.update(visible=False),
242
- gr.Textbox.update(visible=False),
243
- gr.Dropdown.update(visible=False),
244
- gr.Button.update(visible=False),
245
- gr.Audio.update(visible=False),
246
- gr.Audio.update(visible=False),
247
- gr.Audio.update(visible=False),
248
- gr.Slider.update(visible=False),
249
- gr.Audio.update(visible=False),
250
- gr.Button.update(visible=False),
251
- # TTS
252
- gr.Textbox.update(visible=True),
253
- gr.Dropdown.update(visible=True)
254
- )
255
- else:
256
- return (
257
- # Input & Upload
258
- gr.Textbox.update(visible=False),
259
- gr.Audio.update(visible=True),
260
- # Youtube
261
- gr.Dropdown.update(visible=False),
262
- gr.Textbox.update(visible=False),
263
- gr.Dropdown.update(visible=False),
264
- gr.Button.update(visible=False),
265
- gr.Audio.update(visible=False),
266
- gr.Audio.update(visible=False),
267
- gr.Audio.update(visible=False),
268
- gr.Slider.update(visible=False),
269
- gr.Audio.update(visible=False),
270
- gr.Button.update(visible=False),
271
- # TTS
272
- gr.Textbox.update(visible=False),
273
- gr.Dropdown.update(visible=False)
274
- )
275
-
276
- if __name__ == '__main__':
277
- load_hubert()
278
- categories = []
279
- tts_voice_list = asyncio.get_event_loop().run_until_complete(edge_tts.list_voices())
280
- voices = [f"{v['ShortName']}-{v['Gender']}" for v in tts_voice_list]
281
- with open("weights/folder_info.json", "r", encoding="utf-8") as f:
282
- folder_info = json.load(f)
283
- for category_name, category_info in folder_info.items():
284
- if not category_info['enable']:
285
- continue
286
- category_title = category_info['title']
287
- category_folder = category_info['folder_path']
288
- description = category_info['description']
289
- models = []
290
- with open(f"weights/{category_folder}/model_info.json", "r", encoding="utf-8") as f:
291
- models_info = json.load(f)
292
- for model_name, info in models_info.items():
293
- if not info['enable']:
294
- continue
295
- model_title = info['title']
296
- model_author = info.get("author", None)
297
- model_cover = f"weights/{category_folder}/{model_name}/{info['cover']}"
298
- model_index = f"weights/{category_folder}/{model_name}/{info['feature_retrieval_library']}"
299
- cpt = torch.load(f"weights/{category_folder}/{model_name}/{model_name}.pth", map_location="cpu")
300
- tgt_sr = cpt["config"][-1]
301
- cpt["config"][-3] = cpt["weight"]["emb_g.weight"].shape[0] # n_spk
302
- if_f0 = cpt.get("f0", 1)
303
- version = cpt.get("version", "v1")
304
- if version == "v1":
305
- if if_f0 == 1:
306
- net_g = SynthesizerTrnMs256NSFsid(*cpt["config"], is_half=config.is_half)
307
- else:
308
- net_g = SynthesizerTrnMs256NSFsid_nono(*cpt["config"])
309
- nodel_version = "V1"
310
- elif version == "v2":
311
- if if_f0 == 1:
312
- net_g = SynthesizerTrnMs768NSFsid(*cpt["config"], is_half=config.is_half)
313
- else:
314
- net_g = SynthesizerTrnMs768NSFsid_nono(*cpt["config"])
315
- nodel_version = "V2"
316
- del net_g.enc_q
317
- print(net_g.load_state_dict(cpt["weight"], strict=False))
318
- net_g.eval().to(config.device)
319
- if config.is_half:
320
- net_g = net_g.half()
321
- else:
322
- net_g = net_g.float()
323
- vc = VC(tgt_sr, config)
324
- print(f"Model loaded: {model_name}")
325
- models.append((model_name, model_title, model_author, model_cover, nodel_version, create_vc_fn(tgt_sr, net_g, vc, if_f0, model_index)))
326
- categories.append([category_title, category_folder, description, models])
327
- with gr.Blocks() as app:
328
- gr.Markdown(
329
- "# <center> Multi Model RVC Inference\n"
330
- "#### [Google Collab RVC Blue Archives](https://colab.research.google.com/drive/1Hl0zix92NYI5HsylyjAy_7XmuXTBC-J9?usp=sharing)\n"
331
- "[![Original Repo](https://badgen.net/badge/icon/github?icon=github&label=Original%20Repo)](https://github.com/ArkanDash/Multi-Model-RVC-Inference)"
332
- )
333
- for (folder_title, folder, description, models) in categories:
334
- with gr.TabItem(folder_title):
335
- if description:
336
- gr.Markdown(f"### <center> {description}")
337
- with gr.Tabs():
338
- if not models:
339
- gr.Markdown("# <center> No Model Loaded.")
340
- gr.Markdown("## <center> Please add model or fix your model path.")
341
- continue
342
- for (name, title, author, cover, model_version, vc_fn) in models:
343
- with gr.TabItem(name):
344
- with gr.Row():
345
- gr.Markdown(
346
- '<div align="center">'
347
- f'<div>{title}</div>\n'+
348
- f'<div>RVC {model_version} Model</div>\n'+
349
- (f'<div>Model author: {author}</div>' if author else "")+
350
- (f'<img style="width:auto;height:300px;" src="file/{cover}">' if cover else "")+
351
- '</div>'
352
- )
353
- with gr.Row():
354
- with gr.Column():
355
- vc_audio_mode = gr.Dropdown(label="Input voice", choices=["Upload audio", "TTS Audio"], allow_custom_value=False, value="Upload audio")
356
- # Input and Upload
357
- vc_input = gr.Textbox(label="Input audio path", visible=False)
358
- vc_upload = gr.Audio(label="Upload audio file", visible=True, interactive=True)
359
- # Youtube
360
- vc_download_audio = gr.Dropdown(label="Provider", choices=["Youtube"], allow_custom_value=False, visible=False, value="Youtube", info="Select provider (Default: Youtube)")
361
- 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=...")
362
- 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)")
363
- vc_split = gr.Button("Split Audio", variant="primary", visible=False)
364
- vc_vocal_preview = gr.Audio(label="Vocal Preview", visible=False)
365
- vc_inst_preview = gr.Audio(label="Instrumental Preview", visible=False)
366
- vc_audio_preview = gr.Audio(label="Audio Preview", visible=False)
367
- # TTS
368
- tts_text = gr.Textbox(visible=False, label="TTS text", info="Text to speech input")
369
- tts_voice = gr.Dropdown(label="Edge-tts speaker", choices=voices, visible=False, allow_custom_value=False, value="en-US-AnaNeural-Female")
370
- with gr.Column():
371
- spk_item = gr.Slider(
372
- minimum=0,
373
- maximum=2333,
374
- step=1,
375
- label="Speaker ID",
376
- info="(Default: 0)",
377
- value=0,
378
- interactive=True,
379
- )
380
- 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')
381
- f0method0 = gr.Radio(
382
- label="Pitch extraction algorithm",
383
- info="PM is fast, Harvest is good but extremely slow (Default: PM)",
384
- choices=["pm", "harvest"],
385
- value="pm",
386
- interactive=True,
387
- )
388
- index_rate1 = gr.Slider(
389
- minimum=0,
390
- maximum=1,
391
- label="Retrieval feature ratio",
392
- info="(Default: 0.6)",
393
- value=0.6,
394
- interactive=True,
395
- )
396
- filter_radius0 = gr.Slider(
397
- minimum=0,
398
- maximum=7,
399
- label="Apply Median Filtering",
400
- info="The value represents the filter radius and can reduce breathiness.",
401
- value=3,
402
- step=1,
403
- interactive=True,
404
- )
405
- resample_sr0 = gr.Slider(
406
- minimum=0,
407
- maximum=48000,
408
- label="Resample the output audio",
409
- info="Resample the output audio in post-processing to the final sample rate. Set to 0 for no resampling",
410
- value=0,
411
- step=1,
412
- interactive=True,
413
- )
414
- rms_mix_rate0 = gr.Slider(
415
- minimum=0,
416
- maximum=1,
417
- label="Volume Envelope",
418
- 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",
419
- value=1,
420
- interactive=True,
421
- )
422
- protect0 = gr.Slider(
423
- minimum=0,
424
- maximum=0.5,
425
- label="Voice Protection",
426
- 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",
427
- value=0.35,
428
- step=0.01,
429
- interactive=True,
430
- )
431
- with gr.Column():
432
- vc_log = gr.Textbox(label="Output Information", interactive=False)
433
- vc_output = gr.Audio(label="Output Audio", interactive=False)
434
- vc_convert = gr.Button("Convert", variant="primary")
435
- vc_volume = gr.Slider(
436
- minimum=0,
437
- maximum=10,
438
- label="Vocal volume",
439
- value=4,
440
- interactive=True,
441
- step=1,
442
- info="Adjust vocal volume (Default: 4}",
443
- visible=False
444
- )
445
- vc_combined_output = gr.Audio(label="Output Combined Audio", visible=False)
446
- vc_combine = gr.Button("Combine",variant="primary", visible=False)
447
- vc_convert.click(
448
- fn=vc_fn,
449
- inputs=[
450
- vc_audio_mode,
451
- vc_input,
452
- vc_upload,
453
- tts_text,
454
- tts_voice,
455
- spk_item,
456
- vc_transform0,
457
- f0method0,
458
- index_rate1,
459
- filter_radius0,
460
- resample_sr0,
461
- rms_mix_rate0,
462
- protect0,
463
- ],
464
- outputs=[vc_log ,vc_output]
465
- )
466
- vc_split.click(
467
- fn=cut_vocal_and_inst,
468
- inputs=[vc_link, vc_download_audio, vc_split_model],
469
- outputs=[vc_vocal_preview, vc_inst_preview, vc_audio_preview, vc_input]
470
- )
471
- vc_combine.click(
472
- fn=combine_vocal_and_inst,
473
- inputs=[vc_output, vc_volume, vc_split_model],
474
- outputs=[vc_combined_output]
475
- )
476
- vc_audio_mode.change(
477
- fn=change_audio_mode,
478
- inputs=[vc_audio_mode],
479
- outputs=[
480
- vc_input,
481
- vc_upload,
482
- vc_download_audio,
483
- vc_link,
484
- vc_split_model,
485
- vc_split,
486
- vc_vocal_preview,
487
- vc_inst_preview,
488
- vc_audio_preview,
489
- vc_volume,
490
- vc_combined_output,
491
- vc_combine,
492
- tts_text,
493
- tts_voice
494
- ]
495
- )
496
- app.queue(concurrency_count=1, max_size=20, api_open=config.api).launch(share=config.colab)