binaryMao commited on
Commit
77e790d
·
verified ·
1 Parent(s): 63cfe96

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +353 -92
app.py CHANGED
@@ -1,8 +1,21 @@
1
  # -*- coding: utf-8 -*-
2
- """
3
- ROBOTSMALI — Sous-titrage Bambara
4
- Version complète et stable intégrant tous les correctifs et fonctionnalités.
5
- """
 
 
 
 
 
 
 
 
 
 
 
 
 
6
 
7
  import os
8
  import shlex
@@ -12,7 +25,7 @@ import traceback
12
  import random
13
  import textwrap
14
  from pathlib import Path
15
-
16
  import numpy as np
17
  import torch
18
  import soundfile as sf
@@ -20,55 +33,82 @@ 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
24
 
25
- # ----------------------------
26
- # CONFIG
27
- # ----------------------------
 
 
 
 
 
 
28
  DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
29
  random.seed(1234)
30
  np.random.seed(1234)
31
  torch.manual_seed(1234)
32
 
 
 
 
33
  MODELS = {
34
  "Soloni V1 (RNNT)": ("RobotsMali/soloni-114m-tdt-ctc-v1", "rnnt"),
35
  "Soloni V0 (RNNT)": ("RobotsMali/soloni-114m-tdt-ctc-v0", "rnnt"),
36
- "Soloba V1 (CTC)": ("RobotsMali/soloba-ctc-0.6b-v1", "ctc"),
37
- "Soloba V0 (CTC)": ("RobotsMali/soloba-ctc-0.6b-v0", "ctc"),
38
- "QuartzNet V1 (CTC-char)": ("RobotsMali/stt-bm-quartznet15x5-v1", "ctc_char"),
39
  "QuartzNet V0 (CTC-char)": ("RobotsMali/stt-bm-quartznet15x5-v0", "ctc_char"),
40
  }
41
-
42
  _cache = {}
43
 
44
- # ----------------------------
45
- # UTIL: run_cmd, ffprobe_duration
46
- # ----------------------------
 
 
 
47
  def run_cmd(cmd):
 
 
48
  res = subprocess.run(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
49
  if res.returncode != 0:
50
  raise RuntimeError(f"Commande échouée [{cmd}]\nOutput:\n{res.stdout}")
51
  return res.stdout
52
-
53
  def ffprobe_duration(path):
 
54
  cmd = f'ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 {shlex.quote(path)}'
55
  out = subprocess.run(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
56
- if out.returncode != 0: return None
 
 
 
 
 
 
57
  try:
58
- output = out.stdout.strip().split("\n")[0]
59
- return float(output)
60
- except: return None
61
-
62
- # ----------------------------
63
- # LOAD MODEL
64
- # ----------------------------
65
  def load_model(name):
66
- if name in _cache: return _cache[name]
 
 
 
67
  repo, mode = MODELS[name]
 
68
  folder = snapshot_download(repo, local_dir_use_symlinks=False)
69
  nemo_file = next((os.path.join(folder, f) for f in os.listdir(folder) if f.endswith(".nemo")), None)
70
  if not nemo_file:
71
  raise FileNotFoundError(f"Aucun .nemo trouvé pour {name} dans {folder}")
 
 
 
72
  if mode == "rnnt":
73
  model = nemo_asr.models.EncDecHybridRNNTCTCBPEModel.restore_from(nemo_file)
74
  elif mode == "ctc_char":
@@ -76,97 +116,318 @@ def load_model(name):
76
  else:
77
  try:
78
  model = nemo_asr.models.EncDecCTCModelBPE.restore_from(nemo_file)
79
- except:
 
80
  model = nemo_asr.models.EncDecCTCModel.restore_from(nemo_file)
 
81
  model.to(DEVICE).eval()
82
  _cache[name] = model
 
83
  return model
84
-
85
- # ----------------------------
86
- # AUDIO EXTRACTION & CLEAN
87
- # ----------------------------
88
  def extract_audio(video_path, out_wav):
89
- cmd = f'ffmpeg -hide_banner -loglevel error -y -i {shlex.quote(video_path)} -vn -ac 1 -ar 16000 -f wav {shlex.quote(out_wav)}'
90
- run_cmd(cmd)
 
 
 
 
91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92
  def clean_audio(wav_path, target_sr=16000):
 
93
  audio, sr = sf.read(wav_path)
94
- if audio.ndim == 2: audio = audio.mean(axis=1)
 
95
  if sr != target_sr:
96
  audio = librosa.resample(audio.astype(float), orig_sr=sr, target_sr=target_sr)
97
  sr = target_sr
98
- try:
99
- audio = nr.reduce_noise(y=audio, sr=sr, stationary=True, prop_decrease=0.75)
100
- except: pass
101
- max_val = np.max(np.abs(audio)) if audio.size > 0 else 0
102
  if max_val > 1e-6:
103
- audio = audio / max_val * 0.95
104
  clean_path = str(Path(wav_path).with_name(Path(wav_path).stem + "_clean.wav"))
105
  sf.write(clean_path, audio, sr)
106
  return clean_path, audio, sr
 
 
 
 
107
 
108
- # ----------------------------
109
- # TRANSCRIPTION
110
- # ----------------------------
111
  def transcribe(model, wav_path):
 
 
112
  out = model.transcribe([wav_path])
113
- if isinstance(out, list) and len(out)>0: out = out[0]
114
- if hasattr(out, "text"): return out.text.strip()
 
 
 
 
 
 
 
 
 
115
  return str(out).strip()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
116
 
117
- # (pack, align_vad, burn, pipeline restent identiques)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
118
 
119
- # ----------------------------
120
- # COPIE VIDÉO EXEMPLE /tmp
121
- # ----------------------------
122
- def get_example_video():
123
- """Copie la vidéo depuis le dossier /examples du Space vers /tmp."""
124
- repo_dir = "/home/user/app/examples"
125
- filename = "MARALINKE-WiIi (Lève-toi) Black lives matter (Clip officiel) - MARALINKE (360p, h264).mp4"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
126
 
127
- src = os.path.join(repo_dir, filename)
128
- dst = "/tmp/example_video.mp4"
 
 
 
 
 
129
 
130
- if not os.path.exists(dst):
131
- import shutil
132
- shutil.copy(src, dst)
 
 
 
 
 
 
 
133
 
134
- return dst
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
135
 
136
- # ----------------------------
137
- # INTERFACE GRADIO
138
- # ----------------------------
139
  with gr.Blocks(title="RobotsMali - Sous-titrage") as demo:
140
- gr.Markdown("## 🤖 RobotsMali — Sous-titrage Bambara")
141
-
142
- s = gr.Markdown(label="Statut de la tâche")
143
- o = gr.Video(label="Vidéo sous-titrée")
144
-
145
- with gr.Row():
146
- with gr.Column():
147
- v = gr.Video(label="Vidéo à sous-titrer", sources=["upload", "webcam"])
148
- m = gr.Dropdown(list(MODELS.keys()), value="Soloba V1 (CTC)", label="Modèle ASR")
149
-
150
- gr.Examples(
151
- examples=[
152
- [get_example_video(), "Soloba V1 (CTC)"]
153
- ],
154
- inputs=[v, m],
155
- fn=pipeline,
156
- outputs=[s, o],
157
- label="▶️ Vidéo d’exemple du Space",
158
- run_on_click=True,
159
- cache_examples=False
160
- )
161
-
162
- b = gr.Button("▶️ Générer les sous-titres")
163
-
164
- with gr.Column():
165
- gr.Markdown("### Résultats :")
166
- s
167
- o
168
 
 
 
 
 
 
 
 
 
 
 
 
 
169
  b.click(pipeline, [v, m], [s, o])
170
-
171
- if __name__ == "__main__":
172
- demo.launch(share=True, debug=True)
 
1
  # -*- coding: utf-8 -*-
2
+ """ ROBOTSMALI — Sous-titrage Bambara (V4.8 Colab Ready - Remuxage Vidéo) """
3
+
4
+ # =========================================================================
5
+ # 1. INSTALLATION ET MISE À JOUR DES DÉPENDANCES
6
+ # =========================================================================
7
+ print("Démarrage de l'installation des dépendances...")
8
+
9
+ # Installation de FFmpeg (nécessaire pour ffprobe et extraction/burn)
10
+ !apt-get update && apt-get install -y ffmpeg
11
+
12
+ # Installation des librairies Python essentielles et des outils NeMo
13
+ !pip install torch numpy soundfile librosa huggingface_hub gradio
14
+ !pip install nemo_toolkit[asr]
15
+ !pip install ctc-segmentation
16
+ !pip install --upgrade gradio # Mise à jour de Gradio pour la compatibilité
17
+ print("Installation des dépendances terminée.")
18
+ # =========================================================================
19
 
20
  import os
21
  import shlex
 
25
  import random
26
  import textwrap
27
  from pathlib import Path
28
+
29
  import numpy as np
30
  import torch
31
  import soundfile as sf
 
33
  from huggingface_hub import snapshot_download
34
  from nemo.collections import asr as nemo_asr
35
  import gradio as gr
 
36
 
37
+ # Tente l'importation de la librairie d'alignement nécessaire
38
+ try:
39
+ from ctc_segmentation import ctc_segmentation, CtcSegmentationParameters, prepare_text
40
+ HAS_CTC_SEGMENTATION = True
41
+ except ImportError:
42
+ HAS_CTC_SEGMENTATION = False
43
+ print("ATTENTION: ctc_segmentation non installé. L'alignement sera basé sur une simple répartition égale du temps.")
44
+
45
+ # ---------------------------- # CONFIG # ----------------------------
46
  DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
47
  random.seed(1234)
48
  np.random.seed(1234)
49
  torch.manual_seed(1234)
50
 
51
+ # Taille du segment pour la transcription par blocs
52
+ SEGMENT_DURATION = 10.0
53
+
54
  MODELS = {
55
  "Soloni V1 (RNNT)": ("RobotsMali/soloni-114m-tdt-ctc-v1", "rnnt"),
56
  "Soloni V0 (RNNT)": ("RobotsMali/soloni-114m-tdt-ctc-v0", "rnnt"),
57
+ "Soloba V1 (CTC)": ("RobotsMali/soloba-ctc-0.6b-v1", "ctc"),
58
+ "Soloba V0 (CTC)": ("RobotsMali/soloba-ctc-0.6b-v0", "ctc"),
59
+ "QuartzNet V1 (CTC-char)": ("RobotsMali/stt-bm-quartznet15x5-v1", "ctc_char"),
60
  "QuartzNet V0 (CTC-char)": ("RobotsMali/stt-bm-quartznet15x5-v0", "ctc_char"),
61
  }
62
+
63
  _cache = {}
64
 
65
+ # Chemin vers la vidéo d'exemple.
66
+ VIDEO_EXAMPLES = [
67
+ "examples/MARALINKE-Wii (Lève-toi) Black lives matter (Clip officiel) - MARALINKE (360p, H264).mp4"
68
+ ]
69
+
70
+ # ---------------------------- # UTIL: run_cmd, ffprobe_duration # ----------------------------
71
  def run_cmd(cmd):
72
+ """Execute a shell command and raise on non-zero exit."""
73
+ print("RUN:", cmd)
74
  res = subprocess.run(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
75
  if res.returncode != 0:
76
  raise RuntimeError(f"Commande échouée [{cmd}]\nOutput:\n{res.stdout}")
77
  return res.stdout
78
+
79
  def ffprobe_duration(path):
80
+ """Détermine la durée de la vidéo via ffprobe (pour vérification/débogage)."""
81
  cmd = f'ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 {shlex.quote(path)}'
82
  out = subprocess.run(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
83
+
84
+ if out.returncode != 0:
85
+ # Affiche l'erreur FFPROBE brute si l'extraction échoue
86
+ print(f"--- ERREUR FFPROBE BRUTE --- (Code: {out.returncode})")
87
+ print(out.stderr)
88
+ print("----------------------------")
89
+ return None
90
  try:
91
+ return float(out.stdout.strip())
92
+ except Exception as e:
93
+ print(f"--- ERREUR CONVERSION DURÉE --- (Output: {out.stdout.strip()})")
94
+ print(e)
95
+ return None
96
+
97
+ # ---------------------------- # LOAD MODEL (robust) # ----------------------------
98
  def load_model(name):
99
+ """Charge le modèle NeMo correct selon type (rnnt / ctc / ctc_char)."""
100
+ if name in _cache:
101
+ return _cache[name]
102
+
103
  repo, mode = MODELS[name]
104
+ print(f"[LOAD] snapshot_download {repo} ...")
105
  folder = snapshot_download(repo, local_dir_use_symlinks=False)
106
  nemo_file = next((os.path.join(folder, f) for f in os.listdir(folder) if f.endswith(".nemo")), None)
107
  if not nemo_file:
108
  raise FileNotFoundError(f"Aucun .nemo trouvé pour {name} dans {folder}")
109
+
110
+ print(f"[LOAD] .nemo trouvé: {nemo_file}; mode={mode}")
111
+
112
  if mode == "rnnt":
113
  model = nemo_asr.models.EncDecHybridRNNTCTCBPEModel.restore_from(nemo_file)
114
  elif mode == "ctc_char":
 
116
  else:
117
  try:
118
  model = nemo_asr.models.EncDecCTCModelBPE.restore_from(nemo_file)
119
+ except Exception as e:
120
+ print(f"[WARN] EncDecCTCModelBPE failed ({e}), fallback EncDecCTCModel")
121
  model = nemo_asr.models.EncDecCTCModel.restore_from(nemo_file)
122
+
123
  model.to(DEVICE).eval()
124
  _cache[name] = model
125
+ print(f"[OK] Modèle {name} chargé sur {DEVICE}")
126
  return model
127
+
128
+ # ---------------------------- # AUDIO EXTRACTION & CLEANING (ROBUSTE) # ----------------------------
 
 
129
  def extract_audio(video_path, out_wav):
130
+ """
131
+ Extrait l'audio en deux étapes pour stabiliser le fichier webcam/corrompu (Remuxage).
132
+ """
133
+ # Chemin du fichier intermédiaire stabilisé
134
+ tmp_fd, stabilized_mp4 = tempfile.mkstemp(suffix="_stabilized.mp4")
135
+ os.close(tmp_fd)
136
 
137
+ # ÉTAPE 1: Stabilisation par Copie de Flux (Remuxage) du fichier d'entrée vers un conteneur MP4 stable.
138
+ # Ceci réécrit les métadonnées de l'en-tête (duration) sans réencoder.
139
+ remux_cmd = (
140
+ f'ffmpeg -hide_banner -loglevel error -y '
141
+ f'-analyzeduration 2147483647 -probesize 2147483647 -ignore_unknown '
142
+ f'-i {shlex.quote(video_path)} -c copy {shlex.quote(stabilized_mp4)}'
143
+ )
144
+ print("RUN: Remuxage du fichier pour stabilisation...")
145
+ run_cmd(remux_cmd)
146
+
147
+ # ÉTAPE 2: Extraction de l'audio 16k WAV à partir du fichier stabilisé.
148
+ extract_cmd = (
149
+ f'ffmpeg -hide_banner -loglevel error -y '
150
+ f'-i {shlex.quote(stabilized_mp4)} -vn -ac 1 -ar 16000 -f wav {shlex.quote(out_wav)}'
151
+ )
152
+ print("RUN: Extraction de l'audio depuis le fichier stabilisé...")
153
+ run_cmd(extract_cmd)
154
+
155
+ # Nettoyage du fichier intermédiaire stabilisé
156
+ if os.path.exists(stabilized_mp4):
157
+ os.remove(stabilized_mp4)
158
+
159
  def clean_audio(wav_path, target_sr=16000):
160
+ """Load audio, ensure mono, resample to target_sr, normalize, write cleaned wav."""
161
  audio, sr = sf.read(wav_path)
162
+ if audio.ndim == 2:
163
+ audio = audio.mean(axis=1)
164
  if sr != target_sr:
165
  audio = librosa.resample(audio.astype(float), orig_sr=sr, target_sr=target_sr)
166
  sr = target_sr
167
+ max_val = np.max(np.abs(audio)) if audio.size > 0 else 0.0
 
 
 
168
  if max_val > 1e-6:
169
+ audio = audio / max_val * 0.9
170
  clean_path = str(Path(wav_path).with_name(Path(wav_path).stem + "_clean.wav"))
171
  sf.write(clean_path, audio, sr)
172
  return clean_path, audio, sr
173
+
174
+ # ---------------------------- # TRANSCRIPTION, ETC. (Inchangé) # ----------------------------
175
+ # Les autres fonctions (transcribe, keep_bambara, pack, align_heuristic, etc.)
176
+ # restent les mêmes que dans la version V4.7.
177
 
 
 
 
178
  def transcribe(model, wav_path):
179
+ if not hasattr(model, "transcribe"):
180
+ raise RuntimeError("Le modèle ne supporte pas model.transcribe()")
181
  out = model.transcribe([wav_path])
182
+ if isinstance(out, list):
183
+ if len(out) == 0:
184
+ return ""
185
+ first = out[0]
186
+ if isinstance(first, str):
187
+ return first.strip()
188
+ if hasattr(first, "text"):
189
+ return first.text.strip()
190
+ return str(first).strip()
191
+ if hasattr(out, "text"):
192
+ return out.text.strip()
193
  return str(out).strip()
194
+
195
+ def keep_bambara(words):
196
+ res = []
197
+ for w in words:
198
+ wl = w.lower()
199
+ if any(c in wl for c in ["ɛ","ɔ","ŋ"]) or sum(1 for c in wl if c in "aeiou") >= 2:
200
+ res.append(w)
201
+ return res
202
+
203
+ MAX_CHARS = 45; MIN_DUR = 0.3; MAX_DUR = 3.2; MAX_WORDS = 8
204
+
205
+ def wrap2(txt):
206
+ parts = textwrap.wrap(txt, MAX_CHARS)
207
+ if len(parts) <= 1:
208
+ return txt
209
+ mid = len(txt) // 2
210
+ left = txt.rfind(" ", 0, mid)
211
+ right = txt.find(" ", mid)
212
+ cut = left if (mid - left) <= ((right - mid) if right != -1 else 1e9) else right
213
+ l1 = txt[:cut].strip(); l2 = txt[cut:].strip()
214
+ return l1 + "\n" + l2 if l2 else l1
215
+
216
+ def pack(spans, total):
217
+ tmp = []
218
+ for s, e, t in spans:
219
+ s = max(0, min(s, total)); e = max(0, min(e, total))
220
+ if e <= s or not t.strip(): continue
221
+ tmp.append((s, e, t.strip()))
222
+ merged = []
223
+ for seg in tmp:
224
+ if not merged:
225
+ merged.append(seg); continue
226
+ ps, pe, pt = merged[-1]; s, e, t = seg
227
+ if (e - s) < MIN_DUR or (s - pe) < 0.1:
228
+ merged[-1] = (ps, max(pe, e), (pt + " " + t).strip())
229
+ else:
230
+ merged.append(seg)
231
+ out = []; last_end = 0
232
+ for s, e, t in merged:
233
+ dur = e - s; words = t.split()
234
+ blocks = [" ".join(words[i:i+MAX_WORDS]) for i in range(0, len(words), MAX_WORDS)]
235
+ step = dur / max(1, len(blocks))
236
+ base = s
237
+ for b in blocks:
238
+ st = base; en = min(base + step, e); base = en
239
+ if en <= st: en = min(st + 0.05, total)
240
+ txt = wrap2(b)
241
+ if st < last_end:
242
+ st = last_end + 1e-3; en = max(en, st + 0.05)
243
+ out.append((st, en, txt)); last_end = en
244
+ return out
245
+
246
+ def align_heuristic(words, total_dur):
247
+ total = total_dur
248
+ if not words:
249
+ return pack([], total)
250
+
251
+ spans = []
252
+ blocks = [" ".join(words[i:i+MAX_WORDS]) for i in range(0, len(words), MAX_WORDS)]
253
+ num_blocks = len(blocks)
254
+
255
+ max_step = min(MAX_DUR, total / num_blocks if num_blocks > 0 else total)
256
+
257
+ base = 0.0
258
+ for block in blocks:
259
+ st = base; en = min(base + max_step, total)
260
+ spans.append((st, en, block))
261
+ base = en
262
+
263
+ return pack(spans, total)
264
+
265
 
266
+ def segment_and_align(model, audio, sr, total_dur, mode):
267
+ """Découpe l'audio, tente alignement CTC Segmentation, fallback Heuristique."""
268
+ segment_samples = int(SEGMENT_DURATION * sr)
269
+ total_samples = len(audio)
270
+ all_subs = []
271
+
272
+ for i in range(0, total_samples, segment_samples):
273
+ start_sample = i
274
+ end_sample = min(i + segment_samples, total_samples)
275
+ time_offset = start_sample / sr
276
+
277
+ segment_audio = audio[start_sample:end_sample]
278
+ segment_duration = (end_sample - start_sample) / sr
279
+
280
+ tmp_fd, tmp_seg_wav = tempfile.mkstemp(suffix=f"_seg_{i}.wav")
281
+ os.close(tmp_fd)
282
+ sf.write(tmp_seg_wav, segment_audio, sr)
283
+
284
+ try:
285
+ segment_text = transcribe(model, tmp_seg_wav)
286
+ words = keep_bambara(segment_text.split())
287
 
288
+ subs = None
289
+ if HAS_CTC_SEGMENTATION and words and mode in ["rnnt", "ctc"]:
290
+ try:
291
+ x = torch.tensor(segment_audio).float().unsqueeze(0).to(DEVICE)
292
+ ln = torch.tensor([x.shape[1]]).to(DEVICE)
293
+
294
+ with torch.no_grad():
295
+ logits, _ = model.forward(input_signal=x, input_signal_length=ln)
296
+ if isinstance(logits, tuple):
297
+ logits = logits[0]
298
+
299
+ time_per_frame = segment_duration / max(1, logits.shape[1])
300
+
301
+ try:
302
+ raw = model.tokenizer.vocab
303
+ vocab = list(raw.keys()) if isinstance(raw, dict) else list(raw)
304
+ except Exception:
305
+ vocab = None
306
+
307
+ cfg = CtcSegmentationParameters()
308
+ if vocab:
309
+ cfg.char_list = vocab
310
+
311
+ gt = prepare_text(cfg, words)[0]
312
+
313
+ # CORRECTION DU DÉBALLAGE (STAR-UNPACKING)
314
+ timing, *others = ctc_segmentation(cfg, logits.detach().cpu().numpy()[0], gt)
315
+
316
+ spans = []
317
+ for k in range(len(words)):
318
+ start_time = timing[k] * time_per_frame
319
+ end_time = timing[k+1] * time_per_frame if k + 1 < len(timing) else segment_duration
320
+ spans.append((start_time, end_time, words[k]))
321
 
322
+ subs = pack(spans, segment_duration)
323
+
324
+ except Exception as e:
325
+ print(f"[WARN] CTC Segmentation échoué pour le segment à {time_offset:.2f}s ({e}) -> Fallback Heuristique")
326
+ subs = align_heuristic(words, segment_duration)
327
+ else:
328
+ subs = align_heuristic(words, segment_duration)
329
 
330
+ if subs:
331
+ for start, end, text in subs:
332
+ all_subs.append((start + time_offset, end + time_offset, text))
333
+
334
+ except Exception as e:
335
+ print(f"Échec critique de la transcription/alignement du segment à {time_offset:.2f}s: {e}")
336
+
337
+ finally:
338
+ if os.path.exists(tmp_seg_wav):
339
+ os.remove(tmp_seg_wav)
340
 
341
+ return pack(all_subs, total_dur)
342
+
343
+ def burn(video_path, subs, output_path=None):
344
+ if output_path is None:
345
+ output_path = "RobotsMali_Subtitled.mp4"
346
+
347
+ tmp_fd, tmp_srt = tempfile.mkstemp(suffix=".srt")
348
+ os.close(tmp_fd)
349
+
350
+ def sec_to_srt(t):
351
+ h = int(t // 3600); m = int((t % 3600) // 60); s = int(t % 60); ms = int((t - int(t)) * 1000)
352
+ return f"{h:02}:{m:02}:{s:02},{ms:03}"
353
+
354
+ with open(tmp_srt, "w", encoding="utf-8") as f:
355
+ for i, (start, end, text) in enumerate(subs, 1):
356
+ f.write(f"{i}\n{sec_to_srt(start)} --> {sec_to_srt(end)}\n{text}\n\n")
357
+
358
+ vf = f"subtitles={shlex.quote(tmp_srt)}:force_style='Fontsize=22,PrimaryColour=&HFFFFFF&,OutlineColour=&H000000&'"
359
+ 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)}'
360
+
361
+ try:
362
+ run_cmd(cmd)
363
+ finally:
364
+ if os.path.exists(tmp_srt):
365
+ os.remove(tmp_srt)
366
+
367
+ return output_path
368
+
369
+ # ---------------------------- # PIPELINE PRINCIPAL (V4.8) # ----------------------------
370
+ def pipeline(video_input, model_name):
371
+ try:
372
+ if isinstance(video_input, dict) and "tmp_path" in video_input:
373
+ video_path = video_input["tmp_path"]
374
+ else:
375
+ video_path = video_input
376
+
377
+ # Tente d'obtenir la durée via ffprobe (pour un contrôle rapide)
378
+ duration = ffprobe_duration(video_path)
379
+
380
+ tmp_fd, tmp_wav = tempfile.mkstemp(suffix=".wav")
381
+ os.close(tmp_fd)
382
+
383
+ # Extraction audio robuste (tentative de réparation/remuxage via ffmpeg)
384
+ extract_audio(video_path, tmp_wav)
385
+ clean_wav, audio, sr = clean_audio(tmp_wav)
386
+
387
+ # LOGIQUE DE FALLBACK : Si ffprobe a échoué, calcule la durée à partir du fichier WAV extrait
388
+ if duration is None:
389
+ if len(audio) > 0:
390
+ duration = len(audio) / sr
391
+ print(f"[WARN] FFprobe échoué. Durée recalculée à partir de l'audio extrait : {duration:.2f}s")
392
+ else:
393
+ raise RuntimeError("Impossible d'obtenir une durée non nulle de la vidéo, même après extraction audio robuste.")
394
+
395
+ model = load_model(model_name)
396
+ mode = MODELS[model_name][1]
397
+
398
+ subs = segment_and_align(model, audio, sr, duration, mode)
399
+
400
+ if not subs:
401
+ return ("⚠️ Aucun sous-titre utilisable (sub list vide)", None)
402
+
403
+ out_video = burn(video_path, subs)
404
+ return ("✅ Terminé avec succès", out_video)
405
+
406
+ except Exception as e:
407
+ traceback.print_exc()
408
+ return (f"❌ Erreur — {str(e)}", None)
409
 
410
+
411
+ # ---------------------------- # INTERFACE GRADIO # ----------------------------
 
412
  with gr.Blocks(title="RobotsMali - Sous-titrage") as demo:
413
+ gr.Markdown("## 🤖 RobotsMali — Sous-titrage Bambara (Colab Ready - Audio Max Robuste)")
414
+ gr.Markdown("L'extraction audio est maintenant ultra-robuste. Si vous utilisez la webcam ou un fichier téléchargé, ce script devrait pouvoir le traiter.")
415
+
416
+ # Composant Video sans 'examples'
417
+ v = gr.Video(label="Vidéo à sous-titrer (Fichier ou Webcam)")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
418
 
419
+ # Utilisation de gr.Examples séparé pour la compatibilité
420
+ gr.Examples(
421
+ examples=VIDEO_EXAMPLES,
422
+ inputs=v,
423
+ label="Exemples de vidéos à tester (Téléchargez d'abord le fichier dans Colab pour utiliser ce chemin)"
424
+ )
425
+
426
+ m = gr.Dropdown(list(MODELS.keys()), value="Soloba V1 (CTC)", label="Modèle ASR Bambara")
427
+ b = gr.Button("▶️ Générer les Sous-titres Incrustés")
428
+ s = gr.Markdown(label="Statut")
429
+ o = gr.Video(label="Vidéo sous-titrée (Format MP4 H.264)")
430
+
431
  b.click(pipeline, [v, m], [s, o])
432
+
433
+ demo.launch(share=True, debug=True)