Views
No views yet

1git clone https://github.com/amphionspace/FlexiCodec.git
2cd FlexiCodec
3pip install -r requirements.txtflexicodec/modeling_flexicodec.py.1import torch
2import torchaudio
3from flexicodec.infer import prepare_model, encode_flexicodec
4
5model_dict = prepare_model()
6
7# Load a real audio file
8audio_path = "YOUR_WAV.wav"
9audio, sample_rate = torchaudio.load(audio_path)
10with torch.no_grad():
11 encoded_output = encode_flexicodec(audio, model_dict, sample_rate, num_quantizers=8, merging_threshold=0.91)
12
13 reconstructed_audio = model_dict['model'].decode_from_codes(
14 semantic_codes=encoded_output['semantic_codes'],
15 acoustic_codes=encoded_output['acoustic_codes'],
16 token_lengths=encoded_output['token_lengths'],
17 )
18
19duration = audio.shape[-1] / sample_rate
20output_path = 'decoded_audio.wav'
21torchaudio.save(output_path, reconstructed_audio.cpu().squeeze(1), 16000)
22
23print(f"Saved decoded audio to {output_path}")
24print(f"This sample avg frame rate: {encoded_output['token_lengths'].shape[-1] / duration:.4f} frames/sec")num_quantizers=xxx (maximum 24), merging_threshold=xxx (maximum 1.0) parameters. If you set merging_threshold=1.0, it will be a standard 12.5Hz neural audio codec. All of its token_lengths items will be 1.export HF_ENDPOINT=https://hf-mirror.com in terminal, before running the code. If you don't want to automatically download from huggingface, you can manually specify your downloaded checkpoint paths prepare_model.audio_lens parameter to encode_flexicodec, and you can crop the output for each audio in encoded_output[speech_token_len].sys.path.append('/path/to/FlexiCodec') to find the code.feat = model_dict['model'].get_semantic_feature(encoded_output['semantic_codes'])1sudo apt install espeak-ng
2pip install cached_path phonemizer openai-whisper1import torch
2import torchaudio
3from flexicodec.nar_tts.inference_voicebox import (
4 prepare_voicebox_model,
5 infer_voicebox_tts
6)
7import cached_path
8# Prepare model (loads model and vocoder)
9checkpoint_path = cached_path('hf://jiaqili3/flexicodec/nartts.safetensors')
10model_dict = prepare_voicebox_model(checkpoint_path)
11
12# Option 1: Inference with audio file paths
13gt_audio_path = "audio_examples/61-70968-0000_gt.wav" # Target content. Example GT audio
14ref_audio_path = "audio_examples/61-70968-0000_ref.wav" # Reference voice/style.
15
16output_audio, output_sr = infer_voicebox_tts(
17 model_dict=model_dict,
18 gt_audio_path=gt_audio_path,
19 ref_audio_path=ref_audio_path,
20 n_timesteps=15, # Number of diffusion steps (default: 15)
21 cfg=2.0, # Classifier-free guidance scale (default: 2.0)
22 rescale_cfg=0.75, # CFG rescaling factor (default: 0.75)
23 merging_threshold=1.0 # Merging threshold for frame rate control (default: 1.0, max: 1.0)
24)
25
26# Save output
27torchaudio.save("output.wav", output_audio.unsqueeze(0) if output_audio.dim() == 1 else output_audio, output_sr)
28
29# Option 2: Inference with audio tensors
30gt_audio, gt_sr = torchaudio.load("path/to/ground_truth.wav")
31ref_audio, ref_sr = torchaudio.load("path/to/reference.wav")
32
33output_audio, output_sr = infer_voicebox_tts(
34 model_dict=model_dict,
35 gt_audio=gt_audio,
36 ref_audio=ref_audio,
37 gt_sample_rate=gt_sr,
38 ref_sample_rate=ref_sr,
39 n_timesteps=15,
40 cfg=2.0,
41 rescale_cfg=0.75,
42 merging_threshold=1.0
43)gt_audio) determines the semantic content of the outputref_audio) determines the voice/style characteristicsmodel_dict for multiple inference calls to avoid reloading the modelmerging_threshold controls FlexiCodec's dynamic frame rate: lower values (e.g., 0.87, 0.91) enable merging for lower average frame rates, while 1.0 disables merging (standard 12.5Hz)1import torch
2import torchaudio
3from flexicodec.ar_tts.inference_tts import tts_synthesize
4from flexicodec.ar_tts.modeling_artts import prepare_artts_model
5from flexicodec.nar_tts.inference_voicebox import prepare_voicebox_model
6import cached_path
7
8# Prepare both AR and NAR models
9ar_checkpoint = cached_path('hf://jiaqili3/flexicodec/artts.safetensors')
10nar_checkpoint = cached_path('hf://jiaqili3/flexicodec/nartts.safetensors')
11
12ar_model_dict = prepare_artts_model(ar_checkpoint)
13nar_model_dict = prepare_voicebox_model(nar_checkpoint)
14
15# Full TTS synthesis
16output_audio, output_sr = tts_synthesize(
17 ar_model_dict=ar_model_dict,
18 nar_model_dict=nar_model_dict,
19 text="Hello, this is a complete text-to-speech example.",
20 language="en",
21 ref_audio_path="audio_examples/61-70968-0000_ref.wav", # Reference voice
22 ref_text="bear us escort so far as the Sheriff's house", # Optional reference text
23 merging_threshold=0.91, # Frame rate control (used for both AR and NAR)
24 beam_size=1,
25 top_k=25,
26 temperature=1.0,
27 predict_duration=True,
28 duration_top_k=1,
29 n_timesteps=15, # NAR diffusion steps
30 cfg=2.0, # NAR classifier-free guidance
31 rescale_cfg=0.75, # NAR CFG rescaling
32 use_nar=True, # Set to False for AR-only decoding
33)
34
35# Save output
36torchaudio.save("output.wav", output_audio.unsqueeze(0) if output_audio.dim() == 1 else output_audio, output_sr)tts_synthesize performs the full pipeline: AR generation + NAR decoding to audioref_audio_path) provides the voice/style characteristicsref_text) is optional and can help with prosody alignmentuse_nar=False in tts_synthesize to use AR-only decoding (faster but lower quality)flexicodec/ar_tts/modeling_artts.py and flexicodec/nar_tts/modeling_voicebox.py there are training_forward methods that receive audios and prepared sensevoice-small input "FBank" features. (dl_output dictionary containing x (the feature_extractor output), x_lens (length of each x before padding), audio (the 16khz audio tensor)).
Training can be replicated by passing the same data to the training_forward methods.1@article{li2025flexicodec,
2 title={FlexiCodec: A Dynamic Neural Audio Codec for Low Frame Rates},
3 author={Li, Jiaqi and Qian, Yao and Hu, Yuxuan and Zhang, Leying and Wang, Xiaofei and Lu, Heng and Thakker, Manthan and Li, Jinyu and Zhao, Shang and Wu, Zhizheng},
4 journal={arXiv preprint arXiv:2510.00981},
5 year={2025}
6}
7
8@article{li2025dualcodec,
9 title={Dualcodec: A low-frame-rate, semantically-enhanced neural audio codec for speech generation},
10 author={Li, Jiaqi and Lin, Xiaolong and Li, Zhekai and Huang, Shixi and Wang, Yuancheng and Wang, Chaoren and Zhan, Zhenpeng and Wu, Zhizheng},
11 journal={Interspeech 2025},
12 year={2025}
13}