mrfakename commited on
Commit
c355b3e
1 Parent(s): 7ccf7c7

Create app_local.py

Browse files
Files changed (1) hide show
  1. app_local.py +211 -0
app_local.py ADDED
@@ -0,0 +1,211 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ print("WARNING: You are running this unofficial E2/F5 TTS demo locally, it may not be as up-to-date as the hosted version (https://huggingface.co/spaces/mrfakename/E2-F5-TTS)")
2
+
3
+ import os
4
+ import re
5
+ import torch
6
+ import torchaudio
7
+ import gradio as gr
8
+ import numpy as np
9
+ import tempfile
10
+ from einops import rearrange
11
+ from ema_pytorch import EMA
12
+ from vocos import Vocos
13
+ from pydub import AudioSegment
14
+ from model import CFM, UNetT, DiT, MMDiT
15
+ from cached_path import cached_path
16
+ from model.utils import (
17
+ get_tokenizer,
18
+ convert_char_to_pinyin,
19
+ save_spectrogram,
20
+ )
21
+ from transformers import pipeline
22
+ import librosa
23
+
24
+ device = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu"
25
+
26
+ print(f"Using {device} device")
27
+
28
+ pipe = pipeline(
29
+ "automatic-speech-recognition",
30
+ model="openai/whisper-large-v3-turbo",
31
+ torch_dtype=torch.float16,
32
+ device=device,
33
+ )
34
+
35
+ # --------------------- Settings -------------------- #
36
+
37
+ target_sample_rate = 24000
38
+ n_mel_channels = 100
39
+ hop_length = 256
40
+ target_rms = 0.1
41
+ nfe_step = 32 # 16, 32
42
+ cfg_strength = 2.0
43
+ ode_method = 'euler'
44
+ sway_sampling_coef = -1.0
45
+ speed = 1.0
46
+ # fix_duration = 27 # None or float (duration in seconds)
47
+ fix_duration = None
48
+
49
+ def load_model(exp_name, model_cls, model_cfg, ckpt_step):
50
+ checkpoint = torch.load(str(cached_path(f"hf://SWivid/F5-TTS/{exp_name}/model_{ckpt_step}.pt")), map_location=device)
51
+ vocab_char_map, vocab_size = get_tokenizer("Emilia_ZH_EN", "pinyin")
52
+ model = CFM(
53
+ transformer=model_cls(
54
+ **model_cfg,
55
+ text_num_embeds=vocab_size,
56
+ mel_dim=n_mel_channels
57
+ ),
58
+ mel_spec_kwargs=dict(
59
+ target_sample_rate=target_sample_rate,
60
+ n_mel_channels=n_mel_channels,
61
+ hop_length=hop_length,
62
+ ),
63
+ odeint_kwargs=dict(
64
+ method=ode_method,
65
+ ),
66
+ vocab_char_map=vocab_char_map,
67
+ ).to(device)
68
+
69
+ ema_model = EMA(model, include_online_model=False).to(device)
70
+ ema_model.load_state_dict(checkpoint['ema_model_state_dict'])
71
+ ema_model.copy_params_from_ema_to_model()
72
+
73
+ return ema_model, model
74
+
75
+ # load models
76
+ F5TTS_model_cfg = dict(dim=1024, depth=22, heads=16, ff_mult=2, text_dim=512, conv_layers=4)
77
+ E2TTS_model_cfg = dict(dim=1024, depth=24, heads=16, ff_mult=4)
78
+
79
+ F5TTS_ema_model, F5TTS_base_model = load_model("F5TTS_Base", DiT, F5TTS_model_cfg, 1200000)
80
+ E2TTS_ema_model, E2TTS_base_model = load_model("E2TTS_Base", UNetT, E2TTS_model_cfg, 1200000)
81
+
82
+ def infer(ref_audio_orig, ref_text, gen_text, exp_name, remove_silence):
83
+ print(gen_text)
84
+ if len(gen_text) > 200:
85
+ raise gr.Error("Please keep your text under 200 chars.")
86
+ gr.Info("Converting audio...")
87
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as f:
88
+ aseg = AudioSegment.from_file(ref_audio_orig)
89
+ audio_duration = len(aseg)
90
+ if audio_duration > 15000:
91
+ gr.Warning("Audio is over 15s, clipping to only first 15s.")
92
+ aseg = aseg[:15000]
93
+ aseg.export(f.name, format="wav")
94
+ ref_audio = f.name
95
+ if exp_name == "F5-TTS":
96
+ ema_model = F5TTS_ema_model
97
+ base_model = F5TTS_base_model
98
+ elif exp_name == "E2-TTS":
99
+ ema_model = E2TTS_ema_model
100
+ base_model = E2TTS_base_model
101
+
102
+ if not ref_text.strip():
103
+ gr.Info("No reference text provided, transcribing reference audio...")
104
+ ref_text = outputs = pipe(
105
+ ref_audio,
106
+ chunk_length_s=30,
107
+ batch_size=128,
108
+ generate_kwargs={"task": "transcribe"},
109
+ return_timestamps=False,
110
+ )['text'].strip()
111
+ gr.Info("Finished transcription")
112
+ else:
113
+ gr.Info("Using custom reference text...")
114
+ audio, sr = torchaudio.load(ref_audio)
115
+
116
+ rms = torch.sqrt(torch.mean(torch.square(audio)))
117
+ if rms < target_rms:
118
+ audio = audio * target_rms / rms
119
+ if sr != target_sample_rate:
120
+ resampler = torchaudio.transforms.Resample(sr, target_sample_rate)
121
+ audio = resampler(audio)
122
+ audio = audio.to(device)
123
+
124
+ # Prepare the text
125
+ text_list = [ref_text + gen_text]
126
+ final_text_list = convert_char_to_pinyin(text_list)
127
+
128
+ # Calculate duration
129
+ ref_audio_len = audio.shape[-1] // hop_length
130
+ # if fix_duration is not None:
131
+ # duration = int(fix_duration * target_sample_rate / hop_length)
132
+ # else:
133
+ zh_pause_punc = r"。,、;:?!"
134
+ ref_text_len = len(ref_text) + len(re.findall(zh_pause_punc, ref_text))
135
+ gen_text_len = len(gen_text) + len(re.findall(zh_pause_punc, gen_text))
136
+ duration = ref_audio_len + int(ref_audio_len / ref_text_len * gen_text_len / speed)
137
+
138
+ # inference
139
+ gr.Info(f"Generating audio using {exp_name}")
140
+ with torch.inference_mode():
141
+ generated, _ = base_model.sample(
142
+ cond=audio,
143
+ text=final_text_list,
144
+ duration=duration,
145
+ steps=nfe_step,
146
+ cfg_strength=cfg_strength,
147
+ sway_sampling_coef=sway_sampling_coef,
148
+ )
149
+
150
+ generated = generated[:, ref_audio_len:, :]
151
+ generated_mel_spec = rearrange(generated, '1 n d -> 1 d n')
152
+ gr.Info("Running vocoder")
153
+ vocos = Vocos.from_pretrained("charactr/vocos-mel-24khz")
154
+ generated_wave = vocos.decode(generated_mel_spec.cpu())
155
+ if rms < target_rms:
156
+ generated_wave = generated_wave * rms / target_rms
157
+
158
+ # wav -> numpy
159
+ generated_wave = generated_wave.squeeze().cpu().numpy()
160
+
161
+ if remove_silence:
162
+ gr.Info("Removing audio silences... This may take a moment")
163
+ non_silent_intervals = librosa.effects.split(generated_wave, top_db=30)
164
+ non_silent_wave = np.array([])
165
+ for interval in non_silent_intervals:
166
+ start, end = interval
167
+ non_silent_wave = np.concatenate([non_silent_wave, generated_wave[start:end]])
168
+ generated_wave = non_silent_wave
169
+
170
+
171
+ # spectogram
172
+ with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp_spectrogram:
173
+ spectrogram_path = tmp_spectrogram.name
174
+ save_spectrogram(generated_mel_spec[0].cpu().numpy(), spectrogram_path)
175
+
176
+ return (target_sample_rate, generated_wave), spectrogram_path
177
+
178
+ with gr.Blocks() as app:
179
+ gr.Markdown("""
180
+ # E2/F5 TTS
181
+
182
+ This is an unofficial E2/F5 TTS demo. This demo supports the following TTS models:
183
+
184
+ * [E2-TTS](https://arxiv.org/abs/2406.18009) (Embarrassingly Easy Fully Non-Autoregressive Zero-Shot TTS)
185
+ * [F5-TTS](https://arxiv.org/abs/2410.06885) (A Fairytaler that Fakes Fluent and Faithful Speech with Flow Matching)
186
+
187
+ This demo is based on the [F5-TTS](https://github.com/SWivid/F5-TTS) codebase, which is based on an [unofficial E2-TTS implementation](https://github.com/lucidrains/e2-tts-pytorch).
188
+
189
+ The checkpoints support English and Chinese.
190
+
191
+ If you're having issues, try converting your reference audio to WAV or MP3, clipping it to 15s, and shortening your prompt. If you're still running into issues, please open a [community Discussion](https://huggingface.co/spaces/mrfakename/E2-F5-TTS/discussions).
192
+
193
+ **NOTE: Reference text will be automatically transcribed with Whisper if not provided. For best results, keep your reference clips short (<15s). Ensure the audio is fully uploaded before generating.**
194
+ """)
195
+
196
+ ref_audio_input = gr.Audio(label="Reference Audio", type="filepath")
197
+ gen_text_input = gr.Textbox(label="Text to Generate (max 200 chars.)", lines=4)
198
+ model_choice = gr.Radio(choices=["F5-TTS", "E2-TTS"], label="Choose TTS Model", value="F5-TTS")
199
+ generate_btn = gr.Button("Synthesize", variant="primary")
200
+ with gr.Accordion("Advanced Settings", open=False):
201
+ ref_text_input = gr.Textbox(label="Reference Text", info="Leave blank to automatically transcribe the reference audio. If you enter text it will override automatic transcription.", lines=2)
202
+ remove_silence = gr.Checkbox(label="Remove Silences", info="The model tends to produce silences, especially on longer audio. We can manually remove silences if needed. Note that this is an experimental feature and may produce strange results. This will also increase generation time.", value=True)
203
+
204
+ audio_output = gr.Audio(label="Synthesized Audio")
205
+ spectrogram_output = gr.Image(label="Spectrogram")
206
+
207
+ generate_btn.click(infer, inputs=[ref_audio_input, ref_text_input, gen_text_input, model_choice, remove_silence], outputs=[audio_output, spectrogram_output])
208
+ gr.Markdown("Unofficial demo by [mrfakename](https://x.com/realmrfakename)")
209
+
210
+
211
+ app.queue().launch()