File size: 3,103 Bytes
5f4a5e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#!/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()