@@ -85,6 +85,68 @@ def import_required_modules():
8585 print (f"Impossibile importare i moduli anche dopo l'installazione: { e } " )
8686 sys .exit (1 )
8787
88+ def get_supported_audio_formats ():
89+ """
90+ Restituisce la lista dei formati audio supportati per la conversione.
91+ Returns:
92+ list: Lista delle estensioni supportate (senza punto)
93+ """
94+ return [
95+ 'wav' , 'mp3' , 'flac' , 'ogg' , 'm4a' , 'aac' ,
96+ 'wma' , 'opus' , 'aiff' , 'webm' , 'mp4'
97+ ]
98+
99+ def is_audio_format_supported (file_path ):
100+ """
101+ Verifica se il formato del file audio è supportato.
102+ Args:
103+ file_path: Percorso del file da verificare
104+ Returns:
105+ bool: True se il formato è supportato, False altrimenti
106+ """
107+ supported_formats = get_supported_audio_formats ()
108+ file_ext = os .path .splitext (file_path )[1 ][1 :].lower () # Rimuovi il punto e metti minuscolo
109+ return file_ext in supported_formats
110+
111+ def convert_audio_to_wav (input_path , output_path ):
112+ """
113+ Converte un file audio in formato WAV utilizzando FFmpeg.
114+ Args:
115+ input_path: Percorso del file audio da convertire
116+ output_path: Percorso del file WAV di destinazione
117+ Returns:
118+ bool: True se la conversione è riuscita, False altrimenti
119+ """
120+ try :
121+ # Comando FFmpeg per convertire in WAV mantenendo la qualità originale
122+ cmd = [
123+ 'ffmpeg' , '-y' , '-i' , input_path ,
124+ '-acodec' , 'pcm_s16le' , # Codec WAV standard
125+ '-ar' , '44100' , # Sample rate 44.1kHz
126+ '-ac' , '2' , # Canali stereo
127+ output_path
128+ ]
129+
130+ print (f" Conversione in corso: { os .path .basename (input_path )} → WAV" )
131+ result = subprocess .run (cmd , capture_output = True , text = True , timeout = 120 )
132+
133+ if result .returncode == 0 :
134+ print (f" Conversione completata: { os .path .basename (output_path )} " )
135+ return True
136+ else :
137+ print (f" Errore nella conversione: { result .stderr } " )
138+ return False
139+
140+ except subprocess .TimeoutExpired :
141+ print (" Timeout nella conversione audio" )
142+ return False
143+ except FileNotFoundError :
144+ print (" FFmpeg non trovato. Installa FFmpeg per la conversione audio" )
145+ return False
146+ except Exception as e :
147+ print (f" Errore durante la conversione: { e } " )
148+ return False
149+
88150def speed_up_audio (input_path , output_path , speed_factor = 2.0 ):
89151 """
90152 Accelera un file audio utilizzando FFmpeg.
@@ -282,14 +344,17 @@ def save_transcription(transcription, output_path):
282344 with open (output_path , 'w' , encoding = 'utf-8' ) as f :
283345 f .write (transcription )
284346
285- def count_wav_files (podcast_dir ):
347+ def count_supported_audio_files (podcast_dir ):
286348 """
287- Conta il numero totale di file .wav da elaborare.
349+ Conta il numero totale di file audio supportati da elaborare.
288350 """
289351 count = 0
352+ supported_formats = get_supported_audio_formats ()
353+
290354 for root , dirs , files in os .walk (podcast_dir ):
291355 for file_name in files :
292- if file_name .lower ().endswith ('.wav' ):
356+ file_ext = os .path .splitext (file_name )[1 ][1 :].lower ()
357+ if file_ext in supported_formats :
293358 base_name = os .path .splitext (file_name )[0 ]
294359 output_path = os .path .join (root , base_name + '.txt' )
295360 if not (os .path .exists (output_path ) and os .path .getsize (output_path ) > 1 ):
@@ -313,10 +378,11 @@ def main(podcast_dir, speed_up=False):
313378 whisper , tqdm = import_required_modules ()
314379
315380 # Conta i file da elaborare
316- total_files = count_wav_files (podcast_dir )
381+ total_files = count_supported_audio_files (podcast_dir )
317382
318383 if total_files == 0 :
319- print ("Nessun file .wav da elaborare trovato." )
384+ print ("Nessun file audio supportato da elaborare trovato." )
385+ print ("Formati supportati: WAV, MP3, FLAC, OGG, M4A, AAC, WMA, Opus, AIFF, WebM, MP4" )
320386 return
321387
322388 print (f"\n Trovati { total_files } file da trascrivere." )
@@ -330,52 +396,83 @@ def main(podcast_dir, speed_up=False):
330396 for file_name in files :
331397 file_path = os .path .join (root , file_name )
332398 base_name , ext = os .path .splitext (file_name )
333-
334- if ext .lower () == '.wav' :
335- output_file_name = base_name + '.txt'
336- output_path = os .path .join (root , output_file_name )
337-
338- # Verifica se la trascrizione esiste già
339- if os .path .exists (output_path ) and os .path .getsize (output_path ) > 1 :
340- continue
341-
342- try :
343- file_start_time = time .time ()
344-
345- # Aggiorna la descrizione con il file corrente
346- main_pbar .set_description (f"Elaborando: { file_name [:30 ]} ..." )
347-
348- transcription = transcribe_podcast_with_progress (file_path , speed_up = speed_up )
349- save_transcription (transcription , output_path )
350-
351- processed_files += 1
352- elapsed_total = time .time () - start_time
353- file_elapsed = time .time () - file_start_time
354-
355- # Calcola ETA
356- if processed_files > 0 :
357- avg_time_per_file = elapsed_total / processed_files
358- remaining_files = total_files - processed_files
359- eta_seconds = avg_time_per_file * remaining_files
360- eta_formatted = format_time (eta_seconds )
399+
400+ # Verifica se il formato è supportato
401+ if not is_audio_format_supported (file_path ):
402+ continue
403+
404+ output_file_name = base_name + '.txt'
405+ output_path = os .path .join (root , output_file_name )
406+
407+ # Verifica se la trascrizione esiste già
408+ if os .path .exists (output_path ) and os .path .getsize (output_path ) > 1 :
409+ continue
410+
411+ # File WAV da utilizzare per la trascrizione (originale o convertito)
412+ wav_file_path = None
413+ converted_file_path = None
414+
415+ try :
416+ file_start_time = time .time ()
417+
418+ # Aggiorna la descrizione con il file corrente
419+ main_pbar .set_description (f"Elaborando: { file_name [:30 ]} ..." )
420+
421+ # Se non è WAV, convertilo
422+ if ext .lower () != '.wav' :
423+ print (f" Conversione da { ext .upper ()[1 :]} a WAV richiesta..." )
424+ converted_file_path = os .path .join (root , base_name + '_converted.wav' )
425+ if convert_audio_to_wav (file_path , converted_file_path ):
426+ wav_file_path = converted_file_path
427+ print (f" Conversione completata: { file_name } " )
361428 else :
362- eta_formatted = "Calcolando..."
363-
364- # Aggiorna la barra di progresso
365- main_pbar .update (1 )
366- main_pbar .set_postfix ({
367- "File" : f"{ file_elapsed :.1f} s" ,
368- "ETA" : eta_formatted ,
369- "Totale" : format_time (elapsed_total )
370- })
371-
372- print (f"\n ✓ Completato: { file_name } " )
373- print (f" Salvato in: { output_path } " )
374- print (f" Tempo impiegato: { file_elapsed :.1f} secondi" )
375-
376- except Exception as e :
377- print (f"\n ✗ Errore durante la trascrizione di { file_name } : { e } " )
378- main_pbar .update (1 )
429+ print (f" Impossibile convertire { file_name } , salto..." )
430+ main_pbar .update (1 )
431+ continue
432+ else :
433+ # È già WAV, usa il file originale
434+ wav_file_path = file_path
435+
436+ # Procedi con la trascrizione
437+ transcription = transcribe_podcast_with_progress (wav_file_path , speed_up = speed_up )
438+ save_transcription (transcription , output_path )
439+
440+ processed_files += 1
441+ elapsed_total = time .time () - start_time
442+ file_elapsed = time .time () - file_start_time
443+
444+ # Calcola ETA
445+ if processed_files > 0 :
446+ avg_time_per_file = elapsed_total / processed_files
447+ remaining_files = total_files - processed_files
448+ eta_seconds = avg_time_per_file * remaining_files
449+ eta_formatted = format_time (eta_seconds )
450+ else :
451+ eta_formatted = "Calcolando..."
452+
453+ # Aggiorna la barra di progresso
454+ main_pbar .update (1 )
455+ main_pbar .set_postfix ({
456+ "File" : f"{ file_elapsed :.1f} s" ,
457+ "ETA" : eta_formatted ,
458+ "Totale" : format_time (elapsed_total )
459+ })
460+
461+ print (f"\n ✓ Completato: { file_name } " )
462+ print (f" Salvato in: { output_path } " )
463+ print (f" Tempo impiegato: { file_elapsed :.1f} secondi" )
464+
465+ except Exception as e :
466+ print (f"\n ✗ Errore durante la trascrizione di { file_name } : { e } " )
467+ main_pbar .update (1 )
468+ finally :
469+ # Pulisce il file WAV convertito se è stato creato
470+ if converted_file_path and os .path .exists (converted_file_path ):
471+ try :
472+ os .remove (converted_file_path )
473+ print (" File WAV convertito rimosso" )
474+ except Exception as e :
475+ print (f" Attenzione: impossibile rimuovere il file convertito: { e } " )
379476
380477 total_elapsed = time .time () - start_time
381478 print (f"\n 🎉 Trascrizione completata!" )
0 commit comments