PlotweaverModel commited on
Commit
bad74fd
·
verified ·
1 Parent(s): e9d4fed

Upload 8 files

Browse files
Files changed (8) hide show
  1. README.md +21 -9
  2. app.py +555 -0
  3. languages.py +279 -0
  4. packages.txt +1 -0
  5. pipeline.py +260 -0
  6. qwen_engine.py +294 -0
  7. requirements.txt +10 -0
  8. tts_engine.py +146 -0
README.md CHANGED
@@ -1,13 +1,25 @@
1
  ---
2
- title: Live Commentary App
3
- emoji: 📉
4
- colorFrom: gray
5
- colorTo: indigo
6
  sdk: gradio
7
- sdk_version: 6.14.0
8
- python_version: '3.13'
9
  app_file: app.py
10
- pinned: false
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  ---
12
-
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
  ---
2
+ title: PlotWeaver - Live Commentary Translation
3
+ emoji: "\U0001F3DF\uFE0F"
4
+ colorFrom: green
5
+ colorTo: yellow
6
  sdk: gradio
7
+ sdk_version: "5.50.0"
 
8
  app_file: app.py
9
+ pinned: true
10
+ license: mit
11
+ hardware: t4-small
12
+ models:
13
+ - PlotweaverAI/whisper-small-de-en
14
+ - PlotweaverAI/nllb-200-distilled-600M-african-6lang
15
+ - PlotweaverAI/yoruba-mms-tts-new
16
+ tags:
17
+ - speech-to-speech
18
+ - translation
19
+ - dubbing
20
+ - multi-language
21
+ - football
22
+ - commentary
23
+ - streaming
24
+ short_description: Translate live English commentary to 40+ languages with AI
25
  ---
 
 
app.py ADDED
@@ -0,0 +1,555 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ PlotWeaver — Live Commentary Translation Platform
3
+ ===================================================
4
+ Event management, multi-language dubbing, live streaming.
5
+ """
6
+
7
+ import os
8
+ import time
9
+ import tempfile
10
+ import numpy as np
11
+ import re
12
+ import soundfile as sf
13
+ import gradio as gr
14
+ import logging
15
+
16
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
17
+ logger = logging.getLogger(__name__)
18
+
19
+ from languages import LANGUAGES, LANGUAGE_GROUPS, ALL_LANGUAGE_NAMES, QWEN_VOICES
20
+ from tts_engine import synthesize_chunked
21
+ from qwen_engine import dub_video_qwen, translate_chunk_qwen
22
+ from pipeline import (
23
+ load_models, transcribe, translate_text, translate_sentence,
24
+ split_into_sentences, extract_audio_from_video, get_media_duration,
25
+ stretch_audio_to_duration, mux_video_audio, tts_pipe_local,
26
+ )
27
+ import pipeline
28
+
29
+ # Load all models at startup
30
+ load_models()
31
+
32
+
33
+ # =============================================================================
34
+ # Helper functions
35
+ # =============================================================================
36
+
37
+ def get_voices_for_language(lang_name):
38
+ """Get available voices for a language based on its engine."""
39
+ config = LANGUAGES.get(lang_name, {})
40
+ engine = config.get("tts_engine", "local")
41
+ if engine == "qwen":
42
+ return QWEN_VOICES
43
+ elif engine == "yourvoic" and config.get("yourvoic_voices"):
44
+ return config["yourvoic_voices"]
45
+ elif engine == "local":
46
+ return ["Default (local model)"]
47
+ return ["Peter"]
48
+
49
+
50
+ def full_pipeline_audio(audio_input, target_language):
51
+ """Full pipeline: English audio → target language audio."""
52
+ if audio_input is None:
53
+ return None, "Please upload or record audio."
54
+
55
+ lang_config = LANGUAGES.get(target_language)
56
+ if not lang_config:
57
+ return None, f"Language '{target_language}' not configured."
58
+
59
+ sample_rate, audio_array = audio_input
60
+ audio_array = audio_array.astype(np.float32)
61
+ if audio_array.ndim > 1:
62
+ audio_array = audio_array.mean(axis=1)
63
+ if audio_array.max() > 1.0 or audio_array.min() < -1.0:
64
+ max_val = max(abs(audio_array.max()), abs(audio_array.min()))
65
+ if max_val > 0:
66
+ audio_array = audio_array / max_val
67
+
68
+ log = []
69
+ total_start = time.time()
70
+
71
+ # ASR
72
+ t0 = time.time()
73
+ english = transcribe(audio_array, sample_rate)
74
+ log.append(f"**ASR** ({time.time()-t0:.2f}s)\n{english}")
75
+ if not english:
76
+ return None, "ASR returned empty text."
77
+
78
+ # MT
79
+ t0 = time.time()
80
+ nllb_code = lang_config["nllb"]
81
+ translated, en_sents, tgt_sents = translate_text(english, nllb_code, fast=False)
82
+ log.append(f"\n**Translation** ({time.time()-t0:.2f}s)")
83
+ for e, t in zip(en_sents, tgt_sents):
84
+ log.append(f" EN: {e}\n {target_language.upper()}: {t}")
85
+ if not translated:
86
+ return None, "Translation returned empty."
87
+
88
+ # TTS
89
+ t0 = time.time()
90
+ audio_out, sr_out = synthesize_chunked(
91
+ translated, lang_config, tts_pipe=pipeline.tts_pipe_local
92
+ )
93
+ log.append(f"\n**TTS** ({time.time()-t0:.2f}s) = {len(audio_out)/sr_out:.1f}s audio")
94
+
95
+ total = time.time() - total_start
96
+ log.append(f"\n**Total: {total:.2f}s**")
97
+
98
+ return (sr_out, audio_out), "\n".join(log)
99
+
100
+
101
+ def full_pipeline_text(english_text, target_language, voice_name):
102
+ """Text-only pipeline: English text → target language audio."""
103
+ if not english_text or not english_text.strip():
104
+ return None, "Please enter English text."
105
+
106
+ lang_config = LANGUAGES.get(target_language)
107
+ if not lang_config:
108
+ return None, f"Language '{target_language}' not configured."
109
+
110
+ log = []
111
+ total_start = time.time()
112
+
113
+ # MT
114
+ t0 = time.time()
115
+ nllb_code = lang_config["nllb"]
116
+ translated, en_sents, tgt_sents = translate_text(english_text.strip(), nllb_code, fast=False)
117
+ log.append(f"**Translation** ({time.time()-t0:.2f}s)")
118
+ for e, t in zip(en_sents, tgt_sents):
119
+ log.append(f" EN: {e}\n {target_language.upper()}: {t}")
120
+ if not translated:
121
+ return None, "Translation returned empty."
122
+
123
+ # TTS
124
+ t0 = time.time()
125
+ audio_out, sr_out = synthesize_chunked(
126
+ translated, lang_config, tts_pipe=pipeline.tts_pipe_local
127
+ )
128
+ log.append(f"\n**TTS** ({time.time()-t0:.2f}s) = {len(audio_out)/sr_out:.1f}s audio")
129
+
130
+ total = time.time() - total_start
131
+ log.append(f"\n**Total: {total:.2f}s**")
132
+
133
+ return (sr_out, audio_out), "\n".join(log)
134
+
135
+
136
+ def dub_video(video_path, target_languages, dub_voice, chunk_seconds, progress=gr.Progress()):
137
+ """
138
+ Dub a video into one or more target languages.
139
+ Routes to Qwen Omni for global languages, local pipeline for African languages.
140
+ """
141
+ if video_path is None:
142
+ return None, "Please upload a video."
143
+
144
+ if not target_languages:
145
+ return None, "Please select at least one target language."
146
+
147
+ results_log = []
148
+ output_videos = []
149
+
150
+ for lang_name in target_languages:
151
+ lang_config = LANGUAGES.get(lang_name)
152
+ if not lang_config:
153
+ results_log.append(f"**{lang_name}**: not configured, skipped")
154
+ continue
155
+
156
+ engine = lang_config.get("tts_engine", "local")
157
+ results_log.append(f"\n{'='*50}")
158
+ results_log.append(f"**Dubbing: {lang_name}** (engine: {engine})")
159
+ results_log.append(f"{'='*50}")
160
+
161
+ try:
162
+ if engine == "qwen":
163
+ # Qwen Omni: end-to-end speech-to-speech (best for global languages)
164
+ qwen_lang_name = lang_config.get("qwen_name", lang_name)
165
+ voice = dub_voice if dub_voice in QWEN_VOICES else "Ethan"
166
+ out_video, log_text = dub_video_qwen(
167
+ video_path, qwen_lang_name, voice=voice,
168
+ chunk_seconds=chunk_seconds, progress_fn=progress,
169
+ )
170
+ results_log.append(log_text)
171
+ if out_video:
172
+ output_videos.append(out_video)
173
+
174
+ else:
175
+ # Local/YourVoic pipeline: ASR → NLLB → TTS
176
+ work_dir = tempfile.mkdtemp(prefix=f"dub_{lang_name}_")
177
+ extracted_audio = os.path.join(work_dir, "audio.wav")
178
+ tgt_audio_raw = os.path.join(work_dir, "tgt_raw.wav")
179
+ tgt_audio_aligned = os.path.join(work_dir, "tgt_aligned.wav")
180
+ output_video = os.path.join(work_dir, f"dubbed_{lang_name}.mp4")
181
+
182
+ progress(0.05, desc=f"{lang_name}: extracting audio...")
183
+ extract_audio_from_video(video_path, extracted_audio)
184
+ video_duration = get_media_duration(video_path)
185
+ results_log.append(f"Video: {video_duration:.1f}s")
186
+
187
+ audio_array, sr = sf.read(extracted_audio, dtype="float32")
188
+ if audio_array.ndim > 1:
189
+ audio_array = audio_array.mean(axis=1)
190
+
191
+ progress(0.15, desc=f"{lang_name}: transcribing...")
192
+ t0 = time.time()
193
+ english = transcribe(audio_array, sr)
194
+ results_log.append(f"ASR: {time.time()-t0:.1f}s")
195
+ if not english:
196
+ results_log.append("ASR empty — skipped")
197
+ continue
198
+
199
+ progress(0.4, desc=f"{lang_name}: translating...")
200
+ t0 = time.time()
201
+ nllb_code = lang_config["nllb"]
202
+ translated, _, _ = translate_text(english, nllb_code, fast=True)
203
+ results_log.append(f"MT: {time.time()-t0:.1f}s")
204
+ if not translated:
205
+ results_log.append("Translation empty — skipped")
206
+ continue
207
+
208
+ progress(0.65, desc=f"{lang_name}: synthesizing...")
209
+ t0 = time.time()
210
+ tgt_audio, tgt_sr = synthesize_chunked(
211
+ translated, lang_config, tts_pipe=pipeline.tts_pipe_local
212
+ )
213
+ sf.write(tgt_audio_raw, tgt_audio, tgt_sr)
214
+ tgt_duration = len(tgt_audio) / tgt_sr
215
+ results_log.append(f"TTS: {time.time()-t0:.1f}s ({tgt_duration:.1f}s audio)")
216
+
217
+ progress(0.85, desc=f"{lang_name}: aligning...")
218
+ MAX_STRETCH = 1.2
219
+ stretch_ratio = tgt_duration / video_duration
220
+
221
+ if stretch_ratio <= MAX_STRETCH:
222
+ if abs(stretch_ratio - 1.0) > 0.02:
223
+ stretch_audio_to_duration(tgt_audio_raw, tgt_audio_aligned, video_duration)
224
+ else:
225
+ import shutil
226
+ shutil.copy(tgt_audio_raw, tgt_audio_aligned)
227
+ extend_video = False
228
+ final_duration = video_duration
229
+ else:
230
+ import shutil
231
+ shutil.copy(tgt_audio_raw, tgt_audio_aligned)
232
+ extend_video = True
233
+ final_duration = tgt_duration
234
+ results_log.append(f"Audio longer ({stretch_ratio:.1f}x) — extending video")
235
+
236
+ progress(0.95, desc=f"{lang_name}: combining...")
237
+ mux_video_audio(
238
+ video_path, tgt_audio_aligned, output_video,
239
+ extend_video=extend_video, target_duration=final_duration
240
+ )
241
+ output_videos.append(output_video)
242
+
243
+ except Exception as e:
244
+ logger.exception(f"Dubbing {lang_name} failed")
245
+ results_log.append(f"Error: {str(e)}")
246
+
247
+ progress(1.0, desc="Done!")
248
+ final_video = output_videos[0] if output_videos else None
249
+ return final_video, "\n".join(results_log)
250
+
251
+
252
+ def update_voices(language):
253
+ """Update voice dropdown when language changes."""
254
+ voices = get_voices_for_language(language)
255
+ return gr.update(choices=voices, value=voices[0])
256
+
257
+
258
+ # =============================================================================
259
+ # Gradio UI
260
+ # =============================================================================
261
+
262
+ EXAMPLES = [
263
+ "And it's a brilliant goal from the striker!",
264
+ "The referee has shown a yellow card. Corner kick for the home team.",
265
+ "What a save by the goalkeeper! The match is heading into injury time.",
266
+ "He dribbles past two defenders and shoots! The ball hits the back of the net!",
267
+ ]
268
+
269
+ CSS = """
270
+ .main-header { text-align: center; margin-bottom: 0.5rem; }
271
+ .main-header h1 { font-size: 1.8rem; font-weight: 700; margin: 0; }
272
+ .main-header p { color: #666; font-size: 0.95rem; }
273
+ .lang-group-label { font-weight: 600; font-size: 0.85rem; color: #888; text-transform: uppercase; letter-spacing: 0.05em; margin-top: 0.5rem; }
274
+ """
275
+
276
+ with gr.Blocks(
277
+ title="PlotWeaver — Live Commentary Translation",
278
+ theme=gr.themes.Soft(),
279
+ css=CSS,
280
+ ) as demo:
281
+
282
+ gr.HTML("""
283
+ <div class="main-header">
284
+ <h1>PlotWeaver</h1>
285
+ <p>Live commentary translation platform &mdash; English to 40+ languages</p>
286
+ <p style="font-size:0.8rem; color:#999">ASR (Whisper) &rarr; MT (NLLB-200) &rarr; TTS (YourVoic + local models)</p>
287
+ </div>
288
+ """)
289
+
290
+ with gr.Tabs():
291
+
292
+ # ====== TAB 1: EVENT MANAGEMENT ======
293
+ with gr.TabItem("Event Management"):
294
+ gr.Markdown("### Create new event")
295
+ gr.Markdown("Configure your live broadcast event with target languages and input source.")
296
+
297
+ with gr.Row():
298
+ with gr.Column(scale=2):
299
+ event_name = gr.Textbox(
300
+ label="Event name",
301
+ placeholder="e.g. Premier League: Arsenal vs. Chelsea",
302
+ )
303
+ with gr.Row():
304
+ start_time = gr.Textbox(label="Start time", placeholder="08:30 PM")
305
+ end_time = gr.Textbox(label="End time", placeholder="10:30 PM")
306
+ event_date = gr.Textbox(label="Date", placeholder="2026-06-06")
307
+
308
+ gr.Markdown("#### Input source")
309
+ input_method = gr.Radio(
310
+ choices=["RTMP Stream", "WebRTC (Browser)", "Direct Audio Feed"],
311
+ value="RTMP Stream",
312
+ label="Input method",
313
+ )
314
+
315
+ gr.Markdown("#### Target languages")
316
+ gr.Markdown("Select languages for simultaneous broadcast. Additional languages consume more stream minutes.")
317
+
318
+ # Language checkboxes grouped by category
319
+ target_langs = gr.CheckboxGroup(
320
+ choices=ALL_LANGUAGE_NAMES,
321
+ label="Languages",
322
+ value=["Yoruba"],
323
+ )
324
+
325
+ with gr.Column(scale=1):
326
+ gr.Markdown("#### Estimate summary")
327
+ estimate_display = gr.Markdown(
328
+ value="**Event:** Not configured\n\n**Languages:** 1 selected\n\n**Estimated duration:** --\n\n**Total estimate:** --"
329
+ )
330
+ create_event_btn = gr.Button("Create Event", variant="primary", size="lg")
331
+ event_status = gr.Markdown("")
332
+
333
+ def update_estimate(name, langs, start, end):
334
+ n_langs = len(langs) if langs else 0
335
+ lang_list = ", ".join(langs) if langs else "None"
336
+ return (
337
+ f"**Event:** {name or 'Not set'}\n\n"
338
+ f"**Languages:** {n_langs} selected\n\n"
339
+ f"{lang_list}\n\n"
340
+ f"**Input:** Configured\n\n"
341
+ f"**Rate:** 1x (Standard)"
342
+ )
343
+
344
+ for inp in [event_name, target_langs, start_time, end_time]:
345
+ inp.change(
346
+ fn=update_estimate,
347
+ inputs=[event_name, target_langs, start_time, end_time],
348
+ outputs=[estimate_display],
349
+ )
350
+
351
+ def create_event(name, langs):
352
+ if not name:
353
+ return "Please enter an event name."
354
+ if not langs:
355
+ return "Please select at least one language."
356
+ return f"Event **{name}** created with {len(langs)} languages: {', '.join(langs)}"
357
+
358
+ create_event_btn.click(
359
+ fn=create_event,
360
+ inputs=[event_name, target_langs],
361
+ outputs=[event_status],
362
+ )
363
+
364
+ # ====== TAB 2: LIVE STUDIO ======
365
+ with gr.TabItem("Live Studio"):
366
+ gr.Markdown("### Live streaming translation")
367
+ gr.Markdown("Record or stream English commentary and hear it translated in real-time.")
368
+
369
+ with gr.Row():
370
+ studio_language = gr.Dropdown(
371
+ choices=ALL_LANGUAGE_NAMES,
372
+ value="Yoruba",
373
+ label="Target language",
374
+ )
375
+ studio_voice = gr.Dropdown(
376
+ choices=get_voices_for_language("Yoruba"),
377
+ value=get_voices_for_language("Yoruba")[0],
378
+ label="Voice",
379
+ )
380
+
381
+ studio_language.change(
382
+ fn=update_voices,
383
+ inputs=[studio_language],
384
+ outputs=[studio_voice],
385
+ )
386
+
387
+ with gr.Row():
388
+ with gr.Column():
389
+ studio_audio_in = gr.Audio(
390
+ label="English commentary (upload or record)",
391
+ type="numpy",
392
+ sources=["upload", "microphone"],
393
+ )
394
+ studio_translate_btn = gr.Button("Translate", variant="primary", size="lg")
395
+
396
+ with gr.Column():
397
+ studio_audio_out = gr.Audio(label="Translated audio", type="numpy", autoplay=True)
398
+ studio_log = gr.Markdown(label="Pipeline log")
399
+
400
+ studio_translate_btn.click(
401
+ fn=full_pipeline_audio,
402
+ inputs=[studio_audio_in, studio_language],
403
+ outputs=[studio_audio_out, studio_log],
404
+ )
405
+
406
+ # ====== TAB 3: VIDEO DUBBING ======
407
+ with gr.TabItem("Video Dubbing"):
408
+ gr.Markdown("### Video dubbing (English → multi-language)")
409
+ gr.Markdown(
410
+ "Upload a video with English commentary and get back a dubbed version. "
411
+ "**Global languages** (Arabic, French, Spanish, etc.) use Qwen Omni for best quality. "
412
+ "**African languages** (Yoruba, Hausa, etc.) use the local Whisper → NLLB → MMS-TTS pipeline."
413
+ )
414
+
415
+ with gr.Row():
416
+ with gr.Column():
417
+ dub_video_in = gr.Video(label="Upload English video", sources=["upload"])
418
+ dub_languages = gr.CheckboxGroup(
419
+ choices=ALL_LANGUAGE_NAMES,
420
+ label="Target languages",
421
+ value=["Yoruba"],
422
+ )
423
+ with gr.Row():
424
+ dub_voice = gr.Dropdown(
425
+ choices=QWEN_VOICES,
426
+ value="Ethan",
427
+ label="Voice (for Qwen languages)",
428
+ info="Applies to Arabic, French, Spanish, etc. Local languages use default voice.",
429
+ )
430
+ dub_chunk_slider = gr.Slider(
431
+ minimum=30, maximum=300, value=120, step=10,
432
+ label="Chunk duration (seconds)",
433
+ info="Shorter = more API calls but less timeout risk.",
434
+ )
435
+ dub_btn = gr.Button("Dub Video", variant="primary", size="lg")
436
+
437
+ with gr.Column():
438
+ dub_video_out = gr.Video(label="Dubbed video (download from player)")
439
+ dub_log = gr.Markdown(
440
+ label="Processing log",
441
+ value="Upload a video and select languages to start."
442
+ )
443
+
444
+ dub_btn.click(
445
+ fn=dub_video,
446
+ inputs=[dub_video_in, dub_languages, dub_voice, dub_chunk_slider],
447
+ outputs=[dub_video_out, dub_log],
448
+ )
449
+
450
+ # ====== TAB 4: TEXT TRANSLATION ======
451
+ with gr.TabItem("Text \u2192 Audio"):
452
+ gr.Markdown("### Text to translated speech")
453
+ gr.Markdown("Type English text, choose a language, and hear the translated audio.")
454
+
455
+ with gr.Row():
456
+ text_language = gr.Dropdown(
457
+ choices=ALL_LANGUAGE_NAMES,
458
+ value="Yoruba",
459
+ label="Target language",
460
+ )
461
+ text_voice = gr.Dropdown(
462
+ choices=get_voices_for_language("Yoruba"),
463
+ value=get_voices_for_language("Yoruba")[0],
464
+ label="Voice",
465
+ )
466
+
467
+ text_language.change(
468
+ fn=update_voices,
469
+ inputs=[text_language],
470
+ outputs=[text_voice],
471
+ )
472
+
473
+ with gr.Row():
474
+ with gr.Column():
475
+ text_input = gr.Textbox(
476
+ label="English text",
477
+ placeholder="Type English football commentary here...",
478
+ lines=4,
479
+ )
480
+ text_btn = gr.Button("Translate to speech", variant="primary", size="lg")
481
+ gr.Examples(
482
+ examples=[[e] for e in EXAMPLES],
483
+ inputs=[text_input],
484
+ label="Example commentary",
485
+ )
486
+
487
+ with gr.Column():
488
+ text_audio_out = gr.Audio(label="Translated audio", type="numpy", autoplay=True)
489
+ text_log = gr.Markdown(label="Pipeline log")
490
+
491
+ text_btn.click(
492
+ fn=full_pipeline_text,
493
+ inputs=[text_input, text_language, text_voice],
494
+ outputs=[text_audio_out, text_log],
495
+ )
496
+
497
+ # ====== TAB 5: RECORDINGS ======
498
+ with gr.TabItem("Recordings & Clips"):
499
+ gr.Markdown("### Recordings management")
500
+ gr.Markdown(
501
+ "Past dubbed recordings will appear here. "
502
+ "This feature is coming soon — for now, use Video Dubbing to create new recordings "
503
+ "and download them from the player."
504
+ )
505
+
506
+ # ====== TAB 6: VOICE MODELS ======
507
+ with gr.TabItem("Voice Models"):
508
+ gr.Markdown("### Voice model library")
509
+ gr.Markdown("Browse available voices for each language.")
510
+
511
+ voice_lang_select = gr.Dropdown(
512
+ choices=ALL_LANGUAGE_NAMES,
513
+ value="Yoruba",
514
+ label="Select language",
515
+ )
516
+ voice_info = gr.Markdown()
517
+
518
+ def show_voice_info(lang):
519
+ config = LANGUAGES.get(lang, {})
520
+ engine = config.get("tts_engine", "unknown")
521
+ voices = config.get("yourvoic_voices", [])
522
+
523
+ info = f"### {lang}\n\n"
524
+ if engine == "qwen":
525
+ info += f"**Engine:** Qwen 3.5 Omni (end-to-end speech-to-speech)\n\n"
526
+ info += f"This is the highest quality option. Qwen handles ASR + translation + TTS in a single API call, "
527
+ info += f"preserving tone, emotion, and pacing from the original speaker.\n\n"
528
+ info += f"**Available voices ({len(QWEN_VOICES)}):** {', '.join(QWEN_VOICES[:10])}... and {len(QWEN_VOICES)-10} more\n\n"
529
+ info += f"All voices support all Qwen languages."
530
+ elif engine == "yourvoic":
531
+ info += f"**Engine:** YourVoic API (TTS) + NLLB-200 (translation)\n\n"
532
+ info += f"**YourVoic language:** `{config.get('yourvoic_lang', 'N/A')}`\n\n"
533
+ info += f"**Available voices:** {', '.join(voices) if voices else 'Peter (default)'}"
534
+ else:
535
+ info += f"**Engine:** Local pipeline (Whisper ASR + NLLB MT + MMS-TTS)\n\n"
536
+ info += f"**NLLB code:** `{config.get('nllb', 'N/A')}`\n\n"
537
+ info += "Uses locally fine-tuned models on GPU. Voice selection not available."
538
+
539
+ return info
540
+
541
+ voice_lang_select.change(fn=show_voice_info, inputs=[voice_lang_select], outputs=[voice_info])
542
+ demo.load(fn=show_voice_info, inputs=[voice_lang_select], outputs=[voice_info])
543
+
544
+ gr.Markdown("""
545
+ ---
546
+ **PlotWeaver** by PlotweaverAI | Models:
547
+ [ASR](https://huggingface.co/PlotweaverAI/whisper-small-de-en) |
548
+ [MT](https://huggingface.co/PlotweaverAI/nllb-200-distilled-600M-african-6lang) |
549
+ [TTS](https://huggingface.co/PlotweaverAI/yoruba-mms-tts-new) |
550
+ [YourVoic API](https://yourvoic.com)
551
+ """)
552
+
553
+
554
+ if __name__ == "__main__":
555
+ demo.launch()
languages.py ADDED
@@ -0,0 +1,279 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Language configuration for PlotWeaver.
3
+ Three TTS/translation engines:
4
+ 1. "qwen" — Qwen 3.5 Omni (end-to-end speech-to-speech, best for global languages)
5
+ 2. "yourvoic" — YourVoic API (TTS only, paired with NLLB MT)
6
+ 3. "local" — Local MMS-TTS on GPU (for Yoruba, Hausa, etc.), paired with NLLB MT
7
+ """
8
+
9
+ # Qwen Omni voices (work across all Qwen-supported languages)
10
+ QWEN_VOICES = [
11
+ "Cherry", "Serena", "Ethan", "Chelsie", "Momo", "Vivian", "Moon", "Maia",
12
+ "Kai", "Nofish", "Bella", "Jennifer", "Ryan", "Katerina", "Aiden",
13
+ "Eldric Sage", "Mia", "Mochi", "Bellona", "Vincent", "Bunny", "Neil",
14
+ "Elias", "Arthur", "Seren", "Bodega", "Sonrisa", "Alek", "Dolce",
15
+ "Sohee", "Ono Anna", "Lenn", "Emilien", "Andre",
16
+ ]
17
+
18
+ # Each language entry:
19
+ # "Display Name": {
20
+ # "nllb": NLLB-200 language code (for local/yourvoic pipeline translation),
21
+ # "yourvoic_lang": YourVoic language code (or None),
22
+ # "yourvoic_voices": list of YourVoic voice names,
23
+ # "tts_engine": "qwen" | "yourvoic" | "local",
24
+ # "qwen_code": short language code for Qwen prompts (or None),
25
+ # "qwen_name": full language name for Qwen system prompt (or None),
26
+ # }
27
+
28
+ LANGUAGES = {
29
+ # ---- Global Languages (Qwen Omni — best quality) ----
30
+ "Arabic": {
31
+ "nllb": "arb_Arab", "yourvoic_lang": "ar-SA",
32
+ "yourvoic_voices": ["Peter"], "tts_engine": "qwen",
33
+ "qwen_code": "ar", "qwen_name": "Modern Standard Arabic (العربية الفصحى)",
34
+ },
35
+ "Spanish": {
36
+ "nllb": "spa_Latn", "yourvoic_lang": "es-ES",
37
+ "yourvoic_voices": ["Peter", "Kylie"], "tts_engine": "qwen",
38
+ "qwen_code": "es", "qwen_name": "Spanish",
39
+ },
40
+ "French": {
41
+ "nllb": "fra_Latn", "yourvoic_lang": "fr-FR",
42
+ "yourvoic_voices": ["Peter", "Kylie"], "tts_engine": "qwen",
43
+ "qwen_code": "fr", "qwen_name": "French",
44
+ },
45
+ "German": {
46
+ "nllb": "deu_Latn", "yourvoic_lang": "de-DE",
47
+ "yourvoic_voices": ["Peter", "Kylie"], "tts_engine": "qwen",
48
+ "qwen_code": "de", "qwen_name": "German",
49
+ },
50
+ "Mandarin": {
51
+ "nllb": "zho_Hans", "yourvoic_lang": "zh-CN",
52
+ "yourvoic_voices": ["Peter", "Kylie"], "tts_engine": "qwen",
53
+ "qwen_code": "zh", "qwen_name": "Mandarin Chinese",
54
+ },
55
+ "Italian": {
56
+ "nllb": "ita_Latn", "yourvoic_lang": "it-IT",
57
+ "yourvoic_voices": ["Peter", "Kylie"], "tts_engine": "qwen",
58
+ "qwen_code": "it", "qwen_name": "Italian",
59
+ },
60
+ "Japanese": {
61
+ "nllb": "jpn_Jpan", "yourvoic_lang": "ja-JP",
62
+ "yourvoic_voices": ["Peter", "Kylie"], "tts_engine": "qwen",
63
+ "qwen_code": "ja", "qwen_name": "Japanese",
64
+ },
65
+ "Portuguese": {
66
+ "nllb": "por_Latn", "yourvoic_lang": "pt-BR",
67
+ "yourvoic_voices": ["Peter", "Kylie"], "tts_engine": "qwen",
68
+ "qwen_code": "pt", "qwen_name": "Portuguese",
69
+ },
70
+ "Hindi": {
71
+ "nllb": "hin_Deva", "yourvoic_lang": "hi-IN",
72
+ "yourvoic_voices": ["Rahul", "Deepika", "Aditya"], "tts_engine": "qwen",
73
+ "qwen_code": "hi", "qwen_name": "Hindi",
74
+ },
75
+ "Korean": {
76
+ "nllb": "kor_Hang", "yourvoic_lang": "ko-KR",
77
+ "yourvoic_voices": ["Peter", "Kylie"], "tts_engine": "qwen",
78
+ "qwen_code": "ko", "qwen_name": "Korean",
79
+ },
80
+ "Russian": {
81
+ "nllb": "rus_Cyrl", "yourvoic_lang": "ru-RU",
82
+ "yourvoic_voices": ["Peter", "Kylie"], "tts_engine": "qwen",
83
+ "qwen_code": "ru", "qwen_name": "Russian",
84
+ },
85
+
86
+ # ---- African Languages (Local pipeline: Whisper → NLLB → MMS-TTS) ----
87
+ "Yoruba": {
88
+ "nllb": "yor_Latn", "yourvoic_lang": None,
89
+ "yourvoic_voices": [], "tts_engine": "local",
90
+ "qwen_code": None, "qwen_name": None,
91
+ },
92
+ "Hausa": {
93
+ "nllb": "hau_Latn", "yourvoic_lang": None,
94
+ "yourvoic_voices": [], "tts_engine": "local",
95
+ "qwen_code": None, "qwen_name": None,
96
+ },
97
+ "Igbo": {
98
+ "nllb": "ibo_Latn", "yourvoic_lang": None,
99
+ "yourvoic_voices": [], "tts_engine": "local",
100
+ "qwen_code": None, "qwen_name": None,
101
+ },
102
+ "Swahili": {
103
+ "nllb": "swh_Latn", "yourvoic_lang": "sw-KE",
104
+ "yourvoic_voices": ["Peter"], "tts_engine": "yourvoic",
105
+ "qwen_code": None, "qwen_name": None,
106
+ },
107
+ "Zulu": {
108
+ "nllb": "zul_Latn", "yourvoic_lang": None,
109
+ "yourvoic_voices": [], "tts_engine": "local",
110
+ "qwen_code": None, "qwen_name": None,
111
+ },
112
+ "Amharic": {
113
+ "nllb": "amh_Ethi", "yourvoic_lang": "am-ET",
114
+ "yourvoic_voices": ["Peter"], "tts_engine": "yourvoic",
115
+ "qwen_code": None, "qwen_name": None,
116
+ },
117
+ "Afrikaans": {
118
+ "nllb": "afr_Latn", "yourvoic_lang": "af-ZA",
119
+ "yourvoic_voices": ["Peter"], "tts_engine": "yourvoic",
120
+ "qwen_code": None, "qwen_name": None,
121
+ },
122
+
123
+ # ---- South Asian (YourVoic TTS + NLLB MT) ----
124
+ "Bengali": {
125
+ "nllb": "ben_Beng", "yourvoic_lang": "bn-IN",
126
+ "yourvoic_voices": ["Sneha", "Aryan"], "tts_engine": "yourvoic",
127
+ "qwen_code": None, "qwen_name": None,
128
+ },
129
+ "Tamil": {
130
+ "nllb": "tam_Taml", "yourvoic_lang": "ta-IN",
131
+ "yourvoic_voices": ["Priya", "Kumar"], "tts_engine": "yourvoic",
132
+ "qwen_code": None, "qwen_name": None,
133
+ },
134
+ "Telugu": {
135
+ "nllb": "tel_Telu", "yourvoic_lang": "te-IN",
136
+ "yourvoic_voices": ["Arjun", "Lakshmi"], "tts_engine": "yourvoic",
137
+ "qwen_code": None, "qwen_name": None,
138
+ },
139
+ "Marathi": {
140
+ "nllb": "mar_Deva", "yourvoic_lang": "mr-IN",
141
+ "yourvoic_voices": ["Anjali", "Rohan"], "tts_engine": "yourvoic",
142
+ "qwen_code": None, "qwen_name": None,
143
+ },
144
+ "Urdu": {
145
+ "nllb": "urd_Arab", "yourvoic_lang": "ur-PK",
146
+ "yourvoic_voices": ["Peter"], "tts_engine": "yourvoic",
147
+ "qwen_code": None, "qwen_name": None,
148
+ },
149
+ "Nepali": {
150
+ "nllb": "npi_Deva", "yourvoic_lang": "ne-NP",
151
+ "yourvoic_voices": ["Peter"], "tts_engine": "yourvoic",
152
+ "qwen_code": None, "qwen_name": None,
153
+ },
154
+
155
+ # ---- Southeast Asian (YourVoic) ----
156
+ "Indonesian": {
157
+ "nllb": "ind_Latn", "yourvoic_lang": "id-ID",
158
+ "yourvoic_voices": ["Peter"], "tts_engine": "yourvoic",
159
+ "qwen_code": None, "qwen_name": None,
160
+ },
161
+ "Vietnamese": {
162
+ "nllb": "vie_Latn", "yourvoic_lang": "vi-VN",
163
+ "yourvoic_voices": ["Peter"], "tts_engine": "yourvoic",
164
+ "qwen_code": None, "qwen_name": None,
165
+ },
166
+ "Thai": {
167
+ "nllb": "tha_Thai", "yourvoic_lang": "th-TH",
168
+ "yourvoic_voices": ["Peter"], "tts_engine": "yourvoic",
169
+ "qwen_code": None, "qwen_name": None,
170
+ },
171
+ "Malay": {
172
+ "nllb": "zsm_Latn", "yourvoic_lang": "ms-MY",
173
+ "yourvoic_voices": ["Peter"], "tts_engine": "yourvoic",
174
+ "qwen_code": None, "qwen_name": None,
175
+ },
176
+ "Filipino": {
177
+ "nllb": "tgl_Latn", "yourvoic_lang": "fil-PH",
178
+ "yourvoic_voices": ["Peter"], "tts_engine": "yourvoic",
179
+ "qwen_code": None, "qwen_name": None,
180
+ },
181
+
182
+ # ---- European (YourVoic) ----
183
+ "Dutch": {
184
+ "nllb": "nld_Latn", "yourvoic_lang": "nl-NL",
185
+ "yourvoic_voices": ["Peter"], "tts_engine": "yourvoic",
186
+ "qwen_code": None, "qwen_name": None,
187
+ },
188
+ "Polish": {
189
+ "nllb": "pol_Latn", "yourvoic_lang": "pl-PL",
190
+ "yourvoic_voices": ["Peter"], "tts_engine": "yourvoic",
191
+ "qwen_code": None, "qwen_name": None,
192
+ },
193
+ "Turkish": {
194
+ "nllb": "tur_Latn", "yourvoic_lang": "tr-TR",
195
+ "yourvoic_voices": ["Peter"], "tts_engine": "yourvoic",
196
+ "qwen_code": None, "qwen_name": None,
197
+ },
198
+ "Swedish": {
199
+ "nllb": "swe_Latn", "yourvoic_lang": "sv-SE",
200
+ "yourvoic_voices": ["Peter"], "tts_engine": "yourvoic",
201
+ "qwen_code": None, "qwen_name": None,
202
+ },
203
+ "Romanian": {
204
+ "nllb": "ron_Latn", "yourvoic_lang": "ro-RO",
205
+ "yourvoic_voices": ["Peter"], "tts_engine": "yourvoic",
206
+ "qwen_code": None, "qwen_name": None,
207
+ },
208
+ "Greek": {
209
+ "nllb": "ell_Grek", "yourvoic_lang": "el-GR",
210
+ "yourvoic_voices": ["Peter"], "tts_engine": "yourvoic",
211
+ "qwen_code": None, "qwen_name": None,
212
+ },
213
+ "Ukrainian": {
214
+ "nllb": "ukr_Cyrl", "yourvoic_lang": "uk-UA",
215
+ "yourvoic_voices": ["Peter"], "tts_engine": "yourvoic",
216
+ "qwen_code": None, "qwen_name": None,
217
+ },
218
+ "Finnish": {
219
+ "nllb": "fin_Latn", "yourvoic_lang": "fi-FI",
220
+ "yourvoic_voices": ["Peter"], "tts_engine": "yourvoic",
221
+ "qwen_code": None, "qwen_name": None,
222
+ },
223
+ "Danish": {
224
+ "nllb": "dan_Latn", "yourvoic_lang": "da-DK",
225
+ "yourvoic_voices": ["Peter"], "tts_engine": "yourvoic",
226
+ "qwen_code": None, "qwen_name": None,
227
+ },
228
+ "Norwegian": {
229
+ "nllb": "nob_Latn", "yourvoic_lang": "nb-NO",
230
+ "yourvoic_voices": ["Peter"], "tts_engine": "yourvoic",
231
+ "qwen_code": None, "qwen_name": None,
232
+ },
233
+
234
+ # ---- Middle Eastern (YourVoic) ----
235
+ "Persian": {
236
+ "nllb": "pes_Arab", "yourvoic_lang": "fa-IR",
237
+ "yourvoic_voices": ["Peter"], "tts_engine": "yourvoic",
238
+ "qwen_code": None, "qwen_name": None,
239
+ },
240
+ "Hebrew": {
241
+ "nllb": "heb_Hebr", "yourvoic_lang": "he-IL",
242
+ "yourvoic_voices": ["Peter"], "tts_engine": "yourvoic",
243
+ "qwen_code": None, "qwen_name": None,
244
+ },
245
+ }
246
+
247
+
248
+ # Group languages by category for the UI
249
+ LANGUAGE_GROUPS = {
250
+ "Global Languages": [
251
+ "Spanish", "French", "German", "Mandarin", "Italian",
252
+ "Japanese", "Portuguese", "Hindi", "Arabic", "Korean", "Russian",
253
+ ],
254
+ "African Languages": [
255
+ "Yoruba", "Hausa", "Igbo", "Swahili", "Zulu", "Amharic", "Afrikaans",
256
+ ],
257
+ "South Asian": [
258
+ "Bengali", "Tamil", "Telugu", "Marathi", "Urdu", "Nepali",
259
+ ],
260
+ "Southeast Asian": [
261
+ "Indonesian", "Vietnamese", "Thai", "Malay", "Filipino",
262
+ ],
263
+ "European": [
264
+ "Dutch", "Polish", "Turkish", "Swedish", "Romanian",
265
+ "Greek", "Ukrainian", "Finnish", "Danish", "Norwegian",
266
+ ],
267
+ "Middle Eastern": [
268
+ "Persian", "Hebrew",
269
+ ],
270
+ }
271
+
272
+ # All language display names (for dropdowns)
273
+ ALL_LANGUAGE_NAMES = sorted(LANGUAGES.keys())
274
+
275
+ # Languages that use local TTS (your fine-tuned models)
276
+ LOCAL_TTS_LANGUAGES = [k for k, v in LANGUAGES.items() if v["tts_engine"] == "local"]
277
+
278
+ # Languages that use YourVoic API
279
+ YOURVOIC_LANGUAGES = [k for k, v in LANGUAGES.items() if v["tts_engine"] == "yourvoic"]
packages.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ ffmpeg
pipeline.py ADDED
@@ -0,0 +1,260 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Core pipeline: ASR (Whisper) + MT (NLLB-200) functions.
3
+ TTS is handled by tts_engine.py.
4
+ """
5
+
6
+ import torch
7
+ import numpy as np
8
+ import re
9
+ import time
10
+ import os
11
+ import subprocess
12
+ import tempfile
13
+ import logging
14
+ import soundfile as sf
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+ DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
19
+ TORCH_DTYPE = torch.float16 if torch.cuda.is_available() else torch.float32
20
+
21
+ # Models (loaded once at startup)
22
+ asr_pipe = None
23
+ mt_tokenizer = None
24
+ mt_model = None
25
+ tts_pipe_local = None # Local TTS for Yoruba/Hausa/Igbo/Zulu
26
+
27
+
28
+ def load_models():
29
+ """Load all models at startup."""
30
+ global asr_pipe, mt_tokenizer, mt_model, tts_pipe_local
31
+ from transformers import (
32
+ pipeline as hf_pipeline,
33
+ AutoTokenizer,
34
+ AutoModelForSeq2SeqLM,
35
+ )
36
+
37
+ print(f"Device: {DEVICE} | Dtype: {TORCH_DTYPE}")
38
+ print("Loading models...")
39
+
40
+ # ASR
41
+ ASR_MODEL_ID = "PlotweaverAI/whisper-small-de-en"
42
+ print(f" Loading ASR: {ASR_MODEL_ID}")
43
+ asr_pipe = hf_pipeline(
44
+ "automatic-speech-recognition",
45
+ model=ASR_MODEL_ID,
46
+ device=DEVICE,
47
+ torch_dtype=TORCH_DTYPE,
48
+ )
49
+ print(" ASR loaded")
50
+
51
+ # MT
52
+ MT_MODEL_ID = "PlotweaverAI/nllb-200-distilled-600M-african-6lang"
53
+ print(f" Loading MT: {MT_MODEL_ID}")
54
+ mt_tokenizer = AutoTokenizer.from_pretrained(MT_MODEL_ID)
55
+ mt_model = AutoModelForSeq2SeqLM.from_pretrained(
56
+ MT_MODEL_ID, torch_dtype=TORCH_DTYPE
57
+ ).to(DEVICE)
58
+ mt_tokenizer.src_lang = "eng_Latn"
59
+ print(" MT loaded")
60
+
61
+ # Local TTS (Yoruba)
62
+ TTS_MODEL_ID = "PlotweaverAI/yoruba-mms-tts-new"
63
+ print(f" Loading local TTS: {TTS_MODEL_ID}")
64
+ tts_pipe_local = hf_pipeline(
65
+ "text-to-speech",
66
+ model=TTS_MODEL_ID,
67
+ device=DEVICE,
68
+ torch_dtype=TORCH_DTYPE,
69
+ )
70
+ print(" Local TTS loaded")
71
+
72
+ # Diagnostics
73
+ print(f"\n=== Device diagnostics ===")
74
+ print(f"CUDA available: {torch.cuda.is_available()}")
75
+ if torch.cuda.is_available():
76
+ print(f"CUDA device: {torch.cuda.get_device_name(0)}")
77
+ print(f"ASR on: {next(asr_pipe.model.parameters()).device}")
78
+ print(f"MT on: {next(mt_model.parameters()).device}")
79
+ print(f"TTS on: {next(tts_pipe_local.model.parameters()).device}")
80
+ print(f"YourVoic API key: {'set' if os.environ.get('YOURVOIC_API_KEY') else 'NOT SET'}")
81
+ print(f"==========================\n")
82
+ print("All models loaded!")
83
+
84
+
85
+ # ---- Text Processing ----
86
+
87
+ def split_into_sentences(text):
88
+ """Split raw ASR text into individual sentences."""
89
+ text = text.strip()
90
+ if not text:
91
+ return []
92
+ text = '. '.join(s.strip().capitalize() for s in text.split('. ') if s.strip())
93
+ if re.search(r'[.!?]', text):
94
+ sentences = re.split(r'(?<=[.!?])\s+', text)
95
+ return [s.strip() for s in sentences if s.strip()]
96
+ words = text.split()
97
+ MAX_WORDS = 12
98
+ sentences = []
99
+ for i in range(0, len(words), MAX_WORDS):
100
+ chunk = ' '.join(words[i:i + MAX_WORDS])
101
+ if not chunk.endswith(('.', '!', '?')):
102
+ chunk += '.'
103
+ chunk = chunk[0].upper() + chunk[1:] if len(chunk) > 1 else chunk.upper()
104
+ sentences.append(chunk)
105
+ return sentences
106
+
107
+
108
+ # ---- ASR ----
109
+
110
+ def transcribe(audio_array, sample_rate=16000):
111
+ """ASR: English audio to text. Handles both short and long audio."""
112
+ if len(audio_array) < 1600:
113
+ return ""
114
+
115
+ duration_s = len(audio_array) / sample_rate
116
+
117
+ if sample_rate != 16000:
118
+ import torchaudio.functional as F_audio
119
+ audio_tensor = torch.from_numpy(audio_array).float()
120
+ audio_tensor = F_audio.resample(audio_tensor, sample_rate, 16000)
121
+ audio_array = audio_tensor.numpy()
122
+ sample_rate = 16000
123
+
124
+ if duration_s <= 28:
125
+ result = asr_pipe(
126
+ {"raw": audio_array, "sampling_rate": sample_rate},
127
+ return_timestamps=False,
128
+ )
129
+ return result["text"].strip()
130
+
131
+ # Long-form: native Whisper generate
132
+ model = asr_pipe.model
133
+ processor = asr_pipe.feature_extractor
134
+ tokenizer = asr_pipe.tokenizer
135
+
136
+ inputs = processor(
137
+ audio_array, sampling_rate=16000, return_tensors="pt",
138
+ truncation=False, padding="longest", return_attention_mask=True,
139
+ )
140
+ input_features = inputs.input_features.to(DEVICE, dtype=TORCH_DTYPE)
141
+ attention_mask = inputs.attention_mask.to(DEVICE) if "attention_mask" in inputs else None
142
+
143
+ generate_kwargs = {"return_timestamps": True, "language": "en", "task": "transcribe"}
144
+ if attention_mask is not None:
145
+ generate_kwargs["attention_mask"] = attention_mask
146
+
147
+ with torch.no_grad():
148
+ predicted_ids = model.generate(input_features, **generate_kwargs)
149
+
150
+ transcription = tokenizer.batch_decode(predicted_ids, skip_special_tokens=True)[0]
151
+ return transcription.strip()
152
+
153
+
154
+ # ---- MT ----
155
+
156
+ def translate_sentence(text, target_nllb_code, fast=True, max_length=256):
157
+ """Translate a single sentence from English to target language."""
158
+ inputs = mt_tokenizer(text, return_tensors="pt", truncation=True).to(DEVICE)
159
+ tgt_lang_id = mt_tokenizer.convert_tokens_to_ids(target_nllb_code)
160
+
161
+ generate_kwargs = {
162
+ "forced_bos_token_id": tgt_lang_id,
163
+ "repetition_penalty": 1.5,
164
+ "no_repeat_ngram_size": 3,
165
+ }
166
+ if fast:
167
+ generate_kwargs.update({"max_length": 128, "num_beams": 1, "do_sample": False})
168
+ else:
169
+ generate_kwargs.update({"max_length": max_length, "num_beams": 4, "early_stopping": True})
170
+
171
+ with torch.no_grad():
172
+ output_ids = mt_model.generate(**inputs, **generate_kwargs)
173
+
174
+ return mt_tokenizer.decode(output_ids[0], skip_special_tokens=True)
175
+
176
+
177
+ def translate_text(text, target_nllb_code, fast=True):
178
+ """Split and translate full text sentence-by-sentence."""
179
+ sentences = split_into_sentences(text)
180
+ if not sentences:
181
+ return "", [], []
182
+ translations = []
183
+ for s in sentences:
184
+ yo = translate_sentence(s, target_nllb_code, fast=fast)
185
+ translations.append(yo)
186
+ return ' '.join(translations), sentences, translations
187
+
188
+
189
+ # ---- Video Processing ----
190
+
191
+ def extract_audio_from_video(video_path, output_path, target_sr=16000):
192
+ """Extract audio track from video as 16kHz mono WAV."""
193
+ cmd = [
194
+ "ffmpeg", "-y", "-i", video_path,
195
+ "-vn", "-acodec", "pcm_s16le", "-ar", str(target_sr), "-ac", "1",
196
+ output_path,
197
+ ]
198
+ result = subprocess.run(cmd, capture_output=True, text=True)
199
+ if result.returncode != 0:
200
+ raise RuntimeError(f"ffmpeg extraction failed: {result.stderr[:200]}")
201
+ return output_path
202
+
203
+
204
+ def get_media_duration(path):
205
+ """Get duration in seconds."""
206
+ cmd = [
207
+ "ffprobe", "-v", "error",
208
+ "-show_entries", "format=duration",
209
+ "-of", "default=noprint_wrappers=1:nokey=1", path,
210
+ ]
211
+ result = subprocess.run(cmd, capture_output=True, text=True)
212
+ if result.returncode != 0:
213
+ raise RuntimeError(f"ffprobe failed: {result.stderr[:200]}")
214
+ return float(result.stdout.strip())
215
+
216
+
217
+ def stretch_audio_to_duration(input_path, output_path, target_duration_s):
218
+ """Stretch/compress audio to match target duration."""
219
+ current_duration = get_media_duration(input_path)
220
+ if current_duration <= 0:
221
+ raise RuntimeError("Invalid audio duration")
222
+
223
+ ratio = current_duration / target_duration_s
224
+ filters = []
225
+ remaining = ratio
226
+ while remaining > 2.0:
227
+ filters.append("atempo=2.0")
228
+ remaining /= 2.0
229
+ while remaining < 0.5:
230
+ filters.append("atempo=0.5")
231
+ remaining /= 0.5
232
+ filters.append(f"atempo={remaining:.4f}")
233
+
234
+ cmd = ["ffmpeg", "-y", "-i", input_path, "-filter:a", ",".join(filters), output_path]
235
+ result = subprocess.run(cmd, capture_output=True, text=True)
236
+ if result.returncode != 0:
237
+ raise RuntimeError(f"ffmpeg tempo failed: {result.stderr[:200]}")
238
+ return output_path
239
+
240
+
241
+ def mux_video_audio(video_path, audio_path, output_path, extend_video=False, target_duration=None):
242
+ """Combine video with new audio. Optionally extend video by freezing last frame."""
243
+ if extend_video and target_duration:
244
+ cmd = [
245
+ "ffmpeg", "-y", "-i", video_path, "-i", audio_path,
246
+ "-filter_complex", f"[0:v]tpad=stop_mode=clone:stop_duration={target_duration}[v]",
247
+ "-map", "[v]", "-map", "1:a:0",
248
+ "-c:v", "libx264", "-preset", "fast", "-c:a", "aac",
249
+ "-t", str(target_duration), output_path,
250
+ ]
251
+ else:
252
+ cmd = [
253
+ "ffmpeg", "-y", "-i", video_path, "-i", audio_path,
254
+ "-c:v", "copy", "-c:a", "aac",
255
+ "-map", "0:v:0", "-map", "1:a:0", "-shortest", output_path,
256
+ ]
257
+ result = subprocess.run(cmd, capture_output=True, text=True)
258
+ if result.returncode != 0:
259
+ raise RuntimeError(f"ffmpeg mux failed: {result.stderr[:200]}")
260
+ return output_path
qwen_engine.py ADDED
@@ -0,0 +1,294 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Qwen 3.5 Omni Engine — End-to-end speech-to-speech translation.
3
+ Takes English audio in, returns translated audio + transcript out.
4
+ No separate ASR/MT/TTS needed — Qwen handles everything in one call.
5
+ """
6
+
7
+ import os
8
+ import base64
9
+ import struct
10
+ import subprocess
11
+ import tempfile
12
+ import time
13
+ import shutil
14
+ import logging
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+ QWEN_MODEL = "qwen3.5-omni-plus"
19
+ QWEN_BASE_URL = "https://dashscope-intl.aliyuncs.com/compatible-mode/v1"
20
+
21
+
22
+ def _get_client():
23
+ """Create OpenAI-compatible client for Qwen Dashscope API."""
24
+ from openai import OpenAI
25
+ api_key = os.environ.get("DASHSCOPE_API_KEY", "")
26
+ if not api_key:
27
+ raise RuntimeError(
28
+ "DASHSCOPE_API_KEY not set. Add it as a Space secret."
29
+ )
30
+ return OpenAI(api_key=api_key, base_url=QWEN_BASE_URL)
31
+
32
+
33
+ def _wav_to_base64(wav_path):
34
+ """Read WAV file and return base64 string."""
35
+ with open(wav_path, "rb") as f:
36
+ return base64.b64encode(f.read()).decode("utf-8")
37
+
38
+
39
+ def _base64_to_wav(b64_data, output_path):
40
+ """Convert raw PCM base64 audio to WAV file (24kHz, mono, 16-bit)."""
41
+ audio_bytes = base64.b64decode(b64_data)
42
+ sample_rate = 24000
43
+ num_channels = 1
44
+ bits_per_sample = 16
45
+ byte_rate = sample_rate * num_channels * bits_per_sample // 8
46
+ block_align = num_channels * bits_per_sample // 8
47
+ data_size = len(audio_bytes)
48
+ with open(output_path, "wb") as f:
49
+ f.write(b"RIFF")
50
+ f.write(struct.pack("<I", 36 + data_size))
51
+ f.write(b"WAVE")
52
+ f.write(b"fmt ")
53
+ f.write(struct.pack("<I", 16))
54
+ f.write(struct.pack("<H", 1))
55
+ f.write(struct.pack("<H", num_channels))
56
+ f.write(struct.pack("<I", sample_rate))
57
+ f.write(struct.pack("<I", byte_rate))
58
+ f.write(struct.pack("<H", block_align))
59
+ f.write(struct.pack("<H", bits_per_sample))
60
+ f.write(b"data")
61
+ f.write(struct.pack("<I", data_size))
62
+ f.write(audio_bytes)
63
+
64
+
65
+ def _extract_audio_chunk(video_path, output_wav, start_sec, duration_sec):
66
+ """Extract a chunk of audio from video as 16kHz mono WAV."""
67
+ subprocess.run(
68
+ ["ffmpeg", "-y", "-ss", str(start_sec), "-t", str(duration_sec),
69
+ "-i", video_path, "-vn", "-acodec", "pcm_s16le",
70
+ "-ar", "16000", "-ac", "1", output_wav],
71
+ capture_output=True, check=True,
72
+ )
73
+
74
+
75
+ def _get_duration(filepath):
76
+ """Get media file duration in seconds."""
77
+ result = subprocess.run(
78
+ ["ffprobe", "-v", "quiet", "-show_entries", "format=duration",
79
+ "-of", "default=noprint_wrappers=1:nokey=1", filepath],
80
+ capture_output=True, text=True,
81
+ )
82
+ return float(result.stdout.strip())
83
+
84
+
85
+ def _concatenate_wavs(wav_files, output_path):
86
+ """Concatenate WAV files using ffmpeg."""
87
+ if len(wav_files) == 1:
88
+ shutil.copy2(wav_files[0], output_path)
89
+ return
90
+ list_file = output_path + ".txt"
91
+ with open(list_file, "w") as f:
92
+ for wav in wav_files:
93
+ f.write(f"file '{wav}'\n")
94
+ subprocess.run(
95
+ ["ffmpeg", "-y", "-f", "concat", "-safe", "0",
96
+ "-i", list_file, "-c", "copy", output_path],
97
+ capture_output=True, check=True,
98
+ )
99
+ os.remove(list_file)
100
+
101
+
102
+ def _build_system_prompt(language_name):
103
+ """Build Qwen system prompt for a target language."""
104
+ return (
105
+ f"You are a professional video dubbing translator. You will receive audio in English.\n"
106
+ f"Your task:\n"
107
+ f"1. Listen carefully to the English speech.\n"
108
+ f"2. Translate it into natural, fluent {language_name}.\n"
109
+ f"3. Respond ONLY with the {language_name} translation spoken aloud — no English, no commentary,\n"
110
+ f" no meta-text, no transliteration. Speak entirely in {language_name}.\n"
111
+ f"4. Match the tone, emotion, and pacing of the original speaker as closely as possible.\n"
112
+ f"5. If there are pauses or silence in the original audio, maintain similar pacing.\n"
113
+ f"6. Translate idioms and cultural references into their {language_name} equivalents.\n"
114
+ f"7. Use clear, professional pronunciation suitable for a broad audience."
115
+ )
116
+
117
+
118
+ def translate_chunk_qwen(wav_path, voice, language_name, chunk_index=0):
119
+ """
120
+ Translate a single audio chunk using Qwen Omni.
121
+
122
+ Args:
123
+ wav_path: Path to input WAV file (English audio)
124
+ voice: Qwen voice name (e.g. "Ethan", "Cherry")
125
+ language_name: Full language name for the system prompt
126
+ chunk_index: For logging
127
+
128
+ Returns:
129
+ (output_wav_path, transcript) or (None, transcript) if no audio
130
+ """
131
+ client = _get_client()
132
+ audio_b64 = _wav_to_base64(wav_path)
133
+ output_wav = wav_path.replace(".wav", f"_qwen_{chunk_index}.wav")
134
+
135
+ system_prompt = _build_system_prompt(language_name)
136
+ user_prompt = f"Translate this English speech into {language_name}. Respond only with the spoken {language_name} translation."
137
+
138
+ t0 = time.time()
139
+ completion = client.chat.completions.create(
140
+ model=QWEN_MODEL,
141
+ messages=[
142
+ {"role": "system", "content": system_prompt},
143
+ {
144
+ "role": "user",
145
+ "content": [
146
+ {
147
+ "type": "input_audio",
148
+ "input_audio": {
149
+ "data": f"data:audio/wav;base64,{audio_b64}",
150
+ "format": "wav",
151
+ },
152
+ },
153
+ {"type": "text", "text": user_prompt},
154
+ ],
155
+ },
156
+ ],
157
+ modalities=["text", "audio"],
158
+ audio={"voice": voice, "format": "wav"},
159
+ stream=True,
160
+ stream_options={"include_usage": True},
161
+ )
162
+
163
+ audio_chunks = []
164
+ transcript_parts = []
165
+
166
+ for event in completion:
167
+ if not event.choices:
168
+ continue
169
+ delta = event.choices[0].delta
170
+ if hasattr(delta, "content") and delta.content:
171
+ transcript_parts.append(delta.content)
172
+ if hasattr(delta, "audio") and delta.audio:
173
+ if isinstance(delta.audio, dict):
174
+ if "data" in delta.audio:
175
+ audio_chunks.append(delta.audio["data"])
176
+ elif hasattr(delta.audio, "data") and delta.audio.data:
177
+ audio_chunks.append(delta.audio.data)
178
+
179
+ transcript = "".join(transcript_parts)
180
+ elapsed = time.time() - t0
181
+ logger.info(f"Qwen chunk {chunk_index}: {elapsed:.1f}s, transcript={transcript[:60]}")
182
+
183
+ if audio_chunks:
184
+ full_audio_b64 = "".join(audio_chunks)
185
+ _base64_to_wav(full_audio_b64, output_wav)
186
+ return output_wav, transcript
187
+
188
+ return None, transcript
189
+
190
+
191
+ def dub_video_qwen(video_path, language_name, voice="Ethan", chunk_seconds=120, progress_fn=None):
192
+ """
193
+ Full video dubbing pipeline using Qwen Omni.
194
+ Splits video into chunks, translates each chunk via Qwen API,
195
+ concatenates results, and muxes back onto video.
196
+
197
+ Args:
198
+ video_path: Path to input video
199
+ language_name: Full language name (e.g. "French", "Arabic")
200
+ voice: Qwen voice name
201
+ chunk_seconds: Audio chunk duration for API calls
202
+ progress_fn: Optional gradio progress callback
203
+
204
+ Returns:
205
+ (output_video_path, log_text)
206
+ """
207
+ tmp_dir = tempfile.mkdtemp(prefix=f"qwen_dub_")
208
+ log = []
209
+
210
+ try:
211
+ # Duration
212
+ if progress_fn:
213
+ progress_fn(0.05, desc="Analyzing video...")
214
+ total_duration = _get_duration(video_path)
215
+ log.append(f"**Video:** {total_duration:.1f}s")
216
+ log.append(f"**Engine:** Qwen 3.5 Omni")
217
+ log.append(f"**Voice:** {voice}")
218
+ log.append(f"**Language:** {language_name}")
219
+
220
+ if total_duration > 3600:
221
+ return None, "Video longer than 1 hour — please use a shorter clip."
222
+
223
+ # Split into chunks
224
+ if progress_fn:
225
+ progress_fn(0.1, desc="Extracting audio chunks...")
226
+ num_chunks = max(1, int(total_duration // chunk_seconds) + (1 if total_duration % chunk_seconds > 0 else 0))
227
+ log.append(f"**Chunks:** {num_chunks} ({chunk_seconds}s each)")
228
+
229
+ input_chunks = []
230
+ for i in range(num_chunks):
231
+ start = i * chunk_seconds
232
+ duration = min(chunk_seconds, total_duration - start)
233
+ chunk_path = os.path.join(tmp_dir, f"chunk_{i:03d}.wav")
234
+ _extract_audio_chunk(video_path, chunk_path, start, duration)
235
+ input_chunks.append(chunk_path)
236
+
237
+ # Translate each chunk
238
+ output_chunks = []
239
+ all_transcripts = []
240
+
241
+ for i, chunk_path in enumerate(input_chunks):
242
+ if progress_fn:
243
+ frac = 0.15 + 0.7 * (i / num_chunks)
244
+ progress_fn(frac, desc=f"Translating chunk {i+1}/{num_chunks}...")
245
+
246
+ result_path, transcript = translate_chunk_qwen(
247
+ chunk_path, voice, language_name, i
248
+ )
249
+ if transcript:
250
+ all_transcripts.append(f"**[{i+1}]** {transcript}")
251
+
252
+ if result_path:
253
+ output_chunks.append(result_path)
254
+ else:
255
+ # Silence fallback
256
+ duration = _get_duration(chunk_path)
257
+ silence_path = os.path.join(tmp_dir, f"silence_{i:03d}.wav")
258
+ subprocess.run(
259
+ ["ffmpeg", "-y", "-f", "lavfi",
260
+ "-i", "anullsrc=r=24000:cl=mono",
261
+ "-t", str(duration), "-acodec", "pcm_s16le", silence_path],
262
+ capture_output=True, check=True,
263
+ )
264
+ output_chunks.append(silence_path)
265
+
266
+ # Concatenate
267
+ if progress_fn:
268
+ progress_fn(0.88, desc="Assembling audio...")
269
+ full_audio = os.path.join(tmp_dir, "full_dubbed.wav")
270
+ _concatenate_wavs(output_chunks, full_audio)
271
+
272
+ # Mux onto video
273
+ if progress_fn:
274
+ progress_fn(0.93, desc="Combining audio and video...")
275
+ output_video = os.path.join(tmp_dir, "dubbed_output.mp4")
276
+ subprocess.run(
277
+ ["ffmpeg", "-y", "-i", video_path, "-i", full_audio,
278
+ "-c:v", "copy", "-map", "0:v:0", "-map", "1:a:0",
279
+ "-shortest", output_video],
280
+ capture_output=True, check=True,
281
+ )
282
+
283
+ if progress_fn:
284
+ progress_fn(1.0, desc="Done!")
285
+
286
+ log.append(f"\n**Transcript:**")
287
+ log.extend(all_transcripts)
288
+
289
+ return output_video, "\n".join(log)
290
+
291
+ except Exception as e:
292
+ logger.exception("Qwen dubbing failed")
293
+ shutil.rmtree(tmp_dir, ignore_errors=True)
294
+ return None, f"Error: {str(e)}"
requirements.txt ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ torch>=2.0.0
2
+ torchaudio>=2.0.0
3
+ transformers>=4.36.0
4
+ accelerate>=0.25.0
5
+ soundfile>=0.12.0
6
+ numpy>=1.24.0
7
+ gradio>=5.0.0
8
+ audioop-lts
9
+ requests>=2.28.0
10
+ openai>=1.0.0
tts_engine.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ TTS Engine Router — routes synthesis to local models or YourVoic API.
3
+ """
4
+
5
+ import os
6
+ import io
7
+ import time
8
+ import tempfile
9
+ import requests
10
+ import numpy as np
11
+ import soundfile as sf
12
+ import logging
13
+
14
+ logger = logging.getLogger(__name__)
15
+
16
+ YOURVOIC_API_KEY = os.environ.get("YOURVOIC_API_KEY", "")
17
+ YOURVOIC_STREAM_URL = "https://yourvoic.com/api/v1/tts/stream"
18
+
19
+
20
+ def synthesize_yourvoic(text, language_code, voice="Peter", speed=1.0):
21
+ """
22
+ Synthesize text using YourVoic API.
23
+ Returns (audio_array, sample_rate) or raises on failure.
24
+ """
25
+ if not YOURVOIC_API_KEY:
26
+ raise RuntimeError(
27
+ "YOURVOIC_API_KEY not set. Add it as a Space secret."
28
+ )
29
+
30
+ headers = {
31
+ "X-API-Key": YOURVOIC_API_KEY,
32
+ "Content-Type": "application/json",
33
+ }
34
+ payload = {
35
+ "text": text,
36
+ "voice": voice,
37
+ "language": language_code,
38
+ "model": "aura-prime",
39
+ "speed": speed,
40
+ }
41
+
42
+ t0 = time.time()
43
+ response = requests.post(
44
+ YOURVOIC_STREAM_URL,
45
+ headers=headers,
46
+ json=payload,
47
+ stream=True,
48
+ timeout=60,
49
+ )
50
+
51
+ if response.status_code != 200:
52
+ raise RuntimeError(
53
+ f"YourVoic API error {response.status_code}: {response.text[:200]}"
54
+ )
55
+
56
+ # Collect streamed audio bytes
57
+ audio_bytes = io.BytesIO()
58
+ for chunk in response.iter_content(chunk_size=8192):
59
+ audio_bytes.write(chunk)
60
+ audio_bytes.seek(0)
61
+
62
+ elapsed = time.time() - t0
63
+ logger.info(f"YourVoic TTS: {len(text)} chars, {elapsed:.2f}s")
64
+
65
+ # Read audio from WAV bytes
66
+ audio_array, sample_rate = sf.read(audio_bytes, dtype="float32")
67
+ return audio_array, sample_rate
68
+
69
+
70
+ def synthesize_yourvoic_to_file(text, language_code, output_path, voice="Peter", speed=1.0):
71
+ """Synthesize via YourVoic and save to file."""
72
+ audio, sr = synthesize_yourvoic(text, language_code, voice, speed)
73
+ sf.write(output_path, audio, sr)
74
+ return output_path, sr
75
+
76
+
77
+ def synthesize_local(text, tts_pipe):
78
+ """
79
+ Synthesize text using local HuggingFace TTS pipeline (MMS-TTS).
80
+ Returns (audio_array, sample_rate).
81
+ """
82
+ t0 = time.time()
83
+ result = tts_pipe(text)
84
+ audio = np.array(result["audio"]).squeeze()
85
+ sr = result["sampling_rate"]
86
+ elapsed = time.time() - t0
87
+ logger.info(f"Local TTS: {len(text)} chars, {elapsed:.2f}s, {len(audio)/sr:.1f}s audio")
88
+ return audio, sr
89
+
90
+
91
+ def synthesize_chunked(text, language_config, tts_pipe=None, sentences_per_chunk=2):
92
+ """
93
+ Synthesize long text by chunking into sentence groups.
94
+ Routes to either YourVoic or local TTS based on language config.
95
+
96
+ Args:
97
+ text: Full text to synthesize
98
+ language_config: Dict from LANGUAGES (has tts_engine, yourvoic_lang, etc.)
99
+ tts_pipe: Local HuggingFace TTS pipeline (needed for local engine)
100
+ sentences_per_chunk: How many sentences to synthesize per API call
101
+
102
+ Returns:
103
+ (audio_array, sample_rate)
104
+ """
105
+ import re
106
+ sentences = re.split(r'(?<=[.!?])\s+', text)
107
+ sentences = [s.strip() for s in sentences if s.strip()]
108
+
109
+ if not sentences:
110
+ return np.array([], dtype=np.float32), 16000
111
+
112
+ engine = language_config["tts_engine"]
113
+ audio_segments = []
114
+ output_sr = None
115
+
116
+ for i in range(0, len(sentences), sentences_per_chunk):
117
+ chunk_text = ' '.join(sentences[i:i + sentences_per_chunk])
118
+ if not chunk_text:
119
+ continue
120
+
121
+ try:
122
+ if engine == "yourvoic":
123
+ voice = language_config["yourvoic_voices"][0] if language_config["yourvoic_voices"] else "Peter"
124
+ lang_code = language_config["yourvoic_lang"]
125
+ audio_seg, seg_sr = synthesize_yourvoic(chunk_text, lang_code, voice)
126
+ else:
127
+ if tts_pipe is None:
128
+ raise RuntimeError("Local TTS pipeline not loaded")
129
+ audio_seg, seg_sr = synthesize_local(chunk_text, tts_pipe)
130
+
131
+ if output_sr is None:
132
+ output_sr = seg_sr
133
+ if len(audio_seg) > 0:
134
+ audio_segments.append(audio_seg)
135
+ # Small silence between chunks
136
+ silence = np.zeros(int(0.15 * seg_sr), dtype=np.float32)
137
+ audio_segments.append(silence)
138
+
139
+ except Exception as e:
140
+ logger.error(f"TTS chunk failed: {e}")
141
+ continue
142
+
143
+ if not audio_segments:
144
+ return np.array([], dtype=np.float32), output_sr or 16000
145
+
146
+ return np.concatenate(audio_segments), output_sr