Plachta commited on
Commit
5e78e49
·
verified ·
1 Parent(s): 500b392

Update modules/v2/vc_wrapper.py

Browse files
Files changed (1) hide show
  1. modules/v2/vc_wrapper.py +664 -606
modules/v2/vc_wrapper.py CHANGED
@@ -1,606 +1,664 @@
1
- import spaces
2
- import torch
3
- import librosa
4
- import torchaudio
5
- import numpy as np
6
- from pydub import AudioSegment
7
- from hf_utils import load_custom_model_from_hf
8
-
9
- DEFAULT_REPO_ID = "Plachta/Seed-VC"
10
- DEFAULT_CFM_CHECKPOINT = "v2/cfm_small.pth"
11
- DEFAULT_AR_CHECKPOINT = "v2/ar_base.pth"
12
-
13
- DEFAULT_CE_REPO_ID = "Plachta/ASTRAL-quantization"
14
- DEFAULT_CE_NARROW_CHECKPOINT = "bsq32/bsq32_light.pth"
15
- DEFAULT_CE_WIDE_CHECKPOINT = "bsq2048/bsq2048_light.pth"
16
-
17
- DEFAULT_SE_REPO_ID = "funasr/campplus"
18
- DEFAULT_SE_CHECKPOINT = "campplus_cn_common.bin"
19
-
20
- class VoiceConversionWrapper(torch.nn.Module):
21
- def __init__(
22
- self,
23
- sr: int,
24
- hop_size: int,
25
- mel_fn: callable,
26
- cfm: torch.nn.Module,
27
- cfm_length_regulator: torch.nn.Module,
28
- content_extractor_narrow: torch.nn.Module,
29
- content_extractor_wide: torch.nn.Module,
30
- ar_length_regulator: torch.nn.Module,
31
- ar: torch.nn.Module,
32
- style_encoder: torch.nn.Module,
33
- vocoder: torch.nn.Module,
34
- ):
35
- super(VoiceConversionWrapper, self).__init__()
36
- self.sr = sr
37
- self.hop_size = hop_size
38
- self.mel_fn = mel_fn
39
- self.cfm = cfm
40
- self.cfm_length_regulator = cfm_length_regulator
41
- self.content_extractor_narrow = content_extractor_narrow
42
- self.content_extractor_wide = content_extractor_wide
43
- self.vocoder = vocoder
44
- self.ar_length_regulator = ar_length_regulator
45
- self.ar = ar
46
- self.style_encoder = style_encoder
47
- # Set streaming parameters
48
- self.overlap_frame_len = 16
49
- self.bitrate = "320k"
50
- self.compiled_decode_fn = None
51
- self.dit_compiled = False
52
- self.dit_max_context_len = 30 # in seconds
53
- self.compile_len = 87 * self.dit_max_context_len
54
-
55
- def compile_ar(self):
56
- """
57
- Compile the AR model for inference.
58
- """
59
- self.compiled_decode_fn = torch.compile(
60
- self.ar.model.forward_generate,
61
- fullgraph=True,
62
- backend="inductor" if torch.cuda.is_available() else "aot_eager",
63
- mode="reduce-overhead" if torch.cuda.is_available() else None,
64
- )
65
-
66
- def compile_cfm(self):
67
- self.cfm.estimator.transformer = torch.compile(
68
- self.cfm.estimator.transformer,
69
- fullgraph=True,
70
- backend="inductor" if torch.cuda.is_available() else "aot_eager",
71
- mode="reduce-overhead" if torch.cuda.is_available() else None,
72
- )
73
- self.dit_compiled = True
74
-
75
- @staticmethod
76
- def strip_prefix(state_dict: dict, prefix: str = "module.") -> dict:
77
- """
78
- Strip the prefix from the state_dict keys.
79
- """
80
- new_state_dict = {}
81
- for k, v in state_dict.items():
82
- if k.startswith(prefix):
83
- new_key = k[len(prefix):]
84
- else:
85
- new_key = k
86
- new_state_dict[new_key] = v
87
- return new_state_dict
88
-
89
- @staticmethod
90
- def duration_reduction_func(token_seq, n_gram=1):
91
- """
92
- Args:
93
- token_seq: (T,)
94
- Returns:
95
- reduced_token_seq: (T')
96
- reduced_token_seq_len: T'
97
- """
98
- n_gram_seq = token_seq.unfold(0, n_gram, 1)
99
- mask = torch.all(n_gram_seq[1:] != n_gram_seq[:-1], dim=1)
100
- reduced_token_seq = torch.cat(
101
- (n_gram_seq[0, :n_gram], n_gram_seq[1:, -1][mask])
102
- )
103
- return reduced_token_seq, len(reduced_token_seq)
104
-
105
- @staticmethod
106
- def crossfade(chunk1, chunk2, overlap):
107
- """Apply crossfade between two audio chunks."""
108
- fade_out = np.cos(np.linspace(0, np.pi / 2, overlap)) ** 2
109
- fade_in = np.cos(np.linspace(np.pi / 2, 0, overlap)) ** 2
110
- if len(chunk2) < overlap:
111
- chunk2[:overlap] = chunk2[:overlap] * fade_in[:len(chunk2)] + (chunk1[-overlap:] * fade_out)[:len(chunk2)]
112
- else:
113
- chunk2[:overlap] = chunk2[:overlap] * fade_in + chunk1[-overlap:] * fade_out
114
- return chunk2
115
-
116
- def _stream_wave_chunks(self, vc_wave, processed_frames, vc_mel, overlap_wave_len,
117
- generated_wave_chunks, previous_chunk, is_last_chunk, stream_output):
118
- """
119
- Helper method to handle streaming wave chunks.
120
-
121
- Args:
122
- vc_wave: The current wave chunk
123
- processed_frames: Number of frames processed so far
124
- vc_mel: The mel spectrogram
125
- overlap_wave_len: Length of overlap between chunks
126
- generated_wave_chunks: List of generated wave chunks
127
- previous_chunk: Previous wave chunk for crossfading
128
- is_last_chunk: Whether this is the last chunk
129
- stream_output: Whether to stream the output
130
-
131
- Returns:
132
- Tuple of (processed_frames, previous_chunk, should_break, mp3_bytes, full_audio)
133
- where should_break indicates if processing should stop
134
- mp3_bytes is the MP3 bytes if streaming, None otherwise
135
- full_audio is the full audio if this is the last chunk, None otherwise
136
- """
137
- mp3_bytes = None
138
- full_audio = None
139
-
140
- if processed_frames == 0:
141
- if is_last_chunk:
142
- output_wave = vc_wave[0].cpu().numpy()
143
- generated_wave_chunks.append(output_wave)
144
-
145
- if stream_output:
146
- output_wave_int16 = (output_wave * 32768.0).astype(np.int16)
147
- mp3_bytes = AudioSegment(
148
- output_wave_int16.tobytes(), frame_rate=self.sr,
149
- sample_width=output_wave_int16.dtype.itemsize, channels=1
150
- ).export(format="mp3", bitrate=self.bitrate).read()
151
- full_audio = (self.sr, np.concatenate(generated_wave_chunks))
152
- else:
153
- return processed_frames, previous_chunk, True, None, np.concatenate(generated_wave_chunks)
154
-
155
- return processed_frames, previous_chunk, True, mp3_bytes, full_audio
156
-
157
- output_wave = vc_wave[0, :-overlap_wave_len].cpu().numpy()
158
- generated_wave_chunks.append(output_wave)
159
- previous_chunk = vc_wave[0, -overlap_wave_len:]
160
- processed_frames += vc_mel.size(2) - self.overlap_frame_len
161
-
162
- if stream_output:
163
- output_wave_int16 = (output_wave * 32768.0).astype(np.int16)
164
- mp3_bytes = AudioSegment(
165
- output_wave_int16.tobytes(), frame_rate=self.sr,
166
- sample_width=output_wave_int16.dtype.itemsize, channels=1
167
- ).export(format="mp3", bitrate=self.bitrate).read()
168
-
169
- elif is_last_chunk:
170
- output_wave = self.crossfade(previous_chunk.cpu().numpy(), vc_wave[0].cpu().numpy(), overlap_wave_len)
171
- generated_wave_chunks.append(output_wave)
172
- processed_frames += vc_mel.size(2) - self.overlap_frame_len
173
-
174
- if stream_output:
175
- output_wave_int16 = (output_wave * 32768.0).astype(np.int16)
176
- mp3_bytes = AudioSegment(
177
- output_wave_int16.tobytes(), frame_rate=self.sr,
178
- sample_width=output_wave_int16.dtype.itemsize, channels=1
179
- ).export(format="mp3", bitrate=self.bitrate).read()
180
- full_audio = (self.sr, np.concatenate(generated_wave_chunks))
181
- else:
182
- return processed_frames, previous_chunk, True, None, np.concatenate(generated_wave_chunks)
183
-
184
- return processed_frames, previous_chunk, True, mp3_bytes, full_audio
185
-
186
- else:
187
- output_wave = self.crossfade(previous_chunk.cpu().numpy(), vc_wave[0, :-overlap_wave_len].cpu().numpy(), overlap_wave_len)
188
- generated_wave_chunks.append(output_wave)
189
- previous_chunk = vc_wave[0, -overlap_wave_len:]
190
- processed_frames += vc_mel.size(2) - self.overlap_frame_len
191
-
192
- if stream_output:
193
- output_wave_int16 = (output_wave * 32768.0).astype(np.int16)
194
- mp3_bytes = AudioSegment(
195
- output_wave_int16.tobytes(), frame_rate=self.sr,
196
- sample_width=output_wave_int16.dtype.itemsize, channels=1
197
- ).export(format="mp3", bitrate=self.bitrate).read()
198
-
199
- return processed_frames, previous_chunk, False, mp3_bytes, full_audio
200
-
201
- def load_checkpoints(
202
- self,
203
- cfm_checkpoint_path = None,
204
- ar_checkpoint_path = None,
205
- ):
206
- if cfm_checkpoint_path is None:
207
- cfm_checkpoint_path = load_custom_model_from_hf(
208
- repo_id=DEFAULT_REPO_ID,
209
- model_filename=DEFAULT_CFM_CHECKPOINT,
210
- )
211
- if ar_checkpoint_path is None:
212
- ar_checkpoint_path = load_custom_model_from_hf(
213
- repo_id=DEFAULT_REPO_ID,
214
- model_filename=DEFAULT_AR_CHECKPOINT,
215
- )
216
- # cfm
217
- cfm_checkpoint = torch.load(cfm_checkpoint_path, map_location="cpu")
218
- cfm_length_regulator_state_dict = self.strip_prefix(cfm_checkpoint["net"]['length_regulator'], "module.")
219
- cfm_state_dict = self.strip_prefix(cfm_checkpoint["net"]['cfm'], "module.")
220
- self.cfm.load_state_dict(cfm_state_dict, strict=False)
221
- self.cfm_length_regulator.load_state_dict(cfm_length_regulator_state_dict, strict=False)
222
-
223
- # ar
224
- ar_checkpoint = torch.load(ar_checkpoint_path, map_location="cpu")
225
- ar_length_regulator_state_dict = self.strip_prefix(ar_checkpoint["net"]['length_regulator'], "module.")
226
- ar_state_dict = self.strip_prefix(ar_checkpoint["net"]['ar'], "module.")
227
- self.ar.load_state_dict(ar_state_dict, strict=False)
228
- self.ar_length_regulator.load_state_dict(ar_length_regulator_state_dict, strict=False)
229
-
230
- # content extractor
231
- content_extractor_narrow_checkpoint_path = load_custom_model_from_hf(
232
- repo_id=DEFAULT_CE_REPO_ID,
233
- model_filename=DEFAULT_CE_NARROW_CHECKPOINT,
234
- )
235
- content_extractor_narrow_checkpoint = torch.load(content_extractor_narrow_checkpoint_path, map_location="cpu")
236
- self.content_extractor_narrow.load_state_dict(
237
- content_extractor_narrow_checkpoint, strict=False
238
- )
239
-
240
- content_extractor_wide_checkpoint_path = load_custom_model_from_hf(
241
- repo_id=DEFAULT_CE_REPO_ID,
242
- model_filename=DEFAULT_CE_WIDE_CHECKPOINT,
243
- )
244
- content_extractor_wide_checkpoint = torch.load(content_extractor_wide_checkpoint_path, map_location="cpu")
245
- self.content_extractor_wide.load_state_dict(
246
- content_extractor_wide_checkpoint, strict=False
247
- )
248
-
249
- # style encoder
250
- style_encoder_checkpoint_path = load_custom_model_from_hf(DEFAULT_SE_REPO_ID, DEFAULT_SE_CHECKPOINT, config_filename=None)
251
- style_encoder_checkpoint = torch.load(style_encoder_checkpoint_path, map_location="cpu")
252
- self.style_encoder.load_state_dict(style_encoder_checkpoint, strict=False)
253
-
254
- def setup_ar_caches(self, max_batch_size=1, max_seq_len=4096, dtype=torch.float32, device=torch.device("cpu")):
255
- self.ar.setup_caches(max_batch_size=max_batch_size, max_seq_len=max_seq_len, dtype=dtype, device=device)
256
-
257
- def compute_style(self, waves_16k: torch.Tensor):
258
- feat = torchaudio.compliance.kaldi.fbank(waves_16k,
259
- num_mel_bins=80,
260
- dither=0,
261
- sample_frequency=16000)
262
- feat = feat - feat.mean(dim=0, keepdim=True)
263
- style = self.style_encoder(feat.unsqueeze(0))
264
- return style
265
-
266
- @torch.no_grad()
267
- @torch.inference_mode()
268
- def convert_timbre(
269
- self,
270
- source_audio_path: str,
271
- target_audio_path: str,
272
- diffusion_steps: int = 30,
273
- length_adjust: float = 1.0,
274
- inference_cfg_rate: float = 0.5,
275
- use_sway_sampling: bool = False,
276
- use_amo_sampling: bool = False,
277
- device: torch.device = torch.device("cpu"),
278
- dtype: torch.dtype = torch.float32,
279
- ):
280
- source_wave = librosa.load(source_audio_path, sr=self.sr)[0]
281
- target_wave = librosa.load(target_audio_path, sr=self.sr)[0]
282
- source_wave_tensor = torch.tensor(source_wave).unsqueeze(0).to(device)
283
- target_wave_tensor = torch.tensor(target_wave).unsqueeze(0).to(device)
284
-
285
- # get 16khz audio
286
- source_wave_16k = librosa.resample(source_wave, orig_sr=self.sr, target_sr=16000)
287
- target_wave_16k = librosa.resample(target_wave, orig_sr=self.sr, target_sr=16000)
288
- source_wave_16k_tensor = torch.tensor(source_wave_16k).unsqueeze(0).to(device)
289
- target_wave_16k_tensor = torch.tensor(target_wave_16k).unsqueeze(0).to(device)
290
-
291
- # compute mel spectrogram
292
- source_mel = self.mel_fn(source_wave_tensor)
293
- target_mel = self.mel_fn(target_wave_tensor)
294
- source_mel_len = source_mel.size(2)
295
- target_mel_len = target_mel.size(2)
296
-
297
- with torch.autocast(device_type=device.type, dtype=dtype):
298
- # compute content features
299
- _, source_content_indices, _ = self.content_extractor_wide(source_wave_16k_tensor, [source_wave_16k.size])
300
- _, target_content_indices, _ = self.content_extractor_wide(target_wave_16k_tensor, [target_wave_16k.size])
301
-
302
- # compute style features
303
- target_style = self.compute_style(target_wave_16k_tensor)
304
-
305
- # Length regulation
306
- cond, _ = self.cfm_length_regulator(source_content_indices, ylens=torch.LongTensor([source_mel_len]).to(device))
307
- prompt_condition, _, = self.cfm_length_regulator(target_content_indices, ylens=torch.LongTensor([target_mel_len]).to(device))
308
-
309
- cat_condition = torch.cat([prompt_condition, cond], dim=1)
310
- # generate mel spectrogram
311
- vc_mel = self.cfm.inference(
312
- cat_condition,
313
- torch.LongTensor([cat_condition.size(1)]).to(device),
314
- target_mel, target_style, diffusion_steps,
315
- inference_cfg_rate=inference_cfg_rate,
316
- sway_sampling=use_sway_sampling,
317
- amo_sampling=use_amo_sampling,
318
- )
319
- vc_mel = vc_mel[:, :, target_mel_len:]
320
- vc_wave = self.vocoder(vc_mel.float()).squeeze()[None]
321
- return vc_wave.cpu().numpy()
322
-
323
- @torch.no_grad()
324
- @torch.inference_mode()
325
- def convert_voice(
326
- self,
327
- source_audio_path: str,
328
- target_audio_path: str,
329
- diffusion_steps: int = 30,
330
- length_adjust: float = 1.0,
331
- inference_cfg_rate: float = 0.5,
332
- top_p: float = 0.7,
333
- temperature: float = 0.7,
334
- repetition_penalty: float = 1.5,
335
- use_sway_sampling: bool = False,
336
- use_amo_sampling: bool = False,
337
- device: torch.device = torch.device("cpu"),
338
- dtype: torch.dtype = torch.float32,
339
- ):
340
- source_wave = librosa.load(source_audio_path, sr=self.sr)[0]
341
- target_wave = librosa.load(target_audio_path, sr=self.sr)[0]
342
- source_wave_tensor = torch.tensor(source_wave).unsqueeze(0).to(device)
343
- target_wave_tensor = torch.tensor(target_wave).unsqueeze(0).to(device)
344
-
345
- # get 16khz audio
346
- source_wave_16k = librosa.resample(source_wave, orig_sr=self.sr, target_sr=16000)
347
- target_wave_16k = librosa.resample(target_wave, orig_sr=self.sr, target_sr=16000)
348
- source_wave_16k_tensor = torch.tensor(source_wave_16k).unsqueeze(0).to(device)
349
- target_wave_16k_tensor = torch.tensor(target_wave_16k).unsqueeze(0).to(device)
350
-
351
- # compute mel spectrogram
352
- source_mel = self.mel_fn(source_wave_tensor)
353
- target_mel = self.mel_fn(target_wave_tensor)
354
- source_mel_len = source_mel.size(2)
355
- target_mel_len = target_mel.size(2)
356
-
357
- with torch.autocast(device_type=device.type, dtype=dtype):
358
- # compute content features
359
- _, source_content_indices, _ = self.content_extractor_wide(source_wave_16k_tensor, [source_wave_16k.size])
360
- _, target_content_indices, _ = self.content_extractor_wide(target_wave_16k_tensor, [target_wave_16k.size])
361
-
362
- _, source_narrow_indices, _ = self.content_extractor_narrow(source_wave_16k_tensor,
363
- [source_wave_16k.size], ssl_model=self.content_extractor_wide.ssl_model)
364
- _, target_narrow_indices, _ = self.content_extractor_narrow(target_wave_16k_tensor,
365
- [target_wave_16k.size], ssl_model=self.content_extractor_wide.ssl_model)
366
-
367
- src_narrow_reduced, src_narrow_len = self.duration_reduction_func(source_narrow_indices[0], 1)
368
- tgt_narrow_reduced, tgt_narrow_len = self.duration_reduction_func(target_narrow_indices[0], 1)
369
-
370
- ar_cond = self.ar_length_regulator(torch.cat([tgt_narrow_reduced, src_narrow_reduced], dim=0)[None])[0]
371
-
372
- ar_out = self.ar.generate(ar_cond, target_content_indices, top_p=top_p, temperature=temperature, repetition_penalty=repetition_penalty)
373
- ar_out_mel_len = torch.LongTensor([int(source_mel_len / source_content_indices.size(-1) * ar_out.size(-1) * length_adjust)]).to(device)
374
- # compute style features
375
- target_style = self.compute_style(target_wave_16k_tensor)
376
-
377
- # Length regulation
378
- cond, _ = self.cfm_length_regulator(ar_out, ylens=torch.LongTensor([ar_out_mel_len]).to(device))
379
- prompt_condition, _, = self.cfm_length_regulator(target_content_indices, ylens=torch.LongTensor([target_mel_len]).to(device))
380
-
381
- cat_condition = torch.cat([prompt_condition, cond], dim=1)
382
- # generate mel spectrogram
383
- vc_mel = self.cfm.inference(
384
- cat_condition,
385
- torch.LongTensor([cat_condition.size(1)]).to(device),
386
- target_mel, target_style, diffusion_steps,
387
- inference_cfg_rate=inference_cfg_rate,
388
- sway_sampling=use_sway_sampling,
389
- amo_sampling=use_amo_sampling,
390
- )
391
- vc_mel = vc_mel[:, :, target_mel_len:]
392
- vc_wave = self.vocoder(vc_mel.float()).squeeze()[None]
393
- return vc_wave.cpu().numpy()
394
-
395
- def _process_content_features(self, audio_16k_tensor, is_narrow=False):
396
- """Process audio through Whisper model to extract features."""
397
- content_extractor_fn = self.content_extractor_narrow if is_narrow else self.content_extractor_wide
398
- if audio_16k_tensor.size(-1) <= 16000 * 30:
399
- # Compute content features
400
- _, content_indices, _ = content_extractor_fn(audio_16k_tensor, [audio_16k_tensor.size(-1)], ssl_model=self.content_extractor_wide.ssl_model)
401
- else:
402
- # Process long audio in chunks
403
- overlapping_time = 5 # 5 seconds
404
- features_list = []
405
- buffer = None
406
- traversed_time = 0
407
- while traversed_time < audio_16k_tensor.size(-1):
408
- if buffer is None: # first chunk
409
- chunk = audio_16k_tensor[:, traversed_time:traversed_time + 16000 * 30]
410
- else:
411
- chunk = torch.cat([
412
- buffer,
413
- audio_16k_tensor[:, traversed_time:traversed_time + 16000 * (30 - overlapping_time)]
414
- ], dim=-1)
415
- _, chunk_content_indices, _ = content_extractor_fn(chunk, [chunk.size(-1)], ssl_model=self.content_extractor_wide.ssl_model)
416
- if traversed_time == 0:
417
- features_list.append(chunk_content_indices)
418
- else:
419
- features_list.append(chunk_content_indices[:, 50 * overlapping_time:])
420
- buffer = chunk[:, -16000 * overlapping_time:]
421
- traversed_time += 30 * 16000 if traversed_time == 0 else chunk.size(-1) - 16000 * overlapping_time
422
- content_indices = torch.cat(features_list, dim=1)
423
-
424
- return content_indices
425
-
426
- @spaces.GPU
427
- @torch.no_grad()
428
- @torch.inference_mode()
429
- def convert_voice_with_streaming(
430
- self,
431
- source_audio_path: str,
432
- target_audio_path: str,
433
- diffusion_steps: int = 30,
434
- length_adjust: float = 1.0,
435
- intelligebility_cfg_rate: float = 0.7,
436
- similarity_cfg_rate: float = 0.7,
437
- top_p: float = 0.7,
438
- temperature: float = 0.7,
439
- repetition_penalty: float = 1.5,
440
- convert_style: bool = False,
441
- anonymization_only: bool = False,
442
- device: torch.device = torch.device("cuda"),
443
- dtype: torch.dtype = torch.float16,
444
- stream_output: bool = True,
445
- ):
446
- """
447
- Convert voice with streaming support for long audio files.
448
-
449
- Args:
450
- source_audio_path: Path to source audio file
451
- target_audio_path: Path to target audio file
452
- diffusion_steps: Number of diffusion steps (default: 30)
453
- length_adjust: Length adjustment factor (default: 1.0)
454
- intelligebility_cfg_rate: CFG rate for intelligibility (default: 0.7)
455
- similarity_cfg_rate: CFG rate for similarity (default: 0.7)
456
- top_p: Top-p sampling parameter (default: 0.7)
457
- temperature: Temperature for sampling (default: 0.7)
458
- repetition_penalty: Repetition penalty (default: 1.5)
459
- device: Device to use (default: cpu)
460
- dtype: Data type to use (default: float32)
461
- stream_output: Whether to stream the output (default: True)
462
-
463
- Returns:
464
- If stream_output is True, yields (mp3_bytes, full_audio) tuples
465
- If stream_output is False, returns the full audio as a numpy array
466
- """
467
- # Load audio
468
- source_wave = librosa.load(source_audio_path, sr=self.sr)[0]
469
- target_wave = librosa.load(target_audio_path, sr=self.sr)[0]
470
-
471
- # Limit target audio to 25 seconds
472
- target_wave = target_wave[:self.sr * (self.dit_max_context_len - 5)]
473
-
474
- source_wave_tensor = torch.tensor(source_wave).unsqueeze(0).float().to(device)
475
- target_wave_tensor = torch.tensor(target_wave).unsqueeze(0).float().to(device)
476
-
477
- # Resample to 16kHz for feature extraction
478
- source_wave_16k = librosa.resample(source_wave, orig_sr=self.sr, target_sr=16000)
479
- target_wave_16k = librosa.resample(target_wave, orig_sr=self.sr, target_sr=16000)
480
- source_wave_16k_tensor = torch.tensor(source_wave_16k).unsqueeze(0).to(device)
481
- target_wave_16k_tensor = torch.tensor(target_wave_16k).unsqueeze(0).to(device)
482
-
483
- # Compute mel spectrograms
484
- source_mel = self.mel_fn(source_wave_tensor)
485
- target_mel = self.mel_fn(target_wave_tensor)
486
- source_mel_len = source_mel.size(2)
487
- target_mel_len = target_mel.size(2)
488
-
489
- # Set up chunk processing parameters
490
- max_context_window = self.sr // self.hop_size * self.dit_max_context_len
491
- overlap_wave_len = self.overlap_frame_len * self.hop_size
492
-
493
- with torch.autocast(device_type=device.type, dtype=dtype):
494
- # Compute content features
495
- source_content_indices = self._process_content_features(source_wave_16k_tensor, is_narrow=False)
496
- target_content_indices = self._process_content_features(target_wave_16k_tensor, is_narrow=False)
497
- # Compute style features
498
- target_style = self.compute_style(target_wave_16k_tensor)
499
- prompt_condition, _, = self.cfm_length_regulator(target_content_indices,
500
- ylens=torch.LongTensor([target_mel_len]).to(device))
501
-
502
- # prepare for streaming
503
- generated_wave_chunks = []
504
- processed_frames = 0
505
- previous_chunk = None
506
- if convert_style:
507
- with torch.autocast(device_type=device.type, dtype=dtype):
508
- source_narrow_indices = self._process_content_features(source_wave_16k_tensor, is_narrow=True)
509
- target_narrow_indices = self._process_content_features(target_wave_16k_tensor, is_narrow=True)
510
- src_narrow_reduced, src_narrow_len = self.duration_reduction_func(source_narrow_indices[0], 1)
511
- tgt_narrow_reduced, tgt_narrow_len = self.duration_reduction_func(target_narrow_indices[0], 1)
512
- # Process src_narrow_reduced in chunks of max 1000 tokens
513
- max_chunk_size = 1000
514
-
515
- # Process src_narrow_reduced in chunks
516
- for i in range(0, len(src_narrow_reduced), max_chunk_size):
517
- is_last_chunk = i + max_chunk_size >= len(src_narrow_reduced)
518
- with torch.autocast(device_type=device.type, dtype=dtype):
519
- chunk = src_narrow_reduced[i:i + max_chunk_size]
520
- if anonymization_only:
521
- chunk_ar_cond = self.ar_length_regulator(chunk[None])[0]
522
- chunk_ar_out = self.ar.generate(chunk_ar_cond, torch.zeros([1, 0]).long().to(device),
523
- compiled_decode_fn=self.compiled_decode_fn,
524
- top_p=top_p, temperature=temperature,
525
- repetition_penalty=repetition_penalty)
526
- else:
527
- # For each chunk, we need to include tgt_narrow_reduced as context
528
- chunk_ar_cond = self.ar_length_regulator(torch.cat([tgt_narrow_reduced, chunk], dim=0)[None])[0]
529
- chunk_ar_out = self.ar.generate(chunk_ar_cond, target_content_indices, compiled_decode_fn=self.compiled_decode_fn,
530
- top_p=top_p, temperature=temperature,
531
- repetition_penalty=repetition_penalty)
532
- chunkar_out_mel_len = torch.LongTensor([int(source_mel_len / source_content_indices.size(
533
- -1) * chunk_ar_out.size(-1) * length_adjust)]).to(device)
534
- # Length regulation
535
- chunk_cond, _ = self.cfm_length_regulator(chunk_ar_out, ylens=torch.LongTensor([chunkar_out_mel_len]).to(device))
536
- cat_condition = torch.cat([prompt_condition, chunk_cond], dim=1)
537
- original_len = cat_condition.size(1)
538
- # pad cat_condition to compile_len
539
- if self.dit_compiled:
540
- cat_condition = torch.nn.functional.pad(cat_condition,
541
- (0, 0, 0, self.compile_len - cat_condition.size(1),),
542
- value=0)
543
- # Voice Conversion
544
- vc_mel = self.cfm.inference(
545
- cat_condition,
546
- torch.LongTensor([original_len]).to(device),
547
- target_mel, target_style, diffusion_steps,
548
- inference_cfg_rate=[intelligebility_cfg_rate, similarity_cfg_rate],
549
- random_voice=anonymization_only,
550
- )
551
- vc_mel = vc_mel[:, :, target_mel_len:original_len]
552
- vc_wave = self.vocoder(vc_mel).squeeze()[None]
553
- processed_frames, previous_chunk, should_break, mp3_bytes, full_audio = self._stream_wave_chunks(
554
- vc_wave, processed_frames, vc_mel, overlap_wave_len,
555
- generated_wave_chunks, previous_chunk, is_last_chunk, stream_output
556
- )
557
-
558
- if stream_output and mp3_bytes is not None:
559
- yield mp3_bytes, full_audio
560
-
561
- if should_break:
562
- if not stream_output:
563
- return full_audio
564
- break
565
- else:
566
- cond, _ = self.cfm_length_regulator(source_content_indices, ylens=torch.LongTensor([source_mel_len]).to(device))
567
-
568
- # Process in chunks for streaming
569
- max_source_window = max_context_window - target_mel.size(2)
570
-
571
- # Generate chunk by chunk and stream the output
572
- while processed_frames < cond.size(1):
573
- chunk_cond = cond[:, processed_frames:processed_frames + max_source_window]
574
- is_last_chunk = processed_frames + max_source_window >= cond.size(1)
575
- cat_condition = torch.cat([prompt_condition, chunk_cond], dim=1)
576
- original_len = cat_condition.size(1)
577
- # pad cat_condition to compile_len
578
- if self.dit_compiled:
579
- cat_condition = torch.nn.functional.pad(cat_condition,
580
- (0, 0, 0, self.compile_len - cat_condition.size(1),), value=0)
581
- with torch.autocast(device_type=device.type, dtype=dtype):
582
- # Voice Conversion
583
- vc_mel = self.cfm.inference(
584
- cat_condition,
585
- torch.LongTensor([original_len]).to(device),
586
- target_mel, target_style, diffusion_steps,
587
- inference_cfg_rate=[intelligebility_cfg_rate, similarity_cfg_rate],
588
- random_voice=anonymization_only,
589
- )
590
- vc_mel = vc_mel[:, :, target_mel_len:original_len]
591
- vc_wave = self.vocoder(vc_mel).squeeze()[None]
592
-
593
- processed_frames, previous_chunk, should_break, mp3_bytes, full_audio = self._stream_wave_chunks(
594
- vc_wave, processed_frames, vc_mel, overlap_wave_len,
595
- generated_wave_chunks, previous_chunk, is_last_chunk, stream_output
596
- )
597
-
598
- if stream_output and mp3_bytes is not None:
599
- yield mp3_bytes, full_audio
600
-
601
- if should_break:
602
- if not stream_output:
603
- return full_audio
604
- break
605
-
606
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import librosa
3
+ import torchaudio
4
+ import numpy as np
5
+ from pydub import AudioSegment
6
+ from hf_utils import load_custom_model_from_hf
7
+
8
+ DEFAULT_REPO_ID = "Plachta/Seed-VC"
9
+ DEFAULT_CFM_CHECKPOINT = "v2/cfm_small.pth"
10
+ DEFAULT_AR_CHECKPOINT = "v2/ar_base.pth"
11
+
12
+ DEFAULT_CE_REPO_ID = "Plachta/ASTRAL-quantization"
13
+ DEFAULT_CE_NARROW_CHECKPOINT = "bsq32/bsq32_light.pth"
14
+ DEFAULT_CE_WIDE_CHECKPOINT = "bsq2048/bsq2048_light.pth"
15
+
16
+ DEFAULT_SE_REPO_ID = "funasr/campplus"
17
+ DEFAULT_SE_CHECKPOINT = "campplus_cn_common.bin"
18
+
19
+ class VoiceConversionWrapper(torch.nn.Module):
20
+ def __init__(
21
+ self,
22
+ sr: int,
23
+ hop_size: int,
24
+ mel_fn: callable,
25
+ cfm: torch.nn.Module,
26
+ cfm_length_regulator: torch.nn.Module,
27
+ content_extractor_narrow: torch.nn.Module,
28
+ content_extractor_wide: torch.nn.Module,
29
+ ar_length_regulator: torch.nn.Module,
30
+ ar: torch.nn.Module,
31
+ style_encoder: torch.nn.Module,
32
+ vocoder: torch.nn.Module,
33
+ ):
34
+ super(VoiceConversionWrapper, self).__init__()
35
+ self.sr = sr
36
+ self.hop_size = hop_size
37
+ self.mel_fn = mel_fn
38
+ self.cfm = cfm
39
+ self.cfm_length_regulator = cfm_length_regulator
40
+ self.content_extractor_narrow = content_extractor_narrow
41
+ self.content_extractor_wide = content_extractor_wide
42
+ self.vocoder = vocoder
43
+ self.ar_length_regulator = ar_length_regulator
44
+ self.ar = ar
45
+ self.style_encoder = style_encoder
46
+ # Set streaming parameters
47
+ self.overlap_frame_len = 16
48
+ self.bitrate = "320k"
49
+ self.compiled_decode_fn = None
50
+ self.dit_compiled = False
51
+ self.dit_max_context_len = 30 # in seconds
52
+ self.ar_max_content_len = 1500 # in num of narrow tokens
53
+ self.compile_len = 87 * self.dit_max_context_len
54
+
55
+ def forward_cfm(self, content_indices_wide, content_lens, mels, mel_lens, style_vectors):
56
+ device = content_indices_wide.device
57
+ B = content_indices_wide.size(0)
58
+ cond, _ = self.cfm_length_regulator(content_indices_wide, ylens=mel_lens)
59
+
60
+ # randomly set a length as prompt
61
+ prompt_len_max = mel_lens - 1
62
+ prompt_len = (torch.rand([B], device=device) * prompt_len_max).floor().to(dtype=torch.long)
63
+ prompt_len[torch.rand([B], device=device) < 0.1] = 0
64
+
65
+ loss = self.cfm(mels, mel_lens, prompt_len, cond, style_vectors)
66
+ return loss
67
+
68
+ def forward_ar(self, content_indices_narrow, content_indices_wide, content_lens):
69
+ device = content_indices_narrow.device
70
+ duration_reduced_narrow_tokens = []
71
+ duration_reduced_narrow_lens = []
72
+ for bib in range(content_indices_narrow.size(0)):
73
+ reduced, reduced_len = self.duration_reduction_func(content_indices_narrow[bib])
74
+ duration_reduced_narrow_tokens.append(reduced)
75
+ duration_reduced_narrow_lens.append(reduced_len)
76
+ duration_reduced_narrow_tokens = torch.nn.utils.rnn.pad_sequence(duration_reduced_narrow_tokens,
77
+ batch_first=True, padding_value=0).to(device)
78
+ duration_reduced_narrow_lens = torch.LongTensor(duration_reduced_narrow_lens).to(device)
79
+
80
+ # interpolate speech token to match acoustic feature length
81
+ cond, _ = self.ar_length_regulator(duration_reduced_narrow_tokens)
82
+ loss = self.ar(cond, duration_reduced_narrow_lens, content_indices_wide, content_lens)
83
+ return loss
84
+
85
+ def forward(self, waves_16k, mels, wave_lens_16k, mel_lens, forward_ar=False, forward_cfm=True):
86
+ """
87
+ Forward pass for the model.
88
+ """
89
+ # extract wide content features as both AR and CFM models use them
90
+ with torch.no_grad():
91
+ _, content_indices_wide, content_lens = self.content_extractor_wide(waves_16k, wave_lens_16k)
92
+ if forward_ar:
93
+ # extract narrow content features for AR model
94
+ _, content_indices_narrow, _ = self.content_extractor_narrow(waves_16k, wave_lens_16k, ssl_model=self.content_extractor_wide.ssl_model)
95
+ loss_ar = self.forward_ar(content_indices_narrow.clone(), content_indices_wide.clone(), content_lens)
96
+ else:
97
+ loss_ar = torch.tensor(0.0, device=waves_16k.device, dtype=waves_16k.dtype)
98
+ if forward_cfm:
99
+ style_vectors = self.compute_style(waves_16k, wave_lens_16k)
100
+ loss_cfm = self.forward_cfm(content_indices_wide, content_lens, mels, mel_lens, style_vectors)
101
+ else:
102
+ loss_cfm = torch.tensor(0.0, device=waves_16k.device, dtype=waves_16k.dtype)
103
+ return loss_ar, loss_cfm
104
+
105
+ def compile_ar(self):
106
+ """
107
+ Compile the AR model for inference.
108
+ """
109
+ self.compiled_decode_fn = torch.compile(
110
+ self.ar.model.forward_generate,
111
+ fullgraph=True,
112
+ backend="inductor" if torch.cuda.is_available() else "aot_eager",
113
+ mode="reduce-overhead" if torch.cuda.is_available() else None,
114
+ )
115
+
116
+ def compile_cfm(self):
117
+ self.cfm.estimator.transformer = torch.compile(
118
+ self.cfm.estimator.transformer,
119
+ fullgraph=True,
120
+ backend="inductor" if torch.cuda.is_available() else "aot_eager",
121
+ mode="reduce-overhead" if torch.cuda.is_available() else None,
122
+ )
123
+ self.dit_compiled = True
124
+
125
+ @staticmethod
126
+ def strip_prefix(state_dict: dict, prefix: str = "module.") -> dict:
127
+ """
128
+ Strip the prefix from the state_dict keys.
129
+ """
130
+ new_state_dict = {}
131
+ for k, v in state_dict.items():
132
+ if k.startswith(prefix):
133
+ new_key = k[len(prefix):]
134
+ else:
135
+ new_key = k
136
+ new_state_dict[new_key] = v
137
+ return new_state_dict
138
+
139
+ @staticmethod
140
+ def duration_reduction_func(token_seq, n_gram=1):
141
+ """
142
+ Args:
143
+ token_seq: (T,)
144
+ Returns:
145
+ reduced_token_seq: (T')
146
+ reduced_token_seq_len: T'
147
+ """
148
+ n_gram_seq = token_seq.unfold(0, n_gram, 1)
149
+ mask = torch.all(n_gram_seq[1:] != n_gram_seq[:-1], dim=1)
150
+ reduced_token_seq = torch.cat(
151
+ (n_gram_seq[0, :n_gram], n_gram_seq[1:, -1][mask])
152
+ )
153
+ return reduced_token_seq, len(reduced_token_seq)
154
+
155
+ @staticmethod
156
+ def crossfade(chunk1, chunk2, overlap):
157
+ """Apply crossfade between two audio chunks."""
158
+ fade_out = np.cos(np.linspace(0, np.pi / 2, overlap)) ** 2
159
+ fade_in = np.cos(np.linspace(np.pi / 2, 0, overlap)) ** 2
160
+ if len(chunk2) < overlap:
161
+ chunk2[:overlap] = chunk2[:overlap] * fade_in[:len(chunk2)] + (chunk1[-overlap:] * fade_out)[:len(chunk2)]
162
+ else:
163
+ chunk2[:overlap] = chunk2[:overlap] * fade_in + chunk1[-overlap:] * fade_out
164
+ return chunk2
165
+
166
+ def _stream_wave_chunks(self, vc_wave, processed_frames, vc_mel, overlap_wave_len,
167
+ generated_wave_chunks, previous_chunk, is_last_chunk, stream_output):
168
+ """
169
+ Helper method to handle streaming wave chunks.
170
+
171
+ Args:
172
+ vc_wave: The current wave chunk
173
+ processed_frames: Number of frames processed so far
174
+ vc_mel: The mel spectrogram
175
+ overlap_wave_len: Length of overlap between chunks
176
+ generated_wave_chunks: List of generated wave chunks
177
+ previous_chunk: Previous wave chunk for crossfading
178
+ is_last_chunk: Whether this is the last chunk
179
+ stream_output: Whether to stream the output
180
+
181
+ Returns:
182
+ Tuple of (processed_frames, previous_chunk, should_break, mp3_bytes, full_audio)
183
+ where should_break indicates if processing should stop
184
+ mp3_bytes is the MP3 bytes if streaming, None otherwise
185
+ full_audio is the full audio if this is the last chunk, None otherwise
186
+ """
187
+ mp3_bytes = None
188
+ full_audio = None
189
+
190
+ if processed_frames == 0:
191
+ if is_last_chunk:
192
+ output_wave = vc_wave[0].cpu().numpy()
193
+ generated_wave_chunks.append(output_wave)
194
+
195
+ if stream_output:
196
+ output_wave_int16 = (output_wave * 32768.0).astype(np.int16)
197
+ mp3_bytes = AudioSegment(
198
+ output_wave_int16.tobytes(), frame_rate=self.sr,
199
+ sample_width=output_wave_int16.dtype.itemsize, channels=1
200
+ ).export(format="mp3", bitrate=self.bitrate).read()
201
+ full_audio = (self.sr, np.concatenate(generated_wave_chunks))
202
+ else:
203
+ return processed_frames, previous_chunk, True, None, np.concatenate(generated_wave_chunks)
204
+
205
+ return processed_frames, previous_chunk, True, mp3_bytes, full_audio
206
+
207
+ output_wave = vc_wave[0, :-overlap_wave_len].cpu().numpy()
208
+ generated_wave_chunks.append(output_wave)
209
+ previous_chunk = vc_wave[0, -overlap_wave_len:]
210
+ processed_frames += vc_mel.size(2) - self.overlap_frame_len
211
+
212
+ if stream_output:
213
+ output_wave_int16 = (output_wave * 32768.0).astype(np.int16)
214
+ mp3_bytes = AudioSegment(
215
+ output_wave_int16.tobytes(), frame_rate=self.sr,
216
+ sample_width=output_wave_int16.dtype.itemsize, channels=1
217
+ ).export(format="mp3", bitrate=self.bitrate).read()
218
+
219
+ elif is_last_chunk:
220
+ output_wave = self.crossfade(previous_chunk.cpu().numpy(), vc_wave[0].cpu().numpy(), overlap_wave_len)
221
+ generated_wave_chunks.append(output_wave)
222
+ processed_frames += vc_mel.size(2) - self.overlap_frame_len
223
+
224
+ if stream_output:
225
+ output_wave_int16 = (output_wave * 32768.0).astype(np.int16)
226
+ mp3_bytes = AudioSegment(
227
+ output_wave_int16.tobytes(), frame_rate=self.sr,
228
+ sample_width=output_wave_int16.dtype.itemsize, channels=1
229
+ ).export(format="mp3", bitrate=self.bitrate).read()
230
+ full_audio = (self.sr, np.concatenate(generated_wave_chunks))
231
+ else:
232
+ return processed_frames, previous_chunk, True, None, np.concatenate(generated_wave_chunks)
233
+
234
+ return processed_frames, previous_chunk, True, mp3_bytes, full_audio
235
+
236
+ else:
237
+ output_wave = self.crossfade(previous_chunk.cpu().numpy(), vc_wave[0, :-overlap_wave_len].cpu().numpy(), overlap_wave_len)
238
+ generated_wave_chunks.append(output_wave)
239
+ previous_chunk = vc_wave[0, -overlap_wave_len:]
240
+ processed_frames += vc_mel.size(2) - self.overlap_frame_len
241
+
242
+ if stream_output:
243
+ output_wave_int16 = (output_wave * 32768.0).astype(np.int16)
244
+ mp3_bytes = AudioSegment(
245
+ output_wave_int16.tobytes(), frame_rate=self.sr,
246
+ sample_width=output_wave_int16.dtype.itemsize, channels=1
247
+ ).export(format="mp3", bitrate=self.bitrate).read()
248
+
249
+ return processed_frames, previous_chunk, False, mp3_bytes, full_audio
250
+
251
+ def load_checkpoints(
252
+ self,
253
+ cfm_checkpoint_path = None,
254
+ ar_checkpoint_path = None,
255
+ ):
256
+ if cfm_checkpoint_path is None:
257
+ cfm_checkpoint_path = load_custom_model_from_hf(
258
+ repo_id=DEFAULT_REPO_ID,
259
+ model_filename=DEFAULT_CFM_CHECKPOINT,
260
+ )
261
+ else:
262
+ print(f"Loading CFM checkpoint from {cfm_checkpoint_path}...")
263
+ if ar_checkpoint_path is None:
264
+ ar_checkpoint_path = load_custom_model_from_hf(
265
+ repo_id=DEFAULT_REPO_ID,
266
+ model_filename=DEFAULT_AR_CHECKPOINT,
267
+ )
268
+ else:
269
+ print(f"Loading AR checkpoint from {ar_checkpoint_path}...")
270
+ # cfm
271
+ cfm_checkpoint = torch.load(cfm_checkpoint_path, map_location="cpu")
272
+ cfm_length_regulator_state_dict = self.strip_prefix(cfm_checkpoint["net"]['length_regulator'], "module.")
273
+ cfm_state_dict = self.strip_prefix(cfm_checkpoint["net"]['cfm'], "module.")
274
+ missing_keys, unexpected_keys = self.cfm.load_state_dict(cfm_state_dict, strict=False)
275
+ missing_keys, unexpected_keys = self.cfm_length_regulator.load_state_dict(cfm_length_regulator_state_dict, strict=False)
276
+
277
+ # ar
278
+ ar_checkpoint = torch.load(ar_checkpoint_path, map_location="cpu")
279
+ ar_length_regulator_state_dict = self.strip_prefix(ar_checkpoint["net"]['length_regulator'], "module.")
280
+ ar_state_dict = self.strip_prefix(ar_checkpoint["net"]['ar'], "module.")
281
+ missing_keys, unexpected_keys = self.ar.load_state_dict(ar_state_dict, strict=False)
282
+ missing_keys, unexpected_keys = self.ar_length_regulator.load_state_dict(ar_length_regulator_state_dict, strict=False)
283
+
284
+ # content extractor
285
+ content_extractor_narrow_checkpoint_path = load_custom_model_from_hf(
286
+ repo_id=DEFAULT_CE_REPO_ID,
287
+ model_filename=DEFAULT_CE_NARROW_CHECKPOINT,
288
+ )
289
+ content_extractor_narrow_checkpoint = torch.load(content_extractor_narrow_checkpoint_path, map_location="cpu")
290
+ self.content_extractor_narrow.load_state_dict(
291
+ content_extractor_narrow_checkpoint, strict=False
292
+ )
293
+
294
+ content_extractor_wide_checkpoint_path = load_custom_model_from_hf(
295
+ repo_id=DEFAULT_CE_REPO_ID,
296
+ model_filename=DEFAULT_CE_WIDE_CHECKPOINT,
297
+ )
298
+ content_extractor_wide_checkpoint = torch.load(content_extractor_wide_checkpoint_path, map_location="cpu")
299
+ self.content_extractor_wide.load_state_dict(
300
+ content_extractor_wide_checkpoint, strict=False
301
+ )
302
+
303
+ # style encoder
304
+ style_encoder_checkpoint_path = load_custom_model_from_hf(DEFAULT_SE_REPO_ID, DEFAULT_SE_CHECKPOINT, config_filename=None)
305
+ style_encoder_checkpoint = torch.load(style_encoder_checkpoint_path, map_location="cpu")
306
+ self.style_encoder.load_state_dict(style_encoder_checkpoint, strict=False)
307
+
308
+ def setup_ar_caches(self, max_batch_size=1, max_seq_len=4096, dtype=torch.float32, device=torch.device("cpu")):
309
+ self.ar.setup_caches(max_batch_size=max_batch_size, max_seq_len=max_seq_len, dtype=dtype, device=device)
310
+
311
+ @torch.no_grad()
312
+ def compute_style(self, waves_16k: torch.Tensor, wave_lens_16k: torch.Tensor = None):
313
+ if wave_lens_16k is None:
314
+ wave_lens_16k = torch.tensor([waves_16k.size(-1)], dtype=torch.int32).to(waves_16k.device)
315
+ feat_list = []
316
+ for bib in range(waves_16k.size(0)):
317
+ feat = torchaudio.compliance.kaldi.fbank(waves_16k[bib:bib + 1, :wave_lens_16k[bib]],
318
+ num_mel_bins=80,
319
+ dither=0,
320
+ sample_frequency=16000)
321
+ feat = feat - feat.mean(dim=0, keepdim=True)
322
+ feat_list.append(feat)
323
+ max_feat_len = max([feat.size(0) for feat in feat_list])
324
+ feat_lens = torch.tensor([feat.size(0) for feat in feat_list], dtype=torch.int32).to(waves_16k.device) // 2
325
+ feat_list = [
326
+ torch.nn.functional.pad(feat, (0, 0, 0, max_feat_len - feat.size(0)), value=float(feat.min().item()))
327
+ for feat in feat_list
328
+ ]
329
+ feat = torch.stack(feat_list, dim=0)
330
+ style = self.style_encoder(feat, feat_lens)
331
+ return style
332
+
333
+ @torch.no_grad()
334
+ @torch.inference_mode()
335
+ def convert_timbre(
336
+ self,
337
+ source_audio_path: str,
338
+ target_audio_path: str,
339
+ diffusion_steps: int = 30,
340
+ length_adjust: float = 1.0,
341
+ inference_cfg_rate: float = 0.5,
342
+ use_sway_sampling: bool = False,
343
+ use_amo_sampling: bool = False,
344
+ device: torch.device = torch.device("cpu"),
345
+ dtype: torch.dtype = torch.float32,
346
+ ):
347
+ source_wave = librosa.load(source_audio_path, sr=self.sr)[0]
348
+ target_wave = librosa.load(target_audio_path, sr=self.sr)[0]
349
+ source_wave_tensor = torch.tensor(source_wave).unsqueeze(0).to(device)
350
+ target_wave_tensor = torch.tensor(target_wave).unsqueeze(0).to(device)
351
+
352
+ # get 16khz audio
353
+ source_wave_16k = librosa.resample(source_wave, orig_sr=self.sr, target_sr=16000)
354
+ target_wave_16k = librosa.resample(target_wave, orig_sr=self.sr, target_sr=16000)
355
+ source_wave_16k_tensor = torch.tensor(source_wave_16k).unsqueeze(0).to(device)
356
+ target_wave_16k_tensor = torch.tensor(target_wave_16k).unsqueeze(0).to(device)
357
+
358
+ # compute mel spectrogram
359
+ source_mel = self.mel_fn(source_wave_tensor)
360
+ target_mel = self.mel_fn(target_wave_tensor)
361
+ source_mel_len = source_mel.size(2)
362
+ target_mel_len = target_mel.size(2)
363
+
364
+ with torch.autocast(device_type=device.type, dtype=dtype):
365
+ # compute content features
366
+ _, source_content_indices, _ = self.content_extractor_wide(source_wave_16k_tensor, [source_wave_16k.size])
367
+ _, target_content_indices, _ = self.content_extractor_wide(target_wave_16k_tensor, [target_wave_16k.size])
368
+
369
+ # compute style features
370
+ target_style = self.compute_style(target_wave_16k_tensor)
371
+
372
+ # Length regulation
373
+ cond, _ = self.cfm_length_regulator(source_content_indices, ylens=torch.LongTensor([source_mel_len]).to(device))
374
+ prompt_condition, _, = self.cfm_length_regulator(target_content_indices, ylens=torch.LongTensor([target_mel_len]).to(device))
375
+
376
+ cat_condition = torch.cat([prompt_condition, cond], dim=1)
377
+ # generate mel spectrogram
378
+ vc_mel = self.cfm.inference(
379
+ cat_condition,
380
+ torch.LongTensor([cat_condition.size(1)]).to(device),
381
+ target_mel, target_style, diffusion_steps,
382
+ inference_cfg_rate=inference_cfg_rate,
383
+ sway_sampling=use_sway_sampling,
384
+ amo_sampling=use_amo_sampling,
385
+ )
386
+ vc_mel = vc_mel[:, :, target_mel_len:]
387
+ vc_wave = self.vocoder(vc_mel.float()).squeeze()[None]
388
+ return vc_wave.cpu().numpy()
389
+
390
+ @torch.no_grad()
391
+ @torch.inference_mode()
392
+ def convert_voice(
393
+ self,
394
+ source_audio_path: str,
395
+ target_audio_path: str,
396
+ diffusion_steps: int = 30,
397
+ length_adjust: float = 1.0,
398
+ inference_cfg_rate: float = 0.5,
399
+ top_p: float = 0.7,
400
+ temperature: float = 0.7,
401
+ repetition_penalty: float = 1.5,
402
+ use_sway_sampling: bool = False,
403
+ use_amo_sampling: bool = False,
404
+ device: torch.device = torch.device("cpu"),
405
+ dtype: torch.dtype = torch.float32,
406
+ ):
407
+ source_wave = librosa.load(source_audio_path, sr=self.sr)[0]
408
+ target_wave = librosa.load(target_audio_path, sr=self.sr)[0]
409
+ source_wave_tensor = torch.tensor(source_wave).unsqueeze(0).to(device)
410
+ target_wave_tensor = torch.tensor(target_wave).unsqueeze(0).to(device)
411
+
412
+ # get 16khz audio
413
+ source_wave_16k = librosa.resample(source_wave, orig_sr=self.sr, target_sr=16000)
414
+ target_wave_16k = librosa.resample(target_wave, orig_sr=self.sr, target_sr=16000)
415
+ source_wave_16k_tensor = torch.tensor(source_wave_16k).unsqueeze(0).to(device)
416
+ target_wave_16k_tensor = torch.tensor(target_wave_16k).unsqueeze(0).to(device)
417
+
418
+ # compute mel spectrogram
419
+ source_mel = self.mel_fn(source_wave_tensor)
420
+ target_mel = self.mel_fn(target_wave_tensor)
421
+ source_mel_len = source_mel.size(2)
422
+ target_mel_len = target_mel.size(2)
423
+
424
+ with torch.autocast(device_type=device.type, dtype=dtype):
425
+ # compute content features
426
+ _, source_content_indices, _ = self.content_extractor_wide(source_wave_16k_tensor, [source_wave_16k.size])
427
+ _, target_content_indices, _ = self.content_extractor_wide(target_wave_16k_tensor, [target_wave_16k.size])
428
+
429
+ _, source_narrow_indices, _ = self.content_extractor_narrow(source_wave_16k_tensor,
430
+ [source_wave_16k.size], ssl_model=self.content_extractor_wide.ssl_model)
431
+ _, target_narrow_indices, _ = self.content_extractor_narrow(target_wave_16k_tensor,
432
+ [target_wave_16k.size], ssl_model=self.content_extractor_wide.ssl_model)
433
+
434
+ src_narrow_reduced, src_narrow_len = self.duration_reduction_func(source_narrow_indices[0], 1)
435
+ tgt_narrow_reduced, tgt_narrow_len = self.duration_reduction_func(target_narrow_indices[0], 1)
436
+
437
+ ar_cond = self.ar_length_regulator(torch.cat([tgt_narrow_reduced, src_narrow_reduced], dim=0)[None])[0]
438
+
439
+ ar_out = self.ar.generate(ar_cond, target_content_indices, top_p=top_p, temperature=temperature, repetition_penalty=repetition_penalty)
440
+ ar_out_mel_len = torch.LongTensor([int(source_mel_len / source_content_indices.size(-1) * ar_out.size(-1) * length_adjust)]).to(device)
441
+ # compute style features
442
+ target_style = self.compute_style(target_wave_16k_tensor)
443
+
444
+ # Length regulation
445
+ cond, _ = self.cfm_length_regulator(ar_out, ylens=torch.LongTensor([ar_out_mel_len]).to(device))
446
+ prompt_condition, _, = self.cfm_length_regulator(target_content_indices, ylens=torch.LongTensor([target_mel_len]).to(device))
447
+
448
+ cat_condition = torch.cat([prompt_condition, cond], dim=1)
449
+ # generate mel spectrogram
450
+ vc_mel = self.cfm.inference(
451
+ cat_condition,
452
+ torch.LongTensor([cat_condition.size(1)]).to(device),
453
+ target_mel, target_style, diffusion_steps,
454
+ inference_cfg_rate=inference_cfg_rate,
455
+ sway_sampling=use_sway_sampling,
456
+ amo_sampling=use_amo_sampling,
457
+ )
458
+ vc_mel = vc_mel[:, :, target_mel_len:]
459
+ vc_wave = self.vocoder(vc_mel.float()).squeeze()[None]
460
+ return vc_wave.cpu().numpy()
461
+
462
+ def _process_content_features(self, audio_16k_tensor, is_narrow=False):
463
+ """Process audio through Whisper model to extract features."""
464
+ content_extractor_fn = self.content_extractor_narrow if is_narrow else self.content_extractor_wide
465
+ if audio_16k_tensor.size(-1) <= 16000 * 30:
466
+ # Compute content features
467
+ _, content_indices, _ = content_extractor_fn(audio_16k_tensor, [audio_16k_tensor.size(-1)], ssl_model=self.content_extractor_wide.ssl_model)
468
+ else:
469
+ # Process long audio in chunks
470
+ overlapping_time = 5 # 5 seconds
471
+ features_list = []
472
+ buffer = None
473
+ traversed_time = 0
474
+ while traversed_time < audio_16k_tensor.size(-1):
475
+ if buffer is None: # first chunk
476
+ chunk = audio_16k_tensor[:, traversed_time:traversed_time + 16000 * 30]
477
+ else:
478
+ chunk = torch.cat([
479
+ buffer,
480
+ audio_16k_tensor[:, traversed_time:traversed_time + 16000 * (30 - overlapping_time)]
481
+ ], dim=-1)
482
+ _, chunk_content_indices, _ = content_extractor_fn(chunk, [chunk.size(-1)], ssl_model=self.content_extractor_wide.ssl_model)
483
+ if traversed_time == 0:
484
+ features_list.append(chunk_content_indices)
485
+ else:
486
+ features_list.append(chunk_content_indices[:, 50 * overlapping_time:])
487
+ buffer = chunk[:, -16000 * overlapping_time:]
488
+ traversed_time += 30 * 16000 if traversed_time == 0 else chunk.size(-1) - 16000 * overlapping_time
489
+ content_indices = torch.cat(features_list, dim=1)
490
+
491
+ return content_indices
492
+
493
+ @torch.no_grad()
494
+ @torch.inference_mode()
495
+ def convert_voice_with_streaming(
496
+ self,
497
+ source_audio_path: str,
498
+ target_audio_path: str,
499
+ diffusion_steps: int = 30,
500
+ length_adjust: float = 1.0,
501
+ intelligebility_cfg_rate: float = 0.7,
502
+ similarity_cfg_rate: float = 0.7,
503
+ top_p: float = 0.7,
504
+ temperature: float = 0.7,
505
+ repetition_penalty: float = 1.5,
506
+ convert_style: bool = False,
507
+ anonymization_only: bool = False,
508
+ device: torch.device = torch.device("cuda"),
509
+ dtype: torch.dtype = torch.float16,
510
+ stream_output: bool = True,
511
+ ):
512
+ """
513
+ Convert voice with streaming support for long audio files.
514
+
515
+ Args:
516
+ source_audio_path: Path to source audio file
517
+ target_audio_path: Path to target audio file
518
+ diffusion_steps: Number of diffusion steps (default: 30)
519
+ length_adjust: Length adjustment factor (default: 1.0)
520
+ intelligebility_cfg_rate: CFG rate for intelligibility (default: 0.7)
521
+ similarity_cfg_rate: CFG rate for similarity (default: 0.7)
522
+ top_p: Top-p sampling parameter (default: 0.7)
523
+ temperature: Temperature for sampling (default: 0.7)
524
+ repetition_penalty: Repetition penalty (default: 1.5)
525
+ device: Device to use (default: cpu)
526
+ dtype: Data type to use (default: float32)
527
+ stream_output: Whether to stream the output (default: True)
528
+
529
+ Returns:
530
+ If stream_output is True, yields (mp3_bytes, full_audio) tuples
531
+ If stream_output is False, returns the full audio as a numpy array
532
+ """
533
+ # Load audio
534
+ source_wave = librosa.load(source_audio_path, sr=self.sr)[0]
535
+ target_wave = librosa.load(target_audio_path, sr=self.sr)[0]
536
+
537
+ # Limit target audio to 25 seconds
538
+ target_wave = target_wave[:self.sr * (self.dit_max_context_len - 5)]
539
+
540
+ source_wave_tensor = torch.tensor(source_wave).unsqueeze(0).float().to(device)
541
+ target_wave_tensor = torch.tensor(target_wave).unsqueeze(0).float().to(device)
542
+
543
+ # Resample to 16kHz for feature extraction
544
+ source_wave_16k = librosa.resample(source_wave, orig_sr=self.sr, target_sr=16000)
545
+ target_wave_16k = librosa.resample(target_wave, orig_sr=self.sr, target_sr=16000)
546
+ source_wave_16k_tensor = torch.tensor(source_wave_16k).unsqueeze(0).to(device)
547
+ target_wave_16k_tensor = torch.tensor(target_wave_16k).unsqueeze(0).to(device)
548
+
549
+ # Compute mel spectrograms
550
+ source_mel = self.mel_fn(source_wave_tensor)
551
+ target_mel = self.mel_fn(target_wave_tensor)
552
+ source_mel_len = source_mel.size(2)
553
+ target_mel_len = target_mel.size(2)
554
+
555
+ # Set up chunk processing parameters
556
+ max_context_window = self.sr // self.hop_size * self.dit_max_context_len
557
+ overlap_wave_len = self.overlap_frame_len * self.hop_size
558
+
559
+ with torch.autocast(device_type=device.type, dtype=dtype):
560
+ # Compute content features
561
+ source_content_indices = self._process_content_features(source_wave_16k_tensor, is_narrow=False)
562
+ target_content_indices = self._process_content_features(target_wave_16k_tensor, is_narrow=False)
563
+ # Compute style features
564
+ target_style = self.compute_style(target_wave_16k_tensor)
565
+ prompt_condition, _, = self.cfm_length_regulator(target_content_indices,
566
+ ylens=torch.LongTensor([target_mel_len]).to(device))
567
+
568
+ # prepare for streaming
569
+ generated_wave_chunks = []
570
+ processed_frames = 0
571
+ previous_chunk = None
572
+ if convert_style:
573
+ with torch.autocast(device_type=device.type, dtype=dtype):
574
+ source_narrow_indices = self._process_content_features(source_wave_16k_tensor, is_narrow=True)
575
+ target_narrow_indices = self._process_content_features(target_wave_16k_tensor, is_narrow=True)
576
+ src_narrow_reduced, src_narrow_len = self.duration_reduction_func(source_narrow_indices[0], 1)
577
+ tgt_narrow_reduced, tgt_narrow_len = self.duration_reduction_func(target_narrow_indices[0], 1)
578
+ # Process src_narrow_reduced in chunks of max 1000 tokens
579
+ max_chunk_size = self.ar_max_content_len - tgt_narrow_len
580
+
581
+ # Process src_narrow_reduced in chunks
582
+ for i in range(0, len(src_narrow_reduced), max_chunk_size):
583
+ is_last_chunk = i + max_chunk_size >= len(src_narrow_reduced)
584
+ with torch.autocast(device_type=device.type, dtype=dtype):
585
+ chunk = src_narrow_reduced[i:i + max_chunk_size]
586
+ if anonymization_only:
587
+ chunk_ar_cond = self.ar_length_regulator(chunk[None])[0]
588
+ chunk_ar_out = self.ar.generate(chunk_ar_cond, torch.zeros([1, 0]).long().to(device),
589
+ compiled_decode_fn=self.compiled_decode_fn,
590
+ top_p=top_p, temperature=temperature,
591
+ repetition_penalty=repetition_penalty)
592
+ else:
593
+ # For each chunk, we need to include tgt_narrow_reduced as context
594
+ chunk_ar_cond = self.ar_length_regulator(torch.cat([tgt_narrow_reduced, chunk], dim=0)[None])[0]
595
+ chunk_ar_out = self.ar.generate(chunk_ar_cond, target_content_indices, compiled_decode_fn=self.compiled_decode_fn,
596
+ top_p=top_p, temperature=temperature,
597
+ repetition_penalty=repetition_penalty)
598
+ chunkar_out_mel_len = torch.LongTensor([int(source_mel_len / source_content_indices.size(
599
+ -1) * chunk_ar_out.size(-1) * length_adjust)]).to(device)
600
+ # Length regulation
601
+ chunk_cond, _ = self.cfm_length_regulator(chunk_ar_out, ylens=torch.LongTensor([chunkar_out_mel_len]).to(device))
602
+ cat_condition = torch.cat([prompt_condition, chunk_cond], dim=1)
603
+ original_len = cat_condition.size(1)
604
+ # pad cat_condition to compile_len
605
+ if self.dit_compiled:
606
+ cat_condition = torch.nn.functional.pad(cat_condition,
607
+ (0, 0, 0, self.compile_len - cat_condition.size(1),),
608
+ value=0)
609
+ # Voice Conversion
610
+ vc_mel = self.cfm.inference(
611
+ cat_condition,
612
+ torch.LongTensor([original_len]).to(device),
613
+ target_mel, target_style, diffusion_steps,
614
+ inference_cfg_rate=[intelligebility_cfg_rate, similarity_cfg_rate],
615
+ random_voice=anonymization_only,
616
+ )
617
+ vc_mel = vc_mel[:, :, target_mel_len:original_len]
618
+ vc_wave = self.vocoder(vc_mel).squeeze()[None]
619
+ processed_frames, previous_chunk, should_break, mp3_bytes, full_audio = self._stream_wave_chunks(
620
+ vc_wave, processed_frames, vc_mel, overlap_wave_len,
621
+ generated_wave_chunks, previous_chunk, is_last_chunk, stream_output
622
+ )
623
+
624
+ if stream_output and mp3_bytes is not None:
625
+ yield mp3_bytes, full_audio
626
+ if should_break:
627
+ break
628
+ else:
629
+ cond, _ = self.cfm_length_regulator(source_content_indices, ylens=torch.LongTensor([source_mel_len]).to(device))
630
+
631
+ # Process in chunks for streaming
632
+ max_source_window = max_context_window - target_mel.size(2)
633
+
634
+ # Generate chunk by chunk and stream the output
635
+ while processed_frames < cond.size(1):
636
+ chunk_cond = cond[:, processed_frames:processed_frames + max_source_window]
637
+ is_last_chunk = processed_frames + max_source_window >= cond.size(1)
638
+ cat_condition = torch.cat([prompt_condition, chunk_cond], dim=1)
639
+ original_len = cat_condition.size(1)
640
+ # pad cat_condition to compile_len
641
+ if self.dit_compiled:
642
+ cat_condition = torch.nn.functional.pad(cat_condition,
643
+ (0, 0, 0, self.compile_len - cat_condition.size(1),), value=0)
644
+ with torch.autocast(device_type=device.type, dtype=torch.float32): # force CFM to use float32
645
+ # Voice Conversion
646
+ vc_mel = self.cfm.inference(
647
+ cat_condition,
648
+ torch.LongTensor([original_len]).to(device),
649
+ target_mel, target_style, diffusion_steps,
650
+ inference_cfg_rate=[intelligebility_cfg_rate, similarity_cfg_rate],
651
+ random_voice=anonymization_only,
652
+ )
653
+ vc_mel = vc_mel[:, :, target_mel_len:original_len]
654
+ vc_wave = self.vocoder(vc_mel).squeeze()[None]
655
+
656
+ processed_frames, previous_chunk, should_break, mp3_bytes, full_audio = self._stream_wave_chunks(
657
+ vc_wave, processed_frames, vc_mel, overlap_wave_len,
658
+ generated_wave_chunks, previous_chunk, is_last_chunk, stream_output
659
+ )
660
+
661
+ if stream_output and mp3_bytes is not None:
662
+ yield mp3_bytes, full_audio
663
+ if should_break:
664
+ break