Woziii commited on
Commit
7b676ff
·
verified ·
1 Parent(s): e53e60d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +61 -37
app.py CHANGED
@@ -1,6 +1,6 @@
1
  import os
2
- import spaces
3
  import re
 
4
  import shutil
5
  import zipfile
6
  import torch
@@ -41,8 +41,6 @@ def correct_typography(text):
41
  corrected_text = re.sub(r"([?!:;])(?=\w)", r"\1 ", corrected_text) # Ajout d'un espace après !, ?, : et ; si nécessaire
42
  corrected_text = re.sub(r"(?<!\d) (\.)", r"\1", corrected_text) # Suppression de l'espace avant un point
43
  corrected_text = re.sub(r"(\.) (?=\w)", r". \2", corrected_text) # Ajout d'un espace après un point si nécessaire
44
-
45
- # Appliquer la correction uniquement si le texte a changé
46
  return corrected_text.strip() if corrected_text != text else text
47
 
48
  # -------------------------------------------------
@@ -50,11 +48,10 @@ def correct_typography(text):
50
  # -------------------------------------------------
51
  @spaces.GPU(duration=120)
52
  def transcribe_audio(audio_path):
53
- import os
54
  if not audio_path:
55
  return "Aucun fichier audio fourni", None, [], "", ""
56
 
57
- file_name = os.path.basename(audio_path).rsplit('.', 1)[0] # Extraire le nom sans extension
58
 
59
  result = pipe(audio_path, return_timestamps="word")
60
  words = result.get("chunks", [])
@@ -67,39 +64,76 @@ def transcribe_audio(audio_path):
67
  transcription_with_timestamps = " ".join([f"{w[0]}[{w[1]:.2f}-{w[2]:.2f}]" for w in word_timestamps])
68
 
69
  return raw_transcription, word_timestamps, transcription_with_timestamps, audio_path, file_name
70
- if not audio_path:
71
- return "Aucun fichier audio fourni", None, [], ""
72
-
73
- result = pipe(audio_path, return_timestamps="word")
74
- words = result.get("chunks", [])
75
-
76
- if not words:
77
- return "Erreur : Aucun timestamp détecté.", None, [], ""
78
-
79
- raw_transcription = " ".join([w["text"] for w in words])
80
- word_timestamps = [(w["text"], w["timestamp"][0], w["timestamp"][1]) for w in words]
81
- transcription_with_timestamps = " ".join([f"{w[0]}[{w[1]:.2f}-{w[2]:.2f}]" for w in word_timestamps])
82
-
83
- return raw_transcription, word_timestamps, transcription_with_timestamps, audio_path
84
 
85
  # -------------------------------------------------
86
  # 3. Enregistrement des segments définis par l'utilisateur
87
  # -------------------------------------------------
88
- def save_segments(table_data):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89
  formatted_data = []
90
  for i, row in table_data.iterrows():
91
  formatted_data.append([row["Texte"], float(row["Début (s)"]), float(row["Fin (s)"])] )
92
- return pd.DataFrame(formatted_data, columns=["Texte", "Début (s)", "Fin (s)"])
93
 
94
  # -------------------------------------------------
95
  # 4. Génération du fichier ZIP avec correction typographique
96
  # -------------------------------------------------
97
  def generate_zip(metadata_state, audio_path, zip_name):
 
 
 
98
  if metadata_state is None or metadata_state.empty:
 
99
  return None
100
 
101
- if not zip_name.strip():
102
- zip_name = "processed_audio"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103
 
104
  zip_folder_name = f"{zip_name}_dataset"
105
  zip_path = os.path.join(TEMP_DIR, f"{zip_folder_name}.zip")
@@ -112,15 +146,6 @@ def generate_zip(metadata_state, audio_path, zip_name):
112
 
113
  with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf:
114
  zf.write(metadata_csv_path, "metadata.csv")
115
- original_audio = AudioSegment.from_file(audio_path)
116
-
117
- for i, row in metadata_state.iterrows():
118
- start_ms, end_ms = int(row["Début (s)"] * 1000), int(row["Fin (s)"] * 1000)
119
- segment_audio = original_audio[start_ms:end_ms]
120
- segment_filename = f"{zip_name}_seg_{i+1:02d}.wav"
121
- segment_path = os.path.join(TEMP_DIR, segment_filename)
122
- segment_audio.export(segment_path, format="wav")
123
- zf.write(segment_path, segment_filename)
124
 
125
  return zip_path
126
 
@@ -131,17 +156,16 @@ with gr.Blocks() as demo:
131
  gr.Markdown("# Application de Découpe Audio")
132
  metadata_state = gr.State(init_metadata_state())
133
  audio_input = gr.Audio(type="filepath", label="Fichier audio")
134
- zip_name = gr.Textbox(label="Nom du fichier ZIP", placeholder="Nom personnalisé", interactive=True)
135
  raw_transcription = gr.Textbox(label="Transcription", interactive=True)
136
  transcription_timestamps = gr.Textbox(label="Transcription avec Timestamps", interactive=True)
137
- table = gr.Dataframe(headers=["Texte", "Début (s)", "Fin (s)"], datatype=["str", "str", "str"], row_count=(5, "dynamic"))
138
  save_button = gr.Button("Enregistrer les segments")
139
  generate_button = gr.Button("Générer ZIP")
140
  zip_file = gr.File(label="Télécharger le ZIP")
141
- word_timestamps = gr.State()
142
 
143
- audio_input.change(transcribe_audio, inputs=audio_input, outputs=[raw_transcription, word_timestamps, transcription_timestamps, audio_input, zip_name])
144
- save_button.click(save_segments, inputs=table, outputs=[metadata_state, zip_name])
145
  generate_button.click(generate_zip, inputs=[metadata_state, audio_input, zip_name], outputs=zip_file)
146
 
147
  demo.queue().launch()
 
1
  import os
 
2
  import re
3
+ import spaces
4
  import shutil
5
  import zipfile
6
  import torch
 
41
  corrected_text = re.sub(r"([?!:;])(?=\w)", r"\1 ", corrected_text) # Ajout d'un espace après !, ?, : et ; si nécessaire
42
  corrected_text = re.sub(r"(?<!\d) (\.)", r"\1", corrected_text) # Suppression de l'espace avant un point
43
  corrected_text = re.sub(r"(\.) (?=\w)", r". \2", corrected_text) # Ajout d'un espace après un point si nécessaire
 
 
44
  return corrected_text.strip() if corrected_text != text else text
45
 
46
  # -------------------------------------------------
 
48
  # -------------------------------------------------
49
  @spaces.GPU(duration=120)
50
  def transcribe_audio(audio_path):
 
51
  if not audio_path:
52
  return "Aucun fichier audio fourni", None, [], "", ""
53
 
54
+ file_name = os.path.basename(audio_path).rsplit('.', 1)[0] # Extraction du nom sans extension
55
 
56
  result = pipe(audio_path, return_timestamps="word")
57
  words = result.get("chunks", [])
 
64
  transcription_with_timestamps = " ".join([f"{w[0]}[{w[1]:.2f}-{w[2]:.2f}]" for w in word_timestamps])
65
 
66
  return raw_transcription, word_timestamps, transcription_with_timestamps, audio_path, file_name
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
 
68
  # -------------------------------------------------
69
  # 3. Enregistrement des segments définis par l'utilisateur
70
  # -------------------------------------------------
71
+ def save_segments(table_data, zip_name):
72
+ print("[LOG] Enregistrement des segments définis par l'utilisateur...")
73
+ formatted_data = []
74
+ confirmation_message = "**📌 Segments enregistrés :**
75
+ "
76
+
77
+ for i, row in table_data.iterrows():
78
+ text, start_time, end_time = row["Texte"], row["Début (s)"], row["Fin (s)"]
79
+ segment_id = f"{zip_name}_seg_{i+1:02d}"
80
+
81
+ try:
82
+ start_time = str(start_time).replace(",", ".")
83
+ end_time = str(end_time).replace(",", ".")
84
+
85
+ if not start_time.replace(".", "").isdigit() or not end_time.replace(".", "").isdigit():
86
+ raise ValueError("Valeurs de timestamps invalides")
87
+
88
+ start_time = float(start_time)
89
+ end_time = float(end_time)
90
+
91
+ if start_time < 0 or end_time <= start_time:
92
+ raise ValueError("Valeurs incohérentes")
93
+
94
+ formatted_data.append([text, start_time, end_time, segment_id])
95
+ log_message = f"- `{segment_id}` | **Texte** : {text} | ⏱ **{start_time:.2f}s - {end_time:.2f}s**"
96
+ confirmation_message += log_message + "
97
+ "
98
+ print(f"[LOG] {log_message}")
99
+
100
+ except ValueError as e:
101
+ print(f"[LOG ERROR] Erreur de conversion des timestamps : {e}")
102
+ return pd.DataFrame(), "❌ **Erreur** : Vérifiez que les valeurs sont bien des nombres valides."
103
+
104
+ return pd.DataFrame(formatted_data, columns=["Texte", "Début (s)", "Fin (s)", "ID"]), confirmation_message, zip_name
105
  formatted_data = []
106
  for i, row in table_data.iterrows():
107
  formatted_data.append([row["Texte"], float(row["Début (s)"]), float(row["Fin (s)"])] )
108
+ return pd.DataFrame(formatted_data, columns=["Texte", "Début (s)", "Fin (s)"]), zip_name
109
 
110
  # -------------------------------------------------
111
  # 4. Génération du fichier ZIP avec correction typographique
112
  # -------------------------------------------------
113
  def generate_zip(metadata_state, audio_path, zip_name):
114
+ if isinstance(metadata_state, tuple):
115
+ metadata_state = metadata_state[0]
116
+
117
  if metadata_state is None or metadata_state.empty:
118
+ print("[LOG ERROR] Aucun segment valide trouvé pour la génération du ZIP.")
119
  return None
120
 
121
+ zip_folder_name = f"{zip_name}_dataset"
122
+ zip_path = os.path.join(TEMP_DIR, f"{zip_folder_name}.zip")
123
+ metadata_csv_path = os.path.join(TEMP_DIR, "metadata.csv")
124
+
125
+ metadata_state["ID"] = [f"{zip_name}_seg_{i+1:02d}" for i in range(len(metadata_state))]
126
+ metadata_state["Texte"] = metadata_state["Texte"].apply(correct_typography)
127
+ metadata_state["Commentaires"] = ""
128
+ metadata_state.to_csv(metadata_csv_path, sep="|", index=False)
129
+
130
+ with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf:
131
+ zf.write(metadata_csv_path, "metadata.csv")
132
+
133
+ print("[LOG] Fichier ZIP généré avec succès.")
134
+ return zip_path
135
+ if metadata_state is None or metadata_state.empty:
136
+ return None
137
 
138
  zip_folder_name = f"{zip_name}_dataset"
139
  zip_path = os.path.join(TEMP_DIR, f"{zip_folder_name}.zip")
 
146
 
147
  with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf:
148
  zf.write(metadata_csv_path, "metadata.csv")
 
 
 
 
 
 
 
 
 
149
 
150
  return zip_path
151
 
 
156
  gr.Markdown("# Application de Découpe Audio")
157
  metadata_state = gr.State(init_metadata_state())
158
  audio_input = gr.Audio(type="filepath", label="Fichier audio")
159
+ zip_name = gr.Textbox(label="Nom du fichier ZIP", interactive=True)
160
  raw_transcription = gr.Textbox(label="Transcription", interactive=True)
161
  transcription_timestamps = gr.Textbox(label="Transcription avec Timestamps", interactive=True)
162
+ table = gr.Dataframe(headers=["Texte", "Début (s)", "Fin (s)"], datatype=["str", "str", "str"], row_count=(1, "dynamic"))
163
  save_button = gr.Button("Enregistrer les segments")
164
  generate_button = gr.Button("Générer ZIP")
165
  zip_file = gr.File(label="Télécharger le ZIP")
 
166
 
167
+ audio_input.change(transcribe_audio, inputs=audio_input, outputs=[raw_transcription, transcription_timestamps, audio_input, zip_name])
168
+ save_button.click(save_segments, inputs=[table, zip_name], outputs=[metadata_state, zip_name])
169
  generate_button.click(generate_zip, inputs=[metadata_state, audio_input, zip_name], outputs=zip_file)
170
 
171
  demo.queue().launch()