返回 F5-TTS
speech_edit.py
根目录 / src / f5_tts / infer / speech_edit.py
1 import os
2
3
4 os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1" # for MPS device compatibility
5
6 from importlib.resources import files
7
8 import torch
9 import torch.nn.functional as F
10 import torchaudio
11 from cached_path import cached_path
12 from hydra.utils import get_class
13 from omegaconf import OmegaConf
14
15 from f5_tts.device_utils import get_default_device
16 from f5_tts.infer.utils_infer import load_checkpoint, load_vocoder, save_spectrogram
17 from f5_tts.model import CFM
18 from f5_tts.model.utils import convert_char_to_pinyin, get_tokenizer
19
20
21 device = get_default_device()
22
23
24 # ---------------------- infer setting ---------------------- #
25
26 seed = None # int | None
27
28 exp_name = "F5TTS_v1_Base" # F5TTS_v1_Base | E2TTS_Base
29 ckpt_step = 1250000
30
31 nfe_step = 32 # 16, 32
32 cfg_strength = 2.0
33 ode_method = "euler" # euler | midpoint
34 sway_sampling_coef = -1.0
35 speed = 1.0
36 target_rms = 0.1
37
38
39 model_cfg = OmegaConf.load(str(files("f5_tts").joinpath(f"configs/{exp_name}.yaml")))
40 model_cls = get_class(f"f5_tts.model.{model_cfg.model.backbone}")
41 model_arc = model_cfg.model.arch
42
43 dataset_name = model_cfg.datasets.name
44 tokenizer = model_cfg.model.tokenizer
45
46 mel_spec_type = model_cfg.model.mel_spec.mel_spec_type
47 target_sample_rate = model_cfg.model.mel_spec.target_sample_rate
48 n_mel_channels = model_cfg.model.mel_spec.n_mel_channels
49 hop_length = model_cfg.model.mel_spec.hop_length
50 win_length = model_cfg.model.mel_spec.win_length
51 n_fft = model_cfg.model.mel_spec.n_fft
52
53
54 # ckpt_path = str(files("f5_tts").joinpath("../../")) + f"/ckpts/{exp_name}/model_{ckpt_step}.safetensors"
55 ckpt_path = str(cached_path(f"hf://SWivid/F5-TTS/{exp_name}/model_{ckpt_step}.safetensors"))
56 output_dir = "tests"
57
58
59 # [leverage https://github.com/MahmoudAshraf97/ctc-forced-aligner to get char level alignment]
60 # pip install git+https://github.com/MahmoudAshraf97/ctc-forced-aligner.git
61 # [write the origin_text into a file, e.g. tests/test_edit.txt]
62 # ctc-forced-aligner --audio_path "src/f5_tts/infer/examples/basic/basic_ref_en.wav" --text_path "tests/test_edit.txt" --language "zho" --romanize --split_size "char"
63 # [result will be saved at same path of audio file]
64 # [--language "zho" for Chinese, "eng" for English]
65 # [if local ckpt, set --alignment_model "../checkpoints/mms-300m-1130-forced-aligner"]
66
67 audio_to_edit = str(files("f5_tts").joinpath("infer/examples/basic/basic_ref_en.wav"))
68 origin_text = "Some call me nature, others call me mother nature."
69 target_text = "Some call me optimist, others call me realist."
70 parts_to_edit = [
71 [1.42, 2.44],
72 [4.04, 4.9],
73 ] # stard_ends of "nature" & "mother nature", in seconds
74 fix_duration = [
75 1.2,
76 1,
77 ] # fix duration for "optimist" & "realist", in seconds
78
79 # audio_to_edit = "src/f5_tts/infer/examples/basic/basic_ref_zh.wav"
80 # origin_text = "对,这就是我,万人敬仰的太乙真人。"
81 # target_text = "对,那就是你,万人敬仰的太白金星。"
82 # parts_to_edit = [[0.84, 1.4], [1.92, 2.4], [4.26, 6.26], ]
83 # fix_duration = None # use origin text duration
84
85 # audio_to_edit = "src/f5_tts/infer/examples/basic/basic_ref_zh.wav"
86 # origin_text = "对,这就是我,万人敬仰的太乙真人。"
87 # target_text = "对,这就是你,万人敬仰的李白金星。"
88 # parts_to_edit = [[1.500, 2.784], [4.083, 6.760]]
89 # fix_duration = [1.284, 2.677]
90
91
92 # -------------------------------------------------#
93
94 use_ema = True
95
96 if not os.path.exists(output_dir):
97 os.makedirs(output_dir)
98
99 # Vocoder model
100 local = False
101 if mel_spec_type == "vocos":
102 vocoder_local_path = "../checkpoints/charactr/vocos-mel-24khz"
103 elif mel_spec_type == "bigvgan":
104 vocoder_local_path = "../checkpoints/bigvgan_v2_24khz_100band_256x"
105 vocoder = load_vocoder(vocoder_name=mel_spec_type, is_local=local, local_path=vocoder_local_path)
106
107 # Tokenizer
108 vocab_char_map, vocab_size = get_tokenizer(dataset_name, tokenizer)
109
110 # Model
111 model = CFM(
112 transformer=model_cls(**model_arc, text_num_embeds=vocab_size, mel_dim=n_mel_channels),
113 mel_spec_kwargs=dict(
114 n_fft=n_fft,
115 hop_length=hop_length,
116 win_length=win_length,
117 n_mel_channels=n_mel_channels,
118 target_sample_rate=target_sample_rate,
119 mel_spec_type=mel_spec_type,
120 ),
121 odeint_kwargs=dict(
122 method=ode_method,
123 ),
124 vocab_char_map=vocab_char_map,
125 ).to(device)
126
127 dtype = torch.float32 if mel_spec_type == "bigvgan" else None
128 model = load_checkpoint(model, ckpt_path, device, dtype=dtype, use_ema=use_ema)
129
130 # Audio
131 audio, sr = torchaudio.load(audio_to_edit)
132 if audio.shape[0] > 1:
133 audio = torch.mean(audio, dim=0, keepdim=True)
134 rms = torch.sqrt(torch.mean(torch.square(audio)))
135 if rms < target_rms:
136 audio = audio * target_rms / rms
137 if sr != target_sample_rate:
138 resampler = torchaudio.transforms.Resample(sr, target_sample_rate)
139 audio = resampler(audio)
140
141 # Convert to mel spectrogram FIRST (on clean original audio)
142 # This avoids boundary artifacts from mel windows straddling zeros and real audio
143 audio = audio.to(device)
144 with torch.inference_mode():
145 original_mel = model.mel_spec(audio) # (batch, n_mel, n_frames)
146 original_mel = original_mel.permute(0, 2, 1) # (batch, n_frames, n_mel)
147
148 # Build mel_cond and edit_mask at FRAME level
149 # Insert zero frames in mel domain instead of zero samples in wav domain
150 offset_frame = 0
151 mel_cond = torch.zeros(1, 0, n_mel_channels, device=device)
152 edit_mask = torch.zeros(1, 0, dtype=torch.bool, device=device)
153 fix_dur_list = fix_duration.copy() if fix_duration is not None else None
154
155 for part in parts_to_edit:
156 start, end = part
157 part_dur_sec = end - start if fix_dur_list is None else fix_dur_list.pop(0)
158
159 # Convert to frames (this is the authoritative unit)
160 start_frame = round(start * target_sample_rate / hop_length)
161 end_frame = round(end * target_sample_rate / hop_length)
162 part_dur_frames = round(part_dur_sec * target_sample_rate / hop_length)
163
164 # Number of frames for the kept (non-edited) region
165 keep_frames = start_frame - offset_frame
166
167 # Build mel_cond: original mel frames + zero frames for edit region
168 mel_cond = torch.cat(
169 (
170 mel_cond,
171 original_mel[:, offset_frame:start_frame, :],
172 torch.zeros(1, part_dur_frames, n_mel_channels, device=device),
173 ),
174 dim=1,
175 )
176 edit_mask = torch.cat(
177 (
178 edit_mask,
179 torch.ones(1, keep_frames, dtype=torch.bool, device=device),
180 torch.zeros(1, part_dur_frames, dtype=torch.bool, device=device),
181 ),
182 dim=-1,
183 )
184 offset_frame = end_frame
185
186 # Append remaining mel frames after last edit
187 mel_cond = torch.cat((mel_cond, original_mel[:, offset_frame:, :]), dim=1)
188 edit_mask = F.pad(edit_mask, (0, mel_cond.shape[1] - edit_mask.shape[-1]), value=True)
189
190 # Text
191 text_list = [target_text]
192 if tokenizer == "pinyin":
193 final_text_list = convert_char_to_pinyin(text_list)
194 else:
195 final_text_list = [text_list]
196 print(f"text : {text_list}")
197 print(f"pinyin: {final_text_list}")
198
199 # Duration - use mel_cond length (not raw audio length)
200 duration = mel_cond.shape[1]
201
202 # Inference - pass mel_cond directly (not wav)
203 with torch.inference_mode():
204 generated, trajectory = model.sample(
205 cond=mel_cond, # Now passing mel directly, not wav
206 text=final_text_list,
207 duration=duration,
208 steps=nfe_step,
209 cfg_strength=cfg_strength,
210 sway_sampling_coef=sway_sampling_coef,
211 seed=seed,
212 edit_mask=edit_mask,
213 )
214 print(f"Generated mel: {generated.shape}")
215
216 # Final result
217 generated = generated.to(torch.float32)
218 gen_mel_spec = generated.permute(0, 2, 1)
219 if mel_spec_type == "vocos":
220 generated_wave = vocoder.decode(gen_mel_spec).cpu()
221 elif mel_spec_type == "bigvgan":
222 generated_wave = vocoder(gen_mel_spec).squeeze(0).cpu()
223
224 if rms < target_rms:
225 generated_wave = generated_wave * rms / target_rms
226
227 save_spectrogram(gen_mel_spec[0].cpu().numpy(), f"{output_dir}/speech_edit_out.png")
228 torchaudio.save(f"{output_dir}/speech_edit_out.wav", generated_wave, target_sample_rate)
229 print(f"Generated wav: {generated_wave.shape}")
230
230 lines PYTHON