返回 F5-TTS
utils_infer.py
根目录 / src / f5_tts / infer / utils_infer.py
1 # A unified script for inference process
2 # Make adjustments inside functions, and consider both gradio and cli scripts if need to change func output format
3 import os
4 import sys
5 from concurrent.futures import ThreadPoolExecutor
6
7
8 os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1" # for MPS device compatibility
9 sys.path.append(f"{os.path.dirname(os.path.abspath(__file__))}/../../third_party/BigVGAN/")
10
11 import hashlib
12 import re
13 import tempfile
14 from importlib.resources import files
15
16 import matplotlib
17
18
19 matplotlib.use("Agg")
20
21 import matplotlib.pylab as plt
22 import numpy as np
23 import torch
24 import torchaudio
25 import tqdm
26 from huggingface_hub import hf_hub_download
27 from pydub import AudioSegment, silence
28 from transformers import pipeline
29 from vocos import Vocos
30
31 from f5_tts.device_utils import get_default_device
32 from f5_tts.model import CFM
33 from f5_tts.model.utils import convert_char_to_pinyin, get_tokenizer
34
35
36 _ref_audio_cache = {}
37 _ref_text_cache = {}
38
39 device = get_default_device()
40
41 tempfile_kwargs = {"delete_on_close": False} if sys.version_info >= (3, 12) else {"delete": False}
42
43 # -----------------------------------------
44
45 target_sample_rate = 24000
46 n_mel_channels = 100
47 hop_length = 256
48 win_length = 1024
49 n_fft = 1024
50 mel_spec_type = "vocos"
51 target_rms = 0.1
52 cross_fade_duration = 0.15
53 ode_method = "euler"
54 nfe_step = 32 # 16, 32
55 cfg_strength = 2.0
56 sway_sampling_coef = -1.0
57 speed = 1.0
58 fix_duration = None
59
60 # -----------------------------------------
61
62
63 # chunk text into smaller pieces
64
65
66 def chunk_text(text, max_chars=135):
67 """
68 Splits the input text into chunks, each with a maximum number of characters.
69
70 Args:
71 text (str): The text to be split.
72 max_chars (int): The maximum number of characters per chunk.
73
74 Returns:
75 List[str]: A list of text chunks.
76 """
77 chunks = []
78 current_chunk = ""
79 # Split the text into sentences based on punctuation followed by whitespace
80 sentences = re.split(r"(?<=[;:,.!?])\s+|(?<=[;:,。!?])", text)
81
82 for sentence in sentences:
83 if not sentence:
84 continue
85 if len(current_chunk.encode("utf-8")) + len(sentence.encode("utf-8")) <= max_chars:
86 current_chunk += sentence + " " if sentence and len(sentence[-1].encode("utf-8")) == 1 else sentence
87 else:
88 if current_chunk:
89 chunks.append(current_chunk.strip())
90 current_chunk = sentence + " " if sentence and len(sentence[-1].encode("utf-8")) == 1 else sentence
91
92 if current_chunk:
93 chunks.append(current_chunk.strip())
94
95 return chunks
96
97
98 # load vocoder
99 def load_vocoder(vocoder_name="vocos", is_local=False, local_path="", device=device, hf_cache_dir=None):
100 if vocoder_name == "vocos":
101 # vocoder = Vocos.from_pretrained("charactr/vocos-mel-24khz").to(device)
102 if is_local:
103 print(f"Load vocos from local path {local_path}")
104 config_path = f"{local_path}/config.yaml"
105 model_path = f"{local_path}/pytorch_model.bin"
106 else:
107 print("Download Vocos from huggingface charactr/vocos-mel-24khz")
108 repo_id = "charactr/vocos-mel-24khz"
109 config_path = hf_hub_download(repo_id=repo_id, cache_dir=hf_cache_dir, filename="config.yaml")
110 model_path = hf_hub_download(repo_id=repo_id, cache_dir=hf_cache_dir, filename="pytorch_model.bin")
111 vocoder = Vocos.from_hparams(config_path)
112 state_dict = torch.load(model_path, map_location="cpu", weights_only=True)
113 from vocos.feature_extractors import EncodecFeatures
114
115 if isinstance(vocoder.feature_extractor, EncodecFeatures):
116 encodec_parameters = {
117 "feature_extractor.encodec." + key: value
118 for key, value in vocoder.feature_extractor.encodec.state_dict().items()
119 }
120 state_dict.update(encodec_parameters)
121 vocoder.load_state_dict(state_dict)
122 vocoder = vocoder.eval().to(device)
123 elif vocoder_name == "bigvgan":
124 try:
125 from third_party.BigVGAN import bigvgan
126 except ImportError:
127 print("You need to follow the README to init submodule and change the BigVGAN source code.")
128 if is_local:
129 # download generator from https://huggingface.co/nvidia/bigvgan_v2_24khz_100band_256x/tree/main
130 vocoder = bigvgan.BigVGAN.from_pretrained(local_path, use_cuda_kernel=False)
131 else:
132 vocoder = bigvgan.BigVGAN.from_pretrained(
133 "nvidia/bigvgan_v2_24khz_100band_256x", use_cuda_kernel=False, cache_dir=hf_cache_dir
134 )
135
136 vocoder.remove_weight_norm()
137 vocoder = vocoder.eval().to(device)
138 return vocoder
139
140
141 # load asr pipeline
142
143 asr_pipe = None
144
145
146 def initialize_asr_pipeline(device: str = device, dtype=None):
147 if dtype is None:
148 dtype = (
149 torch.float16
150 if "cuda" in device
151 and torch.cuda.get_device_properties(device).major >= 7
152 and not torch.cuda.get_device_name().endswith("[ZLUDA]")
153 else torch.float32
154 )
155 global asr_pipe
156 asr_pipe = pipeline(
157 "automatic-speech-recognition",
158 model="openai/whisper-large-v3-turbo",
159 torch_dtype=dtype,
160 device=device,
161 )
162
163
164 # transcribe
165
166
167 def transcribe(ref_audio, language=None):
168 global asr_pipe
169 if asr_pipe is None:
170 initialize_asr_pipeline(device=device)
171 return asr_pipe(
172 ref_audio,
173 chunk_length_s=30,
174 batch_size=128,
175 generate_kwargs={"task": "transcribe", "language": language} if language else {"task": "transcribe"},
176 return_timestamps=False,
177 )["text"].strip()
178
179
180 # load model checkpoint for inference
181
182
183 def load_checkpoint(model, ckpt_path, device: str, dtype=None, use_ema=True):
184 if dtype is None:
185 dtype = (
186 torch.float16
187 if "cuda" in device
188 and torch.cuda.get_device_properties(device).major >= 7
189 and not torch.cuda.get_device_name().endswith("[ZLUDA]")
190 else torch.float32
191 )
192 model = model.to(dtype)
193
194 ckpt_type = ckpt_path.split(".")[-1]
195 if ckpt_type == "safetensors":
196 from safetensors.torch import load_file
197
198 checkpoint = load_file(ckpt_path, device=device)
199 else:
200 checkpoint = torch.load(ckpt_path, map_location=device, weights_only=True)
201
202 if use_ema:
203 if ckpt_type == "safetensors":
204 checkpoint = {"ema_model_state_dict": checkpoint}
205 checkpoint["model_state_dict"] = {
206 k.replace("ema_model.", ""): v
207 for k, v in checkpoint["ema_model_state_dict"].items()
208 if k not in ["initted", "step"]
209 }
210
211 # patch for backward compatibility, 305e3ea
212 for key in ["mel_spec.mel_stft.mel_scale.fb", "mel_spec.mel_stft.spectrogram.window"]:
213 if key in checkpoint["model_state_dict"]:
214 del checkpoint["model_state_dict"][key]
215
216 model.load_state_dict(checkpoint["model_state_dict"])
217 else:
218 if ckpt_type == "safetensors":
219 checkpoint = {"model_state_dict": checkpoint}
220 model.load_state_dict(checkpoint["model_state_dict"])
221
222 del checkpoint
223 torch.cuda.empty_cache()
224
225 return model.to(device)
226
227
228 # load model for inference
229
230
231 def load_model(
232 model_cls,
233 model_cfg,
234 ckpt_path,
235 mel_spec_type=mel_spec_type,
236 vocab_file="",
237 ode_method=ode_method,
238 use_ema=True,
239 device=device,
240 ):
241 if vocab_file == "":
242 vocab_file = str(files("f5_tts").joinpath("infer/examples/vocab.txt"))
243 tokenizer = "custom"
244
245 print("\nvocab : ", vocab_file)
246 print("token : ", tokenizer)
247 print("model : ", ckpt_path, "\n")
248
249 vocab_char_map, vocab_size = get_tokenizer(vocab_file, tokenizer)
250 model = CFM(
251 transformer=model_cls(**model_cfg, text_num_embeds=vocab_size, mel_dim=n_mel_channels),
252 mel_spec_kwargs=dict(
253 n_fft=n_fft,
254 hop_length=hop_length,
255 win_length=win_length,
256 n_mel_channels=n_mel_channels,
257 target_sample_rate=target_sample_rate,
258 mel_spec_type=mel_spec_type,
259 ),
260 odeint_kwargs=dict(
261 method=ode_method,
262 ),
263 vocab_char_map=vocab_char_map,
264 ).to(device)
265
266 dtype = torch.float32 if mel_spec_type == "bigvgan" else None
267 model = load_checkpoint(model, ckpt_path, device, dtype=dtype, use_ema=use_ema)
268
269 return model
270
271
272 def remove_silence_edges(audio, silence_threshold=-42):
273 # Remove silence from the start
274 non_silent_start_idx = silence.detect_leading_silence(audio, silence_threshold=silence_threshold)
275 audio = audio[non_silent_start_idx:]
276
277 # Remove silence from the end
278 reversed_audio = audio.reverse()
279 non_silent_end_idx = silence.detect_leading_silence(reversed_audio, silence_threshold=silence_threshold)
280 if non_silent_end_idx > 0:
281 trimmed_audio = audio[: len(audio) - non_silent_end_idx]
282 else:
283 trimmed_audio = audio
284
285 return trimmed_audio
286
287
288 # preprocess reference audio and text
289
290
291 def preprocess_ref_audio_text(ref_audio_orig, ref_text, show_info=print):
292 show_info("Converting audio...")
293
294 # Compute a hash of the reference audio file
295 with open(ref_audio_orig, "rb") as audio_file:
296 audio_data = audio_file.read()
297 audio_hash = hashlib.md5(audio_data).hexdigest()
298
299 global _ref_audio_cache
300
301 if audio_hash in _ref_audio_cache:
302 show_info("Using cached preprocessed reference audio...")
303 ref_audio = _ref_audio_cache[audio_hash]
304
305 else: # first pass, do preprocess
306 with tempfile.NamedTemporaryFile(suffix=".wav", **tempfile_kwargs) as f:
307 temp_path = f.name
308
309 aseg = AudioSegment.from_file(ref_audio_orig)
310
311 # 1. try to find long silence for clipping
312 non_silent_segs = silence.split_on_silence(
313 aseg, min_silence_len=1000, silence_thresh=-50, keep_silence=1000, seek_step=10
314 )
315 non_silent_wave = AudioSegment.silent(duration=0)
316 for non_silent_seg in non_silent_segs:
317 if len(non_silent_wave) > 6000 and len(non_silent_wave + non_silent_seg) > 12000:
318 show_info("Audio is over 12s, clipping short. (1)")
319 break
320 non_silent_wave += non_silent_seg
321
322 # 2. try to find short silence for clipping if 1. failed
323 if len(non_silent_wave) > 12000:
324 non_silent_segs = silence.split_on_silence(
325 aseg, min_silence_len=100, silence_thresh=-40, keep_silence=1000, seek_step=10
326 )
327 non_silent_wave = AudioSegment.silent(duration=0)
328 for non_silent_seg in non_silent_segs:
329 if len(non_silent_wave) > 6000 and len(non_silent_wave + non_silent_seg) > 12000:
330 show_info("Audio is over 12s, clipping short. (2)")
331 break
332 non_silent_wave += non_silent_seg
333
334 aseg = non_silent_wave
335
336 # 3. if no proper silence found for clipping
337 if len(aseg) > 12000:
338 aseg = aseg[:12000]
339 show_info("Audio is over 12s, clipping short. (3)")
340
341 aseg = remove_silence_edges(aseg) + AudioSegment.silent(duration=50)
342 aseg.export(temp_path, format="wav")
343 ref_audio = temp_path
344
345 # Cache the processed reference audio
346 _ref_audio_cache[audio_hash] = ref_audio
347
348 if not ref_text.strip():
349 global _ref_text_cache
350 if audio_hash in _ref_text_cache:
351 # Use cached asr transcription
352 show_info("Using cached reference text...")
353 ref_text = _ref_text_cache[audio_hash]
354 else:
355 show_info("No reference text provided, transcribing reference audio...")
356 ref_text = transcribe(ref_audio)
357 # Cache the transcribed text (not caching custom ref_text, enabling users to do manual tweak)
358 _ref_text_cache[audio_hash] = ref_text
359 else:
360 show_info("Using custom reference text...")
361
362 # Ensure ref_text ends with a proper sentence-ending punctuation
363 if not ref_text.endswith(". ") and not ref_text.endswith("。"):
364 if ref_text.endswith("."):
365 ref_text += " "
366 else:
367 ref_text += ". "
368
369 print("\nref_text ", ref_text)
370
371 return ref_audio, ref_text
372
373
374 # infer process: chunk text -> infer batches [i.e. infer_batch_process()]
375
376
377 def infer_process(
378 ref_audio,
379 ref_text,
380 gen_text,
381 model_obj,
382 vocoder,
383 mel_spec_type=mel_spec_type,
384 show_info=print,
385 progress=tqdm,
386 target_rms=target_rms,
387 cross_fade_duration=cross_fade_duration,
388 nfe_step=nfe_step,
389 cfg_strength=cfg_strength,
390 sway_sampling_coef=sway_sampling_coef,
391 speed=speed,
392 fix_duration=fix_duration,
393 device=device,
394 ):
395 # Split the input text into batches
396 audio, sr = torchaudio.load(ref_audio)
397 max_chars = int(len(ref_text.encode("utf-8")) / (audio.shape[-1] / sr) * (30 - audio.shape[-1] / sr) * speed)
398 gen_text_batches = chunk_text(gen_text, max_chars=max_chars)
399 for i, gen_text_i in enumerate(gen_text_batches):
400 print(f"gen_text {i}", gen_text_i)
401 print("\n")
402
403 show_info(f"Generating audio in {len(gen_text_batches)} batches...")
404
405 if not gen_text_batches:
406 show_info("No text batches to generate.")
407 return None, target_sample_rate, None
408
409 return next(
410 infer_batch_process(
411 (audio, sr),
412 ref_text,
413 gen_text_batches,
414 model_obj,
415 vocoder,
416 mel_spec_type=mel_spec_type,
417 progress=progress,
418 target_rms=target_rms,
419 cross_fade_duration=cross_fade_duration,
420 nfe_step=nfe_step,
421 cfg_strength=cfg_strength,
422 sway_sampling_coef=sway_sampling_coef,
423 speed=speed,
424 fix_duration=fix_duration,
425 device=device,
426 )
427 )
428
429
430 # infer batches
431
432
433 def infer_batch_process(
434 ref_audio,
435 ref_text,
436 gen_text_batches,
437 model_obj,
438 vocoder,
439 mel_spec_type="vocos",
440 progress=tqdm,
441 target_rms=0.1,
442 cross_fade_duration=0.15,
443 nfe_step=32,
444 cfg_strength=2.0,
445 sway_sampling_coef=-1,
446 speed=1,
447 fix_duration=None,
448 device=None,
449 streaming=False,
450 chunk_size=2048,
451 ):
452 audio, sr = ref_audio
453 if audio.shape[0] > 1:
454 audio = torch.mean(audio, dim=0, keepdim=True)
455
456 rms = torch.sqrt(torch.mean(torch.square(audio)))
457 if rms < target_rms:
458 audio = audio * target_rms / rms
459 if sr != target_sample_rate:
460 resampler = torchaudio.transforms.Resample(sr, target_sample_rate)
461 audio = resampler(audio)
462 audio = audio.to(device)
463
464 generated_waves = []
465 spectrograms = []
466
467 if len(ref_text[-1].encode("utf-8")) == 1:
468 ref_text = ref_text + " "
469
470 # Allocate fix_duration across chunks to avoid each chunk using the full-sentence duration (N× blow-up)
471 if fix_duration is not None and len(gen_text_batches) > 1:
472 ref_audio_len_frames = audio.shape[-1] // hop_length
473 ref_sec = ref_audio_len_frames * hop_length / target_sample_rate
474 target_total = fix_duration - ref_sec
475 weights = [len(c.encode("utf-8")) for c in gen_text_batches]
476 total_w = sum(weights)
477 allocatable = target_total + cross_fade_duration * (len(gen_text_batches) - 1)
478 fix_durations = [ref_sec + allocatable * w / total_w for w in weights]
479 else:
480 fix_durations = [fix_duration] * len(gen_text_batches)
481
482 def _infer_basic(gen_text, fix_dur):
483 local_speed = speed
484 if len(gen_text.encode("utf-8")) < 10:
485 local_speed = speed * 0.3
486
487 # Prepare the text
488 text_list = [ref_text + gen_text]
489 final_text_list = convert_char_to_pinyin(text_list)
490
491 ref_audio_len = audio.shape[-1] // hop_length
492 if fix_dur is not None:
493 duration = int(fix_dur * target_sample_rate / hop_length)
494 else:
495 # Calculate duration
496 ref_text_len = len(ref_text.encode("utf-8"))
497 gen_text_len = len(gen_text.encode("utf-8"))
498 duration = ref_audio_len + int(ref_audio_len / ref_text_len * gen_text_len / local_speed)
499
500 # inference
501 with torch.inference_mode():
502 generated, _ = model_obj.sample(
503 cond=audio,
504 text=final_text_list,
505 duration=duration,
506 steps=nfe_step,
507 cfg_strength=cfg_strength,
508 sway_sampling_coef=sway_sampling_coef,
509 )
510 del _
511
512 generated = generated.to(torch.float32) # generated mel spectrogram
513 generated = generated[:, ref_audio_len:, :]
514 generated = generated.permute(0, 2, 1)
515 if mel_spec_type == "vocos":
516 generated_wave = vocoder.decode(generated)
517 elif mel_spec_type == "bigvgan":
518 generated_wave = vocoder(generated)
519 if rms < target_rms:
520 generated_wave = generated_wave * rms / target_rms
521
522 # wav -> numpy
523 generated_wave = generated_wave.squeeze().cpu().numpy()
524
525 return generated_wave, generated
526
527 def infer_single_process(gen_text, fix_dur):
528 generated_wave, generated = _infer_basic(gen_text, fix_dur)
529 generated_cpu = generated[0].cpu().numpy()
530 del generated
531 return generated_wave, generated_cpu
532
533 def infer_single_process_streaming(gen_text, fix_dur):
534 # for src/f5_tts/socket_server.py
535 generated_wave, generated = _infer_basic(gen_text, fix_dur)
536 del generated
537 for j in range(0, len(generated_wave), chunk_size):
538 yield generated_wave[j : j + chunk_size], target_sample_rate
539
540 if streaming:
541 batches_iter = progress.tqdm(gen_text_batches) if progress is not None else gen_text_batches
542 for gen_text, fix_dur in zip(batches_iter, fix_durations):
543 for chunk in infer_single_process_streaming(gen_text, fix_dur):
544 yield chunk
545 else:
546 with ThreadPoolExecutor() as executor:
547 futures = [executor.submit(infer_single_process, gt, fd) for gt, fd in zip(gen_text_batches, fix_durations)]
548 for future in progress.tqdm(futures) if progress is not None else futures:
549 result = future.result()
550 if result:
551 generated_wave, generated_mel_spec = result
552 generated_waves.append(generated_wave)
553 spectrograms.append(generated_mel_spec)
554
555 if generated_waves:
556 if cross_fade_duration <= 0:
557 # Simply concatenate
558 final_wave = np.concatenate(generated_waves)
559 else:
560 # Combine all generated waves with cross-fading
561 final_wave = generated_waves[0]
562 for i in range(1, len(generated_waves)):
563 prev_wave = final_wave
564 next_wave = generated_waves[i]
565
566 # Calculate cross-fade samples, ensuring it does not exceed wave lengths
567 cross_fade_samples = int(cross_fade_duration * target_sample_rate)
568 cross_fade_samples = min(cross_fade_samples, len(prev_wave), len(next_wave))
569
570 if cross_fade_samples <= 0:
571 # No overlap possible, concatenate
572 final_wave = np.concatenate([prev_wave, next_wave])
573 continue
574
575 # Overlapping parts
576 prev_overlap = prev_wave[-cross_fade_samples:]
577 next_overlap = next_wave[:cross_fade_samples]
578
579 # Fade out and fade in
580 fade_out = np.linspace(1, 0, cross_fade_samples)
581 fade_in = np.linspace(0, 1, cross_fade_samples)
582
583 # Cross-faded overlap
584 cross_faded_overlap = prev_overlap * fade_out + next_overlap * fade_in
585
586 # Combine
587 new_wave = np.concatenate(
588 [prev_wave[:-cross_fade_samples], cross_faded_overlap, next_wave[cross_fade_samples:]]
589 )
590
591 final_wave = new_wave
592
593 # Create a combined spectrogram
594 combined_spectrogram = np.concatenate(spectrograms, axis=1)
595
596 yield final_wave, target_sample_rate, combined_spectrogram
597
598 else:
599 yield None, target_sample_rate, None
600
601
602 # remove silence from generated wav
603
604
605 def remove_silence_for_generated_wav(filename):
606 aseg = AudioSegment.from_file(filename)
607 non_silent_segs = silence.split_on_silence(
608 aseg, min_silence_len=1000, silence_thresh=-50, keep_silence=500, seek_step=10
609 )
610 non_silent_wave = AudioSegment.silent(duration=0)
611 for non_silent_seg in non_silent_segs:
612 non_silent_wave += non_silent_seg
613 aseg = non_silent_wave
614 aseg.export(filename, format="wav")
615
616
617 # save spectrogram
618
619
620 def save_spectrogram(spectrogram, path):
621 plt.figure(figsize=(12, 4))
622 plt.imshow(spectrogram, origin="lower", aspect="auto")
623 plt.colorbar()
624 plt.savefig(path)
625 plt.close()
626
626 lines PYTHON