binaryMao commited on
Commit
326676b
·
verified ·
1 Parent(s): 88d36f5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +33 -30
app.py CHANGED
@@ -1,5 +1,5 @@
1
  # -*- coding: utf-8 -*-
2
- import os, shlex, subprocess, tempfile, traceback, time, glob, gc
3
  import torch
4
  from huggingface_hub import snapshot_download
5
  from nemo.collections import asr as nemo_asr
@@ -30,7 +30,7 @@ def get_absolute_example():
30
  EXAMPLE_PATH = get_absolute_example()
31
  _cache = {}
32
 
33
- # 3. GESTION DE LA MÉMOIRE ET CHARGEMENT
34
  def clear_memory():
35
  """Libère proprement la RAM et la VRAM."""
36
  _cache.clear()
@@ -39,22 +39,26 @@ def clear_memory():
39
  torch.cuda.empty_cache()
40
 
41
  def get_model(name):
42
- """Charge le modèle avec optimisation FP16 pour la vitesse."""
43
  if name in _cache: return _cache[name]
44
 
45
  clear_memory()
46
- repo, mode = MODELS[name]
 
 
47
  folder = snapshot_download(repo, local_dir_use_symlinks=False)
48
  nemo_file = next((os.path.join(folder, f) for f in os.listdir(folder) if f.endswith(".nemo")), None)
49
 
50
- if mode == "rnnt":
51
- model = nemo_asr.models.EncDecHybridRNNTCTCBPEModel.restore_from(nemo_file)
52
- else:
53
- model = nemo_asr.models.EncDecCTCModelBPE.restore_from(nemo_file)
 
 
54
 
55
  model.to(DEVICE).eval()
56
 
57
- # OPTIMISATION : Inférence en demi-précision (FP16) sur GPU
58
  if DEVICE == "cuda":
59
  model.half()
60
 
@@ -67,18 +71,18 @@ def format_srt_time(sec):
67
  ms = int((sec - int(sec)) * 1000)
68
  return f"{time.strftime('%H:%M:%S', td)},{ms:03}"
69
 
70
- # 5. PIPELINE DE TRANSCRIPTION OPTIMISÉ
71
  def pipeline(video_in, model_name):
72
  tmp_dir = tempfile.mkdtemp()
73
  try:
74
  if not video_in: return "❌ Source vide", None
75
 
76
- # A. Extraction Audio Rapide
77
  yield "⏳ Extraction audio...", None
78
  full_wav = os.path.join(tmp_dir, "full.wav")
79
- subprocess.run(f"ffmpeg -y -i {shlex.quote(video_in)} -vn -ac 1 -ar 16000 -threads 0 {full_wav}", shell=True, check=True)
80
 
81
- # B. Segmentation (20s pour réduire le nombre d'appels IA)
82
  seg_time = 20
83
  segment_pattern = os.path.join(tmp_dir, "seg_%03d.wav")
84
  subprocess.run(f"ffmpeg -i {full_wav} -f segment -segment_time {seg_time} -c copy {segment_pattern}", shell=True, check=True)
@@ -88,20 +92,20 @@ def pipeline(video_in, model_name):
88
  yield f"⏳ IA : Chargement de {model_name}...", None
89
  model = get_model(model_name)
90
 
91
- # Détermination du stride (standard RobotsMali 0.02)
92
  stride = 0.02
93
  if hasattr(model, 'preprocessor') and hasattr(model.preprocessor, 'featurizer'):
94
  stride = model.preprocessor.featurizer.hop_length / model.preprocessor.featurizer.sample_rate
95
 
96
- # D. Transcription Séquentielle
97
  all_words_ts = []
98
  for idx, seg_path in enumerate(audio_segments):
99
  base_time = idx * seg_time
100
  yield f"⏳ IA : Transcription {idx+1}/{len(audio_segments)}...", None
101
 
102
- # Inférence
103
  hyp = model.transcribe([seg_path], return_hypotheses=True)[0]
104
- words = (hyp.text if hasattr(hyp, 'text') else str(hyp)).split()
 
 
105
  offsets = getattr(hyp, 'word_offsets', None)
106
 
107
  if offsets and len(offsets) == len(words):
@@ -109,7 +113,6 @@ def pipeline(video_in, model_name):
109
  t_start = base_time + (offsets[i] * stride)
110
  all_words_ts.append({"word": word, "start": t_start, "end": t_start + 0.45})
111
  else:
112
- # Fallback linéaire si les offsets sont indisponibles
113
  gap = float(seg_time) / max(len(words), 1)
114
  for i, w in enumerate(words):
115
  all_words_ts.append({"word": w, "start": base_time + (i * gap), "end": base_time + ((i+1) * gap)})
@@ -122,18 +125,15 @@ def pipeline(video_in, model_name):
122
  f.write(f"{(i//6)+1}\n{format_srt_time(chunk[0]['start'])} --> {format_srt_time(chunk[-1]['end'])}\n")
123
  f.write(" ".join([c['word'] for c in chunk]) + "\n\n")
124
 
125
- # F. Encodage Vidéo Final (Ultra-rapide)
126
- yield "⏳ Rendu vidéo (Ultra-rapide)...", None
127
  out_path = os.path.abspath(f"robotsmali_final_{int(time.time())}.mp4")
128
-
129
- # Protection des chemins pour FFmpeg
130
  safe_srt = srt_path.replace("\\", "/").replace(":", "\\:")
131
 
132
- # OPTIMISATION : -preset ultrafast pour minimiser le temps de rendu
133
  cmd_ffmpeg = (
134
  f"ffmpeg -y -i {shlex.quote(video_in)} "
135
- f"-vf \"subtitles='{safe_srt}':force_style='Alignment=2,FontSize=18,BorderStyle=4'\" "
136
- f"-c:v libx264 -preset ultrafast -pix_fmt yuv420p -movflags +faststart -c:a aac {out_path}"
137
  )
138
  subprocess.run(cmd_ffmpeg, shell=True, check=True)
139
 
@@ -142,19 +142,22 @@ def pipeline(video_in, model_name):
142
  except Exception as e:
143
  traceback.print_exc()
144
  yield f"❌ Erreur : {str(e)}", None
 
 
 
 
145
 
146
  # 6. INTERFACE GRADIO
147
- with gr.Blocks(theme=gr.themes.Soft(), css="body {background-color: #0f172a;}") as demo:
148
- gr.HTML("<h1 style='text-align:center; color:#facc15;'>🤖 ROBOTSMALI TRANSCRIPTION</h1>")
149
 
150
  with gr.Row():
151
  with gr.Column():
152
- v_in = gr.Video(label="Source Vidéo", sources=["upload", "webcam"])
153
  m_sel = gr.Dropdown(choices=list(MODELS.keys()), value="Soloba V3 (CTC)", label="Modèle IA")
154
  btn_run = gr.Button("🚀 GÉNÉRER SOUS-TITRES", variant="primary")
155
 
156
  if EXAMPLE_PATH:
157
- gr.Markdown("### 💡 Exemple Rapide")
158
  gr.Examples(examples=[[EXAMPLE_PATH, "Soloba V3 (CTC)"]], inputs=[v_in, m_sel])
159
 
160
  with gr.Column():
@@ -164,4 +167,4 @@ with gr.Blocks(theme=gr.themes.Soft(), css="body {background-color: #0f172a;}")
164
  btn_run.click(pipeline, [v_in, m_sel], [status, v_out])
165
 
166
  if __name__ == "__main__":
167
- demo.launch(debug=True)
 
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
 
30
  EXAMPLE_PATH = get_absolute_example()
31
  _cache = {}
32
 
33
+ # 3. GESTION DE LA MÉMOIRE ET CHARGEMENT (CORRIGÉ)
34
  def clear_memory():
35
  """Libère proprement la RAM et la VRAM."""
36
  _cache.clear()
 
39
  torch.cuda.empty_cache()
40
 
41
  def get_model(name):
42
+ """Charge le modèle en utilisant ASRModel pour éviter les erreurs de state_dict."""
43
  if name in _cache: return _cache[name]
44
 
45
  clear_memory()
46
+ repo, _ = MODELS[name]
47
+
48
+ print(f"📥 Téléchargement depuis {repo}...")
49
  folder = snapshot_download(repo, local_dir_use_symlinks=False)
50
  nemo_file = next((os.path.join(folder, f) for f in os.listdir(folder) if f.endswith(".nemo")), None)
51
 
52
+ if not nemo_file:
53
+ raise FileNotFoundError(f"Aucun fichier .nemo trouvé dans {folder}")
54
+
55
+ # SOLUTION : Utilisation de ASRModel.restore_from pour la détection automatique
56
+ # Cela évite l'erreur 'Unexpected key(s) in state_dict'
57
+ model = nemo_asr.models.ASRModel.restore_from(nemo_file)
58
 
59
  model.to(DEVICE).eval()
60
 
61
+ # Optimisation FP16
62
  if DEVICE == "cuda":
63
  model.half()
64
 
 
71
  ms = int((sec - int(sec)) * 1000)
72
  return f"{time.strftime('%H:%M:%S', td)},{ms:03}"
73
 
74
+ # 5. PIPELINE DE TRANSCRIPTION
75
  def pipeline(video_in, model_name):
76
  tmp_dir = tempfile.mkdtemp()
77
  try:
78
  if not video_in: return "❌ Source vide", None
79
 
80
+ # A. Extraction Audio
81
  yield "⏳ Extraction audio...", None
82
  full_wav = os.path.join(tmp_dir, "full.wav")
83
+ subprocess.run(f"ffmpeg -y -i {shlex.quote(video_in)} -vn -ac 1 -ar 16000 {full_wav}", shell=True, check=True)
84
 
85
+ # B. Segmentation
86
  seg_time = 20
87
  segment_pattern = os.path.join(tmp_dir, "seg_%03d.wav")
88
  subprocess.run(f"ffmpeg -i {full_wav} -f segment -segment_time {seg_time} -c copy {segment_pattern}", shell=True, check=True)
 
92
  yield f"⏳ IA : Chargement de {model_name}...", None
93
  model = get_model(model_name)
94
 
 
95
  stride = 0.02
96
  if hasattr(model, 'preprocessor') and hasattr(model.preprocessor, 'featurizer'):
97
  stride = model.preprocessor.featurizer.hop_length / model.preprocessor.featurizer.sample_rate
98
 
99
+ # D. Transcription
100
  all_words_ts = []
101
  for idx, seg_path in enumerate(audio_segments):
102
  base_time = idx * seg_time
103
  yield f"⏳ IA : Transcription {idx+1}/{len(audio_segments)}...", None
104
 
 
105
  hyp = model.transcribe([seg_path], return_hypotheses=True)[0]
106
+ # Gestion des différents formats de retour NeMo
107
+ text = hyp.text if hasattr(hyp, 'text') else str(hyp)
108
+ words = text.split()
109
  offsets = getattr(hyp, 'word_offsets', None)
110
 
111
  if offsets and len(offsets) == len(words):
 
113
  t_start = base_time + (offsets[i] * stride)
114
  all_words_ts.append({"word": word, "start": t_start, "end": t_start + 0.45})
115
  else:
 
116
  gap = float(seg_time) / max(len(words), 1)
117
  for i, w in enumerate(words):
118
  all_words_ts.append({"word": w, "start": base_time + (i * gap), "end": base_time + ((i+1) * gap)})
 
125
  f.write(f"{(i//6)+1}\n{format_srt_time(chunk[0]['start'])} --> {format_srt_time(chunk[-1]['end'])}\n")
126
  f.write(" ".join([c['word'] for c in chunk]) + "\n\n")
127
 
128
+ # F. Encodage Vidéo Final
129
+ yield "⏳ Rendu vidéo final...", None
130
  out_path = os.path.abspath(f"robotsmali_final_{int(time.time())}.mp4")
 
 
131
  safe_srt = srt_path.replace("\\", "/").replace(":", "\\:")
132
 
 
133
  cmd_ffmpeg = (
134
  f"ffmpeg -y -i {shlex.quote(video_in)} "
135
+ f"-vf \"subtitles='{safe_srt}':force_style='Alignment=2,FontSize=18'\" "
136
+ f"-c:v libx264 -preset ultrafast -pix_fmt yuv420p -c:a aac {out_path}"
137
  )
138
  subprocess.run(cmd_ffmpeg, shell=True, check=True)
139
 
 
142
  except Exception as e:
143
  traceback.print_exc()
144
  yield f"❌ Erreur : {str(e)}", None
145
+ finally:
146
+ # Nettoyage des fichiers temporaires
147
+ if os.path.exists(tmp_dir):
148
+ shutil.rmtree(tmp_dir)
149
 
150
  # 6. INTERFACE GRADIO
151
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
152
+ gr.HTML("<h1 style='text-align:center;'>🤖 ROBOTSMALI TRANSCRIPTION</h1>")
153
 
154
  with gr.Row():
155
  with gr.Column():
156
+ v_in = gr.Video(label="Source Vidéo")
157
  m_sel = gr.Dropdown(choices=list(MODELS.keys()), value="Soloba V3 (CTC)", label="Modèle IA")
158
  btn_run = gr.Button("🚀 GÉNÉRER SOUS-TITRES", variant="primary")
159
 
160
  if EXAMPLE_PATH:
 
161
  gr.Examples(examples=[[EXAMPLE_PATH, "Soloba V3 (CTC)"]], inputs=[v_in, m_sel])
162
 
163
  with gr.Column():
 
167
  btn_run.click(pipeline, [v_in, m_sel], [status, v_out])
168
 
169
  if __name__ == "__main__":
170
+ demo.launch()