binaryMao commited on
Commit
c307877
·
verified ·
1 Parent(s): 4d8b436

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +41 -75
app.py CHANGED
@@ -1,15 +1,11 @@
1
  # -*- coding: utf-8 -*-
2
- # !apt-get install -y ffmpeg
3
- # !pip install gradio huggingface_hub torch
4
- # !pip install git+https://github.com/NVIDIA/NeMo.git@main#egg=nemo_toolkit[all]
5
-
6
  import os, shlex, subprocess, tempfile, traceback, time, glob, gc, shutil
7
  import torch
8
  from huggingface_hub import snapshot_download
9
  from nemo.collections import asr as nemo_asr
10
  import gradio as gr
11
 
12
- # 1. CONFIGURATION ET MODÈLES (INTÉGRALITÉ CONSERVÉE)
13
  DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
14
  SEGMENT_DURATION = 5.0
15
 
@@ -25,55 +21,42 @@ MODELS = {
25
  "Traduction Soloni (ST)": ("RobotsMali/st-soloni-114m-tdt-ctc", "rnnt"),
26
  }
27
 
28
- # --- SECTION EXEMPLE (RÉTABLIE) ---
29
  def find_example_video():
30
  paths = ["examples/MARALINKE_FIXED.mp4", "examples/MARALINKE.mp4", "MARALINKE.mp4"]
31
  for p in paths:
32
  if os.path.exists(p): return p
33
-
34
- print("⬇️ Téléchargement de la vidéo d'exemple...")
35
- example_url = "https://huggingface.co/spaces/RobotsMali/Soloni-Demo/resolve/main/examples/MARALINKE.mp4"
36
- target_path = "examples/MARALINKE.mp4"
37
- os.makedirs("examples", exist_ok=True)
38
- try:
39
- subprocess.run(f"wget {example_url} -O {target_path}", shell=True, check=True)
40
- return target_path
41
- except Exception:
42
- return None
43
 
44
  EXAMPLE_PATH = find_example_video()
45
  _cache = {}
46
 
47
- # 2. GESTION MÉMOIRE ET CHARGEMENT SÉCURISÉ
48
- def clear_memory():
49
- _cache.clear()
50
- gc.collect()
51
- if torch.cuda.is_available():
52
- torch.cuda.empty_cache()
53
-
54
  def get_model(name):
55
  if name in _cache: return _cache[name]
56
- clear_memory()
57
- repo, _ = MODELS[name]
58
 
 
59
  folder = snapshot_download(repo, local_dir_use_symlinks=False)
60
  nemo_file = next((os.path.join(folder, f) for f in os.listdir(folder) if f.endswith(".nemo")), None)
61
- if not nemo_file: raise FileNotFoundError("Fichier .nemo introuvable.")
62
-
63
- # FIX CRITIQUE : Importation et instanciation explicite du connecteur
64
- from nemo.core.connectors.save_restore_connector import SaveRestoreConnector
65
 
66
- # On force NeMo à utiliser cette instance précise pour éviter le bug __init__()
67
- model = nemo_asr.models.ASRModel.restore_from(
68
- nemo_file,
69
- map_location=torch.device(DEVICE),
70
- save_restore_connector=SaveRestoreConnector()
71
- )
 
 
 
 
 
 
 
72
 
73
  model.eval()
74
- if DEVICE == "cuda":
75
- model = model.half()
76
-
77
  _cache[name] = model
78
  return model
79
 
@@ -83,53 +66,42 @@ def format_srt_time(sec):
83
  ms = int((sec - int(sec)) * 1000)
84
  return f"{time.strftime('%H:%M:%S', td)},{ms:03}"
85
 
86
- # 4. PIPELINE DE TRANSCRIPTION
87
  def pipeline(video_in, model_name):
88
  tmp_dir = tempfile.mkdtemp()
89
  try:
90
- if not video_in:
91
- yield "❌ Aucune vidéo sélectionnée.", None
92
- return
93
 
94
- yield "⏳ Extraction audio...", None
95
  full_wav = os.path.join(tmp_dir, "full.wav")
96
  subprocess.run(f"ffmpeg -y -i {shlex.quote(video_in)} -vn -ac 1 -ar 16000 {full_wav}", shell=True, check=True)
97
 
98
- yield f"⏳ Segmentation ({SEGMENT_DURATION}s)...", None
 
99
  subprocess.run(f"ffmpeg -i {full_wav} -f segment -segment_time {SEGMENT_DURATION} -c copy {os.path.join(tmp_dir, 'seg_%03d.wav')}", shell=True, check=True)
100
 
101
  files = sorted(glob.glob(os.path.join(tmp_dir, "seg_*.wav")))
102
  valid_segments = [f for f in files if os.path.getsize(f) > 1500]
103
 
104
- if not valid_segments:
105
- yield " Erreur : Audio trop court ou invalide.", None
106
- return
107
-
108
- yield f"⏳ Chargement de {model_name}...", None
109
  model = get_model(model_name)
110
 
111
- yield f"🎙️ Transcription de {len(valid_segments)} segments...", None
112
- b_size = 16 if DEVICE == "cuda" else 2
113
-
114
  with torch.inference_mode():
115
- batch_hypotheses = model.transcribe(valid_segments, batch_size=b_size, return_hypotheses=True)
116
 
 
117
  all_words_ts = []
118
  for idx, hyp in enumerate(batch_hypotheses):
119
  base_time = idx * SEGMENT_DURATION
120
  text = hyp.text if hasattr(hyp, 'text') else str(hyp)
121
  words = text.split()
122
  if not words: continue
123
-
124
  gap = SEGMENT_DURATION / len(words)
125
  for i, w in enumerate(words):
126
- all_words_ts.append({
127
- "word": w,
128
- "start": base_time + (i * gap),
129
- "end": base_time + ((i+1) * gap)
130
- })
131
 
132
- yield "⏳ Encodage vidéo...", None
133
  srt_path = os.path.join(tmp_dir, "final.srt")
134
  with open(srt_path, "w", encoding="utf-8") as f:
135
  for i in range(0, len(all_words_ts), 6):
@@ -139,35 +111,29 @@ def pipeline(video_in, model_name):
139
 
140
  out_path = os.path.abspath(f"resultat_{int(time.time())}.mp4")
141
  safe_srt = srt_path.replace("\\", "/").replace(":", "\\:")
142
-
143
- cmd = f"ffmpeg -y -i {shlex.quote(video_in)} -vf \"subtitles='{safe_srt}':force_style='Alignment=2,FontSize=18,PrimaryColour=&H00FFFF,Outline=1'\" -c:v libx264 -preset ultrafast -c:a copy {out_path}"
144
  subprocess.run(cmd, shell=True, check=True)
145
 
146
- yield "✅ Terminé !", out_path
147
 
148
  except Exception as e:
149
- traceback.print_exc()
150
  yield f"❌ Erreur : {str(e)}", None
151
  finally:
152
  if os.path.exists(tmp_dir): shutil.rmtree(tmp_dir)
153
 
154
- # 5. INTERFACE GRADIO
155
- with gr.Blocks(theme=gr.themes.Soft()) as demo:
156
- gr.HTML("<div style='text-align:center;'><h1>🤖 RobotsMali Speech Lab</h1></div>")
157
-
158
  with gr.Row():
159
  with gr.Column():
160
- v_input = gr.Video(label="Vidéo Source")
161
  m_input = gr.Dropdown(choices=list(MODELS.keys()), value="Soloni V3 (TDT-CTC)", label="Modèle")
162
  run_btn = gr.Button("🚀 GÉNÉRER", variant="primary")
163
-
164
- if EXAMPLE_PATH:
165
- gr.Examples(examples=[[EXAMPLE_PATH, "Soloni V3 (TDT-CTC)"]], inputs=[v_input, m_input])
166
-
167
  with gr.Column():
168
- status = gr.Markdown("### État\nPrêt.")
169
  v_output = gr.Video(label="Résultat")
170
 
171
  run_btn.click(pipeline, [v_input, m_input], [status, v_output])
172
 
173
- demo.queue().launch()
 
1
  # -*- coding: utf-8 -*-
 
 
 
 
2
  import os, shlex, subprocess, tempfile, traceback, time, glob, gc, shutil
3
  import torch
4
  from huggingface_hub import snapshot_download
5
  from nemo.collections import asr as nemo_asr
6
  import gradio as gr
7
 
8
+ # 1. CONFIGURATION ET MODÈLES
9
  DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
10
  SEGMENT_DURATION = 5.0
11
 
 
21
  "Traduction Soloni (ST)": ("RobotsMali/st-soloni-114m-tdt-ctc", "rnnt"),
22
  }
23
 
24
+ # --- SECTION EXEMPLE ---
25
  def find_example_video():
26
  paths = ["examples/MARALINKE_FIXED.mp4", "examples/MARALINKE.mp4", "MARALINKE.mp4"]
27
  for p in paths:
28
  if os.path.exists(p): return p
29
+ return None
 
 
 
 
 
 
 
 
 
30
 
31
  EXAMPLE_PATH = find_example_video()
32
  _cache = {}
33
 
34
+ # 2. GESTION MÉMOIRE ET CHARGEMENT (NOUVELLE MÉTHODE ANTI-BUG)
 
 
 
 
 
 
35
  def get_model(name):
36
  if name in _cache: return _cache[name]
37
+ gc.collect()
38
+ if torch.cuda.is_available(): torch.cuda.empty_cache()
39
 
40
+ repo, model_type = MODELS[name]
41
  folder = snapshot_download(repo, local_dir_use_symlinks=False)
42
  nemo_file = next((os.path.join(folder, f) for f in os.listdir(folder) if f.endswith(".nemo")), None)
 
 
 
 
43
 
44
+ print(f"📦 Restauration forcée du modèle : {name}")
45
+
46
+ # MÉTHODE ALTERNATIVE : On bypass le connecteur automatique
47
+ try:
48
+ # Tentative avec la méthode classique mais simplifiée au maximum
49
+ model = nemo_asr.models.ASRModel.restore_from(nemo_file, map_location=torch.device(DEVICE))
50
+ except TypeError:
51
+ # Si l'erreur object.init() survient, on utilise le chargement par classe spécifique
52
+ print("⚠️ Détection du bug NeMo, basculement sur le chargement spécifique...")
53
+ if "ctc" in name.lower() or model_type == "ctc":
54
+ model = nemo_asr.models.EncDecCTCModel.restore_from(nemo_file, map_location=torch.device(DEVICE))
55
+ else:
56
+ model = nemo_asr.models.EncDecHybridRNNTCTCModel.restore_from(nemo_file, map_location=torch.device(DEVICE))
57
 
58
  model.eval()
59
+ if DEVICE == "cuda": model = model.half()
 
 
60
  _cache[name] = model
61
  return model
62
 
 
66
  ms = int((sec - int(sec)) * 1000)
67
  return f"{time.strftime('%H:%M:%S', td)},{ms:03}"
68
 
69
+ # 4. PIPELINE
70
  def pipeline(video_in, model_name):
71
  tmp_dir = tempfile.mkdtemp()
72
  try:
73
+ if not video_in: return "❌ Vidéo manquante", None
 
 
74
 
75
+ # Audio
76
  full_wav = os.path.join(tmp_dir, "full.wav")
77
  subprocess.run(f"ffmpeg -y -i {shlex.quote(video_in)} -vn -ac 1 -ar 16000 {full_wav}", shell=True, check=True)
78
 
79
+ # Segmentation
80
+ yield "⏳ Segmentation...", None
81
  subprocess.run(f"ffmpeg -i {full_wav} -f segment -segment_time {SEGMENT_DURATION} -c copy {os.path.join(tmp_dir, 'seg_%03d.wav')}", shell=True, check=True)
82
 
83
  files = sorted(glob.glob(os.path.join(tmp_dir, "seg_*.wav")))
84
  valid_segments = [f for f in files if os.path.getsize(f) > 1500]
85
 
86
+ # Transcription
87
+ yield f"🎙️ Chargement & Transcription ({model_name})...", None
 
 
 
88
  model = get_model(model_name)
89
 
 
 
 
90
  with torch.inference_mode():
91
+ batch_hypotheses = model.transcribe(valid_segments, batch_size=16 if DEVICE=="cuda" else 2, return_hypotheses=True)
92
 
93
+ # SRT Generation
94
  all_words_ts = []
95
  for idx, hyp in enumerate(batch_hypotheses):
96
  base_time = idx * SEGMENT_DURATION
97
  text = hyp.text if hasattr(hyp, 'text') else str(hyp)
98
  words = text.split()
99
  if not words: continue
 
100
  gap = SEGMENT_DURATION / len(words)
101
  for i, w in enumerate(words):
102
+ all_words_ts.append({"word": w, "start": base_time + (i * gap), "end": base_time + ((i+1) * gap)})
 
 
 
 
103
 
104
+ # Encodage
105
  srt_path = os.path.join(tmp_dir, "final.srt")
106
  with open(srt_path, "w", encoding="utf-8") as f:
107
  for i in range(0, len(all_words_ts), 6):
 
111
 
112
  out_path = os.path.abspath(f"resultat_{int(time.time())}.mp4")
113
  safe_srt = srt_path.replace("\\", "/").replace(":", "\\:")
114
+ cmd = f"ffmpeg -y -i {shlex.quote(video_in)} -vf \"subtitles='{safe_srt}':force_style='Alignment=2,FontSize=18'\" -c:v libx264 -preset ultrafast -c:a copy {out_path}"
 
115
  subprocess.run(cmd, shell=True, check=True)
116
 
117
+ yield "✅ Succès !", out_path
118
 
119
  except Exception as e:
 
120
  yield f"❌ Erreur : {str(e)}", None
121
  finally:
122
  if os.path.exists(tmp_dir): shutil.rmtree(tmp_dir)
123
 
124
+ # 5. INTERFACE
125
+ with gr.Blocks() as demo:
126
+ gr.HTML("<h1 style='text-align:center;'>RobotsMali Speech Lab</h1>")
 
127
  with gr.Row():
128
  with gr.Column():
129
+ v_input = gr.Video(label="Source")
130
  m_input = gr.Dropdown(choices=list(MODELS.keys()), value="Soloni V3 (TDT-CTC)", label="Modèle")
131
  run_btn = gr.Button("🚀 GÉNÉRER", variant="primary")
132
+ if EXAMPLE_PATH: gr.Examples([[EXAMPLE_PATH, "Soloni V3 (TDT-CTC)"]], [v_input, m_input])
 
 
 
133
  with gr.Column():
134
+ status = gr.Markdown("Prêt.")
135
  v_output = gr.Video(label="Résultat")
136
 
137
  run_btn.click(pipeline, [v_input, m_input], [status, v_output])
138
 
139
+ demo.launch()