jbroot commited on
Commit
898fcac
·
verified ·
1 Parent(s): 683fb96
Files changed (1) hide show
  1. app.py +42 -54
app.py CHANGED
@@ -11,10 +11,11 @@ app = Flask(__name__)
11
  # Récupération du token
12
  HF_TOKEN = os.environ.get("HF_TOKEN")
13
 
 
14
  if HF_TOKEN:
15
- print(f"DEBUG: Token détecté. Début: {HF_TOKEN[:4]}...")
16
  else:
17
- print("DEBUG: ⚠️ ERREUR CRITIQUE: Aucun token HF_TOKEN trouvé !")
18
 
19
  # ==========================================
20
  # 1. INTERFACE WEB
@@ -52,9 +53,9 @@ HTML_TEMPLATE = """
52
 
53
  <div id="loading" class="hidden mt-6 flex-col items-center">
54
  <div class="loader ease-linear rounded-full border-4 border-t-4 border-slate-700 h-12 w-12 mb-4"></div>
55
- <p class="text-slate-300">Analyse IA en cours...<br><span class="text-xs text-slate-500">Patience, cela prend du temps (CPU).</span></p>
56
  </div>
57
- <div id="error-msg" class="hidden mt-4 text-red-400 text-sm font-bold bg-slate-800 p-2 rounded text-left overflow-auto max-h-32"></div>
58
  </div>
59
 
60
  <script>
@@ -105,18 +106,15 @@ HTML_TEMPLATE = """
105
  """
106
 
107
  # ==========================================
108
- # 2. LOGIQUE IA (Blindée)
109
  # ==========================================
110
  def split_audio_logic(file_storage):
111
- print("--> Chargement du modèle IA...")
112
  try:
113
  pipeline = Pipeline.from_pretrained("pyannote/speaker-diarization-3.1", token=HF_TOKEN)
114
- if torch.cuda.is_available():
115
- pipeline.to(torch.device("cuda"))
116
  except Exception as e:
117
- print(f"ERREUR LOAD PIPELINE: {e}")
118
- if "403" in str(e) or "401" in str(e):
119
- raise Exception("Erreur de droits HF. Vérifie les licences.")
120
  raise Exception(f"Erreur chargement IA: {e}")
121
 
122
  # Conversion WAV
@@ -134,47 +132,47 @@ def split_audio_logic(file_storage):
134
 
135
  print("--> Analyse Diarisation...")
136
  try:
 
137
  raw_result = pipeline(wav_filename)
138
 
139
- # --- DEBUG LOG ---
140
- print(f"DEBUG: Type du résultat = {type(raw_result)}")
141
- print(f"DEBUG: Contenu de dir() = {dir(raw_result)}")
142
- # -----------------
143
-
144
- # Extraction intelligente de l'annotation
145
  diarization = None
146
 
147
- # Cas 1 : Attribut 'annotation' (DiarizeOutput standard)
148
- if hasattr(raw_result, 'annotation'):
149
- print("--> Extraction via .annotation")
150
- diarization = raw_result.annotation
151
-
152
- # Cas 2 : Dictionnaire (Parfois utilisé dans les hooks)
153
- elif isinstance(raw_result, dict) and 'annotation' in raw_result:
154
- print("--> Extraction via dict['annotation']")
155
- diarization = raw_result['annotation']
156
-
157
- # Cas 3 : Tuple (Annotation, Embeddings)
158
- elif isinstance(raw_result, tuple):
159
- print("--> Extraction via tuple[0]")
160
- diarization = raw_result[0]
161
-
162
- # Cas 4 : C'est déjà l'annotation (Pyannote Core Annotation)
163
- elif hasattr(raw_result, 'itertracks'):
164
- print("--> Objet Annotation direct")
165
- diarization = raw_result
166
 
 
167
  if diarization is None:
168
- raise Exception(f"Format de résultat IA inconnu: {type(raw_result)}")
 
 
 
 
 
 
 
 
 
169
 
170
  except Exception as e:
171
  if os.path.exists(wav_filename): os.remove(wav_filename)
172
- raise Exception(f"Erreur pendant l'analyse IA : {str(e)}")
173
 
174
- print("--> Construction des pistes...")
175
  speaker_tracks = {}
176
 
177
- # Ici, 'diarization' est forcément le bon objet Annotation
178
  for turn, _, speaker in diarization.itertracks(yield_label=True):
179
  if speaker not in speaker_tracks:
180
  speaker_tracks[speaker] = AudioSegment.silent(duration=total_duration_ms)
@@ -185,18 +183,15 @@ def split_audio_logic(file_storage):
185
  if end_ms > total_duration_ms: end_ms = total_duration_ms
186
  if start_ms >= end_ms: continue
187
 
188
- # On utilise l'audio original converti en wav pour la découpe (c'est le plus sûr)
189
- # On recharge le wav propre qu'on a créé
190
  clean_source = AudioSegment.from_file(wav_filename)
191
  speaker_segment = clean_source[start_ms:end_ms]
192
-
193
  speaker_tracks[speaker] = speaker_tracks[speaker].overlay(speaker_segment, position=start_ms)
194
 
195
  print("--> ZIP...")
196
  memory_file = BytesIO()
197
  with zipfile.ZipFile(memory_file, 'w') as zf:
198
  zf.write(temp_filename, "original.mp3")
199
-
200
  sorted_speakers = sorted(speaker_tracks.keys())
201
  for i, spk in enumerate(sorted_speakers):
202
  track = speaker_tracks[spk]
@@ -207,7 +202,6 @@ def split_audio_logic(file_storage):
207
 
208
  if os.path.exists(wav_filename): os.remove(wav_filename)
209
  if os.path.exists(temp_filename): os.remove(temp_filename)
210
-
211
  memory_file.seek(0)
212
  return memory_file
213
 
@@ -227,14 +221,8 @@ def web_split():
227
  try:
228
  zip_buffer = split_audio_logic(file)
229
  return send_file(
230
- zip_buffer,
231
- mimetype='application/zip',
232
- as_attachment=True,
233
- download_name='podcast_split.zip'
234
  )
235
  except Exception as e:
236
- return {"error": str(e)}, 500
237
-
238
- if __name__ == '__main__':
239
- # Augmentation des threads pour supporter la charge
240
- app.run(host='0.0.0.0', port=7860, threaded=True)
 
11
  # Récupération du token
12
  HF_TOKEN = os.environ.get("HF_TOKEN")
13
 
14
+ # DEBUG: Vérification token
15
  if HF_TOKEN:
16
+ print(f"DEBUG: Token présent. Début: {HF_TOKEN[:4]}...")
17
  else:
18
+ print("DEBUG: ⚠️ ERREUR: Aucun token HF_TOKEN !")
19
 
20
  # ==========================================
21
  # 1. INTERFACE WEB
 
53
 
54
  <div id="loading" class="hidden mt-6 flex-col items-center">
55
  <div class="loader ease-linear rounded-full border-4 border-t-4 border-slate-700 h-12 w-12 mb-4"></div>
56
+ <p class="text-slate-300">Analyse IA en cours...<br><span class="text-xs text-slate-500">Patience, cela peut prendre 1 à 2 minutes (CPU).</span></p>
57
  </div>
58
+ <div id="error-msg" class="hidden mt-4 text-red-400 text-sm font-bold bg-slate-800 p-2 rounded text-left overflow-auto max-h-48 break-words"></div>
59
  </div>
60
 
61
  <script>
 
106
  """
107
 
108
  # ==========================================
109
+ # 2. LOGIQUE IA (Ouvre-Boîte Universel)
110
  # ==========================================
111
  def split_audio_logic(file_storage):
112
+ print("--> Chargement Pipeline...")
113
  try:
114
  pipeline = Pipeline.from_pretrained("pyannote/speaker-diarization-3.1", token=HF_TOKEN)
115
+ if torch.cuda.is_available(): pipeline.to(torch.device("cuda"))
 
116
  except Exception as e:
117
+ if "403" in str(e) or "401" in str(e): raise Exception("Erreur Licence HF (401/403).")
 
 
118
  raise Exception(f"Erreur chargement IA: {e}")
119
 
120
  # Conversion WAV
 
132
 
133
  print("--> Analyse Diarisation...")
134
  try:
135
+ # Exécution IA
136
  raw_result = pipeline(wav_filename)
137
 
138
+ # --- OUVRE-BOÎTE UNIVERSEL ---
 
 
 
 
 
139
  diarization = None
140
 
141
+ # 1. On tente l'attribut .annotation (Cas standard)
142
+ try:
143
+ diarization = raw_result.annotation
144
+ print("--> Succès via .annotation")
145
+ except:
146
+ pass
147
+
148
+ # 2. Si échec, on tente l'index 0 (Cas Tuple)
149
+ if diarization is None:
150
+ try:
151
+ diarization = raw_result[0]
152
+ print("--> Succès via index [0]")
153
+ except:
154
+ pass
 
 
 
 
 
155
 
156
+ # 3. Si échec, on suppose que c'est déjà l'annotation
157
  if diarization is None:
158
+ diarization = raw_result
159
+ print("--> Utilisation de l'objet brut")
160
+
161
+ # VERIFICATION FINALE : Est-ce qu'on a bien une annotation valide ?
162
+ # Une annotation valide DOIT avoir la méthode .itertracks()
163
+ if not hasattr(diarization, 'itertracks'):
164
+ # C'EST ICI QUE CA BLOQUAIT.
165
+ # On génère un message d'erreur ultra-détaillé pour le debug
166
+ debug_info = f"Type: {type(raw_result)} | Dir: {dir(raw_result)}"
167
+ raise Exception(f"Format IA impossible à lire. {debug_info}")
168
 
169
  except Exception as e:
170
  if os.path.exists(wav_filename): os.remove(wav_filename)
171
+ raise Exception(f"Erreur Analyse: {str(e)}")
172
 
173
+ print("--> Construction Pistes...")
174
  speaker_tracks = {}
175
 
 
176
  for turn, _, speaker in diarization.itertracks(yield_label=True):
177
  if speaker not in speaker_tracks:
178
  speaker_tracks[speaker] = AudioSegment.silent(duration=total_duration_ms)
 
183
  if end_ms > total_duration_ms: end_ms = total_duration_ms
184
  if start_ms >= end_ms: continue
185
 
186
+ # Rechargement WAV propre pour découpe
 
187
  clean_source = AudioSegment.from_file(wav_filename)
188
  speaker_segment = clean_source[start_ms:end_ms]
 
189
  speaker_tracks[speaker] = speaker_tracks[speaker].overlay(speaker_segment, position=start_ms)
190
 
191
  print("--> ZIP...")
192
  memory_file = BytesIO()
193
  with zipfile.ZipFile(memory_file, 'w') as zf:
194
  zf.write(temp_filename, "original.mp3")
 
195
  sorted_speakers = sorted(speaker_tracks.keys())
196
  for i, spk in enumerate(sorted_speakers):
197
  track = speaker_tracks[spk]
 
202
 
203
  if os.path.exists(wav_filename): os.remove(wav_filename)
204
  if os.path.exists(temp_filename): os.remove(temp_filename)
 
205
  memory_file.seek(0)
206
  return memory_file
207
 
 
221
  try:
222
  zip_buffer = split_audio_logic(file)
223
  return send_file(
224
+ zip_buffer, mimetype='application/zip',
225
+ as_attachment=True, download_name='podcast_split.zip'
 
 
226
  )
227
  except Exception as e:
228
+ return {"error": str(e)}, 5