Skip to content

Commit 0ad2b6b

Browse files
committed
Update transcribe_wav.py
1 parent c0efbd1 commit 0ad2b6b

File tree

1 file changed

+103
-12
lines changed

1 file changed

+103
-12
lines changed

scripts/transcribe_wav.py

Lines changed: 103 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -258,12 +258,52 @@ def transcribe_chunk_parallel(chunk_path, model, language='it'):
258258
str: Testo trascritto del chunk
259259
"""
260260
try:
261+
print(f" DEBUG: Inizio trascrizione chunk {os.path.basename(chunk_path)}")
262+
263+
# Verifica che il chunk esista e sia valido
264+
if not os.path.exists(chunk_path):
265+
print(f" ❌ ERRORE: Chunk non trovato: {chunk_path}")
266+
return ""
267+
268+
chunk_size = os.path.getsize(chunk_path)
269+
print(f" DEBUG: Chunk size: {chunk_size} bytes")
270+
271+
if chunk_size < 1000:
272+
print(f" ❌ ERRORE: Chunk troppo piccolo: {chunk_size} bytes")
273+
return ""
274+
275+
# Verifica che il modello sia valido
276+
if not hasattr(model, 'transcribe'):
277+
print(f" ❌ ERRORE: Modello non valido, manca metodo transcribe")
278+
return ""
279+
261280
# Trascrive il chunk usando il modello già caricato
262-
result = model.transcribe(chunk_path, language=language)
263-
return result['text']
281+
print(f" DEBUG: Avvio trascrizione con modello {type(model)}")
282+
try:
283+
result = model.transcribe(chunk_path, language=language)
284+
print(f" DEBUG: Trascrizione completata per {os.path.basename(chunk_path)}")
285+
return result['text']
286+
except (AttributeError, KeyError) as e:
287+
if "Linear" in str(e) or any(x in str(e) for x in ["KeyError", "transcribe", "decoder", "encoder"]):
288+
print(f" ❌ ERRORE CRITICO: Modello Whisper danneggiato durante la trascrizione")
289+
print(f" DEBUG: Errore modello: {e}")
290+
print(" 🔧 RISOLUZIONE AUTOMATICA: Reinstallazione forzata di Whisper in corso...")
291+
try:
292+
# Forza la reinstallazione di Whisper
293+
subprocess.check_call([sys.executable, "-m", "pip", "install", "--force-reinstall", "openai-whisper"])
294+
print(" ✅ Whisper reinstallato. Riavvia lo script per utilizzare il modello riparato.")
295+
except subprocess.CalledProcessError:
296+
print(" ❌ Impossibile reinstallare automaticamente. Esegui manualmente:")
297+
print(" pip install --force-reinstall openai-whisper")
298+
return ""
299+
else:
300+
raise e
264301

265302
except Exception as e:
266-
print(f" Errore nella trascrizione del chunk {os.path.basename(chunk_path)}: {e}")
303+
print(f" ❌ ERRORE nella trascrizione del chunk {os.path.basename(chunk_path)}: {e}")
304+
print(f" DEBUG: Tipo errore: {type(e).__name__}")
305+
import traceback
306+
print(f" DEBUG: Traceback: {traceback.format_exc()}")
267307
return ""
268308

269309
def transcribe_audio_parallel(file_path, model, language='it'):
@@ -526,8 +566,31 @@ def update_progress():
526566
progress_thread = threading.Thread(target=update_progress, daemon=True)
527567
progress_thread.start()
528568

569+
# Verifica che il file esista prima della trascrizione
570+
if not os.path.exists(file_path):
571+
print(f" ❌ ERRORE: File non trovato per trascrizione: {file_path}")
572+
return ""
573+
529574
# Esegue la trascrizione
530-
result = model.transcribe(file_path, language=language)
575+
print(f" DEBUG: Esecuzione trascrizione per {os.path.basename(file_path)}")
576+
try:
577+
result = model.transcribe(file_path, language=language)
578+
print(f" DEBUG: Trascrizione completata con successo")
579+
except (AttributeError, KeyError) as e:
580+
if "Linear" in str(e) or any(x in str(e) for x in ["KeyError", "transcribe", "decoder", "encoder"]):
581+
print(f" ❌ ERRORE CRITICO: Modello Whisper danneggiato durante la trascrizione")
582+
print(f" DEBUG: Errore modello: {e}")
583+
print(" 🔧 RISOLUZIONE AUTOMATICA: Reinstallazione forzata di Whisper in corso...")
584+
try:
585+
# Forza la reinstallazione di Whisper
586+
subprocess.check_call([sys.executable, "-m", "pip", "install", "--force-reinstall", "openai-whisper"])
587+
print(" ✅ Whisper reinstallato. Riavvia lo script per utilizzare il modello riparato.")
588+
except subprocess.CalledProcessError:
589+
print(" ❌ Impossibile reinstallare automaticamente. Esegui manualmente:")
590+
print(" pip install --force-reinstall openai-whisper")
591+
return ""
592+
else:
593+
raise e
531594

532595
# Completa la barra di progresso
533596
elapsed = time.time() - start_time
@@ -592,17 +655,45 @@ def main(podcast_dir, model_name='medium', language='it', parallel=False):
592655
# Importa i moduli necessari
593656
whisper, tqdm = import_required_modules()
594657

595-
# Carica il modello Whisper una sola volta
658+
# Carica il modello Whisper con fallback automatico
596659
print(f"Caricamento del modello {model_name}...")
597-
try:
598-
with warnings.catch_warnings():
599-
warnings.filterwarnings("ignore", message="FP16 is not supported on CPU; using FP32 instead")
600-
model = whisper.load_model(model_name)
601-
print(f"DEBUG: Modello {model_name} caricato correttamente")
602-
except Exception as e:
603-
print(f"❌ ERRORE: Impossibile caricare il modello {model_name}: {e}")
660+
661+
# Lista di modelli da provare in ordine di preferenza
662+
model_names = [model_name, 'base', 'small', 'tiny']
663+
664+
model = None
665+
for attempt_model in model_names:
666+
try:
667+
print(f" DEBUG: Tentativo con modello {attempt_model}")
668+
with warnings.catch_warnings():
669+
warnings.filterwarnings("ignore", message="FP16 is not supported on CPU; using FP32 instead")
670+
model = whisper.load_model(attempt_model)
671+
672+
# Verifica che il modello sia valido
673+
if hasattr(model, 'transcribe'):
674+
print(f"✅ SUCCESSO: Modello {attempt_model} caricato correttamente")
675+
if attempt_model != model_name:
676+
print(f"⚠️ ATTENZIONE: Usato modello {attempt_model} invece di {model_name}")
677+
break
678+
else:
679+
print(f"❌ ERRORE: Modello {attempt_model} caricato ma non valido")
680+
model = None
681+
682+
except Exception as e:
683+
print(f"❌ ERRORE: Impossibile caricare il modello {attempt_model}: {e}")
684+
model = None
685+
continue
686+
687+
if model is None:
688+
print(f"❌ ERRORE CRITICO: Impossibile caricare alcun modello Whisper valido")
689+
print("Verifica l'installazione di Whisper e PyTorch")
690+
print("Se il problema persiste, prova a reinstallare:")
691+
print(" pip uninstall openai-whisper torch torchvision torchaudio")
692+
print(" pip install openai-whisper")
604693
return
605694

695+
print(f"DEBUG: Modello verificato, pronto per la trascrizione")
696+
606697
# Conta i file da elaborare
607698
total_files = count_supported_audio_files(podcast_dir)
608699

0 commit comments

Comments
 (0)