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

Update app_quant.py

Browse files
Files changed (1) hide show
  1. app_quant.py +285 -112
app_quant.py CHANGED
@@ -1,122 +1,264 @@
1
- # app_quant_fixed.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, LoraConfig
11
  from snac import SNAC
12
 
 
 
13
  # -------------------------
14
  MODEL_NAME = "rahul7star/nava1.0"
15
  LORA_NAME = "rahul7star/nava-audio"
16
- SNAC_MODEL_NAME = "rahul7star/nava-snac"
17
-
18
  TARGET_SR = 24000
19
  OUT_ROOT = Path("/tmp/data")
20
  OUT_ROOT.mkdir(exist_ok=True, parents=True)
21
 
22
- DEFAULT_TEXT = "राजनीतिज्ञों ने कहा कि उन्होंने निर्णायक मत को अनावश्यक रूप से निर्धारित करने के लिए अफ़गान संविधान में काफी अस्पष्टता पाई थी"
23
-
24
- # conservative defaults
25
- SEQ_LEN_GPU = 240000 # if you really have GPU
26
- SEQ_LEN_CPU = 4096 # keep CPU small to avoid OOM
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  MAX_NEW_TOKENS_CPU = 1024
28
  MAX_NEW_TOKENS_GPU = 240000
29
 
30
- # detect device
 
 
31
  HAS_CUDA = torch.cuda.is_available()
32
  DEVICE = "cuda" if HAS_CUDA else "cpu"
33
 
34
- # optional: try import bitsandbytes only if CUDA available
35
- try:
36
- if HAS_CUDA:
37
  from transformers import BitsAndBytesConfig
38
  bnb_available = True
39
- else:
40
  bnb_available = False
41
- except Exception:
42
- bnb_available = False
43
 
44
- print(f"[init] CUDA available: {HAS_CUDA}, bitsandbytes available: {bnb_available}")
45
 
46
  # -------------------------
47
- # Load tokenizer (always)
48
  # -------------------------
49
  print("[init] Loading tokenizer...")
50
  tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME, trust_remote_code=True)
 
 
 
 
 
 
 
 
 
 
 
51
 
52
  # -------------------------
53
- # Load base model & LoRA (GPU vs CPU safe)
54
- # -------------------------
55
- print("[init] Loading base model + LoRA (this may take a while)...")
56
- if HAS_CUDA and bnb_available:
57
- # GPU + bnb path: use 4-bit quant
58
- quant_config = BitsAndBytesConfig(
59
- load_in_4bit=True,
60
- bnb_4bit_quant_type="nf4",
61
- bnb_4bit_use_double_quant=True,
62
- bnb_4bit_compute_dtype=torch.bfloat16
63
- )
64
- base_model = AutoModelForCausalLM.from_pretrained(
65
- MODEL_NAME,
66
- quantization_config=quant_config,
67
- device_map="auto",
68
- trust_remote_code=True,
69
- )
70
- model = PeftModel.from_pretrained(base_model, LORA_NAME, device_map="auto")
71
- SEQ_LEN = SEQ_LEN_GPU
72
- MAX_NEW_TOKENS = MAX_NEW_TOKENS_GPU
73
- print("[init] Loaded model in 4-bit (GPU).")
74
- else:
75
- # CPU fallback: load in FP32 with low_cpu_mem_usage
76
- # Avoid load_in_4bit on CPU
77
- base_model = AutoModelForCausalLM.from_pretrained(
78
- MODEL_NAME,
79
- torch_dtype=torch.float32,
80
- device_map={"": "cpu"},
81
- low_cpu_mem_usage=True,
82
- trust_remote_code=True,
83
- )
84
- # attach PEFT adapter - this will add LoRA wrappers but keep base weights on CPU
85
- model = PeftModel.from_pretrained(base_model, LORA_NAME, device_map={"": "cpu"})
86
- SEQ_LEN = SEQ_LEN_CPU
87
- MAX_NEW_TOKENS = MAX_NEW_TOKENS_CPU
88
- print("[init] Loaded model on CPU (FP32) with LoRA.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89
 
90
  model.eval()
91
 
92
  # -------------------------
93
- # Load SNAC (once)
94
  # -------------------------
95
- print("[init] Loading SNAC...")
96
  snac_model = SNAC.from_pretrained(SNAC_MODEL_NAME).eval().to(DEVICE)
 
 
 
 
 
97
  print("[init] SNAC loaded.")
98
 
99
  # -------------------------
100
- # Inference function
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
101
  # -------------------------
102
- def generate_audio_cpu_lora(text: str):
 
 
 
 
 
 
 
103
  logs = []
104
  t0 = time.time()
105
  try:
106
- logs.append(f"[INFO] Device: {DEVICE} | SEQ_LEN: {SEQ_LEN} | MAX_NEW_TOKENS: {MAX_NEW_TOKENS}")
 
 
 
 
 
 
 
107
 
108
- # Build prompt (same as your earlier code)
109
- soh = tokenizer.decode([128259]); eoh = tokenizer.decode([128260])
110
- soa = tokenizer.decode([128261]); sos = tokenizer.decode([128257])
111
- eot = tokenizer.decode([128009])
112
- bos = tokenizer.bos_token
113
- prompt = soh + bos + text + eot + eoh + soa + sos
114
 
 
115
  inputs = tokenizer(prompt, return_tensors="pt", padding=True).to(DEVICE)
116
 
117
- # Keep generated tokens small on CPU
118
- max_new = min(MAX_NEW_TOKENS, 1024) if DEVICE == "cpu" else MAX_NEW_TOKENS
 
 
 
 
119
 
 
120
  with torch.inference_mode():
121
  outputs = model.generate(
122
  **inputs,
@@ -126,49 +268,45 @@ def generate_audio_cpu_lora(text: str):
126
  repetition_penalty=1.1,
127
  do_sample=True,
128
  eos_token_id=128258,
129
- pad_token_id=tokenizer.pad_token_id
130
  )
131
 
132
- # extract generated part
133
- gen_ids = outputs[0, inputs['input_ids'].shape[1]:].tolist()
134
  logs.append(f"[INFO] Generated {len(gen_ids)} tokens")
135
 
136
- # filter SNAC tokens (same logic)
137
  snac_min, snac_max = 128266, 156937
138
  eos_id = 128258
139
  eos_idx = gen_ids.index(eos_id) if eos_id in gen_ids else len(gen_ids)
140
  snac_tokens = [t for t in gen_ids[:eos_idx] if snac_min <= t <= snac_max]
141
 
 
142
  frames = len(snac_tokens) // 7
143
- snac_tokens = snac_tokens[:frames*7]
144
-
145
- l1, l2, l3 = [], [], []
146
- for i in range(frames):
147
- s = snac_tokens[i*7:(i+1)*7]
148
- l1.append((s[0]-snac_min) % 4096)
149
- l2.extend([(s[1]-snac_min)%4096, (s[4]-snac_min)%4096])
150
- l3.extend([(s[2]-snac_min)%4096, (s[3]-snac_min)%4096, (s[5]-snac_min)%4096, (s[6]-snac_min)%4096])
151
-
152
- if len(l1) == 0:
153
- logs.append("[WARN] No SNAC frames found in generated tokens. Returning debug logs.")
154
  return None, None, "\n".join(logs)
155
 
156
- codes_tensor = [torch.tensor(l1, dtype=torch.long, device=DEVICE).unsqueeze(0),
157
- torch.tensor(l2, dtype=torch.long, device=DEVICE).unsqueeze(0),
158
- torch.tensor(l3, dtype=torch.long, device=DEVICE).unsqueeze(0)]
 
159
 
 
160
  with torch.inference_mode():
161
- z_q = snac_model.quantizer.from_codes(codes_tensor)
162
- audio = snac_model.decoder(z_q)[0,0].cpu().numpy()
 
 
163
 
 
164
  if len(audio) > 2048:
165
  audio = audio[2048:]
166
 
167
- out_path = OUT_ROOT / f"tts_output_cpu_lora.wav"
168
- sf.write(out_path, audio, TARGET_SR)
169
  logs.append(f"[OK] Audio saved: {out_path} (duration {len(audio)/TARGET_SR:.2f}s)")
170
 
171
- logs.append(f"[TIME] Elapsed {time.time()-t0:.2f}s")
172
  return str(out_path), str(out_path), "\n".join(logs)
173
 
174
  except Exception as e:
@@ -176,28 +314,63 @@ def generate_audio_cpu_lora(text: str):
176
  logs.append(f"[ERROR] {e}\n{tb}")
177
  return None, None, "\n".join(logs)
178
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
179
  # -------------------------
180
  # Gradio UI
181
  # -------------------------
182
- with gr.Blocks() as demo:
183
- gr.Markdown("## Maya TTSCPU/GPU safe")
184
- txt = gr.Textbox(label="Enter text", value=DEFAULT_TEXT, lines=2)
185
- btn = gr.Button("Generate Audio")
186
- audio = gr.Audio(label="Audio", type="filepath")
187
- file = gr.File(label="Download")
188
- logs_box = gr.Textbox(label="Logs", lines=10)
189
- btn.click(generate_audio_cpu_lora, [txt], [audio, file, logs_box])
190
-
191
-
192
- # -----------------------------
193
- # Example section
194
- # -----------------------------
195
- gr.Markdown("### Example")
196
- example_text = DEFAULT_TEXT
197
- example_audio_path = "audio.wav"
198
-
199
- gr.Textbox(label="Example Text", value=example_text, lines=2, interactive=False)
200
- gr.Audio(label="Example Audio", value=example_audio_path, type="filepath", interactive=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
201
 
202
  if __name__ == "__main__":
203
  demo.launch()
 
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,
 
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:
 
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("# 🪶 NAVAMaya1 + 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()