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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
5 |
|
6 |
-
|
7 |
-
|
|
|
|
1 |
+
|
2 |
+
import spaces
|
3 |
+
from snac import SNAC
|
4 |
+
import torch
|
5 |
import gradio as gr
|
6 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
7 |
+
from huggingface_hub import snapshot_download
|
8 |
+
from dotenv import load_dotenv
|
9 |
+
load_dotenv()
|
10 |
+
|
11 |
+
# Check if CUDA is available
|
12 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
13 |
+
|
14 |
+
print("Loading SNAC model...")
|
15 |
+
snac_model = SNAC.from_pretrained("hubertsiuzdak/snac_24khz")
|
16 |
+
snac_model = snac_model.to(device)
|
17 |
+
|
18 |
+
# Available models - LFM2 models
|
19 |
+
MODELS = {
|
20 |
+
"Jenny Voice": "Vyvo/VyvoTTS-LFM2-350M-Jenny",
|
21 |
+
}
|
22 |
+
|
23 |
+
# Pre-load all models
|
24 |
+
print("Loading models...")
|
25 |
+
models = {}
|
26 |
+
tokenizers = {}
|
27 |
+
|
28 |
+
for lang, model_name in MODELS.items():
|
29 |
+
print(f"Loading {lang} model: {model_name}")
|
30 |
+
models[lang] = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=torch.bfloat16)
|
31 |
+
models[lang].to(device)
|
32 |
+
tokenizers[lang] = AutoTokenizer.from_pretrained(model_name)
|
33 |
+
|
34 |
+
print("All models loaded successfully!")
|
35 |
+
|
36 |
+
# LFM2 Special Tokens Configuration
|
37 |
+
TOKENIZER_LENGTH = 64400
|
38 |
+
START_OF_TEXT = 1
|
39 |
+
END_OF_TEXT = 7
|
40 |
+
START_OF_SPEECH = TOKENIZER_LENGTH + 1
|
41 |
+
END_OF_SPEECH = TOKENIZER_LENGTH + 2
|
42 |
+
START_OF_HUMAN = TOKENIZER_LENGTH + 3
|
43 |
+
END_OF_HUMAN = TOKENIZER_LENGTH + 4
|
44 |
+
START_OF_AI = TOKENIZER_LENGTH + 5
|
45 |
+
END_OF_AI = TOKENIZER_LENGTH + 6
|
46 |
+
PAD_TOKEN = TOKENIZER_LENGTH + 7
|
47 |
+
AUDIO_TOKENS_START = TOKENIZER_LENGTH + 10
|
48 |
+
|
49 |
+
# Process text prompt for LFM2
|
50 |
+
def process_prompt(prompt, tokenizer, device):
|
51 |
+
input_ids = tokenizer(prompt, return_tensors="pt").input_ids
|
52 |
+
|
53 |
+
start_token = torch.tensor([[START_OF_HUMAN]], dtype=torch.int64)
|
54 |
+
end_tokens = torch.tensor([[END_OF_TEXT, END_OF_HUMAN]], dtype=torch.int64)
|
55 |
+
|
56 |
+
modified_input_ids = torch.cat([start_token, input_ids, end_tokens], dim=1)
|
57 |
+
|
58 |
+
# No padding needed for single input
|
59 |
+
attention_mask = torch.ones_like(modified_input_ids)
|
60 |
+
|
61 |
+
return modified_input_ids.to(device), attention_mask.to(device)
|
62 |
+
|
63 |
+
# Parse output tokens to audio for LFM2
|
64 |
+
def parse_output(generated_ids):
|
65 |
+
token_to_find = START_OF_SPEECH
|
66 |
+
token_to_remove = END_OF_SPEECH
|
67 |
+
|
68 |
+
token_indices = (generated_ids == token_to_find).nonzero(as_tuple=True)
|
69 |
+
|
70 |
+
if len(token_indices[1]) > 0:
|
71 |
+
last_occurrence_idx = token_indices[1][-1].item()
|
72 |
+
cropped_tensor = generated_ids[:, last_occurrence_idx+1:]
|
73 |
+
else:
|
74 |
+
cropped_tensor = generated_ids
|
75 |
+
|
76 |
+
processed_rows = []
|
77 |
+
for row in cropped_tensor:
|
78 |
+
masked_row = row[row != token_to_remove]
|
79 |
+
processed_rows.append(masked_row)
|
80 |
+
|
81 |
+
code_lists = []
|
82 |
+
for row in processed_rows:
|
83 |
+
row_length = row.size(0)
|
84 |
+
new_length = (row_length // 7) * 7
|
85 |
+
trimmed_row = row[:new_length]
|
86 |
+
trimmed_row = [t - AUDIO_TOKENS_START for t in trimmed_row]
|
87 |
+
code_lists.append(trimmed_row)
|
88 |
+
|
89 |
+
return code_lists[0] # Return just the first one for single sample
|
90 |
+
|
91 |
+
# Redistribute codes for audio generation
|
92 |
+
def redistribute_codes(code_list, snac_model):
|
93 |
+
device = next(snac_model.parameters()).device # Get the device of SNAC model
|
94 |
+
|
95 |
+
layer_1 = []
|
96 |
+
layer_2 = []
|
97 |
+
layer_3 = []
|
98 |
+
for i in range((len(code_list)+1)//7):
|
99 |
+
layer_1.append(code_list[7*i])
|
100 |
+
layer_2.append(code_list[7*i+1]-4096)
|
101 |
+
layer_3.append(code_list[7*i+2]-(2*4096))
|
102 |
+
layer_3.append(code_list[7*i+3]-(3*4096))
|
103 |
+
layer_2.append(code_list[7*i+4]-(4*4096))
|
104 |
+
layer_3.append(code_list[7*i+5]-(5*4096))
|
105 |
+
layer_3.append(code_list[7*i+6]-(6*4096))
|
106 |
+
|
107 |
+
# Move tensors to the same device as the SNAC model
|
108 |
+
codes = [
|
109 |
+
torch.tensor(layer_1, device=device).unsqueeze(0),
|
110 |
+
torch.tensor(layer_2, device=device).unsqueeze(0),
|
111 |
+
torch.tensor(layer_3, device=device).unsqueeze(0)
|
112 |
+
]
|
113 |
+
|
114 |
+
audio_hat = snac_model.decode(codes)
|
115 |
+
return audio_hat.detach().squeeze().cpu().numpy() # Always return CPU numpy array
|
116 |
+
|
117 |
+
# Main generation function
|
118 |
+
@spaces.GPU()
|
119 |
+
def generate_speech(text, model_choice, temperature, top_p, repetition_penalty, max_new_tokens, progress=gr.Progress()):
|
120 |
+
if not text.strip():
|
121 |
+
return None
|
122 |
+
|
123 |
+
try:
|
124 |
+
progress(0.1, "π Processing text...")
|
125 |
+
model = models[model_choice]
|
126 |
+
tokenizer = tokenizers[model_choice]
|
127 |
+
|
128 |
+
# Voice parameter is always None for LFM2 models
|
129 |
+
input_ids, attention_mask = process_prompt(text, tokenizer, device)
|
130 |
+
|
131 |
+
progress(0.3, "π΅ Generating speech tokens...")
|
132 |
+
with torch.no_grad():
|
133 |
+
generated_ids = model.generate(
|
134 |
+
input_ids=input_ids,
|
135 |
+
attention_mask=attention_mask,
|
136 |
+
max_new_tokens=max_new_tokens,
|
137 |
+
do_sample=True,
|
138 |
+
temperature=temperature,
|
139 |
+
top_p=top_p,
|
140 |
+
repetition_penalty=repetition_penalty,
|
141 |
+
num_return_sequences=1,
|
142 |
+
eos_token_id=END_OF_SPEECH,
|
143 |
+
)
|
144 |
+
|
145 |
+
progress(0.6, "π§ Processing speech tokens...")
|
146 |
+
code_list = parse_output(generated_ids)
|
147 |
+
|
148 |
+
progress(0.8, "π§ Converting to audio...")
|
149 |
+
audio_samples = redistribute_codes(code_list, snac_model)
|
150 |
+
|
151 |
+
progress(1.0, "β
Completed!")
|
152 |
+
return (24000, audio_samples)
|
153 |
+
except Exception as e:
|
154 |
+
print(f"Error generating speech: {e}")
|
155 |
+
return None
|
156 |
+
|
157 |
+
# Example texts
|
158 |
+
EXAMPLE_TEXTS = [
|
159 |
+
"Hello! I am a speech system. I can read your text with a natural voice.",
|
160 |
+
"Today is a beautiful day. The weather is perfect for a walk.",
|
161 |
+
"The sun rises from the east and sets in the west. This is a rule of nature.",
|
162 |
+
"Technology makes our lives easier every day."
|
163 |
+
]
|
164 |
|
165 |
+
# Create modern Gradio interface using built-in theme
|
166 |
+
with gr.Blocks(title="π΅ Modern Text-to-Speech", theme=gr.themes.Soft(), css="""
|
167 |
+
.gradio-textbox textarea { background-color: #6b7280 !important; color: white !important; }
|
168 |
+
.gradio-audio { background-color: #6b7280 !important; }
|
169 |
+
""") as demo:
|
170 |
+
# Header section
|
171 |
+
gr.Markdown("""
|
172 |
+
# π΅ VyvoTTS
|
173 |
+
### π [Github](https://github.com/Vyvo-Labs/VyvoTTS) | π€ [HF Model](https://huggingface.co/Vyvo/VyvoTTS-LFM2-350M-Jenny)
|
174 |
+
""")
|
175 |
+
|
176 |
+
gr.Markdown("""
|
177 |
+
VyvoTTS is a text-to-speech model by Vyvo team using LFM2 architecture, fine-tuned on reach-vb/jenny_tts_dataset.
|
178 |
+
Better datasets can achieve higher quality results.
|
179 |
+
|
180 |
+
**Roadmap:**
|
181 |
+
- [ ] Transformers.js support
|
182 |
+
- [ ] Pretrained model release
|
183 |
+
- [ ] vLLM support
|
184 |
+
- [x] Training and inference code release
|
185 |
+
""")
|
186 |
+
|
187 |
+
with gr.Row():
|
188 |
+
with gr.Column(scale=2):
|
189 |
+
# Text input section
|
190 |
+
text_input = gr.Textbox(
|
191 |
+
label="π Text Input",
|
192 |
+
placeholder="Enter the text you want to convert to speech...",
|
193 |
+
lines=6,
|
194 |
+
max_lines=10
|
195 |
+
)
|
196 |
+
|
197 |
+
# Voice model selection (hidden since only Jenny is available)
|
198 |
+
model_choice = gr.Radio(
|
199 |
+
choices=list(MODELS.keys()),
|
200 |
+
value="Jenny Voice",
|
201 |
+
label="π€ Voice Model",
|
202 |
+
visible=False # Hide since only one option
|
203 |
+
)
|
204 |
+
|
205 |
+
# Advanced settings
|
206 |
+
with gr.Accordion("βοΈ Advanced Settings", open=False):
|
207 |
+
temperature = gr.Slider(
|
208 |
+
minimum=0.1, maximum=1.5, value=0.6, step=0.05,
|
209 |
+
label="π‘οΈ Temperature",
|
210 |
+
info="Higher values create more expressive but less stable speech"
|
211 |
+
)
|
212 |
+
top_p = gr.Slider(
|
213 |
+
minimum=0.1, maximum=1.0, value=0.95, step=0.05,
|
214 |
+
label="π― Top P",
|
215 |
+
info="Nucleus sampling threshold value"
|
216 |
+
)
|
217 |
+
repetition_penalty = gr.Slider(
|
218 |
+
minimum=1.0, maximum=2.0, value=1.1, step=0.05,
|
219 |
+
label="π Repetition Penalty",
|
220 |
+
info="Higher values discourage repetitive patterns"
|
221 |
+
)
|
222 |
+
max_new_tokens = gr.Slider(
|
223 |
+
minimum=100, maximum=2000, value=1200, step=100,
|
224 |
+
label="π Maximum Length",
|
225 |
+
info="Maximum length of generated audio (in tokens)"
|
226 |
+
)
|
227 |
+
|
228 |
+
# Action buttons
|
229 |
+
with gr.Row():
|
230 |
+
submit_btn = gr.Button("π΅ Generate Speech", variant="primary", size="lg")
|
231 |
+
clear_btn = gr.Button("ποΈ Clear", size="lg")
|
232 |
+
|
233 |
+
with gr.Column(scale=1):
|
234 |
+
# Output section
|
235 |
+
audio_output = gr.Audio(
|
236 |
+
label="π§ Generated Audio",
|
237 |
+
type="numpy",
|
238 |
+
interactive=False
|
239 |
+
)
|
240 |
+
|
241 |
+
# Example texts at the bottom
|
242 |
+
with gr.Row():
|
243 |
+
example_1_btn = gr.Button(
|
244 |
+
EXAMPLE_TEXTS[0],
|
245 |
+
size="sm",
|
246 |
+
elem_classes="example-button"
|
247 |
+
)
|
248 |
+
example_2_btn = gr.Button(
|
249 |
+
EXAMPLE_TEXTS[1],
|
250 |
+
size="sm",
|
251 |
+
elem_classes="example-button"
|
252 |
+
)
|
253 |
+
|
254 |
+
with gr.Row():
|
255 |
+
example_3_btn = gr.Button(
|
256 |
+
EXAMPLE_TEXTS[2],
|
257 |
+
size="sm",
|
258 |
+
elem_classes="example-button"
|
259 |
+
)
|
260 |
+
example_4_btn = gr.Button(
|
261 |
+
EXAMPLE_TEXTS[3],
|
262 |
+
size="sm",
|
263 |
+
elem_classes="example-button"
|
264 |
+
)
|
265 |
+
|
266 |
+
# Set up example button events
|
267 |
+
example_1_btn.click(fn=lambda: EXAMPLE_TEXTS[0], outputs=text_input)
|
268 |
+
example_2_btn.click(fn=lambda: EXAMPLE_TEXTS[1], outputs=text_input)
|
269 |
+
example_3_btn.click(fn=lambda: EXAMPLE_TEXTS[2], outputs=text_input)
|
270 |
+
example_4_btn.click(fn=lambda: EXAMPLE_TEXTS[3], outputs=text_input)
|
271 |
+
|
272 |
+
# Set up event handlers
|
273 |
+
submit_btn.click(
|
274 |
+
fn=generate_speech,
|
275 |
+
inputs=[text_input, model_choice, temperature, top_p, repetition_penalty, max_new_tokens],
|
276 |
+
outputs=audio_output,
|
277 |
+
show_progress=True
|
278 |
+
)
|
279 |
+
|
280 |
+
def clear_interface():
|
281 |
+
return "", None
|
282 |
+
|
283 |
+
clear_btn.click(
|
284 |
+
fn=clear_interface,
|
285 |
+
inputs=[],
|
286 |
+
outputs=[text_input, audio_output]
|
287 |
+
)
|
288 |
|
289 |
+
# Launch the app
|
290 |
+
if __name__ == "__main__":
|
291 |
+
demo.queue().launch(share=False, ssr_mode=False)
|
requirements.txt
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
snac
|
2 |
+
python-dotenv
|
3 |
+
transformers
|
4 |
+
torch
|
5 |
+
spaces
|
6 |
+
accelerate
|