#!/usr/bin/env python3 """Preenche as transcricoes vazias do metadata.csv usando Whisper. Uso (na pasta fala_pb, na sua maquina com whisper instalado): python transcribe_missing.py # modelo small python transcribe_missing.py --model medium Requer: pip install openai-whisper (voce ja usou no process_dataset.py) Retomavel: salva progresso em transcricoes_parciais.csv a cada arquivo; se interromper, rode de novo que continua de onde parou. """ import argparse import csv import os import re import sys import unicodedata csv.field_size_limit(10_000_000) BASE = os.path.dirname(os.path.abspath(__file__)) META = os.path.join(BASE, 'metadata.csv') PARTIAL = os.path.join(BASE, 'transcricoes_parciais.csv') def norm_text(t): if not t: return '' t = t.replace('...', ' ').replace('…', ' ') t = re.sub(r'[^\w\sÀ-ÿ]', ' ', t, flags=re.UNICODE) return re.sub(r'\s+', ' ', t).strip().lower() def main(): ap = argparse.ArgumentParser() ap.add_argument('--model', default='small') args = ap.parse_args() rows = list(csv.DictReader(open(META, encoding='utf-8'))) pending = [r for r in rows if not r['text'].strip()] print(f'{len(pending)} audios sem transcricao') if not pending: return done = {} if os.path.exists(PARTIAL): for r in csv.DictReader(open(PARTIAL, encoding='utf-8')): done[r['id']] = r['text'] print(f'{len(done)} ja transcritos anteriormente') todo = [r for r in pending if r['id'] not in done] if todo: import whisper model = whisper.load_model(args.model) new_file = not os.path.exists(PARTIAL) with open(PARTIAL, 'a', newline='', encoding='utf-8') as pf: w = csv.writer(pf) if new_file: w.writerow(['id', 'text']) for i, r in enumerate(todo, 1): path = os.path.join(BASE, r['file_name'].replace('/', os.sep)) try: res = model.transcribe(path, language='pt') text = res['text'].strip() except Exception as e: print(f'ERRO {r["id"]}: {e}') text = '' done[r['id']] = text w.writerow([r['id'], text]) pf.flush() print(f'[{i}/{len(todo)}] {r["id"]}: {text[:70]}') # aplica no metadata.csv for r in rows: if r['id'] in done and done[r['id']]: r['text'] = done[r['id']] r['normalized_text'] = norm_text(done[r['id']]) r['notes'] = (r['notes'].replace( 'transcricao pendente (transcribe_missing.py)', 'transcricao automatica (Whisper, revisao manual recomendada)')) tmp = META + '.tmp' with open(tmp, 'w', newline='', encoding='utf-8') as f: w = csv.DictWriter(f, fieldnames=rows[0].keys()) w.writeheader() w.writerows(rows) os.replace(tmp, META) print(f'metadata.csv atualizado. Pode apagar {os.path.basename(PARTIAL)}.') if __name__ == '__main__': main()