ruslanmv commited on
Commit
a28e45a
·
1 Parent(s): 8c573f7
Files changed (2) hide show
  1. app.py +99 -142
  2. requirements.txt +3 -2
app.py CHANGED
@@ -14,7 +14,7 @@ from typing import List, Dict, Tuple, Generator
14
  os.environ.setdefault("HF_HUB_ENABLE_HF_TRANSFER", "1")
15
  os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")
16
  os.environ.setdefault("COQUI_TOS_AGREED", "1")
17
- os.environ.setdefault("GRADIO_ANALYTICS_ENABLED", "false") # truly disable analytics
18
 
19
  # --- Load .env early (HF_TOKEN / SECRET_TOKEN) ---
20
  from dotenv import load_dotenv
@@ -22,8 +22,8 @@ load_dotenv()
22
 
23
  # --- Hugging Face Spaces & ZeroGPU ---
24
  try:
25
- import spaces # Required for ZeroGPU on HF
26
- except Exception:
27
  class _SpacesShim:
28
  def GPU(self, *args, **kwargs):
29
  def _wrap(fn):
@@ -39,22 +39,20 @@ import numpy as np
39
  from huggingface_hub import HfApi, hf_hub_download
40
  from llama_cpp import Llama
41
 
42
- # --- Prefer torchaudio sox_io/soundfile backend (avoid FFmpeg/torio bug) ---
 
43
  try:
44
  import torchaudio
45
- _backend_set = False
46
- for _cand in ("sox_io", "soundfile"):
47
  try:
48
- torchaudio.set_audio_backend(_cand)
49
- _backend_set = True
50
  break
51
  except Exception:
52
- pass
53
- if not _backend_set:
54
- # If neither is available, at least try to disable ffmpeg path
55
- os.environ["TORCHAUDIO_USE_FFMPEG"] = "0"
56
  except Exception:
57
- torchaudio = None # continue; TTS can still read via its own loaders
58
 
59
  # --- TTS Libraries ---
60
  from TTS.tts.configs.xtts_config import XttsConfig
@@ -78,7 +76,7 @@ nltk.download("punkt", quiet=True)
78
  # Cached models & latents
79
  tts_model: Xtts | None = None
80
  llm_model: Llama | None = None
81
- voice_latents: Dict[str, Tuple[np.ndarray, np.ndarray]] = {}
82
 
83
  # Config
84
  HF_TOKEN = os.environ.get("HF_TOKEN")
@@ -140,7 +138,6 @@ def format_prompt_zephyr(message: str, history: List[Tuple[str, str | None]], sy
140
 
141
  def precache_assets() -> None:
142
  """Download voice WAVs, XTTS weights, and Zephyr GGUF to local cache before any inference."""
143
- # Voices
144
  print("Pre-caching voice files...")
145
  file_names = ["cloee-1.wav", "julian-bedtime-style-1.wav", "pirate_by_coqui.wav", "thera-1.wav"]
146
  base_url = "https://raw.githubusercontent.com/ruslanmv/ai-story-server/main/voices/"
@@ -156,39 +153,31 @@ def precache_assets() -> None:
156
  except Exception as e:
157
  print(f"Failed to download {name}: {e}")
158
 
159
- # XTTS model files
160
  print("Pre-caching XTTS v2 model files...")
161
  ModelManager().download_model("tts_models/multilingual/multi-dataset/xtts_v2")
162
 
163
- # LLM GGUF
164
  print("Pre-caching Zephyr GGUF...")
165
  try:
166
  hf_hub_download(
167
  repo_id="TheBloke/zephyr-7B-beta-GGUF",
168
  filename="zephyr-7b-beta.Q5_K_M.gguf",
169
- force_download=False
170
  )
171
  except Exception as e:
172
  print(f"Warning: GGUF pre-cache error: {e}")
173
 
174
  def _load_xtts(device: str) -> Xtts:
175
- """Load XTTS from the local cache. Use checkpoint_dir to avoid None path bug."""
176
  print("Loading Coqui XTTS V2 model (CPU first)...")
177
  model_name = "tts_models/multilingual/multi-dataset/xtts_v2"
178
- ModelManager().download_model(model_name) # idempotent
179
  model_dir = os.path.join(get_user_data_dir("tts"), model_name.replace("/", "--"))
 
 
180
 
181
  cfg = XttsConfig()
182
  cfg.load_json(os.path.join(model_dir, "config.json"))
183
  model = Xtts.init_from_config(cfg)
184
-
185
- # IMPORTANT: use checkpoint_dir (fixes speakers file path resolution)
186
- model.load_checkpoint(
187
- cfg,
188
- checkpoint_dir=model_dir,
189
- eval=True,
190
- use_deepspeed=False, # deepspeed not installed in Spaces
191
- )
192
  model.to(device)
193
  print("XTTS model loaded.")
194
  return model
@@ -202,143 +191,108 @@ def _load_llama() -> Llama:
202
  )
203
  llm = Llama(
204
  model_path=zephyr_model_path,
205
- n_gpu_layers=0, # CPU by default to keep it ready without GPU
206
- n_ctx=4096,
207
- n_batch=512,
208
- verbose=False
209
  )
210
  print("LLM loaded (CPU).")
211
  return llm
212
 
 
 
 
 
 
 
 
 
213
  def init_models_and_latents() -> None:
214
  """Preload TTS and LLM on CPU and compute voice latents once."""
215
  global tts_model, llm_model, voice_latents
216
 
217
  if tts_model is None:
218
- tts_model = _load_xtts(device="cpu") # keep on CPU at startup
219
 
220
  if llm_model is None:
221
  llm_model = _load_llama()
222
 
223
- # Pre-compute latents once (CPU OK); torchaudio backend already forced above
224
  if not voice_latents:
225
  print("Computing voice conditioning latents...")
226
- for role, filename in [
227
- ("Cloée", "cloee-1.wav"),
228
- ("Julian", "julian-bedtime-style-1.wav"),
229
- ("Pirate", "pirate_by_coqui.wav"),
230
- ("Thera", "thera-1.wav"),
231
- ]:
232
  path = os.path.join("voices", filename)
 
 
233
  voice_latents[role] = tts_model.get_conditioning_latents(
234
- audio_path=path, gpt_cond_len=30, max_ref_length=60
235
  )
236
  print("Voice latents ready.")
237
 
238
- # Ensure we close Llama cleanly to avoid __del__ issues at interpreter shutdown
239
  def _close_llm():
240
  global llm_model
241
- try:
242
- if llm_model is not None:
243
- llm_model.close()
244
- except Exception:
245
- pass
246
  atexit.register(_close_llm)
247
 
248
  # ===================================================================================
249
  # 4) INFERENCE HELPERS
250
  # ===================================================================================
251
 
252
- def generate_text_stream(llm_instance: Llama, prompt: str,
253
- history: List[Tuple[str, str | None]],
254
- system_message_text: str) -> Generator[str, None, None]:
255
- formatted_prompt = format_prompt_zephyr(prompt, history, system_message_text)
256
  stream = llm_instance(
257
- formatted_prompt,
258
- temperature=0.7,
259
- max_tokens=512,
260
- top_p=0.95,
261
- stop=LLM_STOP_WORDS,
262
- stream=True
263
  )
264
  for response in stream:
265
- ch = response["choices"][0]["text"]
266
- try:
267
- is_single_emoji = (len(ch) == 1 and emoji.is_emoji(ch))
268
- except Exception:
269
- is_single_emoji = False
270
- if "<|user|>" in ch or is_single_emoji:
271
- continue
272
- yield ch
273
 
274
- def generate_audio_stream(tts_instance: Xtts, text: str, language: str,
275
- latents: Tuple[np.ndarray, np.ndarray]) -> Generator[bytes, None, None]:
276
  gpt_cond_latent, speaker_embedding = latents
277
- try:
278
- for chunk in tts_instance.inference_stream(
279
- text=text,
280
- language=language,
281
- gpt_cond_latent=gpt_cond_latent,
282
- speaker_embedding=speaker_embedding,
283
- temperature=0.85,
284
- ):
285
- if chunk is not None:
286
- yield chunk.detach().cpu().numpy().squeeze().tobytes()
287
- except RuntimeError as e:
288
- print(f"Error during TTS inference: {e}")
289
- if "device-side assert" in str(e) and api:
290
- gr.Warning("Critical GPU error. Attempting to restart the Space...")
291
- try:
292
- api.restart_space(repo_id=repo_id)
293
- except Exception:
294
- pass
295
 
296
  # ===================================================================================
297
  # 5) ZERO-GPU ENTRYPOINT
298
  # ===================================================================================
299
 
300
- @spaces.GPU(duration=120) # Request GPU for 120s (tune as needed)
301
  def generate_story_and_speech(secret_token_input: str, input_text: str, chatbot_role: str) -> List[Dict[str, str]]:
302
  if secret_token_input != SECRET_TOKEN:
303
  raise gr.Error("Invalid secret token provided.")
304
  if not input_text:
305
  return []
306
 
307
- # Models & latents are preloaded at startup; ensure available
308
- if tts_model is None or llm_model is None or not voice_latents:
309
- init_models_and_latents()
310
 
311
- # If ZeroGPU provided a GPU for this call, move XTTS to CUDA for faster audio
312
  try:
313
  if torch.cuda.is_available():
314
  tts_model.to("cuda")
315
- else:
316
- tts_model.to("cpu")
317
- except Exception:
318
- tts_model.to("cpu")
319
-
320
- # Generate story text
321
- history: List[Tuple[str, str | None]] = [(input_text, None)]
322
- full_story_text = "".join(
323
- generate_text_stream(llm_model, history[-1][0], history[:-1], system_message_text=ROLE_PROMPTS[chatbot_role])
324
- ).strip()
325
- if not full_story_text:
326
- return []
327
 
328
- # Tokenize into shorter sentences for TTS
329
- sentences = split_sentences(full_story_text, SENTENCE_SPLIT_LENGTH)
330
- lang = langid.classify(sentences[0])[0] if sentences else "en"
 
331
 
332
- results: List[Dict[str, str]] = []
333
- for sentence in sentences:
334
- if not any(c.isalnum() for c in sentence):
335
- continue
336
 
337
- audio_chunks = generate_audio_stream(tts_model, sentence, lang, voice_latents[chatbot_role])
338
- pcm_data = b"".join(chunk for chunk in audio_chunks if chunk)
 
 
 
 
 
 
 
 
339
 
340
- # Optional noise reduction (best-effort)
341
- try:
342
  data_s16 = np.frombuffer(pcm_data, dtype=np.int16)
343
  if data_s16.size > 0:
344
  float_data = data_s16.astype(np.float32) / 32767.0
@@ -346,43 +300,46 @@ def generate_story_and_speech(secret_token_input: str, input_text: str, chatbot_
346
  final_pcm = (reduced * 32767).astype(np.int16).tobytes()
347
  else:
348
  final_pcm = pcm_data
349
- except Exception:
350
- final_pcm = pcm_data
351
-
352
- b64_wav = base64.b64encode(pcm_to_wav(final_pcm)).decode("utf-8")
353
- results.append({"text": sentence, "audio": b64_wav})
354
-
355
- # Return XTTS to CPU to free GPU instantly after the call
356
- try:
357
- tts_model.to("cpu")
358
- except Exception:
359
- pass
360
-
361
- return results
362
 
363
  # ===================================================================================
364
  # 6) STARTUP: PRECACHE & UI
365
  # ===================================================================================
366
 
367
- def build_ui() -> gr.Interface:
368
- return gr.Interface(
369
- fn=generate_story_and_speech,
370
- inputs=[
371
- gr.Textbox(label="Secret Token", type="password", value=SECRET_TOKEN),
372
- gr.Textbox(placeholder="What should the story be about?", label="Story Prompt"),
373
- gr.Dropdown(choices=ROLES, label="Select a Storyteller", value="Cloée"),
374
- ],
375
- outputs=gr.JSON(label="Story and Audio Output"),
376
- title="AI Storyteller with ZeroGPU",
377
- description="Enter a prompt to generate a short story with voice narration using on-demand GPU.",
378
- flagging_mode="never", # replaces deprecated allow_flagging
379
- )
 
 
 
 
 
 
380
 
381
  if __name__ == "__main__":
382
  print("===== Startup: pre-cache assets and preload models =====")
383
- precache_assets() # 1) download everything to disk
384
- init_models_and_latents() # 2) load models on CPU + compute voice latents
385
  print("Models and assets ready. Launching UI...")
386
 
387
  demo = build_ui()
388
- demo.queue().launch(server_name="0.0.0.0", server_port=int(os.getenv("PORT", "7860")))
 
14
  os.environ.setdefault("HF_HUB_ENABLE_HF_TRANSFER", "1")
15
  os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")
16
  os.environ.setdefault("COQUI_TOS_AGREED", "1")
17
+ os.environ.setdefault("GRADIO_ANALYTICS_ENABLED", "false")
18
 
19
  # --- Load .env early (HF_TOKEN / SECRET_TOKEN) ---
20
  from dotenv import load_dotenv
 
22
 
23
  # --- Hugging Face Spaces & ZeroGPU ---
24
  try:
25
+ import spaces
26
+ except ImportError:
27
  class _SpacesShim:
28
  def GPU(self, *args, **kwargs):
29
  def _wrap(fn):
 
39
  from huggingface_hub import HfApi, hf_hub_download
40
  from llama_cpp import Llama
41
 
42
+ # --- Set torchaudio backend BEFORE it's used ---
43
+ # This attempts to use soundfile or sox_io before falling back, avoiding the buggy ffmpeg backend.
44
  try:
45
  import torchaudio
46
+ # Try to set a more stable backend
47
+ for backend in ("soundfile", "sox_io"):
48
  try:
49
+ torchaudio.set_audio_backend(backend)
50
+ print(f"Torchaudio backend set to: {backend}")
51
  break
52
  except Exception:
53
+ continue
 
 
 
54
  except Exception:
55
+ print("Could not import or set torchaudio backend.")
56
 
57
  # --- TTS Libraries ---
58
  from TTS.tts.configs.xtts_config import XttsConfig
 
76
  # Cached models & latents
77
  tts_model: Xtts | None = None
78
  llm_model: Llama | None = None
79
+ voice_latents: Dict[str, Tuple[torch.Tensor, torch.Tensor]] = {}
80
 
81
  # Config
82
  HF_TOKEN = os.environ.get("HF_TOKEN")
 
138
 
139
  def precache_assets() -> None:
140
  """Download voice WAVs, XTTS weights, and Zephyr GGUF to local cache before any inference."""
 
141
  print("Pre-caching voice files...")
142
  file_names = ["cloee-1.wav", "julian-bedtime-style-1.wav", "pirate_by_coqui.wav", "thera-1.wav"]
143
  base_url = "https://raw.githubusercontent.com/ruslanmv/ai-story-server/main/voices/"
 
153
  except Exception as e:
154
  print(f"Failed to download {name}: {e}")
155
 
 
156
  print("Pre-caching XTTS v2 model files...")
157
  ModelManager().download_model("tts_models/multilingual/multi-dataset/xtts_v2")
158
 
 
159
  print("Pre-caching Zephyr GGUF...")
160
  try:
161
  hf_hub_download(
162
  repo_id="TheBloke/zephyr-7B-beta-GGUF",
163
  filename="zephyr-7b-beta.Q5_K_M.gguf",
164
+ local_dir_use_symlinks=False,
165
  )
166
  except Exception as e:
167
  print(f"Warning: GGUF pre-cache error: {e}")
168
 
169
  def _load_xtts(device: str) -> Xtts:
170
+ """Load XTTS from the local cache."""
171
  print("Loading Coqui XTTS V2 model (CPU first)...")
172
  model_name = "tts_models/multilingual/multi-dataset/xtts_v2"
 
173
  model_dir = os.path.join(get_user_data_dir("tts"), model_name.replace("/", "--"))
174
+ if not os.path.exists(model_dir):
175
+ ModelManager().download_model(model_name)
176
 
177
  cfg = XttsConfig()
178
  cfg.load_json(os.path.join(model_dir, "config.json"))
179
  model = Xtts.init_from_config(cfg)
180
+ model.load_checkpoint(cfg, checkpoint_dir=model_dir, eval=True, use_deepspeed=False)
 
 
 
 
 
 
 
181
  model.to(device)
182
  print("XTTS model loaded.")
183
  return model
 
191
  )
192
  llm = Llama(
193
  model_path=zephyr_model_path,
194
+ n_gpu_layers=0, n_ctx=4096, n_batch=512, verbose=False
 
 
 
195
  )
196
  print("LLM loaded (CPU).")
197
  return llm
198
 
199
+ def load_audio_for_tts(path: str, target_sr: int = 24000) -> torch.Tensor:
200
+ """Loads and resamples audio, returning a Torch tensor to avoid TTS internal loading."""
201
+ waveform, sr = torchaudio.load(path)
202
+ if sr != target_sr:
203
+ resampler = torchaudio.transforms.Resample(orig_freq=sr, new_freq=target_sr)
204
+ waveform = resampler(waveform)
205
+ return waveform.view(1, -1) # Ensure shape is (1, T) for TTS model
206
+
207
  def init_models_and_latents() -> None:
208
  """Preload TTS and LLM on CPU and compute voice latents once."""
209
  global tts_model, llm_model, voice_latents
210
 
211
  if tts_model is None:
212
+ tts_model = _load_xtts(device="cpu")
213
 
214
  if llm_model is None:
215
  llm_model = _load_llama()
216
 
 
217
  if not voice_latents:
218
  print("Computing voice conditioning latents...")
219
+ voice_files = {
220
+ "Cloée": "cloee-1.wav", "Julian": "julian-bedtime-style-1.wav",
221
+ "Pirate": "pirate_by_coqui.wav", "Thera": "thera-1.wav",
222
+ }
223
+ for role, filename in voice_files.items():
 
224
  path = os.path.join("voices", filename)
225
+ # --- FIX: Load audio externally and pass the waveform tensor directly ---
226
+ waveform = load_audio_for_tts(path)
227
  voice_latents[role] = tts_model.get_conditioning_latents(
228
+ waveform=waveform, gpt_cond_len=30, max_ref_length=60
229
  )
230
  print("Voice latents ready.")
231
 
 
232
  def _close_llm():
233
  global llm_model
234
+ if llm_model is not None:
235
+ del llm_model
 
 
 
236
  atexit.register(_close_llm)
237
 
238
  # ===================================================================================
239
  # 4) INFERENCE HELPERS
240
  # ===================================================================================
241
 
242
+ def generate_text_stream(llm_instance: Llama, prompt: str, history: List, sys_prompt: str) -> Generator[str, None, None]:
243
+ formatted_prompt = format_prompt_zephyr(prompt, history, sys_prompt)
 
 
244
  stream = llm_instance(
245
+ formatted_prompt, temperature=0.7, max_tokens=512, top_p=0.95, stop=LLM_STOP_WORDS, stream=True
 
 
 
 
 
246
  )
247
  for response in stream:
248
+ yield response["choices"][0]["text"]
 
 
 
 
 
 
 
249
 
250
+ def generate_audio_stream(tts_instance: Xtts, text: str, lang: str, latents: Tuple) -> Generator[bytes, None, None]:
 
251
  gpt_cond_latent, speaker_embedding = latents
252
+ for chunk in tts_instance.inference_stream(
253
+ text, lang, gpt_cond_latent, speaker_embedding, temperature=0.85,
254
+ ):
255
+ if chunk is not None:
256
+ yield chunk.detach().cpu().numpy().squeeze().tobytes()
 
 
 
 
 
 
 
 
 
 
 
 
 
257
 
258
  # ===================================================================================
259
  # 5) ZERO-GPU ENTRYPOINT
260
  # ===================================================================================
261
 
262
+ @spaces.GPU(duration=120)
263
  def generate_story_and_speech(secret_token_input: str, input_text: str, chatbot_role: str) -> List[Dict[str, str]]:
264
  if secret_token_input != SECRET_TOKEN:
265
  raise gr.Error("Invalid secret token provided.")
266
  if not input_text:
267
  return []
268
 
269
+ # Models must be preloaded, this is a fallback.
270
+ if tts_model is None or llm_model is None:
271
+ raise gr.Error("Models not initialized. Please restart the Space.")
272
 
 
273
  try:
274
  if torch.cuda.is_available():
275
  tts_model.to("cuda")
 
 
 
 
 
 
 
 
 
 
 
 
276
 
277
+ history: List[Tuple[str, str | None]] = [(input_text, None)]
278
+ full_story_text = "".join(
279
+ generate_text_stream(llm_model, history[-1][0], history[:-1], ROLE_PROMPTS[chatbot_role])
280
+ ).strip()
281
 
282
+ if not full_story_text:
283
+ return []
 
 
284
 
285
+ sentences = split_sentences(full_story_text, SENTENCE_SPLIT_LENGTH)
286
+ lang = langid.classify(sentences[0])[0] if sentences else "en"
287
+ results: List[Dict[str, str]] = []
288
+
289
+ for sentence in sentences:
290
+ if not any(c.isalnum() for c in sentence):
291
+ continue
292
+
293
+ audio_chunks = generate_audio_stream(tts_model, sentence, lang, voice_latents[chatbot_role])
294
+ pcm_data = b"".join(chunk for chunk in audio_chunks if chunk)
295
 
 
 
296
  data_s16 = np.frombuffer(pcm_data, dtype=np.int16)
297
  if data_s16.size > 0:
298
  float_data = data_s16.astype(np.float32) / 32767.0
 
300
  final_pcm = (reduced * 32767).astype(np.int16).tobytes()
301
  else:
302
  final_pcm = pcm_data
303
+
304
+ b64_wav = base64.b64encode(pcm_to_wav(final_pcm)).decode("utf-8")
305
+ results.append({"text": sentence, "audio": b64_wav})
306
+
307
+ return results
308
+
309
+ finally:
310
+ # Crucial for ZeroGPU: ensure model returns to CPU to free the GPU
311
+ if tts_model is not None:
312
+ tts_model.to("cpu")
 
 
 
313
 
314
  # ===================================================================================
315
  # 6) STARTUP: PRECACHE & UI
316
  # ===================================================================================
317
 
318
+ def build_ui() -> gr.Blocks:
319
+ with gr.Blocks() as demo:
320
+ gr.Markdown("# AI Storyteller with ZeroGPU")
321
+ gr.Markdown("Enter a prompt to generate a short story with voice narration using on-demand GPU.")
322
+
323
+ with gr.Row():
324
+ secret_token = gr.Textbox(label="Secret Token", type="password", value=SECRET_TOKEN)
325
+ storyteller = gr.Dropdown(choices=ROLES, label="Select a Storyteller", value="Cloée")
326
+
327
+ prompt = gr.Textbox(placeholder="What should the story be about?", label="Story Prompt")
328
+ output = gr.JSON(label="Story and Audio Output")
329
+
330
+ prompt.submit(
331
+ fn=generate_story_and_speech,
332
+ inputs=[secret_token, prompt, storyteller],
333
+ outputs=output,
334
+ )
335
+
336
+ return demo
337
 
338
  if __name__ == "__main__":
339
  print("===== Startup: pre-cache assets and preload models =====")
340
+ precache_assets()
341
+ init_models_and_latents()
342
  print("Models and assets ready. Launching UI...")
343
 
344
  demo = build_ui()
345
+ demo.queue().launch(server_name="0.0.0.0", server_port=int(os.getenv("PORT", "7860")))
requirements.txt CHANGED
@@ -9,7 +9,7 @@ requests
9
  numpy
10
  pandas==1.5.3
11
 
12
- # TTS (legacy)
13
  TTS @ git+https://github.com/coqui-ai/TTS@v0.22.0
14
  pydantic==2.5.3
15
 
@@ -17,6 +17,7 @@ pydantic==2.5.3
17
  llama-cpp-python==0.2.79
18
 
19
  # Audio & Text
 
20
  noisereduce==3.0.3
21
  pydub
22
  langid
@@ -26,4 +27,4 @@ ffmpeg-python
26
 
27
  # Japanese Text (optional)
28
  mecab-python3==1.0.9
29
- unidic-lite==1.0.8
 
9
  numpy
10
  pandas==1.5.3
11
 
12
+ # TTS
13
  TTS @ git+https://github.com/coqui-ai/TTS@v0.22.0
14
  pydantic==2.5.3
15
 
 
17
  llama-cpp-python==0.2.79
18
 
19
  # Audio & Text
20
+ soundfile
21
  noisereduce==3.0.3
22
  pydub
23
  langid
 
27
 
28
  # Japanese Text (optional)
29
  mecab-python3==1.0.9
30
+ unidic-lite==1.0.8