HiTeckGroup commited on
Commit
4d620e7
·
verified ·
1 Parent(s): 685bcdc

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +411 -0
app.py ADDED
@@ -0,0 +1,411 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Vaakya-Open TTS Demo
3
+ Text-to-Speech for Hindi & English by Voxaura Labs
4
+ """
5
+
6
+ import gradio as gr
7
+ import torch
8
+ import numpy as np
9
+ from transformers import AutoModelForCausalLM, AutoTokenizer
10
+ from snac import SNAC
11
+
12
+ # ============================================================================
13
+ # Model Configuration
14
+ # ============================================================================
15
+
16
+ MODEL_ID = "voxaura-labs/vaakya-open"
17
+ SAMPLE_RATE = 24000
18
+
19
+ # Token IDs
20
+ START_OF_SPEECH_TOKEN = 128257
21
+ END_OF_SPEECH_TOKEN = 128258
22
+ START_OF_HUMAN_TOKEN = 128259
23
+ END_OF_HUMAN_TOKEN = 128260
24
+ AUDIO_CODE_BASE_OFFSET = 128266
25
+
26
+ # ============================================================================
27
+ # Model Loading
28
+ # ============================================================================
29
+
30
+ def load_models():
31
+ """Load the TTS model and SNAC decoder."""
32
+
33
+ print("Loading Vaakya-Open model...")
34
+
35
+ # Load main model in FP16 for faster inference
36
+ model = AutoModelForCausalLM.from_pretrained(
37
+ MODEL_ID,
38
+ torch_dtype=torch.float16,
39
+ device_map="auto",
40
+ trust_remote_code=True,
41
+ )
42
+
43
+ # Load tokenizer
44
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
45
+
46
+ # Load SNAC decoder
47
+ print("Loading SNAC decoder...")
48
+ snac_model = SNAC.from_pretrained("hubertsiuzdak/snac_24khz")
49
+
50
+ if torch.cuda.is_available():
51
+ snac_model = snac_model.cuda()
52
+
53
+ snac_model.eval()
54
+
55
+ print("Models loaded successfully!")
56
+
57
+ return model, tokenizer, snac_model
58
+
59
+
60
+ # Global model instances
61
+ print("Initializing models...")
62
+ model, tokenizer, snac_model = load_models()
63
+
64
+
65
+ # ============================================================================
66
+ # Audio Generation Functions
67
+ # ============================================================================
68
+
69
+ def decode_snac_tokens(code_list: list) -> np.ndarray:
70
+ """Decode SNAC tokens to audio waveform.
71
+ This model uses a 7-token interleaved encoding per audio frame with offsets:
72
+ Token 1: offset +0 (level 0, coarse)
73
+ Token 2: offset +4096 (level 1, medium)
74
+ Token 3: offset +8192 (level 2, fine)
75
+ Token 4: offset +12288 (level 2, fine)
76
+ Token 5: offset +16384 (level 1, medium)
77
+ Token 6: offset +20480 (level 2, fine)
78
+ Token 7: offset +24576 (level 2, fine)
79
+ Args:
80
+ code_list: List of audio codes (already offset-adjusted)
81
+ Returns:
82
+ numpy array: Decoded audio waveform
83
+ """
84
+ if not code_list or len(code_list) % 7 != 0:
85
+ raise ValueError("Code list must be non-empty and divisible by 7")
86
+
87
+ # Move SNAC to CPU for decoding (important for stability)
88
+ snac_model.to("cpu")
89
+
90
+ # Redistribute codes into SNAC's 3-level hierarchy
91
+ layer_1 = [] # Coarse: 1 token per frame
92
+ layer_2 = [] # Medium: 2 tokens per frame
93
+ layer_3 = [] # Fine: 4 tokens per frame
94
+
95
+ for i in range(len(code_list) // 7):
96
+ # Extract and adjust each token based on its offset
97
+ layer_1.append(code_list[7*i])
98
+ layer_2.append(code_list[7*i + 1] - 4096)
99
+ layer_3.append(code_list[7*i + 2] - (2*4096))
100
+ layer_3.append(code_list[7*i + 3] - (3*4096))
101
+ layer_2.append(code_list[7*i + 4] - (4*4096))
102
+ layer_3.append(code_list[7*i + 5] - (5*4096))
103
+ layer_3.append(code_list[7*i + 6] - (6*4096))
104
+
105
+ # Create hierarchical code tensors for SNAC (on same device as SNAC model)
106
+ snac_device = next(snac_model.parameters()).device
107
+ codes = [
108
+ torch.tensor(layer_1, device=snac_device).unsqueeze(0),
109
+ torch.tensor(layer_2, device=snac_device).unsqueeze(0),
110
+ torch.tensor(layer_3, device=snac_device).unsqueeze(0)
111
+ ]
112
+
113
+ # Decode to audio waveform
114
+ with torch.no_grad():
115
+ audio_hat = snac_model.decode(codes)
116
+
117
+ # Convert to 16-bit PCM format for Gradio (prevents conversion warning)
118
+ audio_float = audio_hat.squeeze().clamp(-1, 1).cpu().numpy()
119
+ audio_int16 = (audio_float * 32767).astype(np.int16)
120
+
121
+ return audio_int16
122
+
123
+
124
+ def generate_speech(
125
+ text: str,
126
+ max_length: int = 768,
127
+ temperature: float = 0.4,
128
+ top_p: float = 0.95,
129
+ repetition_penalty: float = 1.2,
130
+ ) -> tuple:
131
+ """Generate speech from text with performance metrics."""
132
+ import time
133
+
134
+ if not text or not text.strip():
135
+ raise gr.Error("Please enter some text to synthesize.")
136
+
137
+ text = text.strip()
138
+
139
+ # Start timing
140
+ start_time = time.time()
141
+
142
+ # Move SNAC to CPU for decoding (important for stability)
143
+ snac_model.to("cpu")
144
+
145
+ # Tokenize text (automatically adds BOS token)
146
+ input_ids = tokenizer(text, return_tensors="pt").input_ids
147
+
148
+ start_token = torch.tensor([[START_OF_HUMAN_TOKEN]], dtype=torch.int64)
149
+ end_tokens = torch.tensor([[128009, END_OF_HUMAN_TOKEN]], dtype=torch.int64)
150
+
151
+ input_sequence = torch.cat([start_token, input_ids, end_tokens], dim=1)
152
+ input_sequence = input_sequence.to(model.device)
153
+
154
+ # Generate audio tokens
155
+ with torch.no_grad():
156
+ generated_ids = model.generate(
157
+ input_ids=input_sequence,
158
+ max_new_tokens=max_length,
159
+ do_sample=True,
160
+ temperature=temperature,
161
+ top_p=top_p,
162
+ repetition_penalty=repetition_penalty,
163
+ num_return_sequences=1,
164
+ eos_token_id=END_OF_SPEECH_TOKEN,
165
+ use_cache=True,
166
+ pad_token_id=tokenizer.pad_token_id,
167
+ )
168
+
169
+ # Extract generated tokens
170
+ gen_tokens = generated_ids[0]
171
+
172
+ # Find the last occurrence of START_OF_SPEECH token
173
+ sos_indices = (gen_tokens == START_OF_SPEECH_TOKEN).nonzero(as_tuple=True)[0]
174
+
175
+ if len(sos_indices) > 0:
176
+ # Start from after the last START_OF_SPEECH token
177
+ start_idx = sos_indices[-1].item() + 1
178
+ cropped_tokens = gen_tokens[start_idx:]
179
+ else:
180
+ cropped_tokens = gen_tokens
181
+
182
+ # Remove END_OF_SPEECH tokens
183
+ audio_tokens = cropped_tokens[cropped_tokens != END_OF_SPEECH_TOKEN]
184
+
185
+ # Truncate to make divisible by 7
186
+ num_tokens = len(audio_tokens)
187
+ num_frames = num_tokens // 7
188
+ audio_tokens = audio_tokens[:num_frames * 7]
189
+
190
+ if len(audio_tokens) == 0:
191
+ raise gr.Error("No audio tokens generated. Please try again with different text.")
192
+
193
+ # Convert to list and subtract offset
194
+ code_list = [t.item() - AUDIO_CODE_BASE_OFFSET for t in audio_tokens]
195
+
196
+ # Decode to audio
197
+ try:
198
+ audio = decode_snac_tokens(code_list)
199
+ except Exception as e:
200
+ raise gr.Error(f"Failed to decode audio: {str(e)}")
201
+
202
+ if audio is None or len(audio) == 0:
203
+ raise gr.Error("Failed to generate audio. Please try again.")
204
+
205
+ # Calculate RTF (Real-Time Factor)
206
+ generation_time = time.time() - start_time
207
+ audio_duration = len(audio) / SAMPLE_RATE
208
+ rtf = generation_time / audio_duration if audio_duration > 0 else 0
209
+ speed_text = f"{1/rtf:.1f}x faster" if rtf < 1 else f"{rtf:.1f}x slower"
210
+
211
+ # Format RTF info as 2x2 table
212
+ rtf_info = f"""
213
+ | **Generation Time** | {generation_time:.2f}s | **Audio Duration** | {audio_duration:.2f}s |
214
+ |---------------------|------------------------|--------------------|-----------------------|
215
+ | **Real-Time Factor** | {rtf:.3f}x | **Speed** | {speed_text} than real-time |
216
+ """
217
+
218
+ return (SAMPLE_RATE, audio), rtf_info
219
+
220
+
221
+ # ============================================================================
222
+ # Gradio Interface
223
+ # ============================================================================
224
+
225
+ EXAMPLES = [
226
+ ["Hello, I am your shopping assistant. How can I help you today"],
227
+ ["आज का मौसम बहुत अच्छा है। Let's go for a walk !"],
228
+ ["Welcome to Voxygen AI"],
229
+ ["मुझे आपकी मदद करने में खुशी होगी"],
230
+ ["The weather is beautiful today. चलो बाहर चलते हैं !"],
231
+ ["Thank you for using our service. हम आपकी सेवा में हमेशा तत्पर हैं"],
232
+ ["यह एक बहुत ही रोचक परियोजना है"],
233
+ ["Hello ! This is a test of the text-to-speech system with mixed languages. आप कैसे हैं ?"],
234
+ ["भारत एक विविधताओं से भरा देश है जहाँ अनेक भाषाएँ बोली जाती हैं। India is a land of diversity where many languages are spoken."],
235
+ ]
236
+
237
+ # CSS for styling
238
+ CSS = """
239
+ .gradio-container {
240
+ max-width: 1100px !important;
241
+ margin: auto !important;
242
+ font-size: 16px !important;
243
+ }
244
+ .title-text {
245
+ text-align: center;
246
+ margin-bottom: 0.5em;
247
+ font-size: 2.5em;
248
+ }
249
+ .title-text::first-letter {
250
+ font-size: 1.2em !important;
251
+ }
252
+ .subtitle-text {
253
+ text-align: center;
254
+ color: #666;
255
+ margin-bottom: 1.5em;
256
+ font-size: 1.15em;
257
+ }
258
+ /* Text input styling */
259
+ .gr-textbox textarea {
260
+ font-size: 15px !important;
261
+ line-height: 1.6 !important;
262
+ }
263
+ /* Button styling */
264
+ .gr-button {
265
+ font-size: 16px !important;
266
+ padding: 12px 24px !important;
267
+ font-weight: 500 !important;
268
+ }
269
+ /* Make emoji in buttons bigger */
270
+ .gr-button::first-letter {
271
+ font-size: 1.3em !important;
272
+ }
273
+ /* Labels */
274
+ label {
275
+ font-size: 15px !important;
276
+ font-weight: 500 !important;
277
+ margin-bottom: 8px !important;
278
+ }
279
+ /* Make emoji in labels bigger */
280
+ label::first-letter {
281
+ font-size: 1.3em !important;
282
+ }
283
+ /* Audio player */
284
+ .gr-audio {
285
+ margin-top: 8px !important;
286
+ }
287
+ /* Accordion */
288
+ .gr-accordion {
289
+ margin-top: 20px !important;
290
+ }
291
+ /* Markdown performance display */
292
+ .gr-markdown {
293
+ font-size: 14px !important;
294
+ line-height: 1.8 !important;
295
+ }
296
+ /* Examples section */
297
+ .gr-examples {
298
+ margin-top: 20px !important;
299
+ }
300
+ footer {
301
+ text-align: center;
302
+ margin-top: 2em;
303
+ color: #888;
304
+ font-size: 14px;
305
+ }
306
+ """
307
+
308
+ with gr.Blocks(css=CSS, title="Vaakya-Open TTS") as demo:
309
+ gr.HTML("""
310
+ <div style="text-align: center; padding: 20px 0;">
311
+ <h1 class="title-text" style="margin-bottom: 10px;">🎙️ Vaakya-Open</h1>
312
+ <p class="subtitle-text" style="margin-bottom: 0;">
313
+ High-quality Text-to-Speech for Hindi & English<br>
314
+ by <a href="https://www.voxygen.ai" target="_blank" style="color: #4A90E2; text-decoration: none; font-weight: 600;">Voxygen AI</a>
315
+ </p>
316
+ </div>
317
+ """)
318
+
319
+ with gr.Row():
320
+ with gr.Column(scale=1):
321
+ text_input = gr.Textbox(
322
+ label="📝 Enter Text",
323
+ value="The weather is beautiful today. चलो बाहर चलते हैं !",
324
+ placeholder="Type your text here in English, Hindi, or mix both...",
325
+ lines=5,
326
+ max_lines=12,
327
+ )
328
+ generate_btn = gr.Button("🔊 Generate Speech", variant="primary", size="lg")
329
+
330
+ with gr.Column(scale=1):
331
+ audio_output = gr.Audio(
332
+ label="🎧 Generated Speech",
333
+ type="numpy",
334
+ interactive=False,
335
+ autoplay=True,
336
+ )
337
+ rtf_display = gr.Markdown(
338
+ value="*Performance metrics will appear here after generation*",
339
+ label="⚡ Performance"
340
+ )
341
+
342
+ with gr.Accordion("⚙️ Advanced Settings", open=False):
343
+ gr.Markdown("*Fine-tune generation parameters for optimal results*")
344
+ with gr.Row():
345
+ max_length = gr.Dropdown(
346
+ choices=[256, 384, 512, 768, 1024, 1280, 1536, 1792, 2048],
347
+ value=768,
348
+ label="🎯 Max Length",
349
+ info="Maximum number of tokens to generate (higher = longer audio)"
350
+ )
351
+ temperature = gr.Slider(
352
+ minimum=0.1,
353
+ maximum=1.0,
354
+ value=0.4,
355
+ step=0.05,
356
+ label="🌡️ Temperature",
357
+ info="Higher = more expressive, Lower = more consistent"
358
+ )
359
+ with gr.Row():
360
+ top_p = gr.Slider(
361
+ minimum=0.5,
362
+ maximum=1.0,
363
+ value=0.95,
364
+ step=0.05,
365
+ label="🎲 Top-P",
366
+ info="Nucleus sampling parameter"
367
+ )
368
+ repetition_penalty = gr.Slider(
369
+ minimum=1.0,
370
+ maximum=1.8,
371
+ value=1.4,
372
+ step=0.05,
373
+ label="🔁 Repetition Penalty",
374
+ info="Penalize repeated tokens"
375
+ )
376
+
377
+ gr.Examples(
378
+ examples=EXAMPLES,
379
+ inputs=[text_input],
380
+ label="📝 Example Texts (click to try)",
381
+ )
382
+
383
+ generate_btn.click(
384
+ fn=generate_speech,
385
+ inputs=[text_input, max_length, temperature, top_p, repetition_penalty],
386
+ outputs=[audio_output, rtf_display],
387
+ )
388
+
389
+ text_input.submit(
390
+ fn=generate_speech,
391
+ inputs=[text_input, max_length, temperature, top_p, repetition_penalty],
392
+ outputs=[audio_output, rtf_display],
393
+ )
394
+
395
+ gr.HTML("""
396
+ <footer>
397
+ <p>
398
+ Model: <a href="https://huggingface.co/voxaura-labs/vaakya-open" target="_blank">voxaura-labs/vaakya-open</a>
399
+ · Built on <a href="https://github.com/canopyai/Orpheus-TTS" target="_blank">Orpheus TTS</a> architecture
400
+ · Made in India 🇮🇳
401
+ </p>
402
+ </footer>
403
+ """)
404
+
405
+
406
+ # ============================================================================
407
+ # Launch
408
+ # ============================================================================
409
+
410
+ if __name__ == "__main__":
411
+ demo.launch()