Spaces:
Running
on
Zero
Running
on
Zero
Update modules/v2/vc_wrapper.py
Browse files- modules/v2/vc_wrapper.py +664 -606
modules/v2/vc_wrapper.py
CHANGED
@@ -1,606 +1,664 @@
|
|
1 |
-
import
|
2 |
-
import
|
3 |
-
import
|
4 |
-
import
|
5 |
-
|
6 |
-
from
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
self.
|
37 |
-
self.
|
38 |
-
self.
|
39 |
-
self.
|
40 |
-
self.
|
41 |
-
self.
|
42 |
-
self.
|
43 |
-
self.
|
44 |
-
self.
|
45 |
-
self.
|
46 |
-
|
47 |
-
|
48 |
-
self.
|
49 |
-
self.
|
50 |
-
self.
|
51 |
-
self.
|
52 |
-
self.
|
53 |
-
self.compile_len = 87 * self.dit_max_context_len
|
54 |
-
|
55 |
-
def
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
)
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
return
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
def
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
|
178 |
-
|
179 |
-
|
180 |
-
|
181 |
-
|
182 |
-
|
183 |
-
|
184 |
-
|
185 |
-
|
186 |
-
|
187 |
-
|
188 |
-
|
189 |
-
|
190 |
-
|
191 |
-
|
192 |
-
|
193 |
-
|
194 |
-
|
195 |
-
|
196 |
-
|
197 |
-
|
198 |
-
|
199 |
-
|
200 |
-
|
201 |
-
|
202 |
-
|
203 |
-
|
204 |
-
|
205 |
-
|
206 |
-
|
207 |
-
|
208 |
-
|
209 |
-
|
210 |
-
)
|
211 |
-
|
212 |
-
|
213 |
-
|
214 |
-
|
215 |
-
|
216 |
-
|
217 |
-
|
218 |
-
|
219 |
-
|
220 |
-
|
221 |
-
|
222 |
-
|
223 |
-
|
224 |
-
|
225 |
-
|
226 |
-
|
227 |
-
|
228 |
-
|
229 |
-
|
230 |
-
|
231 |
-
|
232 |
-
|
233 |
-
|
234 |
-
|
235 |
-
|
236 |
-
|
237 |
-
|
238 |
-
|
239 |
-
|
240 |
-
|
241 |
-
|
242 |
-
|
243 |
-
|
244 |
-
|
245 |
-
|
246 |
-
|
247 |
-
|
248 |
-
|
249 |
-
|
250 |
-
|
251 |
-
|
252 |
-
|
253 |
-
|
254 |
-
|
255 |
-
|
256 |
-
|
257 |
-
|
258 |
-
|
259 |
-
|
260 |
-
|
261 |
-
|
262 |
-
|
263 |
-
|
264 |
-
|
265 |
-
|
266 |
-
|
267 |
-
|
268 |
-
|
269 |
-
|
270 |
-
|
271 |
-
|
272 |
-
|
273 |
-
|
274 |
-
|
275 |
-
|
276 |
-
|
277 |
-
|
278 |
-
|
279 |
-
|
280 |
-
|
281 |
-
|
282 |
-
|
283 |
-
|
284 |
-
|
285 |
-
|
286 |
-
|
287 |
-
|
288 |
-
|
289 |
-
|
290 |
-
|
291 |
-
|
292 |
-
|
293 |
-
|
294 |
-
|
295 |
-
|
296 |
-
|
297 |
-
|
298 |
-
|
299 |
-
|
300 |
-
|
301 |
-
|
302 |
-
|
303 |
-
|
304 |
-
|
305 |
-
|
306 |
-
|
307 |
-
|
308 |
-
|
309 |
-
|
310 |
-
|
311 |
-
|
312 |
-
|
313 |
-
|
314 |
-
|
315 |
-
|
316 |
-
|
317 |
-
|
318 |
-
|
319 |
-
|
320 |
-
|
321 |
-
|
322 |
-
|
323 |
-
|
324 |
-
|
325 |
-
|
326 |
-
|
327 |
-
|
328 |
-
|
329 |
-
|
330 |
-
|
331 |
-
|
332 |
-
|
333 |
-
|
334 |
-
|
335 |
-
|
336 |
-
|
337 |
-
|
338 |
-
|
339 |
-
|
340 |
-
|
341 |
-
|
342 |
-
|
343 |
-
|
344 |
-
|
345 |
-
|
346 |
-
|
347 |
-
|
348 |
-
|
349 |
-
|
350 |
-
|
351 |
-
|
352 |
-
|
353 |
-
|
354 |
-
|
355 |
-
|
356 |
-
|
357 |
-
|
358 |
-
|
359 |
-
|
360 |
-
|
361 |
-
|
362 |
-
|
363 |
-
|
364 |
-
|
365 |
-
|
366 |
-
|
367 |
-
|
368 |
-
|
369 |
-
|
370 |
-
|
371 |
-
|
372 |
-
|
373 |
-
|
374 |
-
|
375 |
-
|
376 |
-
|
377 |
-
#
|
378 |
-
|
379 |
-
|
380 |
-
|
381 |
-
|
382 |
-
|
383 |
-
|
384 |
-
|
385 |
-
|
386 |
-
|
387 |
-
|
388 |
-
|
389 |
-
|
390 |
-
|
391 |
-
|
392 |
-
|
393 |
-
|
394 |
-
|
395 |
-
|
396 |
-
|
397 |
-
|
398 |
-
|
399 |
-
|
400 |
-
|
401 |
-
|
402 |
-
|
403 |
-
|
404 |
-
|
405 |
-
|
406 |
-
|
407 |
-
|
408 |
-
|
409 |
-
|
410 |
-
|
411 |
-
|
412 |
-
|
413 |
-
|
414 |
-
|
415 |
-
|
416 |
-
|
417 |
-
|
418 |
-
|
419 |
-
|
420 |
-
|
421 |
-
|
422 |
-
|
423 |
-
|
424 |
-
|
425 |
-
|
426 |
-
|
427 |
-
|
428 |
-
|
429 |
-
|
430 |
-
|
431 |
-
|
432 |
-
|
433 |
-
|
434 |
-
|
435 |
-
|
436 |
-
|
437 |
-
|
438 |
-
|
439 |
-
|
440 |
-
|
441 |
-
|
442 |
-
|
443 |
-
|
444 |
-
|
445 |
-
|
446 |
-
|
447 |
-
|
448 |
-
|
449 |
-
|
450 |
-
|
451 |
-
|
452 |
-
|
453 |
-
|
454 |
-
|
455 |
-
|
456 |
-
|
457 |
-
|
458 |
-
|
459 |
-
|
460 |
-
|
461 |
-
|
462 |
-
|
463 |
-
|
464 |
-
|
465 |
-
|
466 |
-
|
467 |
-
|
468 |
-
|
469 |
-
|
470 |
-
|
471 |
-
|
472 |
-
|
473 |
-
|
474 |
-
|
475 |
-
|
476 |
-
|
477 |
-
|
478 |
-
|
479 |
-
|
480 |
-
|
481 |
-
|
482 |
-
|
483 |
-
|
484 |
-
|
485 |
-
|
486 |
-
|
487 |
-
|
488 |
-
|
489 |
-
|
490 |
-
|
491 |
-
|
492 |
-
|
493 |
-
|
494 |
-
|
495 |
-
|
496 |
-
|
497 |
-
|
498 |
-
|
499 |
-
|
500 |
-
|
501 |
-
|
502 |
-
|
503 |
-
|
504 |
-
|
505 |
-
|
506 |
-
|
507 |
-
|
508 |
-
|
509 |
-
|
510 |
-
|
511 |
-
|
512 |
-
|
513 |
-
|
514 |
-
|
515 |
-
|
516 |
-
|
517 |
-
|
518 |
-
|
519 |
-
|
520 |
-
|
521 |
-
|
522 |
-
|
523 |
-
|
524 |
-
|
525 |
-
|
526 |
-
|
527 |
-
|
528 |
-
|
529 |
-
|
530 |
-
|
531 |
-
|
532 |
-
|
533 |
-
|
534 |
-
|
535 |
-
|
536 |
-
|
537 |
-
|
538 |
-
|
539 |
-
|
540 |
-
|
541 |
-
|
542 |
-
|
543 |
-
|
544 |
-
|
545 |
-
|
546 |
-
|
547 |
-
|
548 |
-
|
549 |
-
|
550 |
-
|
551 |
-
|
552 |
-
|
553 |
-
|
554 |
-
|
555 |
-
|
556 |
-
|
557 |
-
|
558 |
-
|
559 |
-
|
560 |
-
|
561 |
-
|
562 |
-
|
563 |
-
|
564 |
-
|
565 |
-
|
566 |
-
|
567 |
-
|
568 |
-
|
569 |
-
|
570 |
-
|
571 |
-
|
572 |
-
|
573 |
-
|
574 |
-
|
575 |
-
|
576 |
-
|
577 |
-
|
578 |
-
|
579 |
-
|
580 |
-
|
581 |
-
|
582 |
-
|
583 |
-
|
584 |
-
|
585 |
-
|
586 |
-
|
587 |
-
|
588 |
-
|
589 |
-
|
590 |
-
|
591 |
-
|
592 |
-
|
593 |
-
|
594 |
-
|
595 |
-
|
596 |
-
|
597 |
-
|
598 |
-
|
599 |
-
|
600 |
-
|
601 |
-
|
602 |
-
|
603 |
-
|
604 |
-
|
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
|