HiTeckGroup commited on
Commit
c1ebe27
·
verified ·
1 Parent(s): 03be912

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +23 -72
app.py CHANGED
@@ -1,6 +1,7 @@
1
  """
2
  Vaakya-Open TTS Demo
3
  Text-to-Speech for Hindi & English by Voxaura Labs
 
4
  """
5
 
6
  import gradio as gr
@@ -32,18 +33,23 @@ def load_models():
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
 
@@ -67,33 +73,17 @@ model, tokenizer, snac_model = load_models()
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))
@@ -102,7 +92,6 @@ def decode_snac_tokens(code_list: list) -> np.ndarray:
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),
@@ -110,11 +99,9 @@ def decode_snac_tokens(code_list: list) -> np.ndarray:
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
 
@@ -127,7 +114,7 @@ def generate_speech(
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
 
@@ -135,14 +122,10 @@ def generate_speech(
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)
@@ -151,7 +134,6 @@ def generate_speech(
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,
@@ -166,34 +148,27 @@ def generate_speech(
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:
@@ -202,19 +177,18 @@ def generate_speech(
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
 
@@ -234,7 +208,6 @@ EXAMPLES = [
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;
@@ -246,54 +219,36 @@ CSS = """
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
  }
@@ -305,7 +260,7 @@ footer {
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>
@@ -404,15 +359,11 @@ with gr.Blocks(css=CSS, title="Vaakya-Open TTS") as demo:
404
 
405
 
406
  # ============================================================================
407
- # Launch
408
  # ============================================================================
409
 
410
- # Pehle:
411
- if __name__ == "__main__":
412
- demo.launch()
413
-
414
- # Ab ye karo:
415
- app = demo # HF Space ko 'app' chahiye
416
 
417
  if __name__ == "__main__":
418
- demo.launch()
 
1
  """
2
  Vaakya-Open TTS Demo
3
  Text-to-Speech for Hindi & English by Voxaura Labs
4
+ Fixed for Hugging Face Spaces (Gradio 6.0)
5
  """
6
 
7
  import gradio as gr
 
33
 
34
  print("Loading Vaakya-Open model...")
35
 
36
+ # Determine dtype based on device
37
+ if torch.cuda.is_available():
38
+ dtype = torch.float16
39
+ device_map = "auto"
40
+ else:
41
+ dtype = torch.float32
42
+ device_map = "cpu"
43
+
44
  model = AutoModelForCausalLM.from_pretrained(
45
  MODEL_ID,
46
+ dtype=dtype,
47
+ device_map=device_map,
48
  trust_remote_code=True,
49
  )
50
 
 
51
  tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
52
 
 
53
  print("Loading SNAC decoder...")
54
  snac_model = SNAC.from_pretrained("hubertsiuzdak/snac_24khz")
55
 
 
73
  # ============================================================================
74
 
75
  def decode_snac_tokens(code_list: list) -> np.ndarray:
76
+ """Decode SNAC tokens to audio waveform."""
 
 
 
 
 
 
 
 
 
 
 
 
 
77
  if not code_list or len(code_list) % 7 != 0:
78
  raise ValueError("Code list must be non-empty and divisible by 7")
79
 
 
80
  snac_model.to("cpu")
81
 
82
+ layer_1 = []
83
+ layer_2 = []
84
+ layer_3 = []
 
85
 
86
  for i in range(len(code_list) // 7):
 
87
  layer_1.append(code_list[7*i])
88
  layer_2.append(code_list[7*i + 1] - 4096)
89
  layer_3.append(code_list[7*i + 2] - (2*4096))
 
92
  layer_3.append(code_list[7*i + 5] - (5*4096))
93
  layer_3.append(code_list[7*i + 6] - (6*4096))
94
 
 
95
  snac_device = next(snac_model.parameters()).device
96
  codes = [
97
  torch.tensor(layer_1, device=snac_device).unsqueeze(0),
 
99
  torch.tensor(layer_3, device=snac_device).unsqueeze(0)
100
  ]
101
 
 
102
  with torch.no_grad():
103
  audio_hat = snac_model.decode(codes)
104
 
 
105
  audio_float = audio_hat.squeeze().clamp(-1, 1).cpu().numpy()
106
  audio_int16 = (audio_float * 32767).astype(np.int16)
107
 
 
114
  temperature: float = 0.4,
115
  top_p: float = 0.95,
116
  repetition_penalty: float = 1.2,
117
+ ):
118
  """Generate speech from text with performance metrics."""
119
  import time
120
 
 
122
  raise gr.Error("Please enter some text to synthesize.")
123
 
124
  text = text.strip()
 
 
125
  start_time = time.time()
126
 
 
127
  snac_model.to("cpu")
128
 
 
129
  input_ids = tokenizer(text, return_tensors="pt").input_ids
130
 
131
  start_token = torch.tensor([[START_OF_HUMAN_TOKEN]], dtype=torch.int64)
 
134
  input_sequence = torch.cat([start_token, input_ids, end_tokens], dim=1)
135
  input_sequence = input_sequence.to(model.device)
136
 
 
137
  with torch.no_grad():
138
  generated_ids = model.generate(
139
  input_ids=input_sequence,
 
148
  pad_token_id=tokenizer.pad_token_id,
149
  )
150
 
 
151
  gen_tokens = generated_ids[0]
152
 
 
153
  sos_indices = (gen_tokens == START_OF_SPEECH_TOKEN).nonzero(as_tuple=True)[0]
154
 
155
  if len(sos_indices) > 0:
 
156
  start_idx = sos_indices[-1].item() + 1
157
  cropped_tokens = gen_tokens[start_idx:]
158
  else:
159
  cropped_tokens = gen_tokens
160
 
 
161
  audio_tokens = cropped_tokens[cropped_tokens != END_OF_SPEECH_TOKEN]
162
 
 
163
  num_tokens = len(audio_tokens)
164
  num_frames = num_tokens // 7
165
  audio_tokens = audio_tokens[:num_frames * 7]
166
 
167
  if len(audio_tokens) == 0:
168
+ raise gr.Error("No audio tokens generated. Please try again.")
169
 
 
170
  code_list = [t.item() - AUDIO_CODE_BASE_OFFSET for t in audio_tokens]
171
 
 
172
  try:
173
  audio = decode_snac_tokens(code_list)
174
  except Exception as e:
 
177
  if audio is None or len(audio) == 0:
178
  raise gr.Error("Failed to generate audio. Please try again.")
179
 
 
180
  generation_time = time.time() - start_time
181
  audio_duration = len(audio) / SAMPLE_RATE
182
  rtf = generation_time / audio_duration if audio_duration > 0 else 0
183
  speed_text = f"{1/rtf:.1f}x faster" if rtf < 1 else f"{rtf:.1f}x slower"
184
 
 
185
  rtf_info = f"""
186
  | **Generation Time** | {generation_time:.2f}s | **Audio Duration** | {audio_duration:.2f}s |
187
  |---------------------|------------------------|--------------------|-----------------------|
188
  | **Real-Time Factor** | {rtf:.3f}x | **Speed** | {speed_text} than real-time |
189
  """
190
 
191
+ # FIX: Gradio 6.0 expects only audio array (sample rate is set in gr.Audio component)
192
  return (SAMPLE_RATE, audio), rtf_info
193
 
194
 
 
208
  ["भारत एक विविधताओं से भरा देश है जहाँ अनेक भाषाएँ बोली जाती हैं। India is a land of diversity where many languages are spoken."],
209
  ]
210
 
 
211
  CSS = """
212
  .gradio-container {
213
  max-width: 1100px !important;
 
219
  margin-bottom: 0.5em;
220
  font-size: 2.5em;
221
  }
 
 
 
222
  .subtitle-text {
223
  text-align: center;
224
  color: #666;
225
  margin-bottom: 1.5em;
226
  font-size: 1.15em;
227
  }
 
228
  .gr-textbox textarea {
229
  font-size: 15px !important;
230
  line-height: 1.6 !important;
231
  }
 
232
  .gr-button {
233
  font-size: 16px !important;
234
  padding: 12px 24px !important;
235
  font-weight: 500 !important;
236
  }
 
 
 
 
 
237
  label {
238
  font-size: 15px !important;
239
  font-weight: 500 !important;
240
  margin-bottom: 8px !important;
241
  }
 
 
 
 
 
242
  .gr-audio {
243
  margin-top: 8px !important;
244
  }
 
245
  .gr-accordion {
246
  margin-top: 20px !important;
247
  }
 
248
  .gr-markdown {
249
  font-size: 14px !important;
250
  line-height: 1.8 !important;
251
  }
 
252
  .gr-examples {
253
  margin-top: 20px !important;
254
  }
 
260
  }
261
  """
262
 
263
+ with gr.Blocks(title="Vaakya-Open TTS") as demo:
264
  gr.HTML("""
265
  <div style="text-align: center; padding: 20px 0;">
266
  <h1 class="title-text" style="margin-bottom: 10px;">🎙️ Vaakya-Open</h1>
 
359
 
360
 
361
  # ============================================================================
362
+ # HF Space Entry Point
363
  # ============================================================================
364
 
365
+ # HF Spaces needs a variable named 'app'
366
+ app = demo
 
 
 
 
367
 
368
  if __name__ == "__main__":
369
+ demo.launch(css=CSS)