Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -2,8 +2,10 @@ import os
|
|
| 2 |
import shutil
|
| 3 |
import zipfile
|
| 4 |
import torch
|
| 5 |
-
import
|
|
|
|
| 6 |
from pathlib import Path
|
|
|
|
| 7 |
from pydub import AudioSegment
|
| 8 |
from transformers import pipeline
|
| 9 |
|
|
@@ -34,7 +36,7 @@ def init_metadata_state():
|
|
| 34 |
def transcribe_audio(audio_path):
|
| 35 |
if not audio_path:
|
| 36 |
print("[LOG] Aucun fichier audio fourni.")
|
| 37 |
-
return "Aucun fichier audio fourni",
|
| 38 |
|
| 39 |
print(f"[LOG] Début de la transcription de {audio_path}...")
|
| 40 |
result = pipe(audio_path, return_timestamps="word")
|
|
@@ -42,16 +44,14 @@ def transcribe_audio(audio_path):
|
|
| 42 |
|
| 43 |
if not words:
|
| 44 |
print("[LOG ERROR] Erreur : Aucun timestamp détecté.")
|
| 45 |
-
return "Erreur : Aucun timestamp détecté.",
|
| 46 |
|
| 47 |
raw_transcription = " ".join([w["text"] for w in words])
|
| 48 |
word_timestamps = [(w["text"], w["timestamp"][0]) for w in words]
|
| 49 |
-
|
| 50 |
transcription_with_timestamps = " ".join([f"{w[0]}[{w[1]:.2f}]" for w in word_timestamps])
|
| 51 |
|
| 52 |
print(f"[LOG] Transcription brute : {raw_transcription}")
|
| 53 |
-
|
| 54 |
-
return raw_transcription, [], audio_path, word_timestamps, transcription_with_timestamps
|
| 55 |
|
| 56 |
# -------------------------------------------------
|
| 57 |
# 3. Enregistrement des segments définis par l'utilisateur
|
|
@@ -59,71 +59,38 @@ def transcribe_audio(audio_path):
|
|
| 59 |
def save_segments(table_data):
|
| 60 |
print("[LOG] Enregistrement des segments définis par l'utilisateur...")
|
| 61 |
formatted_data = []
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 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 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
start_time = float(start_time)
|
| 72 |
end_time = float(end_time)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
formatted_data.append([text, start_time, end_time, segment_id])
|
| 74 |
-
print(f"[LOG] Segment ajouté : {text} | Début: {start_time}, Fin: {end_time}, ID: {segment_id}")
|
|
|
|
| 75 |
except ValueError as e:
|
| 76 |
-
print(f"[LOG ERROR] Erreur de conversion
|
| 77 |
-
return
|
| 78 |
|
| 79 |
-
return formatted_data
|
| 80 |
|
| 81 |
# -------------------------------------------------
|
| 82 |
-
# 4.
|
| 83 |
# -------------------------------------------------
|
| 84 |
-
def
|
| 85 |
-
|
| 86 |
-
if not audio_path:
|
| 87 |
-
print("[LOG ERROR] Erreur : Aucun fichier audio fourni !")
|
| 88 |
-
return [], metadata_state
|
| 89 |
-
|
| 90 |
-
if os.path.exists(TEMP_DIR):
|
| 91 |
-
shutil.rmtree(TEMP_DIR)
|
| 92 |
-
os.makedirs(TEMP_DIR, exist_ok=True)
|
| 93 |
-
|
| 94 |
-
original_audio = AudioSegment.from_file(audio_path)
|
| 95 |
-
segment_paths = []
|
| 96 |
-
updated_metadata = []
|
| 97 |
-
|
| 98 |
-
for text, start_time, end_time, segment_id in table_data:
|
| 99 |
-
start_ms, end_ms = int(start_time * 1000), int(end_time * 1000)
|
| 100 |
-
if start_ms < 0 or end_ms <= start_ms:
|
| 101 |
-
print(f"[LOG ERROR] Problème de découpage : {text} | {start_time}s - {end_time}s")
|
| 102 |
-
continue
|
| 103 |
-
|
| 104 |
-
segment_filename = f"{Path(audio_path).stem}_{segment_id}.wav"
|
| 105 |
-
segment_path = os.path.join(TEMP_DIR, segment_filename)
|
| 106 |
-
|
| 107 |
-
extract = original_audio[start_ms:end_ms]
|
| 108 |
-
extract.export(segment_path, format="wav")
|
| 109 |
-
|
| 110 |
-
segment_paths.append(segment_path)
|
| 111 |
-
updated_metadata.append({
|
| 112 |
-
"audio_file": segment_filename,
|
| 113 |
-
"text": text,
|
| 114 |
-
"start_time": start_time,
|
| 115 |
-
"end_time": end_time,
|
| 116 |
-
"id": segment_id,
|
| 117 |
-
})
|
| 118 |
-
print(f"[LOG] Extrait généré : {segment_filename}")
|
| 119 |
-
|
| 120 |
-
return segment_paths, updated_metadata
|
| 121 |
-
|
| 122 |
-
# -------------------------------------------------
|
| 123 |
-
# 5. Génération du fichier ZIP
|
| 124 |
-
# -------------------------------------------------
|
| 125 |
-
def generate_zip(metadata_state):
|
| 126 |
-
if not metadata_state:
|
| 127 |
print("[LOG ERROR] Aucun segment valide trouvé pour la génération du ZIP.")
|
| 128 |
return None
|
| 129 |
|
|
@@ -132,42 +99,41 @@ def generate_zip(metadata_state):
|
|
| 132 |
os.remove(zip_path)
|
| 133 |
|
| 134 |
metadata_csv_path = os.path.join(TEMP_DIR, "metadata.csv")
|
| 135 |
-
|
| 136 |
-
f.write("audio_file|text|speaker_name|API\n")
|
| 137 |
-
for seg in metadata_state:
|
| 138 |
-
f.write(f"{seg['audio_file']}|{seg['text']}|projectname|/API_PHONETIC/\n")
|
| 139 |
|
| 140 |
with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf:
|
| 141 |
zf.write(metadata_csv_path, "metadata.csv")
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 146 |
|
| 147 |
print("[LOG] Fichier ZIP généré avec succès.")
|
| 148 |
return zip_path
|
| 149 |
|
| 150 |
# -------------------------------------------------
|
| 151 |
-
#
|
| 152 |
# -------------------------------------------------
|
| 153 |
with gr.Blocks() as demo:
|
| 154 |
gr.Markdown("# Application de Découpe Audio")
|
| 155 |
metadata_state = gr.State(init_metadata_state())
|
| 156 |
-
|
| 157 |
-
|
| 158 |
audio_input = gr.Audio(type="filepath", label="Fichier audio")
|
| 159 |
raw_transcription = gr.Textbox(label="Transcription", interactive=False)
|
| 160 |
transcription_timestamps = gr.Textbox(label="Transcription avec Timestamps", interactive=False)
|
| 161 |
-
table = gr.Dataframe(headers=["Texte", "Début (s)", "Fin (s)"], datatype=["str", "
|
| 162 |
-
|
| 163 |
-
validate_button = gr.Button("Valider")
|
| 164 |
generate_button = gr.Button("Générer ZIP")
|
| 165 |
zip_file = gr.File(label="Télécharger le ZIP")
|
| 166 |
word_timestamps = gr.State()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 167 |
|
| 168 |
-
|
| 169 |
-
save_segments_button.click(save_segments, inputs=table, outputs=table)
|
| 170 |
-
validate_button.click(validate_segments, inputs=[audio_input, table, metadata_state], outputs=[extracted_segments, metadata_state])
|
| 171 |
-
generate_button.click(generate_zip, inputs=metadata_state, outputs=zip_file)
|
| 172 |
-
|
| 173 |
-
demo.queue().launch()
|
|
|
|
| 2 |
import shutil
|
| 3 |
import zipfile
|
| 4 |
import torch
|
| 5 |
+
import numpy as np
|
| 6 |
+
import pandas as pd
|
| 7 |
from pathlib import Path
|
| 8 |
+
import gradio as gr
|
| 9 |
from pydub import AudioSegment
|
| 10 |
from transformers import pipeline
|
| 11 |
|
|
|
|
| 36 |
def transcribe_audio(audio_path):
|
| 37 |
if not audio_path:
|
| 38 |
print("[LOG] Aucun fichier audio fourni.")
|
| 39 |
+
return "Aucun fichier audio fourni", None, [], ""
|
| 40 |
|
| 41 |
print(f"[LOG] Début de la transcription de {audio_path}...")
|
| 42 |
result = pipe(audio_path, return_timestamps="word")
|
|
|
|
| 44 |
|
| 45 |
if not words:
|
| 46 |
print("[LOG ERROR] Erreur : Aucun timestamp détecté.")
|
| 47 |
+
return "Erreur : Aucun timestamp détecté.", None, [], ""
|
| 48 |
|
| 49 |
raw_transcription = " ".join([w["text"] for w in words])
|
| 50 |
word_timestamps = [(w["text"], w["timestamp"][0]) for w in words]
|
|
|
|
| 51 |
transcription_with_timestamps = " ".join([f"{w[0]}[{w[1]:.2f}]" for w in word_timestamps])
|
| 52 |
|
| 53 |
print(f"[LOG] Transcription brute : {raw_transcription}")
|
| 54 |
+
return raw_transcription, word_timestamps, transcription_with_timestamps, audio_path
|
|
|
|
| 55 |
|
| 56 |
# -------------------------------------------------
|
| 57 |
# 3. Enregistrement des segments définis par l'utilisateur
|
|
|
|
| 59 |
def save_segments(table_data):
|
| 60 |
print("[LOG] Enregistrement des segments définis par l'utilisateur...")
|
| 61 |
formatted_data = []
|
| 62 |
+
|
| 63 |
+
for i, row in table_data.iterrows():
|
| 64 |
+
text, start_time, end_time = row["Texte"], row["Début (s)"], row["Fin (s)"]
|
|
|
|
|
|
|
|
|
|
| 65 |
segment_id = f"seg_{i+1:02d}"
|
| 66 |
+
|
| 67 |
try:
|
| 68 |
+
start_time = str(start_time).replace(",", ".")
|
| 69 |
+
end_time = str(end_time).replace(",", ".")
|
| 70 |
+
|
| 71 |
+
if not start_time.replace(".", "").isdigit() or not end_time.replace(".", "").isdigit():
|
| 72 |
+
raise ValueError("Valeurs de timestamps invalides")
|
| 73 |
+
|
| 74 |
start_time = float(start_time)
|
| 75 |
end_time = float(end_time)
|
| 76 |
+
|
| 77 |
+
if start_time < 0 or end_time <= start_time:
|
| 78 |
+
raise ValueError("Valeurs incohérentes")
|
| 79 |
+
|
| 80 |
formatted_data.append([text, start_time, end_time, segment_id])
|
| 81 |
+
print(f"[LOG] Segment ajouté : {text} | Début: {start_time:.2f}s, Fin: {end_time:.2f}s, ID: {segment_id}")
|
| 82 |
+
|
| 83 |
except ValueError as e:
|
| 84 |
+
print(f"[LOG ERROR] Erreur de conversion des timestamps : {e}")
|
| 85 |
+
return pd.DataFrame(), "Erreur : Vérifiez que les valeurs sont bien des nombres valides."
|
| 86 |
|
| 87 |
+
return pd.DataFrame(formatted_data, columns=["Texte", "Début (s)", "Fin (s)", "ID"]), ""
|
| 88 |
|
| 89 |
# -------------------------------------------------
|
| 90 |
+
# 4. Génération du fichier ZIP
|
| 91 |
# -------------------------------------------------
|
| 92 |
+
def generate_zip(metadata_state, audio_path):
|
| 93 |
+
if metadata_state.empty:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
print("[LOG ERROR] Aucun segment valide trouvé pour la génération du ZIP.")
|
| 95 |
return None
|
| 96 |
|
|
|
|
| 99 |
os.remove(zip_path)
|
| 100 |
|
| 101 |
metadata_csv_path = os.path.join(TEMP_DIR, "metadata.csv")
|
| 102 |
+
metadata_state.to_csv(metadata_csv_path, sep="|", index=False)
|
|
|
|
|
|
|
|
|
|
| 103 |
|
| 104 |
with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf:
|
| 105 |
zf.write(metadata_csv_path, "metadata.csv")
|
| 106 |
+
original_audio = AudioSegment.from_file(audio_path)
|
| 107 |
+
|
| 108 |
+
for _, row in metadata_state.iterrows():
|
| 109 |
+
start_ms, end_ms = int(row["Début (s)"] * 1000), int(row["Fin (s)"] * 1000)
|
| 110 |
+
segment_audio = original_audio[start_ms:end_ms]
|
| 111 |
+
segment_filename = f"{Path(audio_path).stem}_{row['ID']}.wav"
|
| 112 |
+
segment_path = os.path.join(TEMP_DIR, segment_filename)
|
| 113 |
+
segment_audio.export(segment_path, format="wav")
|
| 114 |
+
zf.write(segment_path, segment_filename)
|
| 115 |
|
| 116 |
print("[LOG] Fichier ZIP généré avec succès.")
|
| 117 |
return zip_path
|
| 118 |
|
| 119 |
# -------------------------------------------------
|
| 120 |
+
# 5. Interface utilisateur Gradio
|
| 121 |
# -------------------------------------------------
|
| 122 |
with gr.Blocks() as demo:
|
| 123 |
gr.Markdown("# Application de Découpe Audio")
|
| 124 |
metadata_state = gr.State(init_metadata_state())
|
| 125 |
+
|
|
|
|
| 126 |
audio_input = gr.Audio(type="filepath", label="Fichier audio")
|
| 127 |
raw_transcription = gr.Textbox(label="Transcription", interactive=False)
|
| 128 |
transcription_timestamps = gr.Textbox(label="Transcription avec Timestamps", interactive=False)
|
| 129 |
+
table = gr.Dataframe(headers=["Texte", "Début (s)", "Fin (s)"], datatype=["str", "str", "str"], row_count=(1, "dynamic"))
|
| 130 |
+
save_button = gr.Button("Enregistrer les segments")
|
|
|
|
| 131 |
generate_button = gr.Button("Générer ZIP")
|
| 132 |
zip_file = gr.File(label="Télécharger le ZIP")
|
| 133 |
word_timestamps = gr.State()
|
| 134 |
+
|
| 135 |
+
audio_input.change(transcribe_audio, inputs=audio_input, outputs=[raw_transcription, word_timestamps, transcription_timestamps, audio_input])
|
| 136 |
+
save_button.click(save_segments, inputs=table, outputs=[metadata_state])
|
| 137 |
+
generate_button.click(generate_zip, inputs=[metadata_state, audio_input], outputs=zip_file)
|
| 138 |
|
| 139 |
+
demo.queue().launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|