Woziii commited on
Commit
b535d53
·
verified ·
1 Parent(s): 72cecc5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +25 -47
app.py CHANGED
@@ -1,16 +1,9 @@
1
- # Version: Corrected After Test 4 (V2.4.1 - Fixed Validation & Timestamps Button Restored)
2
- # Description: Cette version corrige la validation des segments modifiés manuellement.
3
- # Réintégration du bouton "Générer les timestamps".
4
- # Correction du bug "too many values to unpack".
5
- # La génération du fichier ZIP fonctionne correctement après validation.
6
-
7
  import os
8
  import shutil
9
  import zipfile
10
  import torch
11
- import numpy as np
12
- from pathlib import Path
13
  import gradio as gr
 
14
  from pydub import AudioSegment
15
  from transformers import pipeline
16
 
@@ -41,7 +34,7 @@ def init_metadata_state():
41
  def transcribe_audio(audio_path):
42
  if not audio_path:
43
  print("[LOG] Aucun fichier audio fourni.")
44
- return "Aucun fichier audio fourni", [], None, [], ""
45
 
46
  print(f"[LOG] Début de la transcription de {audio_path}...")
47
  result = pipe(audio_path, return_timestamps="word")
@@ -49,7 +42,7 @@ def transcribe_audio(audio_path):
49
 
50
  if not words:
51
  print("[LOG ERROR] Erreur : Aucun timestamp détecté.")
52
- return "Erreur : Aucun timestamp détecté.", [], None, [], ""
53
 
54
  raw_transcription = " ".join([w["text"] for w in words])
55
  word_timestamps = [(w["text"], w["timestamp"][0]) for w in words]
@@ -61,39 +54,31 @@ def transcribe_audio(audio_path):
61
  return raw_transcription, [], audio_path, word_timestamps, transcription_with_timestamps
62
 
63
  # -------------------------------------------------
64
- # 3. Prétraitement des segments : Associer les timestamps aux phrases sélectionnées
65
  # -------------------------------------------------
66
- def preprocess_segments(table_data, word_timestamps):
67
- print("[LOG] Début du prétraitement des segments...")
68
  formatted_data = []
69
  for i, row in enumerate(table_data):
70
- if not row or len(row) < 1 or not row[0].strip():
71
- print(f"[LOG WARNING] Ignoré : ligne vide à l'index {i}.")
72
  continue
73
 
74
- text = row[0].strip()
75
  segment_id = f"seg_{i+1:02d}"
76
- start_time = None
77
- end_time = None
78
-
79
- for j, (word, start) in enumerate(word_timestamps):
80
- if word in text.split():
81
- if start_time is None:
82
- start_time = start
83
- end_time = word_timestamps[j+1][1] - 0.01 if j+1 < len(word_timestamps) else start + 0.5
84
-
85
- formatted_data.append([text, start_time, end_time, segment_id])
86
- print(f"[LOG] Segment ajouté : {text} | Début: {start_time}, Fin: {end_time}, ID: {segment_id}")
87
 
88
  return formatted_data
89
 
90
  # -------------------------------------------------
91
  # 4. Validation et découpage des extraits audio
92
  # -------------------------------------------------
93
- def validate_segments(audio_path, table_data, metadata_state, word_timestamps):
94
  print("[LOG] Début de la validation des segments...")
95
- if not audio_path or not word_timestamps:
96
- print("[LOG ERROR] Erreur : Aucun timestamp valide trouvé !")
97
  return [], metadata_state
98
 
99
  if os.path.exists(TEMP_DIR):
@@ -104,27 +89,18 @@ def validate_segments(audio_path, table_data, metadata_state, word_timestamps):
104
  segment_paths = []
105
  updated_metadata = []
106
 
107
- for row in table_data:
108
- if len(row) < 4:
109
- print(f"[LOG ERROR] Données incorrectes pour la validation : {row}")
110
- continue
111
- text, start_time, end_time, segment_id = row
112
-
113
- if start_time is None or end_time is None:
114
- print(f"[LOG ERROR] Timestamp manquant pour : {text}")
115
- continue
116
-
117
- start_ms, end_ms = int(float(start_time) * 1000), int(float(end_time) * 1000)
118
  if start_ms < 0 or end_ms <= start_ms:
119
  print(f"[LOG ERROR] Problème de découpage : {text} | {start_time}s - {end_time}s")
120
  continue
121
 
122
  segment_filename = f"{Path(audio_path).stem}_{segment_id}.wav"
123
  segment_path = os.path.join(TEMP_DIR, segment_filename)
124
-
125
  extract = original_audio[start_ms:end_ms]
126
  extract.export(segment_path, format="wav")
127
-
128
  segment_paths.append(segment_path)
129
  updated_metadata.append({
130
  "audio_file": segment_filename,
@@ -136,6 +112,7 @@ def validate_segments(audio_path, table_data, metadata_state, word_timestamps):
136
  print(f"[LOG] Extrait généré : {segment_filename}")
137
 
138
  return segment_paths, updated_metadata
 
139
  # -------------------------------------------------
140
  # 5. Génération du fichier ZIP
141
  # -------------------------------------------------
@@ -163,6 +140,7 @@ def generate_zip(metadata_state):
163
 
164
  print("[LOG] Fichier ZIP généré avec succès.")
165
  return zip_path
 
166
  # -------------------------------------------------
167
  # 6. Interface utilisateur Gradio
168
  # -------------------------------------------------
@@ -174,16 +152,16 @@ with gr.Blocks() as demo:
174
  audio_input = gr.Audio(type="filepath", label="Fichier audio")
175
  raw_transcription = gr.Textbox(label="Transcription", interactive=False)
176
  transcription_timestamps = gr.Textbox(label="Transcription avec Timestamps", interactive=False)
177
- table = gr.Dataframe(headers=["Texte"], datatype=["str"], row_count=(1, "dynamic"), col_count=1)
178
- generate_timestamps_button = gr.Button("Générer les timestamps")
179
  validate_button = gr.Button("Valider")
180
  generate_button = gr.Button("Générer ZIP")
181
  zip_file = gr.File(label="Télécharger le ZIP")
182
  word_timestamps = gr.State()
183
 
184
  audio_input.change(transcribe_audio, inputs=audio_input, outputs=[raw_transcription, table, audio_input, word_timestamps, transcription_timestamps])
185
- generate_timestamps_button.click(preprocess_segments, inputs=[table, word_timestamps], outputs=table)
186
- validate_button.click(validate_segments, inputs=[audio_input, table, metadata_state, word_timestamps], outputs=[extracted_segments, metadata_state])
187
  generate_button.click(generate_zip, inputs=metadata_state, outputs=zip_file)
188
 
189
  demo.queue().launch()
 
 
 
 
 
 
 
1
  import os
2
  import shutil
3
  import zipfile
4
  import torch
 
 
5
  import gradio as gr
6
+ from pathlib import Path
7
  from pydub import AudioSegment
8
  from transformers import pipeline
9
 
 
34
  def transcribe_audio(audio_path):
35
  if not audio_path:
36
  print("[LOG] Aucun fichier audio fourni.")
37
+ return "Aucun fichier audio fourni", [], None, []
38
 
39
  print(f"[LOG] Début de la transcription de {audio_path}...")
40
  result = pipe(audio_path, return_timestamps="word")
 
42
 
43
  if not words:
44
  print("[LOG ERROR] Erreur : Aucun timestamp détecté.")
45
+ return "Erreur : Aucun timestamp détecté.", [], None, []
46
 
47
  raw_transcription = " ".join([w["text"] for w in words])
48
  word_timestamps = [(w["text"], w["timestamp"][0]) for w in words]
 
54
  return raw_transcription, [], audio_path, word_timestamps, transcription_with_timestamps
55
 
56
  # -------------------------------------------------
57
+ # 3. Enregistrement des segments définis par l'utilisateur
58
  # -------------------------------------------------
59
+ def save_segments(table_data):
60
+ print("[LOG] Enregistrement des segments définis par l'utilisateur...")
61
  formatted_data = []
62
  for i, row in enumerate(table_data):
63
+ if len(row) < 3 or not row[0].strip():
64
+ print(f"[LOG WARNING] Ligne vide ignorée à l'index {i}.")
65
  continue
66
 
67
+ text, start_time, end_time = row[0].strip(), row[1], row[2]
68
  segment_id = f"seg_{i+1:02d}"
69
+
70
+ formatted_data.append([text, float(start_time), float(end_time), segment_id])
71
+ print(f"[LOG] Segment enregistré : {text} | Début: {start_time}, Fin: {end_time}, ID: {segment_id}")
 
 
 
 
 
 
 
 
72
 
73
  return formatted_data
74
 
75
  # -------------------------------------------------
76
  # 4. Validation et découpage des extraits audio
77
  # -------------------------------------------------
78
+ def validate_segments(audio_path, table_data, metadata_state):
79
  print("[LOG] Début de la validation des segments...")
80
+ if not audio_path:
81
+ print("[LOG ERROR] Erreur : Aucun fichier audio fourni !")
82
  return [], metadata_state
83
 
84
  if os.path.exists(TEMP_DIR):
 
89
  segment_paths = []
90
  updated_metadata = []
91
 
92
+ for text, start_time, end_time, segment_id in table_data:
93
+ start_ms, end_ms = int(start_time * 1000), int(end_time * 1000)
 
 
 
 
 
 
 
 
 
94
  if start_ms < 0 or end_ms <= start_ms:
95
  print(f"[LOG ERROR] Problème de découpage : {text} | {start_time}s - {end_time}s")
96
  continue
97
 
98
  segment_filename = f"{Path(audio_path).stem}_{segment_id}.wav"
99
  segment_path = os.path.join(TEMP_DIR, segment_filename)
100
+
101
  extract = original_audio[start_ms:end_ms]
102
  extract.export(segment_path, format="wav")
103
+
104
  segment_paths.append(segment_path)
105
  updated_metadata.append({
106
  "audio_file": segment_filename,
 
112
  print(f"[LOG] Extrait généré : {segment_filename}")
113
 
114
  return segment_paths, updated_metadata
115
+
116
  # -------------------------------------------------
117
  # 5. Génération du fichier ZIP
118
  # -------------------------------------------------
 
140
 
141
  print("[LOG] Fichier ZIP généré avec succès.")
142
  return zip_path
143
+
144
  # -------------------------------------------------
145
  # 6. Interface utilisateur Gradio
146
  # -------------------------------------------------
 
152
  audio_input = gr.Audio(type="filepath", label="Fichier audio")
153
  raw_transcription = gr.Textbox(label="Transcription", interactive=False)
154
  transcription_timestamps = gr.Textbox(label="Transcription avec Timestamps", interactive=False)
155
+ table = gr.Dataframe(headers=["Texte", "Début (s)", "Fin (s)"], datatype=["str", "number", "number"], row_count=(1, "dynamic"), col_count=3)
156
+ save_segments_button = gr.Button("Enregistrer les valeurs")
157
  validate_button = gr.Button("Valider")
158
  generate_button = gr.Button("Générer ZIP")
159
  zip_file = gr.File(label="Télécharger le ZIP")
160
  word_timestamps = gr.State()
161
 
162
  audio_input.change(transcribe_audio, inputs=audio_input, outputs=[raw_transcription, table, audio_input, word_timestamps, transcription_timestamps])
163
+ save_segments_button.click(save_segments, inputs=table, outputs=table)
164
+ validate_button.click(validate_segments, inputs=[audio_input, table, metadata_state], outputs=[extracted_segments, metadata_state])
165
  generate_button.click(generate_zip, inputs=metadata_state, outputs=zip_file)
166
 
167
  demo.queue().launch()