J Z commited on
Commit
2ddc7b4
·
verified ·
1 Parent(s): d3fc26f

Update tts.py

Browse files
Files changed (1) hide show
  1. tts.py +183 -169
tts.py CHANGED
@@ -1,14 +1,16 @@
1
  """
2
- TTS module - Local Orpheus TTS with transformers + SNAC.
3
- Supports voice cloning from reference audio + transcript (pretrained model).
4
- Falls back to named voice with finetuned model if no reference available.
5
- No vLLM dependency - uses HuggingFace transformers for maximum compatibility.
6
  """
7
  import os
 
8
  import time
9
  import wave
10
  import logging
11
  import subprocess
 
 
12
  import numpy as np
13
  import torch
14
 
@@ -18,7 +20,6 @@ TEMP_DIR = "/tmp/tts_output"
18
  VOICE_REF_DIR = "/app/assets"
19
  SAMPLE_RATE = 24000
20
 
21
- # Fallback voice for finetuned model (if no reference audio)
22
  FALLBACK_VOICE = os.environ.get("ORPHEUS_VOICE", "leo")
23
 
24
  # Special token IDs for Orpheus
@@ -33,13 +34,16 @@ TOKEN_PAD = 128263
33
  AUDIO_CODE_OFFSET = 128266
34
 
35
  # Singleton state
36
- _model = None
37
  _tokenizer = None
38
  _snac_model = None
39
- _ref_tokens = None # Pre-encoded reference audio SNAC tokens
40
- _ref_transcript = None # Transcript of reference audio (REQUIRED for voice cloning)
41
  _use_voice_cloning = False
42
  _initialized = False
 
 
 
43
 
44
 
45
  def _ts():
@@ -51,93 +55,80 @@ def ensure_temp_dir():
51
  return TEMP_DIR
52
 
53
 
 
 
 
 
 
 
 
 
54
  def initialize():
55
  """
56
- Load Orpheus model, tokenizer, and SNAC decoder.
57
- If reference audio + transcript found, uses pretrained model for voice cloning.
58
- Otherwise, uses finetuned model with named voices.
59
- Call once at startup.
60
  """
61
- global _model, _tokenizer, _snac_model, _ref_tokens, _ref_transcript
62
- global _use_voice_cloning, _initialized
63
 
64
  if _initialized:
65
  return
66
 
67
  t0 = time.time()
68
- logger.info(f"[{_ts()}] [TTS] Initializing local Orpheus TTS...")
69
 
70
- from transformers import AutoModelForCausalLM, AutoTokenizer
71
  from snac import SNAC
72
 
73
- # Determine dtype based on GPU capability
74
- device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
75
- if torch.cuda.is_available():
76
- capability = torch.cuda.get_device_capability()
77
- if capability[0] >= 8:
78
- dtype = torch.bfloat16
79
- logger.info(f"[{_ts()}] [TTS] GPU compute {capability[0]}.{capability[1]} - using bfloat16")
80
- else:
81
- dtype = torch.float16
82
- logger.info(f"[{_ts()}] [TTS] GPU compute {capability[0]}.{capability[1]} - using float16 (T4)")
83
- else:
84
- dtype = torch.float32
85
- logger.info(f"[{_ts()}] [TTS] No GPU - using float32 (will be slow)")
86
-
87
- # 1. Load SNAC decoder first (needed for reference audio encoding)
88
  t1 = time.time()
89
  _snac_model = SNAC.from_pretrained("hubertsiuzdak/snac_24khz").eval()
90
  if torch.cuda.is_available():
91
  _snac_model = _snac_model.cuda()
92
  logger.info(f"[{_ts()}] [TTS] SNAC decoder loaded: {time.time()-t1:.2f}s")
93
 
94
- # 2. Check for reference audio + transcript
95
  _ref_transcript = _load_transcript()
96
  ref_audio_path = _find_reference_audio()
97
 
98
- if ref_audio_path and _ref_transcript:
99
- # Voice cloning mode: use pretrained model
 
100
  _use_voice_cloning = True
101
  model_name = "canopylabs/orpheus-3b-0.1-pretrained"
102
- hf_token = os.environ.get("HF_TOKEN", None)
103
- if not hf_token:
104
- logger.warning(f"[{_ts()}] [TTS] No HF_TOKEN! Pretrained model is gated, falling back to finetuned.")
105
- _use_voice_cloning = False
106
- model_name = "canopylabs/orpheus-3b-0.1-ft"
107
- else:
108
- logger.info(f"[{_ts()}] [TTS] Voice cloning mode: ref audio + transcript found")
109
- logger.info(f"[{_ts()}] [TTS] Transcript: \"{_ref_transcript[:80]}...\"")
110
  else:
111
- # Named voice mode: use finetuned model
112
  _use_voice_cloning = False
113
  model_name = "canopylabs/orpheus-3b-0.1-ft"
114
  if not ref_audio_path:
115
  logger.info(f"[{_ts()}] [TTS] No reference audio found")
116
  if not _ref_transcript:
117
- logger.info(f"[{_ts()}] [TTS] No transcript found (voice_transcript.txt)")
 
 
118
  logger.info(f"[{_ts()}] [TTS] Using finetuned model with voice: {FALLBACK_VOICE}")
119
 
120
- # 3. Load tokenizer
121
  t2 = time.time()
122
- token_kwargs = {}
123
- if _use_voice_cloning:
124
- hf_token = os.environ.get("HF_TOKEN")
125
- token_kwargs["token"] = hf_token
126
- _tokenizer = AutoTokenizer.from_pretrained(model_name, **token_kwargs)
127
  logger.info(f"[{_ts()}] [TTS] Tokenizer loaded: {time.time()-t2:.2f}s")
128
 
129
- # 4. Load model
 
 
 
 
 
 
 
 
130
  t3 = time.time()
131
- _model = AutoModelForCausalLM.from_pretrained(
132
- model_name,
133
- torch_dtype=dtype,
134
- device_map="auto",
135
- **token_kwargs,
136
- )
137
- _model.eval()
138
- logger.info(f"[{_ts()}] [TTS] Model loaded ({model_name.split('/')[-1]}): {time.time()-t3:.2f}s")
139
 
140
- # 5. Encode reference audio if voice cloning
141
  if _use_voice_cloning and ref_audio_path:
142
  _ref_tokens = _encode_reference_audio(ref_audio_path)
143
  if _ref_tokens is None:
@@ -146,11 +137,53 @@ def initialize():
146
 
147
  _initialized = True
148
  mode = f"voice cloning ({len(_ref_tokens)} ref tokens)" if _use_voice_cloning else f"named voice ({FALLBACK_VOICE})"
149
- logger.info(f"[{_ts()}] [TTS] ✓ Orpheus ready in {time.time()-t0:.2f}s | mode: {mode}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
150
 
151
 
152
  def _load_transcript():
153
- """Load transcript of reference audio from voice_transcript.txt."""
154
  for d in [VOICE_REF_DIR, "/app"]:
155
  for name in ["voice_transcript.txt", "transcript.txt"]:
156
  path = os.path.join(d, name)
@@ -162,7 +195,6 @@ def _load_transcript():
162
 
163
 
164
  def _find_reference_audio():
165
- """Find reference audio file."""
166
  for d in [VOICE_REF_DIR, "/app"]:
167
  for name in ["voice.mp4", "voice.wav", "voice.mp3"]:
168
  path = os.path.join(d, name)
@@ -178,7 +210,6 @@ def _encode_reference_audio(ref_path):
178
  logger.info(f"[{_ts()}] [TTS] Encoding reference: {ref_path}")
179
  ensure_temp_dir()
180
 
181
- # Extract to wav if needed
182
  wav_path = ref_path
183
  if not ref_path.endswith(".wav"):
184
  wav_path = os.path.join(TEMP_DIR, "voice_ref.wav")
@@ -195,7 +226,6 @@ def _encode_reference_audio(ref_path):
195
  t0 = time.time()
196
  audio_array, sr = librosa.load(wav_path, sr=SAMPLE_RATE)
197
 
198
- # Limit to 15 seconds
199
  max_samples = 15 * SAMPLE_RATE
200
  if len(audio_array) > max_samples:
201
  audio_array = audio_array[:max_samples]
@@ -204,18 +234,13 @@ def _encode_reference_audio(ref_path):
204
  duration = len(audio_array) / SAMPLE_RATE
205
  logger.info(f"[{_ts()}] [TTS] Reference audio: {duration:.1f}s")
206
 
207
- # Encode with SNAC (matching official Colab code exactly)
208
- waveform = torch.from_numpy(audio_array).unsqueeze(0)
209
- waveform = waveform.to(dtype=torch.float32)
210
- waveform = waveform.unsqueeze(0)
211
-
212
  if torch.cuda.is_available():
213
  waveform = waveform.cuda()
214
 
215
  with torch.inference_mode():
216
  codes = _snac_model.encode(waveform)
217
 
218
- # Interleave SNAC codes into Orpheus token format
219
  all_codes = []
220
  for i in range(codes[0].shape[1]):
221
  all_codes.append(codes[0][0][i].item() + AUDIO_CODE_OFFSET)
@@ -234,79 +259,56 @@ def _encode_reference_audio(ref_path):
234
  return None
235
 
236
 
237
- def _build_prompt_tokens(text):
238
  """
239
- Build input tokens for Orpheus generation.
240
 
241
- Voice cloning (pretrained model) - matches official Colab exactly:
242
- [SOH] [transcript_tokens] [EOT EOH SOA AUDIO_START] [ref_audio_tokens] [AUDIO_END EOAI]
243
- [SOH] [text_tokens] [EOT EOH]
244
 
245
- Named voice (finetuned model):
246
- [SOH] {voice}: {text} [EOT EOH]
247
  """
248
  if _use_voice_cloning and _ref_tokens is not None:
249
- # Voice cloning: pretrained model format (from official Colab)
250
- start_tokens = torch.tensor([[TOKEN_START_OF_HUMAN]], dtype=torch.int64)
251
- end_tokens = torch.tensor([[TOKEN_END_OF_TEXT, TOKEN_END_OF_HUMAN, TOKEN_START_OF_AI, TOKEN_AUDIO_START]], dtype=torch.int64)
252
- final_tokens = torch.tensor([[TOKEN_AUDIO_END, TOKEN_END_OF_AI]], dtype=torch.int64)
253
-
254
- # Transcript tokens (REQUIRED - this is what we were missing before)
255
- transcript_ids = _tokenizer(_ref_transcript, return_tensors="pt").input_ids
256
-
257
- # Build reference conditioning: [SOH][transcript][EOT EOH SOA AUDIO_START][audio][AUDIO_END EOAI]
258
- ref_input = torch.cat([
259
- start_tokens,
260
- transcript_ids,
261
- end_tokens,
262
- torch.tensor([_ref_tokens], dtype=torch.int64),
263
- final_tokens
264
- ], dim=1)
265
-
266
- # Generation prompt: [SOH][text][EOT EOH]
267
- gen_ids = _tokenizer(text, return_tensors="pt").input_ids
268
- gen_end = torch.tensor([[TOKEN_END_OF_TEXT, TOKEN_END_OF_HUMAN]], dtype=torch.int64)
269
-
270
- input_ids = torch.cat([ref_input, start_tokens, gen_ids, gen_end], dim=1)
271
  else:
272
- # Named voice: finetuned model format
273
  prompt = f"{FALLBACK_VOICE}: {text}"
274
- tokens = _tokenizer(prompt, return_tensors="pt")
275
- start = torch.tensor([[TOKEN_START_OF_HUMAN]], dtype=torch.int64)
276
- end = torch.tensor([[TOKEN_END_OF_TEXT, TOKEN_END_OF_HUMAN]], dtype=torch.int64)
277
- input_ids = torch.cat([start, tokens.input_ids, end], dim=1)
278
-
279
- return input_ids.to(_model.device)
280
 
281
 
282
- def _decode_audio_tokens(generated_ids):
283
  """
284
- Extract audio tokens from generated output and decode with SNAC.
285
- Matches official Colab decode logic exactly.
286
  """
287
- # Find last AUDIO_START token, crop after it
288
- indices = (generated_ids == TOKEN_AUDIO_START).nonzero(as_tuple=True)
289
- if len(indices[1]) > 0:
290
- last_idx = indices[1][-1].item()
291
- cropped = generated_ids[:, last_idx + 1:]
292
- else:
293
- cropped = generated_ids
294
-
295
- # Remove end tokens
296
- row = cropped[0]
297
- row = row[row != TOKEN_AUDIO_END]
298
- row = row[row != TOKEN_END_OF_AI]
299
 
300
  # Trim to multiple of 7
301
- length = (row.size(0) // 7) * 7
302
  if length == 0:
303
  logger.warning(f"[{_ts()}] [TTS] No valid audio tokens")
304
  return None
305
 
306
- row = row[:length]
307
- code_list = [t.item() - AUDIO_CODE_OFFSET for t in row]
308
 
309
- # Redistribute into 3 SNAC layers
310
  layer_1, layer_2, layer_3 = [], [], []
311
  for i in range(len(code_list) // 7):
312
  layer_1.append(code_list[7 * i])
@@ -331,31 +333,63 @@ def _decode_audio_tokens(generated_ids):
331
  return audio_hat.detach().squeeze().cpu().numpy()
332
 
333
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
334
  def _clean_text_for_tts(text):
335
- """
336
- Clean text before sending to TTS.
337
- Remove Orpheus emotion tags, asterisk actions, and other artifacts
338
- that can confuse the pretrained model's voice cloning.
339
- """
340
- import re
341
- # Remove Orpheus-style tags: <laugh>, <cough>, etc.
342
  text = re.sub(r'<[^>]+>', '', text)
343
- # Remove asterisk actions: *clears throat*, *pauses*, etc.
344
  text = re.sub(r'\*[^*]+\*', '', text)
345
- # Clean up extra whitespace
346
  text = re.sub(r'\s+', ' ', text).strip()
347
  return text
348
 
349
 
350
  def generate_audio(text: str, output_filename: str = None) -> str:
351
  """
352
- Generate speech audio from text using local Orpheus.
353
  Returns path to wav file, or None on failure.
354
  """
355
  if not text or not text.strip():
356
  return None
357
 
358
- # Clean text: remove tags, actions, fillers that confuse voice cloning
359
  text = _clean_text_for_tts(text)
360
  if not text:
361
  return None
@@ -379,44 +413,24 @@ def generate_audio(text: str, output_filename: str = None) -> str:
379
  logger.info(f"[{_ts()}] [TTS] Generating: {text[:60]}...")
380
 
381
  # Build prompt
382
- input_ids = _build_prompt_tokens(text)
383
- logger.info(f"[{_ts()}] [TTS] Prompt: {input_ids.shape[1]} tokens")
384
 
385
- # Generate with settings matched to mode
386
- t1 = time.time()
387
  if _use_voice_cloning:
388
- # Official pretrained model settings from Colab
389
- gen_kwargs = dict(
390
- max_new_tokens=990,
391
- temperature=0.5,
392
- top_p=0.9,
393
- repetition_penalty=1.1,
394
- )
395
  else:
396
- # Official finetuned model settings
397
- gen_kwargs = dict(
398
- max_new_tokens=1200,
399
- temperature=0.6,
400
- top_p=0.95,
401
- repetition_penalty=1.1,
402
- )
403
-
404
- with torch.no_grad():
405
- generated_ids = _model.generate(
406
- input_ids=input_ids,
407
- # NOTE: attention_mask intentionally omitted — matches official Colab
408
- # The Colab comments out attention_mask for voice cloning
409
- do_sample=True,
410
- eos_token_id=TOKEN_AUDIO_END,
411
- **gen_kwargs,
412
- )
413
  t2 = time.time()
414
- new_tokens = generated_ids.shape[1] - input_ids.shape[1]
415
- logger.info(f"[{_ts()}] [TTS] LLM: {new_tokens} tokens in {t2-t1:.2f}s ({new_tokens/(t2-t1):.0f} tok/s)")
416
 
417
- # Decode
418
  t3 = time.time()
419
- audio_np = _decode_audio_tokens(generated_ids)
420
  if audio_np is None:
421
  return None
422
  t4 = time.time()
 
1
  """
2
+ TTS module - Orpheus TTS with vLLM for fast inference.
3
+ Supports voice cloning (pretrained model) and named voices (finetuned model).
4
+ Uses vLLM's AsyncLLMEngine directly for 2-4x speedup over transformers.
 
5
  """
6
  import os
7
+ import re
8
  import time
9
  import wave
10
  import logging
11
  import subprocess
12
+ import asyncio
13
+ import threading
14
  import numpy as np
15
  import torch
16
 
 
20
  VOICE_REF_DIR = "/app/assets"
21
  SAMPLE_RATE = 24000
22
 
 
23
  FALLBACK_VOICE = os.environ.get("ORPHEUS_VOICE", "leo")
24
 
25
  # Special token IDs for Orpheus
 
34
  AUDIO_CODE_OFFSET = 128266
35
 
36
  # Singleton state
37
+ _engine = None # vLLM AsyncLLMEngine
38
  _tokenizer = None
39
  _snac_model = None
40
+ _ref_tokens = None
41
+ _ref_transcript = None
42
  _use_voice_cloning = False
43
  _initialized = False
44
+ _request_counter = 0
45
+ _event_loop = None
46
+ _loop_thread = None
47
 
48
 
49
  def _ts():
 
55
  return TEMP_DIR
56
 
57
 
58
+ def _start_event_loop():
59
+ """Start a background event loop for vLLM async operations."""
60
+ global _event_loop
61
+ _event_loop = asyncio.new_event_loop()
62
+ asyncio.set_event_loop(_event_loop)
63
+ _event_loop.run_forever()
64
+
65
+
66
  def initialize():
67
  """
68
+ Load vLLM engine, tokenizer, and SNAC decoder.
69
+ Voice cloning uses pretrained model; fallback uses finetuned model.
 
 
70
  """
71
+ global _engine, _tokenizer, _snac_model, _ref_tokens, _ref_transcript
72
+ global _use_voice_cloning, _initialized, _loop_thread
73
 
74
  if _initialized:
75
  return
76
 
77
  t0 = time.time()
78
+ logger.info(f"[{_ts()}] [TTS] Initializing Orpheus TTS with vLLM backend...")
79
 
80
+ from transformers import AutoTokenizer as HFTokenizer
81
  from snac import SNAC
82
 
83
+ # 1. Load SNAC decoder
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
  t1 = time.time()
85
  _snac_model = SNAC.from_pretrained("hubertsiuzdak/snac_24khz").eval()
86
  if torch.cuda.is_available():
87
  _snac_model = _snac_model.cuda()
88
  logger.info(f"[{_ts()}] [TTS] SNAC decoder loaded: {time.time()-t1:.2f}s")
89
 
90
+ # 2. Determine model based on available reference audio + transcript
91
  _ref_transcript = _load_transcript()
92
  ref_audio_path = _find_reference_audio()
93
 
94
+ hf_token = os.environ.get("HF_TOKEN", None)
95
+
96
+ if ref_audio_path and _ref_transcript and hf_token:
97
  _use_voice_cloning = True
98
  model_name = "canopylabs/orpheus-3b-0.1-pretrained"
99
+ logger.info(f"[{_ts()}] [TTS] Voice cloning mode: ref audio + transcript found")
100
+ logger.info(f"[{_ts()}] [TTS] Transcript: \"{_ref_transcript[:80]}...\"")
 
 
 
 
 
 
101
  else:
 
102
  _use_voice_cloning = False
103
  model_name = "canopylabs/orpheus-3b-0.1-ft"
104
  if not ref_audio_path:
105
  logger.info(f"[{_ts()}] [TTS] No reference audio found")
106
  if not _ref_transcript:
107
+ logger.info(f"[{_ts()}] [TTS] No transcript found")
108
+ if not hf_token:
109
+ logger.info(f"[{_ts()}] [TTS] No HF_TOKEN")
110
  logger.info(f"[{_ts()}] [TTS] Using finetuned model with voice: {FALLBACK_VOICE}")
111
 
112
+ # 3. Load tokenizer (HuggingFace tokenizer for prompt building)
113
  t2 = time.time()
114
+ token_kwargs = {"token": hf_token} if hf_token else {}
115
+ _tokenizer = HFTokenizer.from_pretrained(model_name, **token_kwargs)
 
 
 
116
  logger.info(f"[{_ts()}] [TTS] Tokenizer loaded: {time.time()-t2:.2f}s")
117
 
118
+ # 4. Start background event loop for vLLM
119
+ _loop_thread = threading.Thread(target=_start_event_loop, daemon=True)
120
+ _loop_thread.start()
121
+ # Wait for loop to be ready
122
+ import time as _t
123
+ while _event_loop is None:
124
+ _t.sleep(0.01)
125
+
126
+ # 5. Initialize vLLM engine
127
  t3 = time.time()
128
+ _init_vllm_engine(model_name, hf_token)
129
+ logger.info(f"[{_ts()}] [TTS] vLLM engine loaded: {time.time()-t3:.2f}s")
 
 
 
 
 
 
130
 
131
+ # 6. Encode reference audio if voice cloning
132
  if _use_voice_cloning and ref_audio_path:
133
  _ref_tokens = _encode_reference_audio(ref_audio_path)
134
  if _ref_tokens is None:
 
137
 
138
  _initialized = True
139
  mode = f"voice cloning ({len(_ref_tokens)} ref tokens)" if _use_voice_cloning else f"named voice ({FALLBACK_VOICE})"
140
+ logger.info(f"[{_ts()}] [TTS] ✓ Orpheus+vLLM ready in {time.time()-t0:.2f}s | mode: {mode}")
141
+
142
+
143
+ def _init_vllm_engine(model_name, hf_token):
144
+ """Initialize the vLLM AsyncLLMEngine."""
145
+ global _engine
146
+
147
+ from vllm import AsyncLLMEngine, AsyncEngineArgs
148
+
149
+ # Determine GPU memory and dtype
150
+ dtype = "bfloat16"
151
+ if torch.cuda.is_available():
152
+ capability = torch.cuda.get_device_capability()
153
+ if capability[0] < 8:
154
+ dtype = "float16"
155
+
156
+ # SNAC takes ~0.5GB, FLOAT takes ~2-3GB, leave room
157
+ gpu_mem_util = float(os.environ.get("VLLM_GPU_MEM_UTIL", "0.65"))
158
+
159
+ engine_args = AsyncEngineArgs(
160
+ model=model_name,
161
+ dtype=dtype,
162
+ gpu_memory_utilization=gpu_mem_util,
163
+ max_model_len=4096, # Need room for ref audio tokens + generation
164
+ enforce_eager=True, # Avoid CUDA graph issues on HF Spaces
165
+ disable_log_requests=True,
166
+ )
167
+
168
+ # Pass HF token for gated models
169
+ if hf_token:
170
+ os.environ["HF_TOKEN"] = hf_token
171
+
172
+ # Create engine on the background event loop
173
+ future = asyncio.run_coroutine_threadsafe(
174
+ _create_engine(engine_args), _event_loop
175
+ )
176
+ _engine = future.result(timeout=300) # 5 min timeout for model download
177
+
178
+
179
+ async def _create_engine(engine_args):
180
+ """Async engine creation."""
181
+ from vllm import AsyncLLMEngine
182
+ engine = AsyncLLMEngine.from_engine_args(engine_args)
183
+ return engine
184
 
185
 
186
  def _load_transcript():
 
187
  for d in [VOICE_REF_DIR, "/app"]:
188
  for name in ["voice_transcript.txt", "transcript.txt"]:
189
  path = os.path.join(d, name)
 
195
 
196
 
197
  def _find_reference_audio():
 
198
  for d in [VOICE_REF_DIR, "/app"]:
199
  for name in ["voice.mp4", "voice.wav", "voice.mp3"]:
200
  path = os.path.join(d, name)
 
210
  logger.info(f"[{_ts()}] [TTS] Encoding reference: {ref_path}")
211
  ensure_temp_dir()
212
 
 
213
  wav_path = ref_path
214
  if not ref_path.endswith(".wav"):
215
  wav_path = os.path.join(TEMP_DIR, "voice_ref.wav")
 
226
  t0 = time.time()
227
  audio_array, sr = librosa.load(wav_path, sr=SAMPLE_RATE)
228
 
 
229
  max_samples = 15 * SAMPLE_RATE
230
  if len(audio_array) > max_samples:
231
  audio_array = audio_array[:max_samples]
 
234
  duration = len(audio_array) / SAMPLE_RATE
235
  logger.info(f"[{_ts()}] [TTS] Reference audio: {duration:.1f}s")
236
 
237
+ waveform = torch.from_numpy(audio_array).unsqueeze(0).to(dtype=torch.float32).unsqueeze(0)
 
 
 
 
238
  if torch.cuda.is_available():
239
  waveform = waveform.cuda()
240
 
241
  with torch.inference_mode():
242
  codes = _snac_model.encode(waveform)
243
 
 
244
  all_codes = []
245
  for i in range(codes[0].shape[1]):
246
  all_codes.append(codes[0][0][i].item() + AUDIO_CODE_OFFSET)
 
259
  return None
260
 
261
 
262
+ def _build_prompt_token_ids(text):
263
  """
264
+ Build input token IDs list for vLLM (not tensors — vLLM takes lists).
265
 
266
+ Voice cloning (pretrained):
267
+ [SOH][transcript][EOT EOH SOA AUDIO_START][ref_audio][AUDIO_END EOAI]
268
+ [SOH][text][EOT EOH SOA AUDIO_START]
269
 
270
+ Named voice (finetuned):
271
+ [SOH]{voice}: {text}[EOT EOH SOA AUDIO_START]
272
  """
273
  if _use_voice_cloning and _ref_tokens is not None:
274
+ start = [TOKEN_START_OF_HUMAN]
275
+ end = [TOKEN_END_OF_TEXT, TOKEN_END_OF_HUMAN, TOKEN_START_OF_AI, TOKEN_AUDIO_START]
276
+ final = [TOKEN_AUDIO_END, TOKEN_END_OF_AI]
277
+
278
+ transcript_ids = _tokenizer(_ref_transcript, return_tensors="pt").input_ids[0].tolist()
279
+
280
+ # Reference block
281
+ ref_block = start + transcript_ids + end + _ref_tokens + final
282
+
283
+ # Generation block
284
+ gen_ids = _tokenizer(text, return_tensors="pt").input_ids[0].tolist()
285
+ gen_block = start + gen_ids + end # End with AUDIO_START so model generates audio
286
+
287
+ return ref_block + gen_block
 
 
 
 
 
 
 
 
288
  else:
 
289
  prompt = f"{FALLBACK_VOICE}: {text}"
290
+ token_ids = _tokenizer(prompt, return_tensors="pt").input_ids[0].tolist()
291
+ start = [TOKEN_START_OF_HUMAN]
292
+ end = [TOKEN_END_OF_TEXT, TOKEN_END_OF_HUMAN, TOKEN_START_OF_AI, TOKEN_AUDIO_START]
293
+ return start + token_ids + end
 
 
294
 
295
 
296
+ def _decode_audio_tokens_from_list(token_ids):
297
  """
298
+ Decode a list of generated token IDs into audio.
299
+ Expects only the NEW tokens (not the prompt).
300
  """
301
+ # Remove any end tokens
302
+ filtered = [t for t in token_ids if t not in (TOKEN_AUDIO_END, TOKEN_END_OF_AI, TOKEN_AUDIO_START)]
 
 
 
 
 
 
 
 
 
 
303
 
304
  # Trim to multiple of 7
305
+ length = (len(filtered) // 7) * 7
306
  if length == 0:
307
  logger.warning(f"[{_ts()}] [TTS] No valid audio tokens")
308
  return None
309
 
310
+ code_list = [t - AUDIO_CODE_OFFSET for t in filtered[:length]]
 
311
 
 
312
  layer_1, layer_2, layer_3 = [], [], []
313
  for i in range(len(code_list) // 7):
314
  layer_1.append(code_list[7 * i])
 
333
  return audio_hat.detach().squeeze().cpu().numpy()
334
 
335
 
336
+ async def _generate_tokens_async(prompt_token_ids, max_tokens, temperature, top_p, rep_penalty):
337
+ """Run vLLM generation asynchronously and collect all output tokens."""
338
+ global _request_counter
339
+ from vllm import SamplingParams
340
+
341
+ _request_counter += 1
342
+ request_id = f"tts-{_request_counter}"
343
+
344
+ sampling_params = SamplingParams(
345
+ temperature=temperature,
346
+ top_p=top_p,
347
+ max_tokens=max_tokens,
348
+ repetition_penalty=rep_penalty,
349
+ stop_token_ids=[TOKEN_AUDIO_END],
350
+ )
351
+
352
+ # Use TokensPrompt dict for vLLM 0.7.3 compatibility
353
+ prompt_input = {"prompt_token_ids": prompt_token_ids}
354
+
355
+ all_token_ids = []
356
+ async for output in _engine.generate(
357
+ prompt=prompt_input,
358
+ sampling_params=sampling_params,
359
+ request_id=request_id,
360
+ ):
361
+ # vLLM gives cumulative output at each step
362
+ if output.outputs:
363
+ all_token_ids = list(output.outputs[0].token_ids)
364
+
365
+ return all_token_ids
366
+
367
+
368
+ def _generate_tokens_sync(prompt_token_ids, max_tokens, temperature, top_p, rep_penalty):
369
+ """Synchronous wrapper for async vLLM generation."""
370
+ future = asyncio.run_coroutine_threadsafe(
371
+ _generate_tokens_async(prompt_token_ids, max_tokens, temperature, top_p, rep_penalty),
372
+ _event_loop
373
+ )
374
+ return future.result(timeout=120)
375
+
376
+
377
  def _clean_text_for_tts(text):
378
+ """Remove tags and asterisk actions that confuse voice cloning."""
 
 
 
 
 
 
379
  text = re.sub(r'<[^>]+>', '', text)
 
380
  text = re.sub(r'\*[^*]+\*', '', text)
 
381
  text = re.sub(r'\s+', ' ', text).strip()
382
  return text
383
 
384
 
385
  def generate_audio(text: str, output_filename: str = None) -> str:
386
  """
387
+ Generate speech audio from text using Orpheus + vLLM.
388
  Returns path to wav file, or None on failure.
389
  """
390
  if not text or not text.strip():
391
  return None
392
 
 
393
  text = _clean_text_for_tts(text)
394
  if not text:
395
  return None
 
413
  logger.info(f"[{_ts()}] [TTS] Generating: {text[:60]}...")
414
 
415
  # Build prompt
416
+ prompt_ids = _build_prompt_token_ids(text)
417
+ logger.info(f"[{_ts()}] [TTS] Prompt: {len(prompt_ids)} tokens")
418
 
419
+ # Generation settings matched to mode
 
420
  if _use_voice_cloning:
421
+ gen_kwargs = dict(max_tokens=990, temperature=0.5, top_p=0.9, rep_penalty=1.1)
 
 
 
 
 
 
422
  else:
423
+ gen_kwargs = dict(max_tokens=1200, temperature=0.6, top_p=0.95, rep_penalty=1.1)
424
+
425
+ # Generate via vLLM
426
+ t1 = time.time()
427
+ output_ids = _generate_tokens_sync(prompt_ids, **gen_kwargs)
 
 
 
 
 
 
 
 
 
 
 
 
428
  t2 = time.time()
429
+ logger.info(f"[{_ts()}] [TTS] vLLM: {len(output_ids)} tokens in {t2-t1:.2f}s ({len(output_ids)/(t2-t1):.0f} tok/s)")
 
430
 
431
+ # Decode audio
432
  t3 = time.time()
433
+ audio_np = _decode_audio_tokens_from_list(output_ids)
434
  if audio_np is None:
435
  return None
436
  t4 = time.time()