binaryMao commited on
Commit
e9f0a14
·
verified ·
1 Parent(s): 2a33c20

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +66 -176
app.py CHANGED
@@ -20,7 +20,7 @@ import librosa
20
  from huggingface_hub import snapshot_download
21
  from nemo.collections import asr as nemo_asr
22
  import gradio as gr
23
- import noisereduce as nr # Import pour la réduction de bruit
24
 
25
  # ----------------------------
26
  # CONFIG
@@ -53,49 +53,32 @@ def run_cmd(cmd):
53
  return res.stdout
54
 
55
  def ffprobe_duration(path):
56
- """
57
- Tente d'obtenir la durée via ffprobe (robuste pour les conteneurs webcam).
58
- """
59
- # FIXE: On lit la durée du format (conteneur)
60
  cmd = f'ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 {shlex.quote(path)}'
61
  out = subprocess.run(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
62
-
63
- if out.returncode != 0:
64
- return None
65
  try:
66
  output = out.stdout.strip().split('\n')[0]
67
  return float(output)
68
- except:
69
- return None
70
 
71
  # ----------------------------
72
  # LOAD MODEL (robust)
73
  # ----------------------------
74
  def load_model(name):
75
- """Charge le modèle NeMo correct selon type (rnnt / ctc / ctc_char)."""
76
- if name in _cache:
77
- return _cache[name]
78
-
79
  repo, mode = MODELS[name]
80
  print(f"[LOAD] snapshot_download {repo} ...")
81
  folder = snapshot_download(repo, local_dir_use_symlinks=False)
82
  nemo_file = next((os.path.join(folder, f) for f in os.listdir(folder) if f.endswith(".nemo")), None)
83
- if not nemo_file:
84
- raise FileNotFoundError(f"Aucun .nemo trouvé pour {name} dans {folder}")
85
-
86
- print(f"[LOAD] .nemo trouvé: {nemo_file}; mode={mode}")
87
-
88
- # Sélection de la classe NeMo selon le mode
89
- if mode == "rnnt":
90
- model = nemo_asr.models.EncDecHybridRNNTCTCBPEModel.restore_from(nemo_file)
91
- elif mode == "ctc_char":
92
- model = nemo_asr.models.EncDecCTCModel.restore_from(nemo_file)
93
- else: # mode == "ctc" (BPE)
94
- try:
95
- model = nemo_asr.models.EncDecCTCModelBPE.restore_from(nemo_file)
96
- except Exception as e:
97
- print(f"[WARN] EncDecCTCModelBPE failed ({e}), fallback EncDecCTCModel")
98
- model = nemo_asr.models.EncDecCTCModel.restore_from(nemo_file)
99
 
100
  model.to(DEVICE).eval()
101
  _cache[name] = model
@@ -111,83 +94,41 @@ def extract_audio(video_path, out_wav):
111
  run_cmd(cmd)
112
 
113
  def clean_audio(wav_path, target_sr=16000):
114
- """
115
- Load audio, apply noise reduction, resample, normalize, write cleaned wav.
116
- """
117
  audio, sr = sf.read(wav_path)
118
-
119
- if audio.ndim == 2:
120
- audio = audio.mean(axis=1)
121
-
122
  if sr != target_sr:
123
  audio = librosa.resample(audio.astype(float), orig_sr=sr, target_sr=target_sr)
124
  sr = target_sr
125
-
126
- # --- AMÉLIORATION : Réduction de bruit ---
127
  try:
128
  print("[INFO] Application de la réduction de bruit (noisereduce)...")
129
- # Réduit le bruit stationnaire (ventilateur, souffle) de 75%
130
  audio = nr.reduce_noise(y=audio, sr=sr, stationary=True, prop_decrease=0.75)
131
  except Exception as e:
132
  print(f"[WARN] Echec noisereduce: {e}")
133
- # -----------------------------------------
134
-
135
  max_val = np.max(np.abs(audio)) if audio.size > 0 else 0.0
136
- if max_val > 1e-6:
137
- # Normalisation à 0.95
138
- audio = audio / max_val * 0.95
139
 
140
  clean_path = str(Path(wav_path).with_name(Path(wav_path).stem + "_clean.wav"))
141
  sf.write(clean_path, audio, sr)
142
-
143
  return clean_path, audio, sr
144
 
145
  # ----------------------------
146
- # TRANSCRIPTION
147
  # ----------------------------
148
  def transcribe(model, wav_path):
149
  """Robuste: essaie model.transcribe et nettoie la sortie."""
150
- if not hasattr(model, "transcribe"):
151
- raise RuntimeError("Le modèle ne supporte pas model.transcribe()")
152
  out = model.transcribe([wav_path])
153
- if isinstance(out, list):
154
- if len(out) == 0:
155
- return ""
156
- first = out[0]
157
- if isinstance(first, str):
158
- return first.strip()
159
- if hasattr(first, "text"):
160
- return first.text.strip()
161
- return str(first).strip()
162
- if hasattr(out, "text"):
163
- return out.text.strip()
164
  return str(out).strip()
165
 
166
- # ----------------------------
167
- # UTILITAIRES sous-titres / packing
168
- # ----------------------------
169
- def keep_bambara(words):
170
- res = []
171
- for w in words:
172
- wl = w.lower()
173
- if any(c in wl for c in ["ɛ","ɔ","ŋ"]) or sum(1 for c in wl if c in "aeiou") >= 2:
174
- res.append(w)
175
- return res
176
-
177
  MAX_CHARS = 45; MIN_DUR = 0.3; MAX_DUR = 3.2; MAX_WORDS = 8
178
 
179
- def wrap2(txt):
180
- parts = textwrap.wrap(txt, MAX_CHARS)
181
- if len(parts) <= 1:
182
- return txt
183
- mid = len(txt) // 2
184
- left = txt.rfind(" ", 0, mid)
185
- right = txt.find(" ", mid)
186
- cut = left if (mid - left) <= ((right - mid) if right != -1 else 1e9) else right
187
- l1 = txt[:cut].strip(); l2 = txt[cut:].strip()
188
- return l1 + "\n" + l2 if l2 else l1
189
-
190
  def pack(spans, total):
 
191
  tmp = []
192
  for s, e, t in spans:
193
  s = max(0, min(s, total)); e = max(0, min(e, total))
@@ -211,34 +152,29 @@ def pack(spans, total):
211
  for b in blocks:
212
  st = base; en = min(base + step, e); base = en
213
  if en <= st: en = min(st + 0.05, total)
214
- txt = wrap2(b)
 
215
  if st < last_end:
216
  st = last_end + 1e-3; en = max(en, st + 0.05)
217
  out.append((st, en, txt)); last_end = en
218
  return out
219
 
220
- # ----------------------------
221
- # VAD ALIGN (fallback alignment)
222
- # ----------------------------
223
  def align_vad(text, audio, sr, total_dur, top_db=28):
224
- words = keep_bambara(text.split())
 
225
  total = total_dur
226
  if audio is None or len(audio) == 0 or not words:
227
  return pack([(0, total, " ".join(words[:MAX_WORDS]))], total)
228
  iv = librosa.effects.split(audio, top_db=top_db)
229
  if len(iv) == 0:
230
  return pack([(0, total, " ".join(words[:MAX_WORDS]))], total)
231
- spans = []
232
- L = sum(e - s for s, e in iv)
233
- idx = 0
234
  for s, e in iv:
235
  seg = e - s; segt = seg / sr
236
- k = max(1, int(round(len(words) * (seg / L))))
237
- chunk = words[idx:idx+k]; idx += k
238
  if not chunk: continue
239
  lines = [chunk[i:i+MAX_WORDS] for i in range(0, len(chunk), MAX_WORDS)]
240
- step = max(MIN_DUR, min(MAX_DUR, segt / max(1, len(lines))))
241
- base = s / sr
242
  for j, ln in enumerate(lines):
243
  st = base + j * step; en = base + (j + 1) * step
244
  spans.append((st, en, " ".join(ln)))
@@ -248,114 +184,70 @@ def align_vad(text, audio, sr, total_dur, top_db=28):
248
  # Écriture SRT + Burn (réencode)
249
  # ----------------------------
250
  def burn(video_path, subs, output_path=None):
251
- if output_path is None:
252
- output_path = "RobotsMali_Subtitled.mp4"
253
- tmp_fd, tmp_srt = tempfile.mkstemp(suffix=".srt")
254
- os.close(tmp_fd)
255
  def sec_to_srt(t):
256
  h = int(t // 3600); m = int((t % 3600) // 60); s = int(t % 60); ms = int((t - int(t)) * 1000)
257
  return f"{h:02}:{m:02}:{s:02},{ms:03}"
 
258
  with open(tmp_srt, "w", encoding="utf-8") as f:
259
  for i, (start, end, text) in enumerate(subs, 1):
260
  f.write(f"{i}\n{sec_to_srt(start)} --> {sec_to_srt(end)}\n{text}\n\n")
261
 
262
- # On réencode (libx264) car on applique subtitles filter
263
  vf = f"subtitles={shlex.quote(tmp_srt)}:force_style='Fontsize=22,PrimaryColour=&HFFFFFF&,OutlineColour=&H000000&'"
264
  cmd = f'ffmpeg -hide_banner -loglevel error -y -i {shlex.quote(video_path)} -vf {shlex.quote(vf)} -c:v libx264 -preset fast -crf 23 -c:a aac -b:a 192k {shlex.quote(output_path)}'
265
- try:
266
- run_cmd(cmd)
267
  finally:
268
- if os.path.exists(tmp_srt):
269
- os.remove(tmp_srt)
270
  return output_path
271
 
272
  # ----------------------------
273
  # PIPELINE PRINCIPAL (Robuste)
274
  # ----------------------------
275
  def pipeline(video_input, model_name):
276
- """
277
- video_input : chemin ou dict Gradio (tmp_path)
278
- model_name : clé dans MODELS
279
- """
280
  try:
281
- if isinstance(video_input, dict) and "tmp_path" in video_input:
282
- video_path = video_input["tmp_path"]
283
- else:
284
- video_path = video_input
285
 
286
- # 1. Tentative d'obtention de durée via FFPROBE
287
  duration = ffprobe_duration(video_path)
288
-
289
- # 2. Extraction & Nettoyage Audio
290
- tmp_fd, tmp_wav = tempfile.mkstemp(suffix=".wav")
291
- os.close(tmp_fd)
292
-
293
  extract_audio(video_path, tmp_wav)
294
  clean_wav, audio, sr = clean_audio(tmp_wav)
295
 
296
- # 3. FALLBACK: Si FFprobe a échoué (None), on calcule depuis l'audio
297
  if duration is None:
298
  print("[INFO] ffprobe duration failed, calculating from audio...")
299
- if sr and sr > 0:
300
- duration = len(audio) / sr
301
 
302
- # Vérification finale
303
  if not duration or duration <= 0:
304
  raise RuntimeError("Impossible de déterminer la durée de la vidéo (fichier corrompu ?)")
305
 
306
- print(f"[INFO] Durée détectée: {duration:.2f}s")
307
-
308
- # 4. Chargement modèle + Transcription
309
  model = load_model(model_name)
310
  text = transcribe(model, clean_wav)
311
  mode = MODELS[model_name][1]
312
 
313
- # 5. Segmentation / Alignement
314
- subs = None
315
-
316
  if mode == "rnnt":
317
- # Logique d'alignement RNNT (CTC Segmentation)
318
  try:
319
  from ctc_segmentation import ctc_segmentation, CtcSegmentationParameters, prepare_text
320
- words = keep_bambara(text.split())
321
- if not words:
322
- return ("⚠️ Aucun sous-titre utilisable (texte vide après filtrage)", None)
323
- x = torch.tensor(audio).float().unsqueeze(0).to(DEVICE)
324
- ln = torch.tensor([x.shape[1]]).to(DEVICE)
325
- with torch.no_grad():
326
- logits = model(input_signal=x, input_signal_length=ln)[0]
327
  time_per_frame = duration / max(1, logits.shape[1])
328
- try:
329
- raw = model.tokenizer.vocab
330
- vocab = list(raw.keys()) if isinstance(raw, dict) else list(raw)
331
- except Exception:
332
- vocab = None
333
- cfg = CtcSegmentationParameters()
334
- if vocab:
335
- cfg.char_list = vocab
336
  gt = prepare_text(cfg, words)[0]
337
- try:
338
- timing, _, _ = ctc_segmentation(cfg, logits.detach().cpu().numpy()[0], gt)
339
- spans = [(timing[i] * time_per_frame, timing[i+1] * time_per_frame, words[i]) for i in range(len(words) - 1)]
340
- subs = pack(spans, duration)
341
- except AssertionError:
342
- print("[WARN] Audio shorter than text -> fallback to VAD alignment")
343
- subs = align_vad(text, audio, sr, duration)
344
- except Exception as e:
345
- print(f"[WARN] ctc_segmentation not available or failed ({e}) -> fallback VAD")
346
- subs = align_vad(text, audio, sr, duration)
347
-
348
- elif mode == "ctc_char" or mode == "ctc":
349
- # Logique d'alignement CTC / CTC-Char (VAD fallback)
350
- try:
351
  subs = align_vad(text, audio, sr, duration)
352
- except Exception as e:
353
- print(f"[WARN] Alignment failed: {e}")
354
- subs = align_vad(text, audio, sr, duration)
355
-
356
- if not subs:
357
- return ("⚠️ Aucun sous-titre utilisable (sub list vide)", None)
358
 
 
359
  out_video = burn(video_path, subs)
360
  return ("✅ Terminé avec succès", out_video)
361
 
@@ -364,13 +256,12 @@ def pipeline(video_input, model_name):
364
  return (f"❌ Erreur — {str(e)}", None)
365
 
366
  # ----------------------------
367
- # INTERFACE GRADIO (Corrigée Finalement)
368
  # ----------------------------
369
  with gr.Blocks(title="RobotsMali - Sous-titrage") as demo:
370
  gr.Markdown("## 🤖 RobotsMali — Sous-titrage Bambara (Amélioration Audio)")
371
 
372
  # 1. Définir toutes les sorties AVANT leur utilisation.
373
- # Elles sont rendues ici implicitement et sont disponibles pour gr.Examples.
374
  s = gr.Markdown(label="Statut de la tâche")
375
  o = gr.Video(label="Vidéo sous-titrée")
376
 
@@ -380,31 +271,30 @@ with gr.Blocks(title="RobotsMali - Sous-titrage") as demo:
380
  v = gr.Video(label="Vidéo à sous-titrer", sources=["upload", "webcam"])
381
  m = gr.Dropdown(list(MODELS.keys()), value="Soloba V1 (CTC)", label="Modèle ASR")
382
 
383
- # 3. gr.Examples utilise V, M, S, et O (tous sont maintenant définis)
384
  gr.Examples(
385
  examples=[
386
- ["examples/video_bambara_sample.mp4", "Soloba V1 (CTC)"]
 
387
  ],
388
  inputs=[v, m],
389
  fn=pipeline,
390
  outputs=[s, o],
391
  label="▶️ Utiliser un exemple (Vidéo stockée dans le Space)",
392
- run_on_click=True
 
393
  )
394
 
395
  b = gr.Button("▶️ Générer les sous-titres", variant="primary")
396
 
397
  with gr.Column():
398
- # 4. Réorganisation: Pas besoin de .render(), on place juste le titre
399
- # et on fait confiance à Gradio pour afficher S et O dans l'ordre de leur définition.
400
  gr.Markdown("### Résultats:")
401
-
402
- # Note: S et O sont déjà définis et placés dans l'interface au début du Blocks.
403
- # Il n'y a rien à faire ici, à part s'assurer qu'ils sont bien affichés
404
- # (ce qui est le cas par leur définition initiale dans le bloc).
405
 
406
- # 5. Le bouton final fonctionne avec les variables correctement définies.
407
  b.click(pipeline, [v, m], [s, o])
408
 
409
  if __name__ == "__main__":
410
- demo.launch(share=True, debug=True)
 
20
  from huggingface_hub import snapshot_download
21
  from nemo.collections import asr as nemo_asr
22
  import gradio as gr
23
+ import noisereduce as nr
24
 
25
  # ----------------------------
26
  # CONFIG
 
53
  return res.stdout
54
 
55
  def ffprobe_duration(path):
56
+ """Tente d'obtenir la durée via ffprobe."""
 
 
 
57
  cmd = f'ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 {shlex.quote(path)}'
58
  out = subprocess.run(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
59
+ if out.returncode != 0: return None
 
 
60
  try:
61
  output = out.stdout.strip().split('\n')[0]
62
  return float(output)
63
+ except: return None
 
64
 
65
  # ----------------------------
66
  # LOAD MODEL (robust)
67
  # ----------------------------
68
  def load_model(name):
69
+ """Charge le modèle NeMo correct."""
70
+ if name in _cache: return _cache[name]
 
 
71
  repo, mode = MODELS[name]
72
  print(f"[LOAD] snapshot_download {repo} ...")
73
  folder = snapshot_download(repo, local_dir_use_symlinks=False)
74
  nemo_file = next((os.path.join(folder, f) for f in os.listdir(folder) if f.endswith(".nemo")), None)
75
+ if not nemo_file: raise FileNotFoundError(f"Aucun .nemo trouvé pour {name} dans {folder}")
76
+
77
+ if mode == "rnnt": model = nemo_asr.models.EncDecHybridRNNTCTCBPEModel.restore_from(nemo_file)
78
+ elif mode == "ctc_char": model = nemo_asr.models.EncDecCTCModel.restore_from(nemo_file)
79
+ else:
80
+ try: model = nemo_asr.models.EncDecCTCModelBPE.restore_from(nemo_file)
81
+ except Exception: model = nemo_asr.models.EncDecCTCModel.restore_from(nemo_file)
 
 
 
 
 
 
 
 
 
82
 
83
  model.to(DEVICE).eval()
84
  _cache[name] = model
 
94
  run_cmd(cmd)
95
 
96
  def clean_audio(wav_path, target_sr=16000):
97
+ """Load audio, apply noise reduction, resample, normalize, write cleaned wav."""
 
 
98
  audio, sr = sf.read(wav_path)
99
+ if audio.ndim == 2: audio = audio.mean(axis=1)
 
 
 
100
  if sr != target_sr:
101
  audio = librosa.resample(audio.astype(float), orig_sr=sr, target_sr=target_sr)
102
  sr = target_sr
103
+
 
104
  try:
105
  print("[INFO] Application de la réduction de bruit (noisereduce)...")
 
106
  audio = nr.reduce_noise(y=audio, sr=sr, stationary=True, prop_decrease=0.75)
107
  except Exception as e:
108
  print(f"[WARN] Echec noisereduce: {e}")
109
+
 
110
  max_val = np.max(np.abs(audio)) if audio.size > 0 else 0.0
111
+ if max_val > 1e-6: audio = audio / max_val * 0.95
 
 
112
 
113
  clean_path = str(Path(wav_path).with_name(Path(wav_path).stem + "_clean.wav"))
114
  sf.write(clean_path, audio, sr)
 
115
  return clean_path, audio, sr
116
 
117
  # ----------------------------
118
+ # TRANSCRIPTION & ALIGNMENT UTILS
119
  # ----------------------------
120
  def transcribe(model, wav_path):
121
  """Robuste: essaie model.transcribe et nettoie la sortie."""
122
+ if not hasattr(model, "transcribe"): raise RuntimeError("Le modèle ne supporte pas model.transcribe()")
 
123
  out = model.transcribe([wav_path])
124
+ if isinstance(out, list) and len(out) > 0: out = out[0]
125
+ if hasattr(out, "text"): return out.text.strip()
 
 
 
 
 
 
 
 
 
126
  return str(out).strip()
127
 
 
 
 
 
 
 
 
 
 
 
 
128
  MAX_CHARS = 45; MIN_DUR = 0.3; MAX_DUR = 3.2; MAX_WORDS = 8
129
 
 
 
 
 
 
 
 
 
 
 
 
130
  def pack(spans, total):
131
+ # Logique complexe de regroupement et de réemballage (non modifiée)
132
  tmp = []
133
  for s, e, t in spans:
134
  s = max(0, min(s, total)); e = max(0, min(e, total))
 
152
  for b in blocks:
153
  st = base; en = min(base + step, e); base = en
154
  if en <= st: en = min(st + 0.05, total)
155
+ txt = textwrap.wrap(b, MAX_CHARS)
156
+ txt = txt[0] + "\n" + txt[1] if len(txt) > 1 else txt[0]
157
  if st < last_end:
158
  st = last_end + 1e-3; en = max(en, st + 0.05)
159
  out.append((st, en, txt)); last_end = en
160
  return out
161
 
 
 
 
162
  def align_vad(text, audio, sr, total_dur, top_db=28):
163
+ # Logique VAD (non modifiée)
164
+ words = [w for w in text.split() if any(c in w.lower() for c in ["ɛ","ɔ","ŋ"]) or sum(1 for c in w.lower() if c in "aeiou") >= 2]
165
  total = total_dur
166
  if audio is None or len(audio) == 0 or not words:
167
  return pack([(0, total, " ".join(words[:MAX_WORDS]))], total)
168
  iv = librosa.effects.split(audio, top_db=top_db)
169
  if len(iv) == 0:
170
  return pack([(0, total, " ".join(words[:MAX_WORDS]))], total)
171
+ spans = []; L = sum(e - s for s, e in iv); idx = 0
 
 
172
  for s, e in iv:
173
  seg = e - s; segt = seg / sr
174
+ k = max(1, int(round(len(words) * (seg / L)))); chunk = words[idx:idx+k]; idx += k
 
175
  if not chunk: continue
176
  lines = [chunk[i:i+MAX_WORDS] for i in range(0, len(chunk), MAX_WORDS)]
177
+ step = max(MIN_DUR, min(MAX_DUR, segt / max(1, len(lines)))); base = s / sr
 
178
  for j, ln in enumerate(lines):
179
  st = base + j * step; en = base + (j + 1) * step
180
  spans.append((st, en, " ".join(ln)))
 
184
  # Écriture SRT + Burn (réencode)
185
  # ----------------------------
186
  def burn(video_path, subs, output_path=None):
187
+ """Crée le SRT temporaire et brûle les sous-titres dans la vidéo."""
188
+ if output_path is None: output_path = "RobotsMali_Subtitled.mp4"
189
+ tmp_fd, tmp_srt = tempfile.mkstemp(suffix=".srt"); os.close(tmp_fd)
190
+
191
  def sec_to_srt(t):
192
  h = int(t // 3600); m = int((t % 3600) // 60); s = int(t % 60); ms = int((t - int(t)) * 1000)
193
  return f"{h:02}:{m:02}:{s:02},{ms:03}"
194
+
195
  with open(tmp_srt, "w", encoding="utf-8") as f:
196
  for i, (start, end, text) in enumerate(subs, 1):
197
  f.write(f"{i}\n{sec_to_srt(start)} --> {sec_to_srt(end)}\n{text}\n\n")
198
 
 
199
  vf = f"subtitles={shlex.quote(tmp_srt)}:force_style='Fontsize=22,PrimaryColour=&HFFFFFF&,OutlineColour=&H000000&'"
200
  cmd = f'ffmpeg -hide_banner -loglevel error -y -i {shlex.quote(video_path)} -vf {shlex.quote(vf)} -c:v libx264 -preset fast -crf 23 -c:a aac -b:a 192k {shlex.quote(output_path)}'
201
+ try: run_cmd(cmd)
 
202
  finally:
203
+ if os.path.exists(tmp_srt): os.remove(tmp_srt)
 
204
  return output_path
205
 
206
  # ----------------------------
207
  # PIPELINE PRINCIPAL (Robuste)
208
  # ----------------------------
209
  def pipeline(video_input, model_name):
210
+ """Gère le flux de sous-titrage complet."""
 
 
 
211
  try:
212
+ if isinstance(video_input, dict) and "tmp_path" in video_input: video_path = video_input["tmp_path"]
213
+ else: video_path = video_input
 
 
214
 
 
215
  duration = ffprobe_duration(video_path)
216
+ tmp_fd, tmp_wav = tempfile.mkstemp(suffix=".wav"); os.close(tmp_fd)
 
 
 
 
217
  extract_audio(video_path, tmp_wav)
218
  clean_wav, audio, sr = clean_audio(tmp_wav)
219
 
 
220
  if duration is None:
221
  print("[INFO] ffprobe duration failed, calculating from audio...")
222
+ if sr and sr > 0: duration = len(audio) / sr
 
223
 
 
224
  if not duration or duration <= 0:
225
  raise RuntimeError("Impossible de déterminer la durée de la vidéo (fichier corrompu ?)")
226
 
 
 
 
227
  model = load_model(model_name)
228
  text = transcribe(model, clean_wav)
229
  mode = MODELS[model_name][1]
230
 
231
+ # Logique d'alignement (CTC Segmentation ou VAD Fallback)
 
 
232
  if mode == "rnnt":
 
233
  try:
234
  from ctc_segmentation import ctc_segmentation, CtcSegmentationParameters, prepare_text
235
+ words = [w for w in text.split() if any(c in w.lower() for c in ["ɛ","ɔ","ŋ"]) or sum(1 for c in w.lower() if c in "aeiou") >= 2]
236
+ if not words: return ("⚠️ Aucun sous-titre utilisable (texte vide après filtrage)", None)
237
+ x = torch.tensor(audio).float().unsqueeze(0).to(DEVICE); ln = torch.tensor([x.shape[1]]).to(DEVICE)
238
+ with torch.no_grad(): logits = model(input_signal=x, input_signal_length=ln)[0]
 
 
 
239
  time_per_frame = duration / max(1, logits.shape[1])
240
+ cfg = CtcSegmentationParameters(); cfg.char_list = list(model.tokenizer.vocab.keys())
 
 
 
 
 
 
 
241
  gt = prepare_text(cfg, words)[0]
242
+ timing, _, _ = ctc_segmentation(cfg, logits.detach().cpu().numpy()[0], gt)
243
+ spans = [(timing[i] * time_per_frame, timing[i+1] * time_per_frame, words[i]) for i in range(len(words) - 1)]
244
+ subs = pack(spans, duration)
245
+ except Exception:
 
 
 
 
 
 
 
 
 
 
246
  subs = align_vad(text, audio, sr, duration)
247
+ else:
248
+ subs = align_vad(text, audio, sr, duration)
 
 
 
 
249
 
250
+ if not subs: return ("⚠️ Aucun sous-titre utilisable (sub list vide)", None)
251
  out_video = burn(video_path, subs)
252
  return ("✅ Terminé avec succès", out_video)
253
 
 
256
  return (f"❌ Erreur — {str(e)}", None)
257
 
258
  # ----------------------------
259
+ # INTERFACE GRADIO (Version Finale Stabilité)
260
  # ----------------------------
261
  with gr.Blocks(title="RobotsMali - Sous-titrage") as demo:
262
  gr.Markdown("## 🤖 RobotsMali — Sous-titrage Bambara (Amélioration Audio)")
263
 
264
  # 1. Définir toutes les sorties AVANT leur utilisation.
 
265
  s = gr.Markdown(label="Statut de la tâche")
266
  o = gr.Video(label="Vidéo sous-titrée")
267
 
 
271
  v = gr.Video(label="Vidéo à sous-titrer", sources=["upload", "webcam"])
272
  m = gr.Dropdown(list(MODELS.keys()), value="Soloba V1 (CTC)", label="Modèle ASR")
273
 
274
+ # 3. gr.Examples (avec cache_examples=False et nom de fichier corrigé)
275
  gr.Examples(
276
  examples=[
277
+ # Utiliser le nom de fichier exact du dépôt
278
+ ["examples/Upload MARALINKE-WILI (Lève-toi) Black lives matter (Clip officiel) - MARALINKE (360p, h264).mp4", "Soloba V1 (CTC)"]
279
  ],
280
  inputs=[v, m],
281
  fn=pipeline,
282
  outputs=[s, o],
283
  label="▶️ Utiliser un exemple (Vidéo stockée dans le Space)",
284
+ run_on_click=True,
285
+ cache_examples=False
286
  )
287
 
288
  b = gr.Button("▶️ Générer les sous-titres", variant="primary")
289
 
290
  with gr.Column():
291
+ # 4. Affichage des sorties
 
292
  gr.Markdown("### Résultats:")
293
+ s
294
+ o
 
 
295
 
296
+ # 5. L'action du bouton
297
  b.click(pipeline, [v, m], [s, o])
298
 
299
  if __name__ == "__main__":
300
+ demo.launch(share=True)