Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,399 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
os.environ['HF_HUB_CACHE'] = './checkpoints/hf_cache'
|
3 |
+
import gradio as gr
|
4 |
+
import torch
|
5 |
+
import torchaudio
|
6 |
+
import librosa
|
7 |
+
from modules.commons import build_model, load_checkpoint, recursive_munch, str2bool
|
8 |
+
import yaml
|
9 |
+
from hf_utils import load_custom_model_from_hf
|
10 |
+
import numpy as np
|
11 |
+
from pydub import AudioSegment
|
12 |
+
import argparse
|
13 |
+
|
14 |
+
# Load model and configuration
|
15 |
+
fp16 = False
|
16 |
+
device = None
|
17 |
+
def load_models(args):
|
18 |
+
global sr, hop_length, fp16
|
19 |
+
fp16 = args.fp16
|
20 |
+
print(f"Using device: {device}")
|
21 |
+
print(f"Using fp16: {fp16}")
|
22 |
+
if args.checkpoint is None or args.checkpoint == "":
|
23 |
+
dit_checkpoint_path, dit_config_path = load_custom_model_from_hf("Plachta/Seed-VC",
|
24 |
+
"DiT_seed_v2_uvit_whisper_small_wavenet_bigvgan_pruned.pth",
|
25 |
+
"config_dit_mel_seed_uvit_whisper_small_wavenet.yml")
|
26 |
+
else:
|
27 |
+
dit_checkpoint_path = args.checkpoint
|
28 |
+
dit_config_path = args.config
|
29 |
+
config = yaml.safe_load(open(dit_config_path, "r"))
|
30 |
+
model_params = recursive_munch(config["model_params"])
|
31 |
+
model_params.dit_type = 'DiT'
|
32 |
+
model = build_model(model_params, stage="DiT")
|
33 |
+
hop_length = config["preprocess_params"]["spect_params"]["hop_length"]
|
34 |
+
sr = config["preprocess_params"]["sr"]
|
35 |
+
|
36 |
+
# Load checkpoints
|
37 |
+
model, _, _, _ = load_checkpoint(
|
38 |
+
model,
|
39 |
+
None,
|
40 |
+
dit_checkpoint_path,
|
41 |
+
load_only_params=True,
|
42 |
+
ignore_modules=[],
|
43 |
+
is_distributed=False,
|
44 |
+
)
|
45 |
+
for key in model:
|
46 |
+
model[key].eval()
|
47 |
+
model[key].to(device)
|
48 |
+
model.cfm.estimator.setup_caches(max_batch_size=1, max_seq_length=8192)
|
49 |
+
|
50 |
+
# Load additional modules
|
51 |
+
from modules.campplus.DTDNN import CAMPPlus
|
52 |
+
|
53 |
+
campplus_ckpt_path = load_custom_model_from_hf(
|
54 |
+
"funasr/campplus", "campplus_cn_common.bin", config_filename=None
|
55 |
+
)
|
56 |
+
campplus_model = CAMPPlus(feat_dim=80, embedding_size=192)
|
57 |
+
campplus_model.load_state_dict(torch.load(campplus_ckpt_path, map_location="cpu"))
|
58 |
+
campplus_model.eval()
|
59 |
+
campplus_model.to(device)
|
60 |
+
|
61 |
+
vocoder_type = model_params.vocoder.type
|
62 |
+
|
63 |
+
if vocoder_type == 'bigvgan':
|
64 |
+
from modules.bigvgan import bigvgan
|
65 |
+
bigvgan_name = model_params.vocoder.name
|
66 |
+
bigvgan_model = bigvgan.BigVGAN.from_pretrained(bigvgan_name, use_cuda_kernel=False)
|
67 |
+
# remove weight norm in the model and set to eval mode
|
68 |
+
bigvgan_model.remove_weight_norm()
|
69 |
+
bigvgan_model = bigvgan_model.eval().to(device)
|
70 |
+
vocoder_fn = bigvgan_model
|
71 |
+
elif vocoder_type == 'hifigan':
|
72 |
+
from modules.hifigan.generator import HiFTGenerator
|
73 |
+
from modules.hifigan.f0_predictor import ConvRNNF0Predictor
|
74 |
+
hift_config = yaml.safe_load(open('configs/hifigan.yml', 'r'))
|
75 |
+
hift_gen = HiFTGenerator(**hift_config['hift'], f0_predictor=ConvRNNF0Predictor(**hift_config['f0_predictor']))
|
76 |
+
hift_path = load_custom_model_from_hf("FunAudioLLM/CosyVoice-300M", 'hift.pt', None)
|
77 |
+
hift_gen.load_state_dict(torch.load(hift_path, map_location='cpu'))
|
78 |
+
hift_gen.eval()
|
79 |
+
hift_gen.to(device)
|
80 |
+
vocoder_fn = hift_gen
|
81 |
+
elif vocoder_type == "vocos":
|
82 |
+
vocos_config = yaml.safe_load(open(model_params.vocoder.vocos.config, 'r'))
|
83 |
+
vocos_path = model_params.vocoder.vocos.path
|
84 |
+
vocos_model_params = recursive_munch(vocos_config['model_params'])
|
85 |
+
vocos = build_model(vocos_model_params, stage='mel_vocos')
|
86 |
+
vocos_checkpoint_path = vocos_path
|
87 |
+
vocos, _, _, _ = load_checkpoint(vocos, None, vocos_checkpoint_path,
|
88 |
+
load_only_params=True, ignore_modules=[], is_distributed=False)
|
89 |
+
_ = [vocos[key].eval().to(device) for key in vocos]
|
90 |
+
_ = [vocos[key].to(device) for key in vocos]
|
91 |
+
total_params = sum(sum(p.numel() for p in vocos[key].parameters() if p.requires_grad) for key in vocos.keys())
|
92 |
+
print(f"Vocoder model total parameters: {total_params / 1_000_000:.2f}M")
|
93 |
+
vocoder_fn = vocos.decoder
|
94 |
+
else:
|
95 |
+
raise ValueError(f"Unknown vocoder type: {vocoder_type}")
|
96 |
+
|
97 |
+
speech_tokenizer_type = model_params.speech_tokenizer.type
|
98 |
+
if speech_tokenizer_type == 'whisper':
|
99 |
+
# whisper
|
100 |
+
from transformers import AutoFeatureExtractor, WhisperModel
|
101 |
+
whisper_name = model_params.speech_tokenizer.name
|
102 |
+
whisper_model = WhisperModel.from_pretrained(whisper_name, torch_dtype=torch.float16).to(device)
|
103 |
+
del whisper_model.decoder
|
104 |
+
whisper_feature_extractor = AutoFeatureExtractor.from_pretrained(whisper_name)
|
105 |
+
|
106 |
+
def semantic_fn(waves_16k):
|
107 |
+
ori_inputs = whisper_feature_extractor([waves_16k.squeeze(0).cpu().numpy()],
|
108 |
+
return_tensors="pt",
|
109 |
+
return_attention_mask=True)
|
110 |
+
ori_input_features = whisper_model._mask_input_features(
|
111 |
+
ori_inputs.input_features, attention_mask=ori_inputs.attention_mask).to(device)
|
112 |
+
with torch.no_grad():
|
113 |
+
ori_outputs = whisper_model.encoder(
|
114 |
+
ori_input_features.to(whisper_model.encoder.dtype),
|
115 |
+
head_mask=None,
|
116 |
+
output_attentions=False,
|
117 |
+
output_hidden_states=False,
|
118 |
+
return_dict=True,
|
119 |
+
)
|
120 |
+
S_ori = ori_outputs.last_hidden_state.to(torch.float32)
|
121 |
+
S_ori = S_ori[:, :waves_16k.size(-1) // 320 + 1]
|
122 |
+
return S_ori
|
123 |
+
elif speech_tokenizer_type == 'cnhubert':
|
124 |
+
from transformers import (
|
125 |
+
Wav2Vec2FeatureExtractor,
|
126 |
+
HubertModel,
|
127 |
+
)
|
128 |
+
hubert_model_name = config['model_params']['speech_tokenizer']['name']
|
129 |
+
hubert_feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained(hubert_model_name)
|
130 |
+
hubert_model = HubertModel.from_pretrained(hubert_model_name)
|
131 |
+
hubert_model = hubert_model.to(device)
|
132 |
+
hubert_model = hubert_model.eval()
|
133 |
+
hubert_model = hubert_model.half()
|
134 |
+
|
135 |
+
def semantic_fn(waves_16k):
|
136 |
+
ori_waves_16k_input_list = [
|
137 |
+
waves_16k[bib].cpu().numpy()
|
138 |
+
for bib in range(len(waves_16k))
|
139 |
+
]
|
140 |
+
ori_inputs = hubert_feature_extractor(ori_waves_16k_input_list,
|
141 |
+
return_tensors="pt",
|
142 |
+
return_attention_mask=True,
|
143 |
+
padding=True,
|
144 |
+
sampling_rate=16000).to(device)
|
145 |
+
with torch.no_grad():
|
146 |
+
ori_outputs = hubert_model(
|
147 |
+
ori_inputs.input_values.half(),
|
148 |
+
)
|
149 |
+
S_ori = ori_outputs.last_hidden_state.float()
|
150 |
+
return S_ori
|
151 |
+
elif speech_tokenizer_type == 'xlsr':
|
152 |
+
from transformers import (
|
153 |
+
Wav2Vec2FeatureExtractor,
|
154 |
+
Wav2Vec2Model,
|
155 |
+
)
|
156 |
+
model_name = config['model_params']['speech_tokenizer']['name']
|
157 |
+
output_layer = config['model_params']['speech_tokenizer']['output_layer']
|
158 |
+
wav2vec_feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained(model_name)
|
159 |
+
wav2vec_model = Wav2Vec2Model.from_pretrained(model_name)
|
160 |
+
wav2vec_model.encoder.layers = wav2vec_model.encoder.layers[:output_layer]
|
161 |
+
wav2vec_model = wav2vec_model.to(device)
|
162 |
+
wav2vec_model = wav2vec_model.eval()
|
163 |
+
wav2vec_model = wav2vec_model.half()
|
164 |
+
|
165 |
+
def semantic_fn(waves_16k):
|
166 |
+
ori_waves_16k_input_list = [
|
167 |
+
waves_16k[bib].cpu().numpy()
|
168 |
+
for bib in range(len(waves_16k))
|
169 |
+
]
|
170 |
+
ori_inputs = wav2vec_feature_extractor(ori_waves_16k_input_list,
|
171 |
+
return_tensors="pt",
|
172 |
+
return_attention_mask=True,
|
173 |
+
padding=True,
|
174 |
+
sampling_rate=16000).to(device)
|
175 |
+
with torch.no_grad():
|
176 |
+
ori_outputs = wav2vec_model(
|
177 |
+
ori_inputs.input_values.half(),
|
178 |
+
)
|
179 |
+
S_ori = ori_outputs.last_hidden_state.float()
|
180 |
+
return S_ori
|
181 |
+
else:
|
182 |
+
raise ValueError(f"Unknown speech tokenizer type: {speech_tokenizer_type}")
|
183 |
+
# Generate mel spectrograms
|
184 |
+
mel_fn_args = {
|
185 |
+
"n_fft": config['preprocess_params']['spect_params']['n_fft'],
|
186 |
+
"win_size": config['preprocess_params']['spect_params']['win_length'],
|
187 |
+
"hop_size": config['preprocess_params']['spect_params']['hop_length'],
|
188 |
+
"num_mels": config['preprocess_params']['spect_params']['n_mels'],
|
189 |
+
"sampling_rate": sr,
|
190 |
+
"fmin": config['preprocess_params']['spect_params'].get('fmin', 0),
|
191 |
+
"fmax": None if config['preprocess_params']['spect_params'].get('fmax', "None") == "None" else 8000,
|
192 |
+
"center": False
|
193 |
+
}
|
194 |
+
from modules.audio import mel_spectrogram
|
195 |
+
|
196 |
+
to_mel = lambda x: mel_spectrogram(x, **mel_fn_args)
|
197 |
+
|
198 |
+
return (
|
199 |
+
model,
|
200 |
+
semantic_fn,
|
201 |
+
vocoder_fn,
|
202 |
+
campplus_model,
|
203 |
+
to_mel,
|
204 |
+
mel_fn_args,
|
205 |
+
)
|
206 |
+
def crossfade(chunk1, chunk2, overlap):
|
207 |
+
fade_out = np.cos(np.linspace(0, np.pi / 2, overlap)) ** 2
|
208 |
+
fade_in = np.cos(np.linspace(np.pi / 2, 0, overlap)) ** 2
|
209 |
+
chunk2[:overlap] = chunk2[:overlap] * fade_in + chunk1[-overlap:] * fade_out
|
210 |
+
return chunk2
|
211 |
+
|
212 |
+
bitrate = "320k"
|
213 |
+
|
214 |
+
model, semantic_fn, vocoder_fn, campplus_model, to_mel, mel_fn_args = None, None, None, None, None, None
|
215 |
+
overlap_wave_len = None
|
216 |
+
max_context_window = None
|
217 |
+
sr = None
|
218 |
+
hop_length = None
|
219 |
+
overlap_frame_len = 16
|
220 |
+
@torch.no_grad()
|
221 |
+
@torch.inference_mode()
|
222 |
+
def voice_conversion(source, target, diffusion_steps, length_adjust, inference_cfg_rate):
|
223 |
+
inference_module = model
|
224 |
+
mel_fn = to_mel
|
225 |
+
# Load audio
|
226 |
+
source_audio = librosa.load(source, sr=sr)[0]
|
227 |
+
ref_audio = librosa.load(target, sr=sr)[0]
|
228 |
+
|
229 |
+
# Process audio
|
230 |
+
source_audio = torch.tensor(source_audio).unsqueeze(0).float().to(device)
|
231 |
+
ref_audio = torch.tensor(ref_audio[:sr * 25]).unsqueeze(0).float().to(device)
|
232 |
+
|
233 |
+
# Resample
|
234 |
+
ref_waves_16k = torchaudio.functional.resample(ref_audio, sr, 16000)
|
235 |
+
converted_waves_16k = torchaudio.functional.resample(source_audio, sr, 16000)
|
236 |
+
# if source audio less than 30 seconds, whisper can handle in one forward
|
237 |
+
if converted_waves_16k.size(-1) <= 16000 * 30:
|
238 |
+
S_alt = semantic_fn(converted_waves_16k)
|
239 |
+
else:
|
240 |
+
overlapping_time = 5 # 5 seconds
|
241 |
+
S_alt_list = []
|
242 |
+
buffer = None
|
243 |
+
traversed_time = 0
|
244 |
+
while traversed_time < converted_waves_16k.size(-1):
|
245 |
+
if buffer is None: # first chunk
|
246 |
+
chunk = converted_waves_16k[:, traversed_time:traversed_time + 16000 * 30]
|
247 |
+
else:
|
248 |
+
chunk = torch.cat([buffer, converted_waves_16k[:, traversed_time:traversed_time + 16000 * (30 - overlapping_time)]], dim=-1)
|
249 |
+
S_alt = semantic_fn(chunk)
|
250 |
+
if traversed_time == 0:
|
251 |
+
S_alt_list.append(S_alt)
|
252 |
+
else:
|
253 |
+
S_alt_list.append(S_alt[:, 50 * overlapping_time:])
|
254 |
+
buffer = chunk[:, -16000 * overlapping_time:]
|
255 |
+
traversed_time += 30 * 16000 if traversed_time == 0 else chunk.size(-1) - 16000 * overlapping_time
|
256 |
+
S_alt = torch.cat(S_alt_list, dim=1)
|
257 |
+
|
258 |
+
ori_waves_16k = torchaudio.functional.resample(ref_audio, sr, 16000)
|
259 |
+
S_ori = semantic_fn(ori_waves_16k)
|
260 |
+
|
261 |
+
mel = mel_fn(source_audio.to(device).float())
|
262 |
+
mel2 = mel_fn(ref_audio.to(device).float())
|
263 |
+
|
264 |
+
target_lengths = torch.LongTensor([int(mel.size(2) * length_adjust)]).to(mel.device)
|
265 |
+
target2_lengths = torch.LongTensor([mel2.size(2)]).to(mel2.device)
|
266 |
+
|
267 |
+
feat2 = torchaudio.compliance.kaldi.fbank(ref_waves_16k,
|
268 |
+
num_mel_bins=80,
|
269 |
+
dither=0,
|
270 |
+
sample_frequency=16000)
|
271 |
+
feat2 = feat2 - feat2.mean(dim=0, keepdim=True)
|
272 |
+
style2 = campplus_model(feat2.unsqueeze(0))
|
273 |
+
|
274 |
+
F0_ori = None
|
275 |
+
F0_alt = None
|
276 |
+
shifted_f0_alt = None
|
277 |
+
|
278 |
+
# Length regulation
|
279 |
+
cond, _, codes, commitment_loss, codebook_loss = inference_module.length_regulator(S_alt, ylens=target_lengths, n_quantizers=3, f0=shifted_f0_alt)
|
280 |
+
prompt_condition, _, codes, commitment_loss, codebook_loss = inference_module.length_regulator(S_ori, ylens=target2_lengths, n_quantizers=3, f0=F0_ori)
|
281 |
+
|
282 |
+
max_source_window = max_context_window - mel2.size(2)
|
283 |
+
# split source condition (cond) into chunks
|
284 |
+
processed_frames = 0
|
285 |
+
generated_wave_chunks = []
|
286 |
+
# generate chunk by chunk and stream the output
|
287 |
+
while processed_frames < cond.size(1):
|
288 |
+
chunk_cond = cond[:, processed_frames:processed_frames + max_source_window]
|
289 |
+
is_last_chunk = processed_frames + max_source_window >= cond.size(1)
|
290 |
+
cat_condition = torch.cat([prompt_condition, chunk_cond], dim=1)
|
291 |
+
with torch.autocast(device_type=device.type, dtype=torch.float16 if fp16 else torch.float32):
|
292 |
+
# Voice Conversion
|
293 |
+
vc_target = inference_module.cfm.inference(cat_condition,
|
294 |
+
torch.LongTensor([cat_condition.size(1)]).to(mel2.device),
|
295 |
+
mel2, style2, None, diffusion_steps,
|
296 |
+
inference_cfg_rate=inference_cfg_rate)
|
297 |
+
vc_target = vc_target[:, :, mel2.size(-1):]
|
298 |
+
vc_wave = vocoder_fn(vc_target.float())[0]
|
299 |
+
if vc_wave.ndim == 1:
|
300 |
+
vc_wave = vc_wave.unsqueeze(0)
|
301 |
+
if processed_frames == 0:
|
302 |
+
if is_last_chunk:
|
303 |
+
output_wave = vc_wave[0].cpu().numpy()
|
304 |
+
generated_wave_chunks.append(output_wave)
|
305 |
+
output_wave = (output_wave * 32768.0).astype(np.int16)
|
306 |
+
mp3_bytes = AudioSegment(
|
307 |
+
output_wave.tobytes(), frame_rate=sr,
|
308 |
+
sample_width=output_wave.dtype.itemsize, channels=1
|
309 |
+
).export(format="mp3", bitrate=bitrate).read()
|
310 |
+
yield mp3_bytes, (sr, np.concatenate(generated_wave_chunks))
|
311 |
+
break
|
312 |
+
output_wave = vc_wave[0, :-overlap_wave_len].cpu().numpy()
|
313 |
+
generated_wave_chunks.append(output_wave)
|
314 |
+
previous_chunk = vc_wave[0, -overlap_wave_len:]
|
315 |
+
processed_frames += vc_target.size(2) - overlap_frame_len
|
316 |
+
output_wave = (output_wave * 32768.0).astype(np.int16)
|
317 |
+
mp3_bytes = AudioSegment(
|
318 |
+
output_wave.tobytes(), frame_rate=sr,
|
319 |
+
sample_width=output_wave.dtype.itemsize, channels=1
|
320 |
+
).export(format="mp3", bitrate=bitrate).read()
|
321 |
+
yield mp3_bytes, None
|
322 |
+
elif is_last_chunk:
|
323 |
+
output_wave = crossfade(previous_chunk.cpu().numpy(), vc_wave[0].cpu().numpy(), overlap_wave_len)
|
324 |
+
generated_wave_chunks.append(output_wave)
|
325 |
+
processed_frames += vc_target.size(2) - overlap_frame_len
|
326 |
+
output_wave = (output_wave * 32768.0).astype(np.int16)
|
327 |
+
mp3_bytes = AudioSegment(
|
328 |
+
output_wave.tobytes(), frame_rate=sr,
|
329 |
+
sample_width=output_wave.dtype.itemsize, channels=1
|
330 |
+
).export(format="mp3", bitrate=bitrate).read()
|
331 |
+
yield mp3_bytes, (sr, np.concatenate(generated_wave_chunks))
|
332 |
+
break
|
333 |
+
else:
|
334 |
+
output_wave = crossfade(previous_chunk.cpu().numpy(), vc_wave[0, :-overlap_wave_len].cpu().numpy(), overlap_wave_len)
|
335 |
+
generated_wave_chunks.append(output_wave)
|
336 |
+
previous_chunk = vc_wave[0, -overlap_wave_len:]
|
337 |
+
processed_frames += vc_target.size(2) - overlap_frame_len
|
338 |
+
output_wave = (output_wave * 32768.0).astype(np.int16)
|
339 |
+
mp3_bytes = AudioSegment(
|
340 |
+
output_wave.tobytes(), frame_rate=sr,
|
341 |
+
sample_width=output_wave.dtype.itemsize, channels=1
|
342 |
+
).export(format="mp3", bitrate=bitrate).read()
|
343 |
+
yield mp3_bytes, None
|
344 |
+
|
345 |
+
|
346 |
+
def main(args):
|
347 |
+
global model, semantic_fn, vocoder_fn, campplus_model, to_mel, mel_fn_args
|
348 |
+
global overlap_wave_len, max_context_window, sr, hop_length
|
349 |
+
model, semantic_fn, vocoder_fn, campplus_model, to_mel, mel_fn_args = load_models(args)
|
350 |
+
# streaming and chunk processing related params
|
351 |
+
max_context_window = sr // hop_length * 30
|
352 |
+
overlap_wave_len = overlap_frame_len * hop_length
|
353 |
+
description = ("Zero-shot voice conversion with in-context learning. For local deployment please check [GitHub repository](https://github.com/Plachtaa/seed-vc) "
|
354 |
+
"for details and updates.<br>Note that any reference audio will be forcefully clipped to 25s if beyond this length.<br> "
|
355 |
+
"If total duration of source and reference audio exceeds 30s, source audio will be processed in chunks.<br> "
|
356 |
+
"无需训练的 zero-shot 语音/歌声转换模型,若需本地部署查看[GitHub页面](https://github.com/Plachtaa/seed-vc)<br>"
|
357 |
+
"请注意,参考音频若超过 25 秒,则会被自动裁剪至此长度。<br>若源音频和参考音频的总时长超过 30 秒,源音频将被分段处理。")
|
358 |
+
inputs = [
|
359 |
+
gr.Audio(type="filepath", label="Source Audio / 源音频"),
|
360 |
+
gr.Audio(type="filepath", label="Reference Audio / 参考音频"),
|
361 |
+
gr.Slider(minimum=1, maximum=200, value=10, step=1, label="Diffusion Steps / 扩散步数", info="10 by default, 50~100 for best quality / 默认为 10,50~100 为最佳质量"),
|
362 |
+
gr.Slider(minimum=0.5, maximum=2.0, step=0.1, value=1.0, label="Length Adjust / 长度调整", info="<1.0 for speed-up speech, >1.0 for slow-down speech / <1.0 加速语速,>1.0 减慢语速"),
|
363 |
+
gr.Slider(minimum=0.0, maximum=1.0, step=0.1, value=0.7, label="Inference CFG Rate", info="has subtle influence / 有微小影响"),
|
364 |
+
]
|
365 |
+
|
366 |
+
examples = [["examples/source/yae_0.wav", "examples/reference/dingzhen_0.wav", 25, 1.0, 0.7, False, True, 0],
|
367 |
+
["examples/source/jay_0.wav", "examples/reference/azuma_0.wav", 25, 1.0, 0.7, True, True, 0],
|
368 |
+
]
|
369 |
+
|
370 |
+
outputs = [gr.Audio(label="Stream Output Audio / 流式输出", streaming=True, format='mp3'),
|
371 |
+
gr.Audio(label="Full Output Audio / 完整输出", streaming=False, format='wav')]
|
372 |
+
|
373 |
+
|
374 |
+
gr.Interface(fn=voice_conversion,
|
375 |
+
description=description,
|
376 |
+
inputs=inputs,
|
377 |
+
outputs=outputs,
|
378 |
+
title="Seed Voice Conversion",
|
379 |
+
examples=examples,
|
380 |
+
cache_examples=False,
|
381 |
+
).launch(share=True)
|
382 |
+
|
383 |
+
if __name__ == "__main__":
|
384 |
+
parser = argparse.ArgumentParser()
|
385 |
+
parser.add_argument("--checkpoint", type=str, help="Path to the checkpoint file", default=None)
|
386 |
+
parser.add_argument("--config", type=str, help="Path to the config file", default=None)
|
387 |
+
parser.add_argument("--share", type=str2bool, nargs="?", const=True, default=False, help="Whether to share the app")
|
388 |
+
parser.add_argument("--fp16", type=str2bool, nargs="?", const=True, help="Whether to use fp16", default=True)
|
389 |
+
parser.add_argument("--gpu", type=int, help="Which GPU id to use", default=0)
|
390 |
+
args = parser.parse_args()
|
391 |
+
cuda_target = f"cuda:{args.gpu}" if args.gpu else "cuda"
|
392 |
+
|
393 |
+
if torch.cuda.is_available():
|
394 |
+
device = torch.device(cuda_target)
|
395 |
+
elif torch.backends.mps.is_available():
|
396 |
+
device = torch.device("mps")
|
397 |
+
else:
|
398 |
+
device = torch.device("cpu")
|
399 |
+
main(args)
|