File size: 10,853 Bytes
cdb8b5c
 
 
6a0b292
cdb8b5c
 
 
 
 
 
 
 
 
 
 
 
8ab15cb
26701f5
 
480f192
8ab15cb
 
 
 
 
 
 
 
 
 
cdb8b5c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6aef93e
6a0b292
cdb8b5c
 
 
 
 
 
 
 
6aef93e
cdb8b5c
 
 
6aef93e
 
 
cdb8b5c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
668e3de
cdb8b5c
 
 
 
 
94b0409
cdb8b5c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6a0b292
cdb8b5c
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
import spaces
from snac import SNAC
import torch
import gradio as gr
from transformers import AutoModelForCausalLM, AutoTokenizer
from huggingface_hub import snapshot_download

# Check if CUDA is available
device = "cuda" if torch.cuda.is_available() else "cpu"

print("Loading SNAC model...")
snac_model = SNAC.from_pretrained("hubertsiuzdak/snac_24khz")
snac_model = snac_model.to(device)

# Available models - LFM2 models
MODELS = {
    "Jenny": "Vyvo/VyvoTTS-LFM2-350M-Jenny",
    "Optimus Prime": "Vyvo/VyvoTTS-LFM2-Optimus-Prime",
    "Itto": "Vyvo/VyvoTTS-LFM2-Itto",
    "Stephen_Fry": "Vyvo/VyvoTTS-LFM2-Stephen_Fry",
    "Alhaitham": "Vyvo/VyvoTTS-LFM2-Alhaitham",
    "Cyno": "Vyvo/VyvoTTS-LFM2-Cyno",
    "Dehya": "Vyvo/VyvoTTS-LFM2-Dehya",
    "Kaeya": "Vyvo/VyvoTTS-LFM2-Kaeya",
    "Kaveh": "Vyvo/VyvoTTS-LFM2-Kaveh",
    "Neuvillette": "Vyvo/VyvoTTS-LFM2-Neuvillette",
    "Ningguang": "Vyvo/VyvoTTS-LFM2-Ningguang",
    "Heizou": "Vyvo/VyvoTTS-LFM2-Heizou",
    "Thoma": "Vyvo/VyvoTTS-LFM2-Thoma",
    "Tighnari": "Vyvo/VyvoTTS-LFM2-Tighnari",
}

# Pre-load all models
print("Loading models...")
models = {}
tokenizers = {}

for lang, model_name in MODELS.items():
    print(f"Loading {lang} model: {model_name}")
    models[lang] = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=torch.bfloat16)
    models[lang].to(device)
    tokenizers[lang] = AutoTokenizer.from_pretrained(model_name)

print("All models loaded successfully!")

# LFM2 Special Tokens Configuration
TOKENIZER_LENGTH = 64400
START_OF_TEXT = 1
END_OF_TEXT = 7
START_OF_SPEECH = TOKENIZER_LENGTH + 1
END_OF_SPEECH = TOKENIZER_LENGTH + 2
START_OF_HUMAN = TOKENIZER_LENGTH + 3
END_OF_HUMAN = TOKENIZER_LENGTH + 4
START_OF_AI = TOKENIZER_LENGTH + 5
END_OF_AI = TOKENIZER_LENGTH + 6
PAD_TOKEN = TOKENIZER_LENGTH + 7
AUDIO_TOKENS_START = TOKENIZER_LENGTH + 10

# Process text prompt for LFM2
def process_prompt(prompt, tokenizer, device):
    input_ids = tokenizer(prompt, return_tensors="pt").input_ids
    
    start_token = torch.tensor([[START_OF_HUMAN]], dtype=torch.int64)
    end_tokens = torch.tensor([[END_OF_TEXT, END_OF_HUMAN]], dtype=torch.int64)
    
    modified_input_ids = torch.cat([start_token, input_ids, end_tokens], dim=1)
    
    # No padding needed for single input
    attention_mask = torch.ones_like(modified_input_ids)
    
    return modified_input_ids.to(device), attention_mask.to(device)

# Parse output tokens to audio for LFM2
def parse_output(generated_ids):
    token_to_find = START_OF_SPEECH
    token_to_remove = END_OF_SPEECH
    
    token_indices = (generated_ids == token_to_find).nonzero(as_tuple=True)

    if len(token_indices[1]) > 0:
        last_occurrence_idx = token_indices[1][-1].item()
        cropped_tensor = generated_ids[:, last_occurrence_idx+1:]
    else:
        cropped_tensor = generated_ids

    processed_rows = []
    for row in cropped_tensor:
        masked_row = row[row != token_to_remove]
        processed_rows.append(masked_row)

    code_lists = []
    for row in processed_rows:
        row_length = row.size(0)
        new_length = (row_length // 7) * 7
        trimmed_row = row[:new_length]
        trimmed_row = [t - AUDIO_TOKENS_START for t in trimmed_row]
        code_lists.append(trimmed_row)
        
    return code_lists[0]  # Return just the first one for single sample

# Redistribute codes for audio generation
def redistribute_codes(code_list, snac_model):
    device = next(snac_model.parameters()).device  # Get the device of SNAC model
    
    layer_1 = []
    layer_2 = []
    layer_3 = []
    for i in range((len(code_list)+1)//7):
        layer_1.append(code_list[7*i])
        layer_2.append(code_list[7*i+1]-4096)
        layer_3.append(code_list[7*i+2]-(2*4096))
        layer_3.append(code_list[7*i+3]-(3*4096))
        layer_2.append(code_list[7*i+4]-(4*4096))
        layer_3.append(code_list[7*i+5]-(5*4096))
        layer_3.append(code_list[7*i+6]-(6*4096))
        
    # Move tensors to the same device as the SNAC model
    codes = [
        torch.tensor(layer_1, device=device).unsqueeze(0),
        torch.tensor(layer_2, device=device).unsqueeze(0),
        torch.tensor(layer_3, device=device).unsqueeze(0)
    ]
    
    audio_hat = snac_model.decode(codes)
    return audio_hat.detach().squeeze().cpu().numpy()  # Always return CPU numpy array

# Main generation function
@spaces.GPU()
def generate_speech(text, model_choice, temperature, top_p, repetition_penalty, max_new_tokens, progress=gr.Progress()):
    if not text.strip():
        return None
    
    try:
        progress(0.1, "πŸ”„ Processing text...")
        model = models[model_choice]
        tokenizer = tokenizers[model_choice]
        
        # Voice parameter is always None for LFM2 models
        input_ids, attention_mask = process_prompt(text, tokenizer, device)
        
        progress(0.3, "🎡 Generating speech tokens...")
        with torch.no_grad():
            generated_ids = model.generate(
                input_ids=input_ids,
                attention_mask=attention_mask,
                max_new_tokens=max_new_tokens,
                do_sample=True,
                temperature=temperature,
                top_p=top_p,
                repetition_penalty=repetition_penalty,
                num_return_sequences=1,
                eos_token_id=END_OF_SPEECH,
            )
        
        progress(0.6, "πŸ”§ Processing speech tokens...")
        code_list = parse_output(generated_ids)
        
        progress(0.8, "🎧 Converting to audio...")
        audio_samples = redistribute_codes(code_list, snac_model)
        
        progress(1.0, "βœ… Completed!")
        return (24000, audio_samples)
    except Exception as e:
        print(f"Error generating speech: {e}")
        return None

# Example texts
EXAMPLE_TEXTS = [
    "Hello! I am a speech system. I can read your text with a natural voice.",
    "Today is a beautiful day. The weather is perfect for a walk.",
    "The sun rises from the east and sets in the west. This is a rule of nature.",
    "Technology makes our lives easier every day."
]    

# Create modern Gradio interface using built-in theme
with gr.Blocks(title="🎡 Modern Text-to-Speech", theme=gr.themes.Soft(), css="""
.gradio-textbox textarea { background-color: #6b7280 !important; color: white !important; }
.gradio-audio { background-color: #6b7280 !important; }
""") as demo:
    # Header section
    gr.Markdown("""
    # 🎡 VyvoTTS
    ### πŸ”— [Github](https://github.com/Vyvo-Labs/VyvoTTS) | πŸ€— [HF Model](https://huggingface.co/collections/Vyvo/lfm2-tts-689eedae5353ff5b048efd55)
    """)
    
    gr.Markdown("""
    VyvoTTS is a text-to-speech model by Vyvo team using LFM2 architecture, trained on multiple diverse open-source datasets. 
    Since some datasets may contain transcription errors or quality issues, output quality can vary. 
    Higher quality datasets typically produce better speech synthesis results.
    
    **Roadmap:**
    - [ ] Transformers.js support
    - [ ] Pretrained model release
    - [ ] vLLM support
    - [x] Training and inference code release
    """)
    
    with gr.Row():
        with gr.Column(scale=2):
            # Text input section
            text_input = gr.Textbox(
                label="πŸ“ Text Input",
                placeholder="Enter the text you want to convert to speech...",
                lines=6,
                max_lines=10
            )
            
            # Voice model selection (hidden since only Jenny is available)
            model_choice = gr.Radio(
                choices=list(MODELS.keys()),
                value="Jenny Voice",
                label="🎀 Voice Model",
                visible=True  # Hide since only one option
            )
            
            # Advanced settings
            with gr.Accordion("βš™οΈ Advanced Settings", open=False):
                temperature = gr.Slider(
                    minimum=0.1, maximum=1.5, value=0.6, step=0.05,
                    label="🌑️ Temperature", 
                    info="Higher values create more expressive but less stable speech"
                )
                top_p = gr.Slider(
                    minimum=0.1, maximum=1.0, value=0.95, step=0.05,
                    label="🎯 Top P", 
                    info="Nucleus sampling threshold value"
                )
                repetition_penalty = gr.Slider(
                    minimum=1.0, maximum=2.0, value=1.1, step=0.05,
                    label="πŸ”„ Repetition Penalty", 
                    info="Higher values discourage repetitive patterns"
                )
                max_new_tokens = gr.Slider(
                    minimum=100, maximum=2000, value=1200, step=100,
                    label="πŸ“ Maximum Length", 
                    info="Maximum length of generated audio (in tokens)"
                )
            
            # Action buttons
            with gr.Row():
                submit_btn = gr.Button("🎡 Generate Speech", variant="primary", size="lg")
                clear_btn = gr.Button("πŸ—‘οΈ Clear", size="lg")
        
        with gr.Column(scale=1):
            # Output section
            audio_output = gr.Audio(
                label="🎧 Generated Audio",
                type="numpy",
                interactive=False
            )
    
    # Example texts at the bottom
    with gr.Row():
        example_1_btn = gr.Button(
            EXAMPLE_TEXTS[0], 
            size="sm",
            elem_classes="example-button"
        )
        example_2_btn = gr.Button(
            EXAMPLE_TEXTS[1], 
            size="sm",
            elem_classes="example-button"
        )
    
    with gr.Row():
        example_3_btn = gr.Button(
            EXAMPLE_TEXTS[2], 
            size="sm",
            elem_classes="example-button"
        )
        example_4_btn = gr.Button(
            EXAMPLE_TEXTS[3], 
            size="sm",
            elem_classes="example-button"
        )
    
    # Set up example button events
    example_1_btn.click(fn=lambda: EXAMPLE_TEXTS[0], outputs=text_input)
    example_2_btn.click(fn=lambda: EXAMPLE_TEXTS[1], outputs=text_input)
    example_3_btn.click(fn=lambda: EXAMPLE_TEXTS[2], outputs=text_input)
    example_4_btn.click(fn=lambda: EXAMPLE_TEXTS[3], outputs=text_input)
    
    # Set up event handlers
    submit_btn.click(
        fn=generate_speech,
        inputs=[text_input, model_choice, temperature, top_p, repetition_penalty, max_new_tokens],
        outputs=audio_output,
        show_progress=True
    )
    
    def clear_interface():
        return "", None
    
    clear_btn.click(
        fn=clear_interface,
        inputs=[],
        outputs=[text_input, audio_output]
    )

# Launch the app
if __name__ == "__main__":
    demo.queue().launch(share=False, ssr_mode=False)