PlotweaverModel commited on
Commit
a197f00
·
verified ·
1 Parent(s): cff4cca

Upload 4 files

Browse files
Files changed (4) hide show
  1. README.md +25 -0
  2. app.py +1519 -0
  3. packages.txt +1 -0
  4. requirements.txt +10 -0
README.md ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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,1519 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ PlotWeaver — Live Commentary Translation Platform (Single File)
3
+ ================================================================
4
+ Three engines: Qwen Omni | YourVoic API | Local (Whisper+NLLB+MMS-TTS)
5
+ """
6
+
7
+ import os, io, re, time, base64, struct, shutil, subprocess, tempfile, logging
8
+ import torch, numpy as np, requests, soundfile as sf, gradio as gr
9
+
10
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
11
+ logger = logging.getLogger(__name__)
12
+
13
+
14
+ # =============================================================================
15
+ # LANGUAGES
16
+ # =============================================================================
17
+
18
+ # Qwen Omni voices (work across all Qwen-supported languages)
19
+ QWEN_VOICES = [
20
+ "Cherry", "Serena", "Ethan", "Chelsie", "Momo", "Vivian", "Moon", "Maia",
21
+ "Kai", "Nofish", "Bella", "Jennifer", "Ryan", "Katerina", "Aiden",
22
+ "Eldric Sage", "Mia", "Mochi", "Bellona", "Vincent", "Bunny", "Neil",
23
+ "Elias", "Arthur", "Seren", "Bodega", "Sonrisa", "Alek", "Dolce",
24
+ "Sohee", "Ono Anna", "Lenn", "Emilien", "Andre",
25
+ ]
26
+
27
+ # Each language entry:
28
+ # "Display Name": {
29
+ # "nllb": NLLB-200 language code (for local/yourvoic pipeline translation),
30
+ # "yourvoic_lang": YourVoic language code (or None),
31
+ # "yourvoic_voices": list of YourVoic voice names,
32
+ # "tts_engine": "qwen" | "yourvoic" | "local",
33
+ # "qwen_code": short language code for Qwen prompts (or None),
34
+ # "qwen_name": full language name for Qwen system prompt (or None),
35
+ # }
36
+
37
+ LANGUAGES = {
38
+ # ---- Global Languages (Qwen Omni — best quality) ----
39
+ "Arabic": {
40
+ "nllb": "arb_Arab", "yourvoic_lang": "ar-SA",
41
+ "yourvoic_voices": ["Peter"], "tts_engine": "qwen",
42
+ "qwen_code": "ar", "qwen_name": "Modern Standard Arabic (العربية الفصحى)",
43
+ },
44
+ "Spanish": {
45
+ "nllb": "spa_Latn", "yourvoic_lang": "es-ES",
46
+ "yourvoic_voices": ["Peter", "Kylie"], "tts_engine": "qwen",
47
+ "qwen_code": "es", "qwen_name": "Spanish",
48
+ },
49
+ "French": {
50
+ "nllb": "fra_Latn", "yourvoic_lang": "fr-FR",
51
+ "yourvoic_voices": ["Peter", "Kylie"], "tts_engine": "qwen",
52
+ "qwen_code": "fr", "qwen_name": "French",
53
+ },
54
+ "German": {
55
+ "nllb": "deu_Latn", "yourvoic_lang": "de-DE",
56
+ "yourvoic_voices": ["Peter", "Kylie"], "tts_engine": "qwen",
57
+ "qwen_code": "de", "qwen_name": "German",
58
+ },
59
+ "Mandarin": {
60
+ "nllb": "zho_Hans", "yourvoic_lang": "zh-CN",
61
+ "yourvoic_voices": ["Peter", "Kylie"], "tts_engine": "qwen",
62
+ "qwen_code": "zh", "qwen_name": "Mandarin Chinese",
63
+ },
64
+ "Italian": {
65
+ "nllb": "ita_Latn", "yourvoic_lang": "it-IT",
66
+ "yourvoic_voices": ["Peter", "Kylie"], "tts_engine": "qwen",
67
+ "qwen_code": "it", "qwen_name": "Italian",
68
+ },
69
+ "Japanese": {
70
+ "nllb": "jpn_Jpan", "yourvoic_lang": "ja-JP",
71
+ "yourvoic_voices": ["Peter", "Kylie"], "tts_engine": "qwen",
72
+ "qwen_code": "ja", "qwen_name": "Japanese",
73
+ },
74
+ "Portuguese": {
75
+ "nllb": "por_Latn", "yourvoic_lang": "pt-BR",
76
+ "yourvoic_voices": ["Peter", "Kylie"], "tts_engine": "qwen",
77
+ "qwen_code": "pt", "qwen_name": "Portuguese",
78
+ },
79
+ "Hindi": {
80
+ "nllb": "hin_Deva", "yourvoic_lang": "hi-IN",
81
+ "yourvoic_voices": ["Rahul", "Deepika", "Aditya"], "tts_engine": "qwen",
82
+ "qwen_code": "hi", "qwen_name": "Hindi",
83
+ },
84
+ "Korean": {
85
+ "nllb": "kor_Hang", "yourvoic_lang": "ko-KR",
86
+ "yourvoic_voices": ["Peter", "Kylie"], "tts_engine": "qwen",
87
+ "qwen_code": "ko", "qwen_name": "Korean",
88
+ },
89
+ "Russian": {
90
+ "nllb": "rus_Cyrl", "yourvoic_lang": "ru-RU",
91
+ "yourvoic_voices": ["Peter", "Kylie"], "tts_engine": "qwen",
92
+ "qwen_code": "ru", "qwen_name": "Russian",
93
+ },
94
+
95
+ # ---- African Languages (Local pipeline: Whisper → NLLB → MMS-TTS) ----
96
+ "Yoruba": {
97
+ "nllb": "yor_Latn", "yourvoic_lang": None,
98
+ "yourvoic_voices": [], "tts_engine": "local",
99
+ "qwen_code": None, "qwen_name": None,
100
+ },
101
+ "Hausa": {
102
+ "nllb": "hau_Latn", "yourvoic_lang": None,
103
+ "yourvoic_voices": [], "tts_engine": "local",
104
+ "qwen_code": None, "qwen_name": None,
105
+ },
106
+ "Igbo": {
107
+ "nllb": "ibo_Latn", "yourvoic_lang": None,
108
+ "yourvoic_voices": [], "tts_engine": "local",
109
+ "qwen_code": None, "qwen_name": None,
110
+ },
111
+ "Swahili": {
112
+ "nllb": "swh_Latn", "yourvoic_lang": "sw-KE",
113
+ "yourvoic_voices": ["Peter"], "tts_engine": "yourvoic",
114
+ "qwen_code": None, "qwen_name": None,
115
+ },
116
+ "Zulu": {
117
+ "nllb": "zul_Latn", "yourvoic_lang": None,
118
+ "yourvoic_voices": [], "tts_engine": "local",
119
+ "qwen_code": None, "qwen_name": None,
120
+ },
121
+ "Amharic": {
122
+ "nllb": "amh_Ethi", "yourvoic_lang": "am-ET",
123
+ "yourvoic_voices": ["Peter"], "tts_engine": "yourvoic",
124
+ "qwen_code": None, "qwen_name": None,
125
+ },
126
+ "Afrikaans": {
127
+ "nllb": "afr_Latn", "yourvoic_lang": "af-ZA",
128
+ "yourvoic_voices": ["Peter"], "tts_engine": "yourvoic",
129
+ "qwen_code": None, "qwen_name": None,
130
+ },
131
+
132
+ # ---- South Asian (YourVoic TTS + NLLB MT) ----
133
+ "Bengali": {
134
+ "nllb": "ben_Beng", "yourvoic_lang": "bn-IN",
135
+ "yourvoic_voices": ["Sneha", "Aryan"], "tts_engine": "yourvoic",
136
+ "qwen_code": None, "qwen_name": None,
137
+ },
138
+ "Tamil": {
139
+ "nllb": "tam_Taml", "yourvoic_lang": "ta-IN",
140
+ "yourvoic_voices": ["Priya", "Kumar"], "tts_engine": "yourvoic",
141
+ "qwen_code": None, "qwen_name": None,
142
+ },
143
+ "Telugu": {
144
+ "nllb": "tel_Telu", "yourvoic_lang": "te-IN",
145
+ "yourvoic_voices": ["Arjun", "Lakshmi"], "tts_engine": "yourvoic",
146
+ "qwen_code": None, "qwen_name": None,
147
+ },
148
+ "Marathi": {
149
+ "nllb": "mar_Deva", "yourvoic_lang": "mr-IN",
150
+ "yourvoic_voices": ["Anjali", "Rohan"], "tts_engine": "yourvoic",
151
+ "qwen_code": None, "qwen_name": None,
152
+ },
153
+ "Urdu": {
154
+ "nllb": "urd_Arab", "yourvoic_lang": "ur-PK",
155
+ "yourvoic_voices": ["Peter"], "tts_engine": "yourvoic",
156
+ "qwen_code": None, "qwen_name": None,
157
+ },
158
+ "Nepali": {
159
+ "nllb": "npi_Deva", "yourvoic_lang": "ne-NP",
160
+ "yourvoic_voices": ["Peter"], "tts_engine": "yourvoic",
161
+ "qwen_code": None, "qwen_name": None,
162
+ },
163
+
164
+ # ---- Southeast Asian (YourVoic) ----
165
+ "Indonesian": {
166
+ "nllb": "ind_Latn", "yourvoic_lang": "id-ID",
167
+ "yourvoic_voices": ["Peter"], "tts_engine": "yourvoic",
168
+ "qwen_code": None, "qwen_name": None,
169
+ },
170
+ "Vietnamese": {
171
+ "nllb": "vie_Latn", "yourvoic_lang": "vi-VN",
172
+ "yourvoic_voices": ["Peter"], "tts_engine": "yourvoic",
173
+ "qwen_code": None, "qwen_name": None,
174
+ },
175
+ "Thai": {
176
+ "nllb": "tha_Thai", "yourvoic_lang": "th-TH",
177
+ "yourvoic_voices": ["Peter"], "tts_engine": "yourvoic",
178
+ "qwen_code": None, "qwen_name": None,
179
+ },
180
+ "Malay": {
181
+ "nllb": "zsm_Latn", "yourvoic_lang": "ms-MY",
182
+ "yourvoic_voices": ["Peter"], "tts_engine": "yourvoic",
183
+ "qwen_code": None, "qwen_name": None,
184
+ },
185
+ "Filipino": {
186
+ "nllb": "tgl_Latn", "yourvoic_lang": "fil-PH",
187
+ "yourvoic_voices": ["Peter"], "tts_engine": "yourvoic",
188
+ "qwen_code": None, "qwen_name": None,
189
+ },
190
+
191
+ # ---- European (YourVoic) ----
192
+ "Dutch": {
193
+ "nllb": "nld_Latn", "yourvoic_lang": "nl-NL",
194
+ "yourvoic_voices": ["Peter"], "tts_engine": "yourvoic",
195
+ "qwen_code": None, "qwen_name": None,
196
+ },
197
+ "Polish": {
198
+ "nllb": "pol_Latn", "yourvoic_lang": "pl-PL",
199
+ "yourvoic_voices": ["Peter"], "tts_engine": "yourvoic",
200
+ "qwen_code": None, "qwen_name": None,
201
+ },
202
+ "Turkish": {
203
+ "nllb": "tur_Latn", "yourvoic_lang": "tr-TR",
204
+ "yourvoic_voices": ["Peter"], "tts_engine": "yourvoic",
205
+ "qwen_code": None, "qwen_name": None,
206
+ },
207
+ "Swedish": {
208
+ "nllb": "swe_Latn", "yourvoic_lang": "sv-SE",
209
+ "yourvoic_voices": ["Peter"], "tts_engine": "yourvoic",
210
+ "qwen_code": None, "qwen_name": None,
211
+ },
212
+ "Romanian": {
213
+ "nllb": "ron_Latn", "yourvoic_lang": "ro-RO",
214
+ "yourvoic_voices": ["Peter"], "tts_engine": "yourvoic",
215
+ "qwen_code": None, "qwen_name": None,
216
+ },
217
+ "Greek": {
218
+ "nllb": "ell_Grek", "yourvoic_lang": "el-GR",
219
+ "yourvoic_voices": ["Peter"], "tts_engine": "yourvoic",
220
+ "qwen_code": None, "qwen_name": None,
221
+ },
222
+ "Ukrainian": {
223
+ "nllb": "ukr_Cyrl", "yourvoic_lang": "uk-UA",
224
+ "yourvoic_voices": ["Peter"], "tts_engine": "yourvoic",
225
+ "qwen_code": None, "qwen_name": None,
226
+ },
227
+ "Finnish": {
228
+ "nllb": "fin_Latn", "yourvoic_lang": "fi-FI",
229
+ "yourvoic_voices": ["Peter"], "tts_engine": "yourvoic",
230
+ "qwen_code": None, "qwen_name": None,
231
+ },
232
+ "Danish": {
233
+ "nllb": "dan_Latn", "yourvoic_lang": "da-DK",
234
+ "yourvoic_voices": ["Peter"], "tts_engine": "yourvoic",
235
+ "qwen_code": None, "qwen_name": None,
236
+ },
237
+ "Norwegian": {
238
+ "nllb": "nob_Latn", "yourvoic_lang": "nb-NO",
239
+ "yourvoic_voices": ["Peter"], "tts_engine": "yourvoic",
240
+ "qwen_code": None, "qwen_name": None,
241
+ },
242
+
243
+ # ---- Middle Eastern (YourVoic) ----
244
+ "Persian": {
245
+ "nllb": "pes_Arab", "yourvoic_lang": "fa-IR",
246
+ "yourvoic_voices": ["Peter"], "tts_engine": "yourvoic",
247
+ "qwen_code": None, "qwen_name": None,
248
+ },
249
+ "Hebrew": {
250
+ "nllb": "heb_Hebr", "yourvoic_lang": "he-IL",
251
+ "yourvoic_voices": ["Peter"], "tts_engine": "yourvoic",
252
+ "qwen_code": None, "qwen_name": None,
253
+ },
254
+ }
255
+
256
+
257
+ # Group languages by category for the UI
258
+ LANGUAGE_GROUPS = {
259
+ "Global Languages": [
260
+ "Spanish", "French", "German", "Mandarin", "Italian",
261
+ "Japanese", "Portuguese", "Hindi", "Arabic", "Korean", "Russian",
262
+ ],
263
+ "African Languages": [
264
+ "Yoruba", "Hausa", "Igbo", "Swahili", "Zulu", "Amharic", "Afrikaans",
265
+ ],
266
+ "South Asian": [
267
+ "Bengali", "Tamil", "Telugu", "Marathi", "Urdu", "Nepali",
268
+ ],
269
+ "Southeast Asian": [
270
+ "Indonesian", "Vietnamese", "Thai", "Malay", "Filipino",
271
+ ],
272
+ "European": [
273
+ "Dutch", "Polish", "Turkish", "Swedish", "Romanian",
274
+ "Greek", "Ukrainian", "Finnish", "Danish", "Norwegian",
275
+ ],
276
+ "Middle Eastern": [
277
+ "Persian", "Hebrew",
278
+ ],
279
+ }
280
+
281
+ # All language display names (for dropdowns)
282
+ ALL_LANGUAGE_NAMES = sorted(LANGUAGES.keys())
283
+
284
+ # Languages that use local TTS (your fine-tuned models)
285
+ LOCAL_TTS_LANGUAGES = [k for k, v in LANGUAGES.items() if v["tts_engine"] == "local"]
286
+
287
+ # Languages that use YourVoic API
288
+ YOURVOIC_LANGUAGES = [k for k, v in LANGUAGES.items() if v["tts_engine"] == "yourvoic"]
289
+
290
+
291
+ # =============================================================================
292
+ # PIPELINE: ASR + MT + Video helpers
293
+ # =============================================================================
294
+
295
+ DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
296
+ TORCH_DTYPE = torch.float16 if torch.cuda.is_available() else torch.float32
297
+
298
+ # Models (loaded once at startup)
299
+ asr_pipe = None
300
+ mt_tokenizer = None
301
+ mt_model = None
302
+ tts_pipe_local = None # Local TTS for Yoruba/Hausa/Igbo/Zulu
303
+
304
+
305
+ def load_models():
306
+ """Load all models at startup."""
307
+ global asr_pipe, mt_tokenizer, mt_model, tts_pipe_local
308
+ from transformers import (
309
+ pipeline as hf_pipeline,
310
+ AutoTokenizer,
311
+ AutoModelForSeq2SeqLM,
312
+ )
313
+
314
+ print(f"Device: {DEVICE} | Dtype: {TORCH_DTYPE}")
315
+ print("Loading models...")
316
+
317
+ # ASR
318
+ ASR_MODEL_ID = "PlotweaverAI/whisper-small-de-en"
319
+ print(f" Loading ASR: {ASR_MODEL_ID}")
320
+ asr_pipe = hf_pipeline(
321
+ "automatic-speech-recognition",
322
+ model=ASR_MODEL_ID,
323
+ device=DEVICE,
324
+ torch_dtype=TORCH_DTYPE,
325
+ )
326
+ print(" ASR loaded")
327
+
328
+ # MT
329
+ MT_MODEL_ID = "PlotweaverAI/nllb-200-distilled-600M-african-6lang"
330
+ print(f" Loading MT: {MT_MODEL_ID}")
331
+ mt_tokenizer = AutoTokenizer.from_pretrained(MT_MODEL_ID)
332
+ mt_model = AutoModelForSeq2SeqLM.from_pretrained(
333
+ MT_MODEL_ID, torch_dtype=TORCH_DTYPE
334
+ ).to(DEVICE)
335
+ mt_tokenizer.src_lang = "eng_Latn"
336
+ print(" MT loaded")
337
+
338
+ # Local TTS (Yoruba)
339
+ TTS_MODEL_ID = "PlotweaverAI/yoruba-mms-tts-new"
340
+ print(f" Loading local TTS: {TTS_MODEL_ID}")
341
+ tts_pipe_local = hf_pipeline(
342
+ "text-to-speech",
343
+ model=TTS_MODEL_ID,
344
+ device=DEVICE,
345
+ torch_dtype=TORCH_DTYPE,
346
+ )
347
+ print(" Local TTS loaded")
348
+
349
+ # Diagnostics
350
+ print(f"\n=== Device diagnostics ===")
351
+ print(f"CUDA available: {torch.cuda.is_available()}")
352
+ if torch.cuda.is_available():
353
+ print(f"CUDA device: {torch.cuda.get_device_name(0)}")
354
+ print(f"ASR on: {next(asr_pipe.model.parameters()).device}")
355
+ print(f"MT on: {next(mt_model.parameters()).device}")
356
+ print(f"TTS on: {next(tts_pipe_local.model.parameters()).device}")
357
+ print(f"YourVoic API key: {'set' if os.environ.get('YOURVOIC_API_KEY') else 'NOT SET'}")
358
+ print(f"==========================\n")
359
+ print("All models loaded!")
360
+
361
+
362
+ # ---- Text Processing ----
363
+
364
+ def split_into_sentences(text):
365
+ """Split raw ASR text into individual sentences."""
366
+ text = text.strip()
367
+ if not text:
368
+ return []
369
+ text = '. '.join(s.strip().capitalize() for s in text.split('. ') if s.strip())
370
+ if re.search(r'[.!?]', text):
371
+ sentences = re.split(r'(?<=[.!?])\s+', text)
372
+ return [s.strip() for s in sentences if s.strip()]
373
+ words = text.split()
374
+ MAX_WORDS = 12
375
+ sentences = []
376
+ for i in range(0, len(words), MAX_WORDS):
377
+ chunk = ' '.join(words[i:i + MAX_WORDS])
378
+ if not chunk.endswith(('.', '!', '?')):
379
+ chunk += '.'
380
+ chunk = chunk[0].upper() + chunk[1:] if len(chunk) > 1 else chunk.upper()
381
+ sentences.append(chunk)
382
+ return sentences
383
+
384
+
385
+ # ---- ASR ----
386
+
387
+ def transcribe(audio_array, sample_rate=16000):
388
+ """ASR: English audio to text. Handles both short and long audio."""
389
+ if len(audio_array) < 1600:
390
+ return ""
391
+
392
+ duration_s = len(audio_array) / sample_rate
393
+
394
+ if sample_rate != 16000:
395
+ import torchaudio.functional as F_audio
396
+ audio_tensor = torch.from_numpy(audio_array).float()
397
+ audio_tensor = F_audio.resample(audio_tensor, sample_rate, 16000)
398
+ audio_array = audio_tensor.numpy()
399
+ sample_rate = 16000
400
+
401
+ if duration_s <= 28:
402
+ result = asr_pipe(
403
+ {"raw": audio_array, "sampling_rate": sample_rate},
404
+ return_timestamps=False,
405
+ )
406
+ return result["text"].strip()
407
+
408
+ # Long-form: native Whisper generate
409
+ model = asr_pipe.model
410
+ processor = asr_pipe.feature_extractor
411
+ tokenizer = asr_pipe.tokenizer
412
+
413
+ inputs = processor(
414
+ audio_array, sampling_rate=16000, return_tensors="pt",
415
+ truncation=False, padding="longest", return_attention_mask=True,
416
+ )
417
+ input_features = inputs.input_features.to(DEVICE, dtype=TORCH_DTYPE)
418
+ attention_mask = inputs.attention_mask.to(DEVICE) if "attention_mask" in inputs else None
419
+
420
+ generate_kwargs = {"return_timestamps": True, "language": "en", "task": "transcribe"}
421
+ if attention_mask is not None:
422
+ generate_kwargs["attention_mask"] = attention_mask
423
+
424
+ with torch.no_grad():
425
+ predicted_ids = model.generate(input_features, **generate_kwargs)
426
+
427
+ transcription = tokenizer.batch_decode(predicted_ids, skip_special_tokens=True)[0]
428
+ return transcription.strip()
429
+
430
+
431
+ # ---- MT ----
432
+
433
+ def translate_sentence(text, target_nllb_code, fast=True, max_length=256):
434
+ """Translate a single sentence from English to target language."""
435
+ inputs = mt_tokenizer(text, return_tensors="pt", truncation=True).to(DEVICE)
436
+ tgt_lang_id = mt_tokenizer.convert_tokens_to_ids(target_nllb_code)
437
+
438
+ generate_kwargs = {
439
+ "forced_bos_token_id": tgt_lang_id,
440
+ "repetition_penalty": 1.5,
441
+ "no_repeat_ngram_size": 3,
442
+ }
443
+ if fast:
444
+ generate_kwargs.update({"max_length": 128, "num_beams": 1, "do_sample": False})
445
+ else:
446
+ generate_kwargs.update({"max_length": max_length, "num_beams": 4, "early_stopping": True})
447
+
448
+ with torch.no_grad():
449
+ output_ids = mt_model.generate(**inputs, **generate_kwargs)
450
+
451
+ return mt_tokenizer.decode(output_ids[0], skip_special_tokens=True)
452
+
453
+
454
+ def translate_text(text, target_nllb_code, fast=True):
455
+ """Split and translate full text sentence-by-sentence."""
456
+ sentences = split_into_sentences(text)
457
+ if not sentences:
458
+ return "", [], []
459
+ translations = []
460
+ for s in sentences:
461
+ yo = translate_sentence(s, target_nllb_code, fast=fast)
462
+ translations.append(yo)
463
+ return ' '.join(translations), sentences, translations
464
+
465
+
466
+ # ---- Video Processing ----
467
+
468
+ def extract_audio_from_video(video_path, output_path, target_sr=16000):
469
+ """Extract audio track from video as 16kHz mono WAV."""
470
+ cmd = [
471
+ "ffmpeg", "-y", "-i", video_path,
472
+ "-vn", "-acodec", "pcm_s16le", "-ar", str(target_sr), "-ac", "1",
473
+ output_path,
474
+ ]
475
+ result = subprocess.run(cmd, capture_output=True, text=True)
476
+ if result.returncode != 0:
477
+ raise RuntimeError(f"ffmpeg extraction failed: {result.stderr[:200]}")
478
+ return output_path
479
+
480
+
481
+ def get_media_duration(path):
482
+ """Get duration in seconds."""
483
+ cmd = [
484
+ "ffprobe", "-v", "error",
485
+ "-show_entries", "format=duration",
486
+ "-of", "default=noprint_wrappers=1:nokey=1", path,
487
+ ]
488
+ result = subprocess.run(cmd, capture_output=True, text=True)
489
+ if result.returncode != 0:
490
+ raise RuntimeError(f"ffprobe failed: {result.stderr[:200]}")
491
+ return float(result.stdout.strip())
492
+
493
+
494
+ def stretch_audio_to_duration(input_path, output_path, target_duration_s):
495
+ """Stretch/compress audio to match target duration."""
496
+ current_duration = get_media_duration(input_path)
497
+ if current_duration <= 0:
498
+ raise RuntimeError("Invalid audio duration")
499
+
500
+ ratio = current_duration / target_duration_s
501
+ filters = []
502
+ remaining = ratio
503
+ while remaining > 2.0:
504
+ filters.append("atempo=2.0")
505
+ remaining /= 2.0
506
+ while remaining < 0.5:
507
+ filters.append("atempo=0.5")
508
+ remaining /= 0.5
509
+ filters.append(f"atempo={remaining:.4f}")
510
+
511
+ cmd = ["ffmpeg", "-y", "-i", input_path, "-filter:a", ",".join(filters), output_path]
512
+ result = subprocess.run(cmd, capture_output=True, text=True)
513
+ if result.returncode != 0:
514
+ raise RuntimeError(f"ffmpeg tempo failed: {result.stderr[:200]}")
515
+ return output_path
516
+
517
+
518
+ def mux_video_audio(video_path, audio_path, output_path, extend_video=False, target_duration=None):
519
+ """Combine video with new audio. Optionally extend video by freezing last frame."""
520
+ if extend_video and target_duration:
521
+ cmd = [
522
+ "ffmpeg", "-y", "-i", video_path, "-i", audio_path,
523
+ "-filter_complex", f"[0:v]tpad=stop_mode=clone:stop_duration={target_duration}[v]",
524
+ "-map", "[v]", "-map", "1:a:0",
525
+ "-c:v", "libx264", "-preset", "fast", "-c:a", "aac",
526
+ "-t", str(target_duration), output_path,
527
+ ]
528
+ else:
529
+ cmd = [
530
+ "ffmpeg", "-y", "-i", video_path, "-i", audio_path,
531
+ "-c:v", "copy", "-c:a", "aac",
532
+ "-map", "0:v:0", "-map", "1:a:0", "-shortest", output_path,
533
+ ]
534
+ result = subprocess.run(cmd, capture_output=True, text=True)
535
+ if result.returncode != 0:
536
+ raise RuntimeError(f"ffmpeg mux failed: {result.stderr[:200]}")
537
+ return output_path
538
+
539
+
540
+ # =============================================================================
541
+ # TTS ENGINE: YourVoic API + Local MMS-TTS
542
+ # =============================================================================
543
+
544
+ YOURVOIC_API_KEY = os.environ.get("YOURVOIC_API_KEY", "")
545
+ YOURVOIC_STREAM_URL = "https://yourvoic.com/api/v1/tts/stream"
546
+
547
+
548
+ def synthesize_yourvoic(text, language_code, voice="Peter", speed=1.0):
549
+ """
550
+ Synthesize text using YourVoic API.
551
+ Returns (audio_array, sample_rate) or raises on failure.
552
+ """
553
+ if not YOURVOIC_API_KEY:
554
+ raise RuntimeError(
555
+ "YOURVOIC_API_KEY not set. Add it as a Space secret."
556
+ )
557
+
558
+ headers = {
559
+ "X-API-Key": YOURVOIC_API_KEY,
560
+ "Content-Type": "application/json",
561
+ }
562
+ payload = {
563
+ "text": text,
564
+ "voice": voice,
565
+ "language": language_code,
566
+ "model": "aura-prime",
567
+ "speed": speed,
568
+ }
569
+
570
+ t0 = time.time()
571
+ response = requests.post(
572
+ YOURVOIC_STREAM_URL,
573
+ headers=headers,
574
+ json=payload,
575
+ stream=True,
576
+ timeout=60,
577
+ )
578
+
579
+ if response.status_code != 200:
580
+ raise RuntimeError(
581
+ f"YourVoic API error {response.status_code}: {response.text[:200]}"
582
+ )
583
+
584
+ # Collect streamed audio bytes into a temp file
585
+ import tempfile
586
+ tmp_raw = tempfile.NamedTemporaryFile(suffix=".audio", delete=False)
587
+ for chunk in response.iter_content(chunk_size=8192):
588
+ tmp_raw.write(chunk)
589
+ tmp_raw.close()
590
+
591
+ elapsed = time.time() - t0
592
+ logger.info(f"YourVoic TTS: {len(text)} chars, {elapsed:.2f}s")
593
+
594
+ # Try reading directly with soundfile
595
+ try:
596
+ audio_array, sample_rate = sf.read(tmp_raw.name, dtype="float32")
597
+ os.unlink(tmp_raw.name)
598
+ return audio_array, sample_rate
599
+ except Exception as e:
600
+ logger.warning(f"soundfile can't read YourVoic output directly: {e}")
601
+
602
+ # Fallback: convert with ffmpeg to WAV
603
+ try:
604
+ import subprocess
605
+ tmp_wav = tmp_raw.name + ".wav"
606
+ result = subprocess.run(
607
+ ["ffmpeg", "-y", "-i", tmp_raw.name,
608
+ "-acodec", "pcm_s16le", "-ar", "24000", "-ac", "1", tmp_wav],
609
+ capture_output=True, text=True,
610
+ )
611
+ os.unlink(tmp_raw.name)
612
+ if result.returncode != 0:
613
+ raise RuntimeError(f"ffmpeg conversion failed: {result.stderr[:200]}")
614
+ audio_array, sample_rate = sf.read(tmp_wav, dtype="float32")
615
+ os.unlink(tmp_wav)
616
+ return audio_array, sample_rate
617
+ except Exception as e2:
618
+ # Clean up
619
+ for f in [tmp_raw.name, tmp_raw.name + ".wav"]:
620
+ if os.path.exists(f):
621
+ os.unlink(f)
622
+ raise RuntimeError(f"Failed to decode YourVoic audio: {e2}")
623
+
624
+
625
+ def synthesize_yourvoic_to_file(text, language_code, output_path, voice="Peter", speed=1.0):
626
+ """Synthesize via YourVoic and save to file."""
627
+ audio, sr = synthesize_yourvoic(text, language_code, voice, speed)
628
+ sf.write(output_path, audio, sr)
629
+ return output_path, sr
630
+
631
+
632
+ def synthesize_local(text, tts_pipe):
633
+ """
634
+ Synthesize text using local HuggingFace TTS pipeline (MMS-TTS).
635
+ Returns (audio_array, sample_rate).
636
+ """
637
+ t0 = time.time()
638
+ result = tts_pipe(text)
639
+ audio = np.array(result["audio"]).squeeze()
640
+ sr = result["sampling_rate"]
641
+ elapsed = time.time() - t0
642
+ logger.info(f"Local TTS: {len(text)} chars, {elapsed:.2f}s, {len(audio)/sr:.1f}s audio")
643
+ return audio, sr
644
+
645
+
646
+ def synthesize_chunked(text, language_config, tts_pipe=None, sentences_per_chunk=2):
647
+ """
648
+ Synthesize long text by chunking into sentence groups.
649
+ Routes to either YourVoic or local TTS based on language config.
650
+
651
+ Args:
652
+ text: Full text to synthesize
653
+ language_config: Dict from LANGUAGES (has tts_engine, yourvoic_lang, etc.)
654
+ tts_pipe: Local HuggingFace TTS pipeline (needed for local engine)
655
+ sentences_per_chunk: How many sentences to synthesize per API call
656
+
657
+ Returns:
658
+ (audio_array, sample_rate)
659
+ """
660
+ import re
661
+ sentences = re.split(r'(?<=[.!?])\s+', text)
662
+ sentences = [s.strip() for s in sentences if s.strip()]
663
+
664
+ if not sentences:
665
+ return np.array([], dtype=np.float32), 16000
666
+
667
+ engine = language_config["tts_engine"]
668
+ audio_segments = []
669
+ output_sr = None
670
+
671
+ for i in range(0, len(sentences), sentences_per_chunk):
672
+ chunk_text = ' '.join(sentences[i:i + sentences_per_chunk])
673
+ if not chunk_text:
674
+ continue
675
+
676
+ try:
677
+ if engine == "yourvoic":
678
+ voice = language_config["yourvoic_voices"][0] if language_config["yourvoic_voices"] else "Peter"
679
+ lang_code = language_config["yourvoic_lang"]
680
+ audio_seg, seg_sr = synthesize_yourvoic(chunk_text, lang_code, voice)
681
+ else:
682
+ if tts_pipe is None:
683
+ raise RuntimeError("Local TTS pipeline not loaded")
684
+ audio_seg, seg_sr = synthesize_local(chunk_text, tts_pipe)
685
+
686
+ if output_sr is None:
687
+ output_sr = seg_sr
688
+ if len(audio_seg) > 0:
689
+ audio_segments.append(audio_seg)
690
+ # Small silence between chunks
691
+ silence = np.zeros(int(0.15 * seg_sr), dtype=np.float32)
692
+ audio_segments.append(silence)
693
+
694
+ except Exception as e:
695
+ logger.error(f"TTS chunk failed: {e}")
696
+ continue
697
+
698
+ if not audio_segments:
699
+ # Return a short silence instead of empty array to prevent Gradio crash
700
+ fallback_sr = output_sr or 16000
701
+ silence = np.zeros(int(0.5 * fallback_sr), dtype=np.float32)
702
+ logger.warning("All TTS chunks failed — returning silence")
703
+ return silence, fallback_sr
704
+
705
+ return np.concatenate(audio_segments), output_sr
706
+
707
+
708
+ # =============================================================================
709
+ # QWEN OMNI ENGINE
710
+ # =============================================================================
711
+
712
+ QWEN_MODEL = "qwen3.5-omni-plus"
713
+ QWEN_BASE_URL = "https://dashscope-intl.aliyuncs.com/compatible-mode/v1"
714
+
715
+
716
+ def _get_client():
717
+ """Create OpenAI-compatible client for Qwen Dashscope API."""
718
+ from openai import OpenAI
719
+ api_key = os.environ.get("DASHSCOPE_API_KEY", "")
720
+ if not api_key:
721
+ raise RuntimeError(
722
+ "DASHSCOPE_API_KEY not set. Add it as a Space secret."
723
+ )
724
+ return OpenAI(api_key=api_key, base_url=QWEN_BASE_URL)
725
+
726
+
727
+ def _wav_to_base64(wav_path):
728
+ """Read WAV file and return base64 string."""
729
+ with open(wav_path, "rb") as f:
730
+ return base64.b64encode(f.read()).decode("utf-8")
731
+
732
+
733
+ def _base64_to_wav(b64_data, output_path):
734
+ """Convert raw PCM base64 audio to WAV file (24kHz, mono, 16-bit)."""
735
+ audio_bytes = base64.b64decode(b64_data)
736
+ sample_rate = 24000
737
+ num_channels = 1
738
+ bits_per_sample = 16
739
+ byte_rate = sample_rate * num_channels * bits_per_sample // 8
740
+ block_align = num_channels * bits_per_sample // 8
741
+ data_size = len(audio_bytes)
742
+ with open(output_path, "wb") as f:
743
+ f.write(b"RIFF")
744
+ f.write(struct.pack("<I", 36 + data_size))
745
+ f.write(b"WAVE")
746
+ f.write(b"fmt ")
747
+ f.write(struct.pack("<I", 16))
748
+ f.write(struct.pack("<H", 1))
749
+ f.write(struct.pack("<H", num_channels))
750
+ f.write(struct.pack("<I", sample_rate))
751
+ f.write(struct.pack("<I", byte_rate))
752
+ f.write(struct.pack("<H", block_align))
753
+ f.write(struct.pack("<H", bits_per_sample))
754
+ f.write(b"data")
755
+ f.write(struct.pack("<I", data_size))
756
+ f.write(audio_bytes)
757
+
758
+
759
+ def _extract_audio_chunk(video_path, output_wav, start_sec, duration_sec):
760
+ """Extract a chunk of audio from video as 16kHz mono WAV."""
761
+ subprocess.run(
762
+ ["ffmpeg", "-y", "-ss", str(start_sec), "-t", str(duration_sec),
763
+ "-i", video_path, "-vn", "-acodec", "pcm_s16le",
764
+ "-ar", "16000", "-ac", "1", output_wav],
765
+ capture_output=True, check=True,
766
+ )
767
+
768
+
769
+ def _get_duration(filepath):
770
+ """Get media file duration in seconds."""
771
+ result = subprocess.run(
772
+ ["ffprobe", "-v", "quiet", "-show_entries", "format=duration",
773
+ "-of", "default=noprint_wrappers=1:nokey=1", filepath],
774
+ capture_output=True, text=True,
775
+ )
776
+ return float(result.stdout.strip())
777
+
778
+
779
+ def _concatenate_wavs(wav_files, output_path):
780
+ """Concatenate WAV files using ffmpeg."""
781
+ if len(wav_files) == 1:
782
+ shutil.copy2(wav_files[0], output_path)
783
+ return
784
+ list_file = output_path + ".txt"
785
+ with open(list_file, "w") as f:
786
+ for wav in wav_files:
787
+ f.write(f"file '{wav}'\n")
788
+ subprocess.run(
789
+ ["ffmpeg", "-y", "-f", "concat", "-safe", "0",
790
+ "-i", list_file, "-c", "copy", output_path],
791
+ capture_output=True, check=True,
792
+ )
793
+ os.remove(list_file)
794
+
795
+
796
+ def _build_system_prompt(language_name):
797
+ """Build Qwen system prompt for a target language."""
798
+ return (
799
+ f"You are a professional video dubbing translator. You will receive audio in English.\n"
800
+ f"Your task:\n"
801
+ f"1. Listen carefully to the English speech.\n"
802
+ f"2. Translate it into natural, fluent {language_name}.\n"
803
+ f"3. Respond ONLY with the {language_name} translation spoken aloud — no English, no commentary,\n"
804
+ f" no meta-text, no transliteration. Speak entirely in {language_name}.\n"
805
+ f"4. Match the tone, emotion, and pacing of the original speaker as closely as possible.\n"
806
+ f"5. If there are pauses or silence in the original audio, maintain similar pacing.\n"
807
+ f"6. Translate idioms and cultural references into their {language_name} equivalents.\n"
808
+ f"7. Use clear, professional pronunciation suitable for a broad audience."
809
+ )
810
+
811
+
812
+ def translate_chunk_qwen(wav_path, voice, language_name, chunk_index=0):
813
+ """
814
+ Translate a single audio chunk using Qwen Omni.
815
+
816
+ Args:
817
+ wav_path: Path to input WAV file (English audio)
818
+ voice: Qwen voice name (e.g. "Ethan", "Cherry")
819
+ language_name: Full language name for the system prompt
820
+ chunk_index: For logging
821
+
822
+ Returns:
823
+ (output_wav_path, transcript) or (None, transcript) if no audio
824
+ """
825
+ client = _get_client()
826
+ audio_b64 = _wav_to_base64(wav_path)
827
+ output_wav = wav_path.replace(".wav", f"_qwen_{chunk_index}.wav")
828
+
829
+ system_prompt = _build_system_prompt(language_name)
830
+ user_prompt = f"Translate this English speech into {language_name}. Respond only with the spoken {language_name} translation."
831
+
832
+ t0 = time.time()
833
+ completion = client.chat.completions.create(
834
+ model=QWEN_MODEL,
835
+ messages=[
836
+ {"role": "system", "content": system_prompt},
837
+ {
838
+ "role": "user",
839
+ "content": [
840
+ {
841
+ "type": "input_audio",
842
+ "input_audio": {
843
+ "data": f"data:audio/wav;base64,{audio_b64}",
844
+ "format": "wav",
845
+ },
846
+ },
847
+ {"type": "text", "text": user_prompt},
848
+ ],
849
+ },
850
+ ],
851
+ modalities=["text", "audio"],
852
+ audio={"voice": voice, "format": "wav"},
853
+ stream=True,
854
+ stream_options={"include_usage": True},
855
+ )
856
+
857
+ audio_chunks = []
858
+ transcript_parts = []
859
+
860
+ for event in completion:
861
+ if not event.choices:
862
+ continue
863
+ delta = event.choices[0].delta
864
+ if hasattr(delta, "content") and delta.content:
865
+ transcript_parts.append(delta.content)
866
+ if hasattr(delta, "audio") and delta.audio:
867
+ if isinstance(delta.audio, dict):
868
+ if "data" in delta.audio:
869
+ audio_chunks.append(delta.audio["data"])
870
+ elif hasattr(delta.audio, "data") and delta.audio.data:
871
+ audio_chunks.append(delta.audio.data)
872
+
873
+ transcript = "".join(transcript_parts)
874
+ elapsed = time.time() - t0
875
+ logger.info(f"Qwen chunk {chunk_index}: {elapsed:.1f}s, transcript={transcript[:60]}")
876
+
877
+ if audio_chunks:
878
+ full_audio_b64 = "".join(audio_chunks)
879
+ _base64_to_wav(full_audio_b64, output_wav)
880
+ return output_wav, transcript
881
+
882
+ return None, transcript
883
+
884
+
885
+ def dub_video_qwen(video_path, language_name, voice="Ethan", chunk_seconds=120, progress_fn=None):
886
+ """
887
+ Full video dubbing pipeline using Qwen Omni.
888
+ Splits video into chunks, translates each chunk via Qwen API,
889
+ concatenates results, and muxes back onto video.
890
+
891
+ Args:
892
+ video_path: Path to input video
893
+ language_name: Full language name (e.g. "French", "Arabic")
894
+ voice: Qwen voice name
895
+ chunk_seconds: Audio chunk duration for API calls
896
+ progress_fn: Optional gradio progress callback
897
+
898
+ Returns:
899
+ (output_video_path, log_text)
900
+ """
901
+ tmp_dir = tempfile.mkdtemp(prefix=f"qwen_dub_")
902
+ log = []
903
+
904
+ try:
905
+ # Duration
906
+ if progress_fn:
907
+ progress_fn(0.05, desc="Analyzing video...")
908
+ total_duration = _get_duration(video_path)
909
+ log.append(f"**Video:** {total_duration:.1f}s")
910
+ log.append(f"**Engine:** Qwen 3.5 Omni")
911
+ log.append(f"**Voice:** {voice}")
912
+ log.append(f"**Language:** {language_name}")
913
+
914
+ if total_duration > 3600:
915
+ return None, "Video longer than 1 hour — please use a shorter clip."
916
+
917
+ # Split into chunks
918
+ if progress_fn:
919
+ progress_fn(0.1, desc="Extracting audio chunks...")
920
+ num_chunks = max(1, int(total_duration // chunk_seconds) + (1 if total_duration % chunk_seconds > 0 else 0))
921
+ log.append(f"**Chunks:** {num_chunks} ({chunk_seconds}s each)")
922
+
923
+ input_chunks = []
924
+ for i in range(num_chunks):
925
+ start = i * chunk_seconds
926
+ duration = min(chunk_seconds, total_duration - start)
927
+ chunk_path = os.path.join(tmp_dir, f"chunk_{i:03d}.wav")
928
+ _extract_audio_chunk(video_path, chunk_path, start, duration)
929
+ input_chunks.append(chunk_path)
930
+
931
+ # Translate each chunk
932
+ output_chunks = []
933
+ all_transcripts = []
934
+
935
+ for i, chunk_path in enumerate(input_chunks):
936
+ if progress_fn:
937
+ frac = 0.15 + 0.7 * (i / num_chunks)
938
+ progress_fn(frac, desc=f"Translating chunk {i+1}/{num_chunks}...")
939
+
940
+ result_path, transcript = translate_chunk_qwen(
941
+ chunk_path, voice, language_name, i
942
+ )
943
+ if transcript:
944
+ all_transcripts.append(f"**[{i+1}]** {transcript}")
945
+
946
+ if result_path:
947
+ output_chunks.append(result_path)
948
+ else:
949
+ # Silence fallback
950
+ duration = _get_duration(chunk_path)
951
+ silence_path = os.path.join(tmp_dir, f"silence_{i:03d}.wav")
952
+ subprocess.run(
953
+ ["ffmpeg", "-y", "-f", "lavfi",
954
+ "-i", "anullsrc=r=24000:cl=mono",
955
+ "-t", str(duration), "-acodec", "pcm_s16le", silence_path],
956
+ capture_output=True, check=True,
957
+ )
958
+ output_chunks.append(silence_path)
959
+
960
+ # Concatenate
961
+ if progress_fn:
962
+ progress_fn(0.88, desc="Assembling audio...")
963
+ full_audio = os.path.join(tmp_dir, "full_dubbed.wav")
964
+ _concatenate_wavs(output_chunks, full_audio)
965
+
966
+ # Mux onto video
967
+ if progress_fn:
968
+ progress_fn(0.93, desc="Combining audio and video...")
969
+ output_video = os.path.join(tmp_dir, "dubbed_output.mp4")
970
+ subprocess.run(
971
+ ["ffmpeg", "-y", "-i", video_path, "-i", full_audio,
972
+ "-c:v", "copy", "-map", "0:v:0", "-map", "1:a:0",
973
+ "-shortest", output_video],
974
+ capture_output=True, check=True,
975
+ )
976
+
977
+ if progress_fn:
978
+ progress_fn(1.0, desc="Done!")
979
+
980
+ log.append(f"\n**Transcript:**")
981
+ log.extend(all_transcripts)
982
+
983
+ return output_video, "\n".join(log)
984
+
985
+ except Exception as e:
986
+ logger.exception("Qwen dubbing failed")
987
+ shutil.rmtree(tmp_dir, ignore_errors=True)
988
+ return None, f"Error: {str(e)}"
989
+
990
+
991
+ # =============================================================================
992
+ # GRADIO APP
993
+ # =============================================================================
994
+
995
+ # Load models at startup
996
+ load_models()
997
+
998
+ # =============================================================================
999
+ # Helper functions
1000
+ # =============================================================================
1001
+
1002
+ def get_voices_for_language(lang_name):
1003
+ """Get available voices for a language based on its engine."""
1004
+ config = LANGUAGES.get(lang_name, {})
1005
+ engine = config.get("tts_engine", "local")
1006
+ if engine == "qwen":
1007
+ return QWEN_VOICES
1008
+ elif engine == "yourvoic" and config.get("yourvoic_voices"):
1009
+ return config["yourvoic_voices"]
1010
+ elif engine == "local":
1011
+ return ["Default (local model)"]
1012
+ return ["Peter"]
1013
+
1014
+
1015
+ def full_pipeline_audio(audio_input, target_language):
1016
+ """Full pipeline: English audio → target language audio."""
1017
+ if audio_input is None:
1018
+ return None, "Please upload or record audio."
1019
+
1020
+ lang_config = LANGUAGES.get(target_language)
1021
+ if not lang_config:
1022
+ return None, f"Language '{target_language}' not configured."
1023
+
1024
+ sample_rate, audio_array = audio_input
1025
+ audio_array = audio_array.astype(np.float32)
1026
+ if audio_array.ndim > 1:
1027
+ audio_array = audio_array.mean(axis=1)
1028
+ if audio_array.max() > 1.0 or audio_array.min() < -1.0:
1029
+ max_val = max(abs(audio_array.max()), abs(audio_array.min()))
1030
+ if max_val > 0:
1031
+ audio_array = audio_array / max_val
1032
+
1033
+ log = []
1034
+ total_start = time.time()
1035
+
1036
+ # ASR
1037
+ t0 = time.time()
1038
+ english = transcribe(audio_array, sample_rate)
1039
+ log.append(f"**ASR** ({time.time()-t0:.2f}s)\n{english}")
1040
+ if not english:
1041
+ return None, "ASR returned empty text."
1042
+
1043
+ # MT
1044
+ t0 = time.time()
1045
+ nllb_code = lang_config["nllb"]
1046
+ translated, en_sents, tgt_sents = translate_text(english, nllb_code, fast=False)
1047
+ log.append(f"\n**Translation** ({time.time()-t0:.2f}s)")
1048
+ for e, t in zip(en_sents, tgt_sents):
1049
+ log.append(f" EN: {e}\n {target_language.upper()}: {t}")
1050
+ if not translated:
1051
+ return None, "Translation returned empty."
1052
+
1053
+ # TTS
1054
+ t0 = time.time()
1055
+ audio_out, sr_out = synthesize_chunked(
1056
+ translated, lang_config, tts_pipe=tts_pipe_local
1057
+ )
1058
+ log.append(f"\n**TTS** ({time.time()-t0:.2f}s) = {len(audio_out)/sr_out:.1f}s audio")
1059
+
1060
+ total = time.time() - total_start
1061
+ log.append(f"\n**Total: {total:.2f}s**")
1062
+
1063
+ return (sr_out, audio_out), "\n".join(log)
1064
+
1065
+
1066
+ def full_pipeline_text(english_text, target_language, voice_name):
1067
+ """Text-only pipeline: English text → target language audio."""
1068
+ if not english_text or not english_text.strip():
1069
+ return None, "Please enter English text."
1070
+
1071
+ lang_config = LANGUAGES.get(target_language)
1072
+ if not lang_config:
1073
+ return None, f"Language '{target_language}' not configured."
1074
+
1075
+ log = []
1076
+ total_start = time.time()
1077
+
1078
+ # MT
1079
+ t0 = time.time()
1080
+ nllb_code = lang_config["nllb"]
1081
+ translated, en_sents, tgt_sents = translate_text(english_text.strip(), nllb_code, fast=False)
1082
+ log.append(f"**Translation** ({time.time()-t0:.2f}s)")
1083
+ for e, t in zip(en_sents, tgt_sents):
1084
+ log.append(f" EN: {e}\n {target_language.upper()}: {t}")
1085
+ if not translated:
1086
+ return None, "Translation returned empty."
1087
+
1088
+ # TTS
1089
+ t0 = time.time()
1090
+ audio_out, sr_out = synthesize_chunked(
1091
+ translated, lang_config, tts_pipe=tts_pipe_local
1092
+ )
1093
+ log.append(f"\n**TTS** ({time.time()-t0:.2f}s) = {len(audio_out)/sr_out:.1f}s audio")
1094
+
1095
+ total = time.time() - total_start
1096
+ log.append(f"\n**Total: {total:.2f}s**")
1097
+
1098
+ return (sr_out, audio_out), "\n".join(log)
1099
+
1100
+
1101
+ def dub_video(video_path, target_languages, dub_voice, chunk_seconds, progress=gr.Progress()):
1102
+ """
1103
+ Dub a video into one or more target languages.
1104
+ Routes to Qwen Omni for global languages, local pipeline for African languages.
1105
+ """
1106
+ if video_path is None:
1107
+ return None, "Please upload a video."
1108
+
1109
+ if not target_languages:
1110
+ return None, "Please select at least one target language."
1111
+
1112
+ results_log = []
1113
+ output_videos = []
1114
+
1115
+ for lang_name in target_languages:
1116
+ lang_config = LANGUAGES.get(lang_name)
1117
+ if not lang_config:
1118
+ results_log.append(f"**{lang_name}**: not configured, skipped")
1119
+ continue
1120
+
1121
+ engine = lang_config.get("tts_engine", "local")
1122
+ results_log.append(f"\n{'='*50}")
1123
+ results_log.append(f"**Dubbing: {lang_name}** (engine: {engine})")
1124
+ results_log.append(f"{'='*50}")
1125
+
1126
+ try:
1127
+ if engine == "qwen":
1128
+ # Qwen Omni: end-to-end speech-to-speech (best for global languages)
1129
+ qwen_lang_name = lang_config.get("qwen_name", lang_name)
1130
+ voice = dub_voice if dub_voice in QWEN_VOICES else "Ethan"
1131
+ out_video, log_text = dub_video_qwen(
1132
+ video_path, qwen_lang_name, voice=voice,
1133
+ chunk_seconds=chunk_seconds, progress_fn=progress,
1134
+ )
1135
+ results_log.append(log_text)
1136
+ if out_video:
1137
+ output_videos.append(out_video)
1138
+
1139
+ else:
1140
+ # Local/YourVoic pipeline: ASR → NLLB → TTS
1141
+ work_dir = tempfile.mkdtemp(prefix=f"dub_{lang_name}_")
1142
+ extracted_audio = os.path.join(work_dir, "audio.wav")
1143
+ tgt_audio_raw = os.path.join(work_dir, "tgt_raw.wav")
1144
+ tgt_audio_aligned = os.path.join(work_dir, "tgt_aligned.wav")
1145
+ output_video = os.path.join(work_dir, f"dubbed_{lang_name}.mp4")
1146
+
1147
+ progress(0.05, desc=f"{lang_name}: extracting audio...")
1148
+ extract_audio_from_video(video_path, extracted_audio)
1149
+ video_duration = get_media_duration(video_path)
1150
+ results_log.append(f"Video: {video_duration:.1f}s")
1151
+
1152
+ audio_array, sr = sf.read(extracted_audio, dtype="float32")
1153
+ if audio_array.ndim > 1:
1154
+ audio_array = audio_array.mean(axis=1)
1155
+
1156
+ progress(0.15, desc=f"{lang_name}: transcribing...")
1157
+ t0 = time.time()
1158
+ english = transcribe(audio_array, sr)
1159
+ results_log.append(f"ASR: {time.time()-t0:.1f}s")
1160
+ if not english:
1161
+ results_log.append("ASR empty — skipped")
1162
+ continue
1163
+
1164
+ progress(0.4, desc=f"{lang_name}: translating...")
1165
+ t0 = time.time()
1166
+ nllb_code = lang_config["nllb"]
1167
+ translated, _, _ = translate_text(english, nllb_code, fast=True)
1168
+ results_log.append(f"MT: {time.time()-t0:.1f}s")
1169
+ if not translated:
1170
+ results_log.append("Translation empty — skipped")
1171
+ continue
1172
+
1173
+ progress(0.65, desc=f"{lang_name}: synthesizing...")
1174
+ t0 = time.time()
1175
+ tgt_audio, tgt_sr = synthesize_chunked(
1176
+ translated, lang_config, tts_pipe=tts_pipe_local
1177
+ )
1178
+ sf.write(tgt_audio_raw, tgt_audio, tgt_sr)
1179
+ tgt_duration = len(tgt_audio) / tgt_sr
1180
+ results_log.append(f"TTS: {time.time()-t0:.1f}s ({tgt_duration:.1f}s audio)")
1181
+
1182
+ progress(0.85, desc=f"{lang_name}: aligning...")
1183
+ MAX_STRETCH = 1.2
1184
+ stretch_ratio = tgt_duration / video_duration
1185
+
1186
+ if stretch_ratio <= MAX_STRETCH:
1187
+ if abs(stretch_ratio - 1.0) > 0.02:
1188
+ stretch_audio_to_duration(tgt_audio_raw, tgt_audio_aligned, video_duration)
1189
+ else:
1190
+ import shutil
1191
+ shutil.copy(tgt_audio_raw, tgt_audio_aligned)
1192
+ extend_video = False
1193
+ final_duration = video_duration
1194
+ else:
1195
+ shutil.copy(tgt_audio_raw, tgt_audio_aligned)
1196
+ extend_video = True
1197
+ final_duration = tgt_duration
1198
+ results_log.append(f"Audio longer ({stretch_ratio:.1f}x) — extending video")
1199
+
1200
+ progress(0.95, desc=f"{lang_name}: combining...")
1201
+ mux_video_audio(
1202
+ video_path, tgt_audio_aligned, output_video,
1203
+ extend_video=extend_video, target_duration=final_duration
1204
+ )
1205
+ output_videos.append(output_video)
1206
+
1207
+ except Exception as e:
1208
+ logger.exception(f"Dubbing {lang_name} failed")
1209
+ results_log.append(f"Error: {str(e)}")
1210
+
1211
+ progress(1.0, desc="Done!")
1212
+ final_video = output_videos[0] if output_videos else None
1213
+ return final_video, "\n".join(results_log)
1214
+
1215
+
1216
+ def update_voices(language):
1217
+ """Update voice dropdown when language changes."""
1218
+ voices = get_voices_for_language(language)
1219
+ return gr.update(choices=voices, value=voices[0])
1220
+
1221
+
1222
+ # =============================================================================
1223
+ # Gradio UI
1224
+ # =============================================================================
1225
+
1226
+ EXAMPLES = [
1227
+ "And it's a brilliant goal from the striker!",
1228
+ "The referee has shown a yellow card. Corner kick for the home team.",
1229
+ "What a save by the goalkeeper! The match is heading into injury time.",
1230
+ "He dribbles past two defenders and shoots! The ball hits the back of the net!",
1231
+ ]
1232
+
1233
+ CSS = """
1234
+ .main-header { text-align: center; margin-bottom: 0.5rem; }
1235
+ .main-header h1 { font-size: 1.8rem; font-weight: 700; margin: 0; }
1236
+ .main-header p { color: #666; font-size: 0.95rem; }
1237
+ .lang-group-label { font-weight: 600; font-size: 0.85rem; color: #888; text-transform: uppercase; letter-spacing: 0.05em; margin-top: 0.5rem; }
1238
+ """
1239
+
1240
+ with gr.Blocks(
1241
+ title="PlotWeaver — Live Commentary Translation",
1242
+ theme=gr.themes.Soft(),
1243
+ css=CSS,
1244
+ ) as demo:
1245
+
1246
+ gr.HTML("""
1247
+ <div class="main-header">
1248
+ <h1>PlotWeaver</h1>
1249
+ <p>Live commentary translation platform &mdash; English to 40+ languages</p>
1250
+ <p style="font-size:0.8rem; color:#999">ASR (Whisper) &rarr; MT (NLLB-200) &rarr; TTS (YourVoic + local models)</p>
1251
+ </div>
1252
+ """)
1253
+
1254
+ with gr.Tabs():
1255
+
1256
+ # ====== TAB 1: EVENT MANAGEMENT ======
1257
+ with gr.TabItem("Event Management"):
1258
+ gr.Markdown("### Create new event")
1259
+ gr.Markdown("Configure your live broadcast event with target languages and input source.")
1260
+
1261
+ with gr.Row():
1262
+ with gr.Column(scale=2):
1263
+ event_name = gr.Textbox(
1264
+ label="Event name",
1265
+ placeholder="e.g. Premier League: Arsenal vs. Chelsea",
1266
+ )
1267
+ with gr.Row():
1268
+ start_time = gr.Textbox(label="Start time", placeholder="08:30 PM")
1269
+ end_time = gr.Textbox(label="End time", placeholder="10:30 PM")
1270
+ event_date = gr.Textbox(label="Date", placeholder="2026-06-06")
1271
+
1272
+ gr.Markdown("#### Input source")
1273
+ input_method = gr.Radio(
1274
+ choices=["RTMP Stream", "WebRTC (Browser)", "Direct Audio Feed"],
1275
+ value="RTMP Stream",
1276
+ label="Input method",
1277
+ )
1278
+
1279
+ gr.Markdown("#### Target languages")
1280
+ gr.Markdown("Select languages for simultaneous broadcast. Additional languages consume more stream minutes.")
1281
+
1282
+ # Language checkboxes grouped by category
1283
+ target_langs = gr.CheckboxGroup(
1284
+ choices=ALL_LANGUAGE_NAMES,
1285
+ label="Languages",
1286
+ value=["Yoruba"],
1287
+ )
1288
+
1289
+ with gr.Column(scale=1):
1290
+ gr.Markdown("#### Estimate summary")
1291
+ estimate_display = gr.Markdown(
1292
+ value="**Event:** Not configured\n\n**Languages:** 1 selected\n\n**Estimated duration:** --\n\n**Total estimate:** --"
1293
+ )
1294
+ create_event_btn = gr.Button("Create Event", variant="primary", size="lg")
1295
+ event_status = gr.Markdown("")
1296
+
1297
+ def update_estimate(name, langs, start, end):
1298
+ n_langs = len(langs) if langs else 0
1299
+ lang_list = ", ".join(langs) if langs else "None"
1300
+ return (
1301
+ f"**Event:** {name or 'Not set'}\n\n"
1302
+ f"**Languages:** {n_langs} selected\n\n"
1303
+ f"{lang_list}\n\n"
1304
+ f"**Input:** Configured\n\n"
1305
+ f"**Rate:** 1x (Standard)"
1306
+ )
1307
+
1308
+ for inp in [event_name, target_langs, start_time, end_time]:
1309
+ inp.change(
1310
+ fn=update_estimate,
1311
+ inputs=[event_name, target_langs, start_time, end_time],
1312
+ outputs=[estimate_display],
1313
+ )
1314
+
1315
+ def create_event(name, langs):
1316
+ if not name:
1317
+ return "Please enter an event name."
1318
+ if not langs:
1319
+ return "Please select at least one language."
1320
+ return f"Event **{name}** created with {len(langs)} languages: {', '.join(langs)}"
1321
+
1322
+ create_event_btn.click(
1323
+ fn=create_event,
1324
+ inputs=[event_name, target_langs],
1325
+ outputs=[event_status],
1326
+ )
1327
+
1328
+ # ====== TAB 2: LIVE STUDIO ======
1329
+ with gr.TabItem("Live Studio"):
1330
+ gr.Markdown("### Live streaming translation")
1331
+ gr.Markdown("Record or stream English commentary and hear it translated in real-time.")
1332
+
1333
+ with gr.Row():
1334
+ studio_language = gr.Dropdown(
1335
+ choices=ALL_LANGUAGE_NAMES,
1336
+ value="Yoruba",
1337
+ label="Target language",
1338
+ )
1339
+ studio_voice = gr.Dropdown(
1340
+ choices=get_voices_for_language("Yoruba"),
1341
+ value=get_voices_for_language("Yoruba")[0],
1342
+ label="Voice",
1343
+ )
1344
+
1345
+ studio_language.change(
1346
+ fn=update_voices,
1347
+ inputs=[studio_language],
1348
+ outputs=[studio_voice],
1349
+ )
1350
+
1351
+ with gr.Row():
1352
+ with gr.Column():
1353
+ studio_audio_in = gr.Audio(
1354
+ label="English commentary (upload or record)",
1355
+ type="numpy",
1356
+ sources=["upload", "microphone"],
1357
+ )
1358
+ studio_translate_btn = gr.Button("Translate", variant="primary", size="lg")
1359
+
1360
+ with gr.Column():
1361
+ studio_audio_out = gr.Audio(label="Translated audio", type="numpy", autoplay=True)
1362
+ studio_log = gr.Markdown(label="Pipeline log")
1363
+
1364
+ studio_translate_btn.click(
1365
+ fn=full_pipeline_audio,
1366
+ inputs=[studio_audio_in, studio_language],
1367
+ outputs=[studio_audio_out, studio_log],
1368
+ )
1369
+
1370
+ # ====== TAB 3: VIDEO DUBBING ======
1371
+ with gr.TabItem("Video Dubbing"):
1372
+ gr.Markdown("### Video dubbing (English → multi-language)")
1373
+ gr.Markdown(
1374
+ "Upload a video with English commentary and get back a dubbed version. "
1375
+ "**Global languages** (Arabic, French, Spanish, etc.) use Qwen Omni for best quality. "
1376
+ "**African languages** (Yoruba, Hausa, etc.) use the local Whisper → NLLB → MMS-TTS pipeline."
1377
+ )
1378
+
1379
+ with gr.Row():
1380
+ with gr.Column():
1381
+ dub_video_in = gr.Video(label="Upload English video", sources=["upload"])
1382
+ dub_languages = gr.CheckboxGroup(
1383
+ choices=ALL_LANGUAGE_NAMES,
1384
+ label="Target languages",
1385
+ value=["Yoruba"],
1386
+ )
1387
+ with gr.Row():
1388
+ dub_voice = gr.Dropdown(
1389
+ choices=QWEN_VOICES,
1390
+ value="Ethan",
1391
+ label="Voice (for Qwen languages)",
1392
+ info="Applies to Arabic, French, Spanish, etc. Local languages use default voice.",
1393
+ )
1394
+ dub_chunk_slider = gr.Slider(
1395
+ minimum=30, maximum=300, value=120, step=10,
1396
+ label="Chunk duration (seconds)",
1397
+ info="Shorter = more API calls but less timeout risk.",
1398
+ )
1399
+ dub_btn = gr.Button("Dub Video", variant="primary", size="lg")
1400
+
1401
+ with gr.Column():
1402
+ dub_video_out = gr.Video(label="Dubbed video (download from player)")
1403
+ dub_log = gr.Markdown(
1404
+ label="Processing log",
1405
+ value="Upload a video and select languages to start."
1406
+ )
1407
+
1408
+ dub_btn.click(
1409
+ fn=dub_video,
1410
+ inputs=[dub_video_in, dub_languages, dub_voice, dub_chunk_slider],
1411
+ outputs=[dub_video_out, dub_log],
1412
+ )
1413
+
1414
+ # ====== TAB 4: TEXT TRANSLATION ======
1415
+ with gr.TabItem("Text \u2192 Audio"):
1416
+ gr.Markdown("### Text to translated speech")
1417
+ gr.Markdown("Type English text, choose a language, and hear the translated audio.")
1418
+
1419
+ with gr.Row():
1420
+ text_language = gr.Dropdown(
1421
+ choices=ALL_LANGUAGE_NAMES,
1422
+ value="Yoruba",
1423
+ label="Target language",
1424
+ )
1425
+ text_voice = gr.Dropdown(
1426
+ choices=get_voices_for_language("Yoruba"),
1427
+ value=get_voices_for_language("Yoruba")[0],
1428
+ label="Voice",
1429
+ )
1430
+
1431
+ text_language.change(
1432
+ fn=update_voices,
1433
+ inputs=[text_language],
1434
+ outputs=[text_voice],
1435
+ )
1436
+
1437
+ with gr.Row():
1438
+ with gr.Column():
1439
+ text_input = gr.Textbox(
1440
+ label="English text",
1441
+ placeholder="Type English football commentary here...",
1442
+ lines=4,
1443
+ )
1444
+ text_btn = gr.Button("Translate to speech", variant="primary", size="lg")
1445
+ gr.Examples(
1446
+ examples=[[e] for e in EXAMPLES],
1447
+ inputs=[text_input],
1448
+ label="Example commentary",
1449
+ )
1450
+
1451
+ with gr.Column():
1452
+ text_audio_out = gr.Audio(label="Translated audio", type="numpy", autoplay=True)
1453
+ text_log = gr.Markdown(label="Pipeline log")
1454
+
1455
+ text_btn.click(
1456
+ fn=full_pipeline_text,
1457
+ inputs=[text_input, text_language, text_voice],
1458
+ outputs=[text_audio_out, text_log],
1459
+ )
1460
+
1461
+ # ====== TAB 5: RECORDINGS ======
1462
+ with gr.TabItem("Recordings & Clips"):
1463
+ gr.Markdown("### Recordings management")
1464
+ gr.Markdown(
1465
+ "Past dubbed recordings will appear here. "
1466
+ "This feature is coming soon — for now, use Video Dubbing to create new recordings "
1467
+ "and download them from the player."
1468
+ )
1469
+
1470
+ # ====== TAB 6: VOICE MODELS ======
1471
+ with gr.TabItem("Voice Models"):
1472
+ gr.Markdown("### Voice model library")
1473
+ gr.Markdown("Browse available voices for each language.")
1474
+
1475
+ voice_lang_select = gr.Dropdown(
1476
+ choices=ALL_LANGUAGE_NAMES,
1477
+ value="Yoruba",
1478
+ label="Select language",
1479
+ )
1480
+ voice_info = gr.Markdown()
1481
+
1482
+ def show_voice_info(lang):
1483
+ config = LANGUAGES.get(lang, {})
1484
+ engine = config.get("tts_engine", "unknown")
1485
+ voices = config.get("yourvoic_voices", [])
1486
+
1487
+ info = f"### {lang}\n\n"
1488
+ if engine == "qwen":
1489
+ info += f"**Engine:** Qwen 3.5 Omni (end-to-end speech-to-speech)\n\n"
1490
+ info += f"This is the highest quality option. Qwen handles ASR + translation + TTS in a single API call, "
1491
+ info += f"preserving tone, emotion, and pacing from the original speaker.\n\n"
1492
+ info += f"**Available voices ({len(QWEN_VOICES)}):** {', '.join(QWEN_VOICES[:10])}... and {len(QWEN_VOICES)-10} more\n\n"
1493
+ info += f"All voices support all Qwen languages."
1494
+ elif engine == "yourvoic":
1495
+ info += f"**Engine:** YourVoic API (TTS) + NLLB-200 (translation)\n\n"
1496
+ info += f"**YourVoic language:** `{config.get('yourvoic_lang', 'N/A')}`\n\n"
1497
+ info += f"**Available voices:** {', '.join(voices) if voices else 'Peter (default)'}"
1498
+ else:
1499
+ info += f"**Engine:** Local pipeline (Whisper ASR + NLLB MT + MMS-TTS)\n\n"
1500
+ info += f"**NLLB code:** `{config.get('nllb', 'N/A')}`\n\n"
1501
+ info += "Uses locally fine-tuned models on GPU. Voice selection not available."
1502
+
1503
+ return info
1504
+
1505
+ voice_lang_select.change(fn=show_voice_info, inputs=[voice_lang_select], outputs=[voice_info])
1506
+ demo.load(fn=show_voice_info, inputs=[voice_lang_select], outputs=[voice_info])
1507
+
1508
+ gr.Markdown("""
1509
+ ---
1510
+ **PlotWeaver** by PlotweaverAI | Models:
1511
+ [ASR](https://huggingface.co/PlotweaverAI/whisper-small-de-en) |
1512
+ [MT](https://huggingface.co/PlotweaverAI/nllb-200-distilled-600M-african-6lang) |
1513
+ [TTS](https://huggingface.co/PlotweaverAI/yoruba-mms-tts-new) |
1514
+ [YourVoic API](https://yourvoic.com)
1515
+ """)
1516
+
1517
+
1518
+ if __name__ == "__main__":
1519
+ demo.launch()
packages.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ ffmpeg
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