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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Script orchestrateur pour le traitement automatique des BOB (Hugging Face version)
|
| 4 |
+
1. Transcrit tous les fichiers audio du dossier input avec Whisper
|
| 5 |
+
2. Analyse toutes les transcriptions avec Hugging Face
|
| 6 |
+
3. Génère le fichier de résumé final
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import os
|
| 10 |
+
import sys
|
| 11 |
+
import subprocess
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
from datetime import datetime
|
| 14 |
+
import time
|
| 15 |
+
|
| 16 |
+
# Configuration
|
| 17 |
+
SCRIPT_DIR = Path(__file__).parent.absolute()
|
| 18 |
+
TRANSCRIBE_SCRIPT = SCRIPT_DIR / "transcribe_audio.py"
|
| 19 |
+
ANALYZE_SCRIPT = SCRIPT_DIR / "analyze_bob_hf.py" # Version HF
|
| 20 |
+
INPUT_DIR = SCRIPT_DIR.parent / "input"
|
| 21 |
+
OUTPUT_DIR = SCRIPT_DIR.parent / "output"
|
| 22 |
+
TRANSCRIPTIONS_DIR = OUTPUT_DIR / "transcriptions"
|
| 23 |
+
RESUME_FILE = OUTPUT_DIR / "resume_bob.txt"
|
| 24 |
+
|
| 25 |
+
def print_header():
|
| 26 |
+
"""Affiche l'en-tête du script"""
|
| 27 |
+
print("=" * 70)
|
| 28 |
+
print("🎙️ TRAITEMENT AUTOMATIQUE DES BOB (Hugging Face)")
|
| 29 |
+
print(" Transcription audio → Analyse IA → Résumé")
|
| 30 |
+
print("=" * 70)
|
| 31 |
+
print(f"Démarré le: {datetime.now().strftime('%d/%m/%Y à %H:%M:%S')}")
|
| 32 |
+
print()
|
| 33 |
+
|
| 34 |
+
def check_prerequisites():
|
| 35 |
+
"""Vérifie que tous les prérequis sont en place"""
|
| 36 |
+
print("🔍 Vérification des prérequis...")
|
| 37 |
+
|
| 38 |
+
# Vérifier les dossiers
|
| 39 |
+
if not INPUT_DIR.exists():
|
| 40 |
+
print(f"❌ Le dossier input n'existe pas: {INPUT_DIR}")
|
| 41 |
+
return False
|
| 42 |
+
|
| 43 |
+
if not TRANSCRIBE_SCRIPT.exists():
|
| 44 |
+
print(f"❌ Script de transcription introuvable: {TRANSCRIBE_SCRIPT}")
|
| 45 |
+
return False
|
| 46 |
+
|
| 47 |
+
if not ANALYZE_SCRIPT.exists():
|
| 48 |
+
print(f"❌ Script d'analyse introuvable: {ANALYZE_SCRIPT}")
|
| 49 |
+
return False
|
| 50 |
+
|
| 51 |
+
# Compter les fichiers audio
|
| 52 |
+
audio_extensions = ['.mp3', '.wav', '.m4a', '.flac', '.ogg', '.mp4', '.avi', '.mov']
|
| 53 |
+
audio_files = []
|
| 54 |
+
for ext in audio_extensions:
|
| 55 |
+
audio_files.extend(INPUT_DIR.glob(f"*{ext}"))
|
| 56 |
+
audio_files.extend(INPUT_DIR.glob(f"*{ext.upper()}"))
|
| 57 |
+
|
| 58 |
+
if not audio_files:
|
| 59 |
+
print(f"⚠️ Aucun fichier audio trouvé dans {INPUT_DIR}")
|
| 60 |
+
print(f" Formats supportés: {', '.join(audio_extensions)}")
|
| 61 |
+
return False
|
| 62 |
+
|
| 63 |
+
print(f"✅ Trouvé {len(audio_files)} fichier(s) audio à traiter:")
|
| 64 |
+
for i, file in enumerate(sorted(set(audio_files)), 1):
|
| 65 |
+
print(f" {i}. {file.name}")
|
| 66 |
+
|
| 67 |
+
print("✅ Scripts de traitement trouvés")
|
| 68 |
+
print("✅ Prérequis validés")
|
| 69 |
+
print()
|
| 70 |
+
return True
|
| 71 |
+
|
| 72 |
+
def run_script(script_path, step_name, python_executable=None):
|
| 73 |
+
"""Exécute un script Python et retourne le succès"""
|
| 74 |
+
if python_executable is None:
|
| 75 |
+
python_executable = sys.executable
|
| 76 |
+
|
| 77 |
+
print(f"🚀 Étape {step_name}...")
|
| 78 |
+
print(f" Exécution: {script_path.name}")
|
| 79 |
+
|
| 80 |
+
start_time = time.time()
|
| 81 |
+
|
| 82 |
+
try:
|
| 83 |
+
# Exécuter le script
|
| 84 |
+
result = subprocess.run(
|
| 85 |
+
[python_executable, str(script_path)],
|
| 86 |
+
cwd=str(script_path.parent),
|
| 87 |
+
capture_output=True,
|
| 88 |
+
text=True,
|
| 89 |
+
encoding='utf-8',
|
| 90 |
+
errors='replace'
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
end_time = time.time()
|
| 94 |
+
duration = end_time - start_time
|
| 95 |
+
|
| 96 |
+
if result.returncode == 0:
|
| 97 |
+
print(f"✅ {step_name} terminée avec succès")
|
| 98 |
+
print(f" Durée: {duration:.1f} secondes")
|
| 99 |
+
|
| 100 |
+
# Afficher les dernières lignes importantes de la sortie
|
| 101 |
+
output_lines = result.stdout.strip().split('\n')
|
| 102 |
+
if output_lines:
|
| 103 |
+
print(" Résultat:")
|
| 104 |
+
for line in output_lines[-3:]: # Dernières 3 lignes
|
| 105 |
+
if line.strip():
|
| 106 |
+
print(f" > {line.strip()}")
|
| 107 |
+
print()
|
| 108 |
+
return True
|
| 109 |
+
else:
|
| 110 |
+
print(f"❌ {step_name} a échoué")
|
| 111 |
+
print(f" Code d'erreur: {result.returncode}")
|
| 112 |
+
if result.stderr:
|
| 113 |
+
print(f" Erreur: {result.stderr.strip()}")
|
| 114 |
+
if result.stdout:
|
| 115 |
+
print(f" Sortie: {result.stdout.strip()}")
|
| 116 |
+
print()
|
| 117 |
+
return False
|
| 118 |
+
|
| 119 |
+
except Exception as e:
|
| 120 |
+
end_time = time.time()
|
| 121 |
+
duration = end_time - start_time
|
| 122 |
+
print(f"❌ Erreur lors de l'exécution de {step_name}")
|
| 123 |
+
print(f" Exception: {e}")
|
| 124 |
+
print(f" Durée avant erreur: {duration:.1f} secondes")
|
| 125 |
+
print()
|
| 126 |
+
return False
|
| 127 |
+
|
| 128 |
+
def check_results():
|
| 129 |
+
"""Vérifie et affiche les résultats finaux"""
|
| 130 |
+
print("📊 Vérification des résultats...")
|
| 131 |
+
|
| 132 |
+
# Vérifier les transcriptions
|
| 133 |
+
if TRANSCRIPTIONS_DIR.exists():
|
| 134 |
+
transcription_files = list(TRANSCRIPTIONS_DIR.glob("*_transcription.txt"))
|
| 135 |
+
print(f"✅ {len(transcription_files)} transcription(s) générée(s)")
|
| 136 |
+
|
| 137 |
+
for file in transcription_files:
|
| 138 |
+
size_kb = file.stat().st_size / 1024
|
| 139 |
+
print(f" • {file.name} ({size_kb:.1f} KB)")
|
| 140 |
+
else:
|
| 141 |
+
print("❌ Dossier de transcriptions non trouvé")
|
| 142 |
+
return False
|
| 143 |
+
|
| 144 |
+
# Vérifier le résumé final
|
| 145 |
+
if RESUME_FILE.exists():
|
| 146 |
+
print(f"✅ Fichier de résumé généré: {RESUME_FILE.name}")
|
| 147 |
+
|
| 148 |
+
# Afficher le contenu du résumé
|
| 149 |
+
try:
|
| 150 |
+
with open(RESUME_FILE, 'r', encoding='utf-8') as f:
|
| 151 |
+
content = f.read().strip()
|
| 152 |
+
|
| 153 |
+
print("📝 Contenu du résumé:")
|
| 154 |
+
print("-" * 50)
|
| 155 |
+
|
| 156 |
+
lines = content.split('\n')
|
| 157 |
+
for line in lines:
|
| 158 |
+
if line.strip() and not line.startswith('#'):
|
| 159 |
+
print(f" {line}")
|
| 160 |
+
|
| 161 |
+
print("-" * 50)
|
| 162 |
+
except Exception as e:
|
| 163 |
+
print(f" Erreur lors de la lecture: {e}")
|
| 164 |
+
|
| 165 |
+
return True
|
| 166 |
+
else:
|
| 167 |
+
print("❌ Fichier de résumé non généré")
|
| 168 |
+
return False
|
| 169 |
+
|
| 170 |
+
def main():
|
| 171 |
+
"""Fonction principale"""
|
| 172 |
+
start_total = time.time()
|
| 173 |
+
|
| 174 |
+
print_header()
|
| 175 |
+
|
| 176 |
+
# Vérification des prérequis
|
| 177 |
+
if not check_prerequisites():
|
| 178 |
+
print("❌ Impossible de continuer sans les prérequis")
|
| 179 |
+
return 1
|
| 180 |
+
|
| 181 |
+
# Confirmation utilisateur
|
| 182 |
+
print("👀 Prêt à démarrer le traitement automatique des BOB")
|
| 183 |
+
response = input(" Continuer ? (o/N): ").lower().strip()
|
| 184 |
+
if response not in ['o', 'oui', 'y', 'yes']:
|
| 185 |
+
print("🚫 Traitement annulé par l'utilisateur")
|
| 186 |
+
return 0
|
| 187 |
+
|
| 188 |
+
print()
|
| 189 |
+
|
| 190 |
+
# Déterminer l'exécutable Python
|
| 191 |
+
python_exe = sys.executable
|
| 192 |
+
print(f"🐍 Utilisation de Python: {python_exe}")
|
| 193 |
+
print()
|
| 194 |
+
|
| 195 |
+
# Étape 1: Transcription
|
| 196 |
+
success_transcription = run_script(
|
| 197 |
+
TRANSCRIBE_SCRIPT,
|
| 198 |
+
"1/2 - Transcription audio (Whisper)",
|
| 199 |
+
python_exe
|
| 200 |
+
)
|
| 201 |
+
|
| 202 |
+
if not success_transcription:
|
| 203 |
+
print("❌ Échec de la transcription. Arrêt du traitement.")
|
| 204 |
+
return 1
|
| 205 |
+
|
| 206 |
+
# Étape 2: Analyse avec Hugging Face
|
| 207 |
+
success_analysis = run_script(
|
| 208 |
+
ANALYZE_SCRIPT,
|
| 209 |
+
"2/2 - Analyse des transcriptions (Hugging Face)",
|
| 210 |
+
python_exe
|
| 211 |
+
)
|
| 212 |
+
|
| 213 |
+
if not success_analysis:
|
| 214 |
+
print("❌ Échec de l'analyse. Vérifiez que les modèles Hugging Face sont accessibles.")
|
| 215 |
+
return 1
|
| 216 |
+
|
| 217 |
+
# Vérification des résultats
|
| 218 |
+
print()
|
| 219 |
+
results_ok = check_results()
|
| 220 |
+
|
| 221 |
+
# Résumé final
|
| 222 |
+
end_total = time.time()
|
| 223 |
+
total_duration = end_total - start_total
|
| 224 |
+
|
| 225 |
+
print()
|
| 226 |
+
print("=" * 70)
|
| 227 |
+
if results_ok:
|
| 228 |
+
print("🎉 TRAITEMENT TERMINÉ AVEC SUCCÈS")
|
| 229 |
+
print(f"⏱️ Durée totale: {total_duration:.1f} secondes ({total_duration/60:.1f} minutes)")
|
| 230 |
+
print(f"📁 Fichier de résumé: {RESUME_FILE}")
|
| 231 |
+
print("✅ Tous vos BOB ont été traités automatiquement !")
|
| 232 |
+
else:
|
| 233 |
+
print("⚠️ TRAITEMENT PARTIELLEMENT RÉUSSI")
|
| 234 |
+
print(f"⏱️ Durée totale: {total_duration:.1f} secondes")
|
| 235 |
+
print("🔍 Vérifiez les fichiers de sortie manuellement")
|
| 236 |
+
print("=" * 70)
|
| 237 |
+
|
| 238 |
+
return 0 if results_ok else 1
|
| 239 |
+
|
| 240 |
+
if __name__ == "__main__":
|
| 241 |
+
try:
|
| 242 |
+
exit_code = main()
|
| 243 |
+
sys.exit(exit_code)
|
| 244 |
+
except KeyboardInterrupt:
|
| 245 |
+
print("\n🚫 Traitement interrompu par l'utilisateur")
|
| 246 |
+
sys.exit(1)
|
| 247 |
+
except Exception as e:
|
| 248 |
+
print(f"\n💥 Erreur inattendue: {e}")
|
| 249 |
+
sys.exit(1)
|