rahul7star commited on
Commit
1c7fd10
·
verified ·
1 Parent(s): 9a49fe3

app imp v 2

Browse files
Files changed (1) hide show
  1. app_quant.py +157 -326
app_quant.py CHANGED
@@ -1,376 +1,207 @@
1
- # app.py
2
- """
3
- Optimized Maya + LoRA + SNAC inference app
4
- Loads model + LoRA + SNAC at startup, vectorized SNAC unpacking,
5
- torch.compile for speed, and Gradio UI with presets & emotions.
6
- """
7
-
8
- import os
9
- import time
10
- import traceback
11
- from pathlib import Path
12
-
13
  import gradio as gr
14
- import numpy as np
15
- import soundfile as sf
16
  import torch
 
 
 
 
17
 
18
  from transformers import AutoTokenizer, AutoModelForCausalLM
19
- from peft import PeftModel, LoraConfig
20
  from snac import SNAC
21
 
22
- # -------------------------
23
- # Config - update if needed
24
- # -------------------------
 
25
  MODEL_NAME = "rahul7star/nava1.0"
26
  LORA_NAME = "rahul7star/nava-audio"
27
- SNAC_MODEL_NAME = "hubertsiuzdak/snac_24khz" # or your snac model name
28
  TARGET_SR = 24000
 
29
  OUT_ROOT = Path("/tmp/data")
30
  OUT_ROOT.mkdir(exist_ok=True, parents=True)
31
 
32
- # default text
33
- DEFAULT_TEXT = ("राजनीतिज्ञों ने कहा कि उन्होंने निर्णायक मत को अनावश्यक रूप से "
34
- "निर्धारित करने के लिए अफ़गान संविधान में काफी अस्पष्टता पाई थी")
35
-
36
- # Preset characters
37
- PRESET_CHARACTERS = {
38
- "Male American": {
39
- "description": "Realistic male voice in the 20s age with an american accent. High pitch, raspy timbre, brisk pacing, neutral tone delivery at medium intensity, viral_content domain, short_form_narrator role, neutral delivery",
40
- "example_text": DEFAULT_TEXT
41
- },
42
- "Female British": {
43
- "description": "Realistic female voice in the 30s age with a british accent. Normal pitch, throaty timbre, conversational pacing, sarcastic tone delivery at low intensity, podcast domain, interviewer role, formal delivery",
44
- "example_text": DEFAULT_TEXT
45
- },
46
- "Robot": {
47
- "description": "Creative, ai_machine_voice character. Male voice in their 30s with an american accent. High pitch, robotic timbre, slow pacing, sad tone at medium intensity.",
48
- "example_text": DEFAULT_TEXT
49
- },
50
- "Singer": {
51
- "description": "Creative, animated_cartoon character. Male voice in their 30s with an american accent. High pitch, deep timbre, slow pacing, sarcastic tone at medium intensity.",
52
- "example_text": DEFAULT_TEXT
53
- },
54
- "Custom (use LoRA)": {
55
- "description": "Use your trained LoRA voice. Edit description or use preset emotions.",
56
- "example_text": DEFAULT_TEXT
57
- },
58
- }
59
-
60
- EMOTION_TAGS = [
61
- "<neutral>", "<angry>", "<chuckle>", "<cry>", "<disappointed>", "<excited>",
62
- "<gasp>", "<giggle>", "<laugh>", "<laugh_harder>", "<sarcastic>", "<sigh>",
63
- "<sing>", "<whisper>"
64
- ]
65
-
66
- # Generation sequence length config
67
- SEQ_LEN_CPU = 4096
68
- SEQ_LEN_GPU = 240000
69
- MAX_NEW_TOKENS_CPU = 1024
70
- MAX_NEW_TOKENS_GPU = 240000
71
-
72
- # -------------------------
73
- # Detect device & bitsandbytes
74
- # -------------------------
75
  HAS_CUDA = torch.cuda.is_available()
76
  DEVICE = "cuda" if HAS_CUDA else "cpu"
77
 
78
- bnb_available = False
79
- if HAS_CUDA:
80
- try:
81
- from transformers import BitsAndBytesConfig
82
- bnb_available = True
83
- except Exception:
84
- bnb_available = False
85
 
86
- print(f"[init] Device: {DEVICE} | CUDA: {HAS_CUDA} | bnb: {bnb_available}")
87
 
88
- # -------------------------
89
- # Load tokenizer
90
- # -------------------------
91
- print("[init] Loading tokenizer...")
 
 
 
92
  tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME, trust_remote_code=True)
93
- # safe tokenizer tweaks
94
- tokenizer.model_max_length = SEQ_LEN_GPU if HAS_CUDA else SEQ_LEN_CPU
95
- tokenizer.padding_side = "left"
96
-
97
- # Cache the special tokens strings once
98
- SOH_TOK = tokenizer.decode([128259])
99
- EOH_TOK = tokenizer.decode([128260])
100
- SOA_TOK = tokenizer.decode([128261])
101
- SOS_TOK = tokenizer.decode([128257])
102
- EOT_TOK = tokenizer.decode([128009])
103
- BOS_TOK = tokenizer.bos_token
104
-
105
- # -------------------------
106
- # Load base model + LoRA once (optimized)
107
- # -------------------------
108
- print("[init] Loading base model and attaching LoRA... this may take some time")
109
- model = None
110
- try:
111
- if HAS_CUDA and bnb_available:
112
- # GPU + bnb (4-bit) path
113
- quant_config = BitsAndBytesConfig(
114
- load_in_4bit=True,
115
- bnb_4bit_quant_type="nf4",
116
- bnb_4bit_use_double_quant=True,
117
- bnb_4bit_compute_dtype=torch.bfloat16
118
- )
119
- base_model = AutoModelForCausalLM.from_pretrained(
120
- MODEL_NAME,
121
- quantization_config=quant_config,
122
- device_map="auto",
123
- trust_remote_code=True,
124
- )
125
- # attach LoRA
126
- model = PeftModel.from_pretrained(base_model, LORA_NAME, device_map="auto")
127
- SEQ_LEN = SEQ_LEN_GPU
128
- MAX_NEW_TOKENS = MAX_NEW_TOKENS_GPU
129
- print("[init] Base+LoRA loaded on GPU (4-bit).")
130
- else:
131
- # CPU (or GPU without bnb): load base model with low_cpu_mem_usage then attach PEFT
132
- base_model = AutoModelForCausalLM.from_pretrained(
133
- MODEL_NAME,
134
- torch_dtype=torch.float32,
135
- device_map={"": "cpu"},
136
- low_cpu_mem_usage=True,
137
- trust_remote_code=True,
138
- )
139
- model = PeftModel.from_pretrained(base_model, LORA_NAME, device_map={"": "cpu"})
140
- SEQ_LEN = SEQ_LEN_CPU
141
- MAX_NEW_TOKENS = MAX_NEW_TOKENS_CPU
142
- print("[init] Base+LoRA loaded on CPU (FP32).")
143
- except Exception as e:
144
- print("[init] Error loading model:", e)
145
- traceback.print_exc()
146
- raise
147
-
148
- # Speed/quality configs
149
- try:
150
- # prefer use_cache and disable extra outputs
151
- model.config.use_cache = True
152
- model.config.output_attentions = False
153
- model.config.output_hidden_states = False
154
- # torch.compile if available (PyTorch >= 2.0)
155
- try:
156
- print("[init] Trying torch.compile for model (may speed up inference)...")
157
- # choose a safe compile mode
158
- if DEVICE == "cuda":
159
- model = torch.compile(model)
160
- else:
161
- # CPU safe mode: reduce overhead
162
- model = torch.compile(model, mode="reduce-overhead", fullgraph=False)
163
- print("[init] torch.compile applied (if supported).")
164
- except Exception as e:
165
- print("[init] torch.compile not applied:", e)
166
- except Exception:
167
- pass
168
 
169
- # If GPU, set half precision where possible
170
- if DEVICE == "cuda":
171
- try:
172
- model.half()
173
- print("[init] model.half() applied for GPU.")
174
- except Exception:
175
- pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
176
 
177
  model.eval()
 
 
 
178
 
179
- # -------------------------
180
- # Load SNAC Model (once)
181
- # -------------------------
182
- print("[init] Loading SNAC decoder...")
 
183
  snac_model = SNAC.from_pretrained(SNAC_MODEL_NAME).eval().to(DEVICE)
184
- if DEVICE == "cuda":
185
- try:
186
- snac_model.half()
187
- except Exception:
188
- pass
189
- print("[init] SNAC loaded.")
190
-
191
- # -------------------------
192
- # Utility: Vectorized SNAC unpacking
193
- # -------------------------
194
- def snac_tokens_to_levels(snac_tokens):
195
- """
196
- snac_tokens: list[int] (already filtered to SNAC-range and multiples of 7)
197
- returns tuple(torch.Tensor l1, l2, l3) each on DEVICE
198
- """
199
- if len(snac_tokens) == 0:
200
- return None, None, None
201
-
202
- # ensure length multiple of 7
203
- frames = len(snac_tokens) // 7
204
- total = frames * 7
205
- arr = torch.tensor(snac_tokens[:total], dtype=torch.long, device=DEVICE)
206
- frames_tensor = arr.view(frames, 7)
207
-
208
- snac_min = 128266
209
- # l1: (frames,)
210
- l1 = ((frames_tensor[:, 0] - snac_min) % 4096).unsqueeze(0)
211
- # l2: interleave frames[:,1] and frames[:,4]
212
- l2_col1 = ((frames_tensor[:, 1] - snac_min) % 4096)
213
- l2_col2 = ((frames_tensor[:, 4] - snac_min) % 4096)
214
- l2 = torch.stack([l2_col1, l2_col2], dim=1).reshape(1, -1)
215
- # l3: frames[:,2], frames[:,3], frames[:,5], frames[:,6]
216
- l3_cols = torch.stack([
217
- (frames_tensor[:, 2] - snac_min) % 4096,
218
- (frames_tensor[:, 3] - snac_min) % 4096,
219
- (frames_tensor[:, 5] - snac_min) % 4096,
220
- (frames_tensor[:, 6] - snac_min) % 4096,
221
- ], dim=1)
222
- l3 = l3_cols.reshape(1, -1)
223
-
224
- return l1, l2, l3
225
-
226
- # -------------------------
227
- # Inference function (single unified, uses loaded model + snac_model)
228
- # -------------------------
229
- def generate_audio_with_lora(text: str,
230
- description: str = "",
231
- emotion_tag: str = "<neutral>",
232
- max_new_tokens_override: int = None):
233
- """
234
- Build prompt using description+emotion (if provided), run model.generate,
235
- extract SNAC tokens, decode via snac_model -> return filepath + logs
236
- """
237
  logs = []
238
  t0 = time.time()
239
  try:
240
- # build prompt: keep consistent with Maya prompt format
241
- if description:
242
- prompt_text = f'<description="{description}"> {text}'
243
- else:
244
- prompt_text = text
245
-
246
- # prepend special tokens (cached)
247
- prompt = SOH_TOK + BOS_TOK + prompt_text + EOT_TOK + EOH_TOK + SOA_TOK + SOS_TOK
248
-
249
- logs.append(f"[INFO] DEVICE={DEVICE} | prompt_len={len(prompt)}")
250
 
251
- # Tokenize
252
- inputs = tokenizer(prompt, return_tensors="pt", padding=True).to(DEVICE)
253
 
254
- # choose max_new
255
- max_new = MAX_NEW_TOKENS
256
- if max_new_tokens_override:
257
- max_new = min(max_new, int(max_new_tokens_override))
258
- if DEVICE == "cpu":
259
- max_new = min(max_new, MAX_NEW_TOKENS_CPU)
260
 
261
- # Generate
262
  with torch.inference_mode():
263
- outputs = model.generate(
264
  **inputs,
265
- max_new_tokens=max_new,
266
- temperature=0.4,
 
267
  top_p=0.9,
268
  repetition_penalty=1.1,
269
- do_sample=True,
270
- eos_token_id=128258,
271
  pad_token_id=tokenizer.pad_token_id,
 
272
  )
273
 
274
- gen_ids = outputs[0, inputs["input_ids"].shape[1]:].tolist()
275
- logs.append(f"[INFO] Generated {len(gen_ids)} tokens")
276
 
277
- # filter SNAC tokens
278
- snac_min, snac_max = 128266, 156937
279
- eos_id = 128258
280
- eos_idx = gen_ids.index(eos_id) if eos_id in gen_ids else len(gen_ids)
281
- snac_tokens = [t for t in gen_ids[:eos_idx] if snac_min <= t <= snac_max]
282
 
283
- # make frames multiple of 7
 
 
 
 
284
  frames = len(snac_tokens) // 7
285
- if frames == 0:
286
- logs.append("[WARN] No SNAC frames found in generated tokens.")
287
- return None, None, "\n".join(logs)
288
 
289
- l1, l2, l3 = snac_tokens_to_levels(snac_tokens)
290
- if l1 is None:
291
- logs.append("[ERROR] SNAC conversion failed.")
292
  return None, None, "\n".join(logs)
293
 
294
- # decode via SNAC (keep on DEVICE)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
295
  with torch.inference_mode():
296
- z_q = snac_model.quantizer.from_codes([l1.to(DEVICE), l2.to(DEVICE), l3.to(DEVICE)])
297
- audio_tensor = snac_model.decoder(z_q)[0, 0]
298
- # ensure float32 on CPU before saving
299
- audio = audio_tensor.cpu().float().numpy()
 
300
 
301
- # trim warmup samples
302
- if len(audio) > 2048:
303
- audio = audio[2048:]
304
 
305
- out_path = OUT_ROOT / "tts_output_lora.wav"
306
- sf.write(str(out_path), audio, TARGET_SR)
307
- logs.append(f"[OK] Audio saved: {out_path} (duration {len(audio)/TARGET_SR:.2f}s)")
308
 
309
- logs.append(f"[TIME] Elapsed: {time.time()-t0:.2f}s")
310
- return str(out_path), str(out_path), "\n".join(logs)
311
 
312
  except Exception as e:
313
- tb = traceback.format_exc()
314
- logs.append(f"[ERROR] {e}\n{tb}")
315
  return None, None, "\n".join(logs)
316
 
317
- # -------------------------
318
- # Small wrapper to provide default description/emotion insertion
319
- # -------------------------
320
- def generate_for_ui(text: str, preset: str, description: str, emotion: str):
321
- # choose description: preset overrides empty
322
- if preset and preset in PRESET_CHARACTERS:
323
- # if user selected "Custom (use LoRA)" keep user-provided description
324
- if preset != "Custom (use LoRA)":
325
- desc = PRESET_CHARACTERS[preset]["description"]
326
- else:
327
- desc = description or PRESET_CHARACTERS[preset]["description"]
328
- else:
329
- desc = description
330
-
331
- # include emotion tag appended to description to make model aware
332
- combined_desc = f"{desc} Emotion: {emotion}"
333
- audio_fp, dl_fp, logs = generate_audio_with_lora(text, description=combined_desc, emotion_tag=emotion)
334
- return audio_fp, dl_fp, logs
335
-
336
- # -------------------------
337
- # Gradio UI
338
- # -------------------------
339
- with gr.Blocks(title="NAVA — Maya1 + LoRA + SNAC (Optimized)", css=".gradio-container {max-width: 1400px}") as demo:
340
- gr.Markdown("# 🪶 NAVA — Maya1 + LoRA + SNAC (Optimized)\nGenerate emotional Hindi speech using Maya1 base + your LoRA adapter.")
341
- with gr.Row():
342
- with gr.Column(scale=3):
343
- gr.Markdown("## Inference (CPU/GPU auto)\nType text + pick a preset or write description manually.")
344
- text_in = gr.Textbox(label="Enter Hindi text", value=DEFAULT_TEXT, lines=3)
345
- preset_select = gr.Dropdown(label="Select Preset Character", choices=list(PRESET_CHARACTERS.keys()), value="Male American")
346
- description_box = gr.Textbox(label="Voice Description (editable)", value=PRESET_CHARACTERS["Male American"]["description"], lines=2)
347
- emotion_select = gr.Dropdown(label="Select Emotion", choices=EMOTION_TAGS, value="<neutral>")
348
- gen_btn = gr.Button("🔊 Generate Audio (LoRA)")
349
- gen_logs = gr.Textbox(label="Logs", lines=10)
350
- with gr.Column(scale=2):
351
- gr.Markdown("### Output")
352
- audio_player = gr.Audio(label="Generated Audio", type="filepath")
353
- download_file = gr.File(label="Download generated file")
354
- gr.Markdown("### Example")
355
- gr.Textbox(label="Example Text", value=DEFAULT_TEXT, lines=2, interactive=False)
356
- # example audio in repo: audio.wav (user can add)
357
- example_audio_path = "audio.wav"
358
- gr.Audio(label="Example Audio (project)", value=example_audio_path, type="filepath", interactive=False)
359
-
360
- # wire updates: preset -> description
361
- def _update_desc(preset_name):
362
- return PRESET_CHARACTERS.get(preset_name, {}).get("description", "")
363
- preset_select.change(fn=_update_desc, inputs=[preset_select], outputs=[description_box])
364
-
365
- # generation
366
- def _generate(text, preset, description, emotion):
367
- return generate_for_ui(text, preset, description, emotion)
368
-
369
- gen_btn.click(fn=_generate,
370
- inputs=[text_in, preset_select, description_box, emotion_select],
371
- outputs=[audio_player, download_file, gen_logs])
372
-
373
- gr.Markdown("### Notes\n- Model & LoRA are loaded once at startup.\n- If you want faster generation on GPU, enable a GPU with `bitsandbytes` installed for 4-bit mode.\n- You can edit description to steer voice (sex/age/timbre).")
374
-
375
- if __name__ == "__main__":
376
- demo.launch()
 
1
+ # app_quant_superfast.py
 
 
 
 
 
 
 
 
 
 
 
2
  import gradio as gr
 
 
3
  import torch
4
+ import soundfile as sf
5
+ from pathlib import Path
6
+ import traceback
7
+ import time
8
 
9
  from transformers import AutoTokenizer, AutoModelForCausalLM
10
+ from peft import PeftModel
11
  from snac import SNAC
12
 
13
+
14
+ # =========================================================
15
+ # CONFIG
16
+ # =========================================================
17
  MODEL_NAME = "rahul7star/nava1.0"
18
  LORA_NAME = "rahul7star/nava-audio"
19
+ SNAC_MODEL_NAME = "rahul7star/nava-snac"
20
  TARGET_SR = 24000
21
+
22
  OUT_ROOT = Path("/tmp/data")
23
  OUT_ROOT.mkdir(exist_ok=True, parents=True)
24
 
25
+ DEFAULT_TEXT = "राजनीतिज्ञों ने कहा कि उन्होंने निर्णायक मत को अनावश्यक रूप से निर्धारित करने के लिए अफ़गान संविधान में काफी अस्पष्टता पाई थी"
26
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  HAS_CUDA = torch.cuda.is_available()
28
  DEVICE = "cuda" if HAS_CUDA else "cpu"
29
 
30
+ MAX_NEW = 240000 if HAS_CUDA else 1024
 
 
 
 
 
 
31
 
 
32
 
33
+ print(f"[INIT] Running on: {DEVICE}")
34
+
35
+
36
+ # =========================================================
37
+ # LOAD TOKENIZER (light)
38
+ # =========================================================
39
+ print("[INIT] Loading tokenizer...")
40
  tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME, trust_remote_code=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
 
42
+
43
+ # =========================================================
44
+ # LOAD BASE MODEL + LORA (ONCE)
45
+ # =========================================================
46
+ print("[INIT] Loading base model...")
47
+ if HAS_CUDA:
48
+ # GPU 4-bit
49
+ from transformers import BitsAndBytesConfig
50
+ quant = BitsAndBytesConfig(
51
+ load_in_4bit=True,
52
+ bnb_4bit_compute_dtype=torch.bfloat16,
53
+ bnb_4bit_use_double_quant=True,
54
+ bnb_4bit_quant_type="nf4",
55
+ )
56
+ base_model = AutoModelForCausalLM.from_pretrained(
57
+ MODEL_NAME,
58
+ quantization_config=quant,
59
+ device_map="auto",
60
+ trust_remote_code=True,
61
+ )
62
+ else:
63
+ # CPU 8-bit (MUCH faster than fp32)
64
+ base_model = AutoModelForCausalLM.from_pretrained(
65
+ MODEL_NAME,
66
+ device_map={"": "cpu"},
67
+ trust_remote_code=True,
68
+ load_in_8bit=True,
69
+ )
70
+
71
+ print("[INIT] Attaching LoRA...")
72
+ model = PeftModel.from_pretrained(base_model, LORA_NAME, device_map={"": DEVICE})
73
+
74
+ # 🔥 Merge LoRA weights permanently = big speedup
75
+ print("[INIT] Merging LoRA -> base weights...")
76
+ model = model.merge_and_unload()
77
 
78
  model.eval()
79
+ torch.set_grad_enabled(False)
80
+
81
+ print("[INIT] Model ready.")
82
 
83
+
84
+ # =========================================================
85
+ # LOAD SNAC DECODER
86
+ # =========================================================
87
+ print("[INIT] Loading SNAC...")
88
  snac_model = SNAC.from_pretrained(SNAC_MODEL_NAME).eval().to(DEVICE)
89
+
90
+ print("[INIT COMPLETE]")
91
+
92
+
93
+ # =========================================================
94
+ # PRE-COMPUTED TOKENS (SPEED-UP)
95
+ # =========================================================
96
+ soh = tokenizer.decode([128259])
97
+ eoh = tokenizer.decode([128260])
98
+ soa = tokenizer.decode([128261])
99
+ sos = tokenizer.decode([128257])
100
+ eot = tokenizer.decode([128009])
101
+ bos = tokenizer.bos_token
102
+ snac_min, snac_max = 128266, 156937
103
+ eos_id = 128258
104
+
105
+
106
+ # =========================================================
107
+ # FAST INFERENCE
108
+ # =========================================================
109
+ def generate_audio(text):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
110
  logs = []
111
  t0 = time.time()
112
  try:
113
+ logs.append(f"[INFO] Using {DEVICE}")
 
 
 
 
 
 
 
 
 
114
 
115
+ prompt = f"{soh}{bos}{text}{eot}{eoh}{soa}{sos}"
 
116
 
117
+ inputs = tokenizer(prompt, return_tensors="pt").to(DEVICE)
 
 
 
 
 
118
 
 
119
  with torch.inference_mode():
120
+ output = model.generate(
121
  **inputs,
122
+ max_new_tokens=MAX_NEW,
123
+ do_sample=True,
124
+ temperature=0.5,
125
  top_p=0.9,
126
  repetition_penalty=1.1,
127
+ eos_token_id=eos_id,
 
128
  pad_token_id=tokenizer.pad_token_id,
129
+ use_cache=True, # 🔥 faster
130
  )
131
 
132
+ gen = output[0, inputs['input_ids'].shape[1]:].tolist()
 
133
 
134
+ logs.append(f"[INFO] Generated token count: {len(gen)}")
 
 
 
 
135
 
136
+ # strip non-SNAC
137
+ if eos_id in gen:
138
+ gen = gen[:gen.index(eos_id)]
139
+
140
+ snac_tokens = [t for t in gen if snac_min <= t <= snac_max]
141
  frames = len(snac_tokens) // 7
142
+ snac_tokens = snac_tokens[:frames * 7]
 
 
143
 
144
+ if frames == 0:
145
+ logs.append("[WARN] No SNAC frames!")
 
146
  return None, None, "\n".join(logs)
147
 
148
+ # unpack
149
+ l1 = []
150
+ l2 = []
151
+ l3 = []
152
+
153
+ for i in range(frames):
154
+ s = snac_tokens[i*7:(i+1)*7]
155
+ l1.append((s[0]-snac_min) % 4096)
156
+ l2 += [(s[1]-snac_min)%4096, (s[4]-snac_min)%4096]
157
+ l3 += [(s[2]-snac_min)%4096, (s[3]-snac_min)%4096,
158
+ (s[5]-snac_min)%4096, (s[6]-snac_min)%4096]
159
+
160
+ codes = [
161
+ torch.tensor(l1, device=DEVICE).unsqueeze(0),
162
+ torch.tensor(l2, device=DEVICE).unsqueeze(0),
163
+ torch.tensor(l3, device=DEVICE).unsqueeze(0),
164
+ ]
165
+
166
+ # decode → audio
167
  with torch.inference_mode():
168
+ zq = snac_model.quantizer.from_codes(codes)
169
+ audio = snac_model.decoder(zq)[0, 0].cpu().numpy()
170
+
171
+ # trim
172
+ audio = audio[2048:]
173
 
174
+ out = OUT_ROOT / "tts.wav"
175
+ sf.write(out, audio, TARGET_SR)
 
176
 
177
+ logs.append(f"[OK] Audio saved {out}")
178
+ logs.append(f"[TIME] {time.time() - t0:.2f}s")
 
179
 
180
+ return str(out), str(out), "\n".join(logs)
 
181
 
182
  except Exception as e:
183
+ logs.append(str(e))
184
+ logs.append(traceback.format_exc())
185
  return None, None, "\n".join(logs)
186
 
187
+
188
+ # =========================================================
189
+ # GRADIO UI
190
+ # =========================================================
191
+ with gr.Blocks() as demo:
192
+ gr.Markdown("## Super-Fast Maya TTS (LoRA Merged + Optimized)")
193
+
194
+ txt = gr.Textbox(label="Enter text", value=DEFAULT_TEXT, lines=2)
195
+ btn = gr.Button("Generate Audio ⚡")
196
+ audio = gr.Audio(label="Audio Output", type="filepath")
197
+ file = gr.File(label="Download")
198
+ logs = gr.Textbox(label="Logs", lines=8)
199
+
200
+ btn.click(generate_audio, [txt], [audio, file, logs])
201
+
202
+ # Example section
203
+ gr.Markdown("### Example")
204
+ gr.Textbox(value=DEFAULT_TEXT, label="Example Text", interactive=False)
205
+ gr.Audio(value="audio.wav", type="filepath", label="Example Audio", interactive=False)
206
+
207
+ demo.launch()