"""WER micro de un manifiesto de WAV 16 kHz con Whisper small local."""
import argparse,hashlib,json,time,unicodedata
from pathlib import Path
import numpy as np,torch
from scipy.io import wavfile
from transformers import WhisperProcessor,WhisperForConditionalGeneration

def norm(text):
    text=unicodedata.normalize('NFC',text.lower())
    return ' '.join(''.join(' ' if unicodedata.category(c)[0] in 'PS' else c for c in text).split())

def errors(ref,hyp):
    a,b=ref.split(),hyp.split();v=list(range(len(b)+1))
    for i,x in enumerate(a,1):
        n=[i]
        for j,y in enumerate(b,1):n.append(min(n[-1]+1,v[j]+1,v[j-1]+(x!=y)))
        v=n
    return v[-1],len(a)

def main():
    p=argparse.ArgumentParser();p.add_argument('--manifest',required=True);p.add_argument('--model',required=True)
    p.add_argument('--out',required=True);p.add_argument('--device',choices=('cpu','cuda'),default='cpu');args=p.parse_args();torch.set_num_threads(2)
    path=Path(args.manifest).resolve();rows=[json.loads(x) for x in path.read_text(encoding='utf8').splitlines() if x.strip()]
    if not rows:raise ValueError('manifiesto vacío')
    weight=Path(args.model)/'model.safetensors';weight_hash=hashlib.sha256()
    with weight.open('rb') as f:
        for chunk in iter(lambda:f.read(1024*1024),b''):weight_hash.update(chunk)
    if weight_hash.hexdigest()!='1d7734884874f1a1513ed9aa760a4f8e97aaa02fd6d93a3a85d27b2ae9ca596b':raise ValueError('pesos Whisper distintos de la revisión fijada')
    dtype=torch.float16 if args.device=='cuda' else torch.float32
    processor=WhisperProcessor.from_pretrained(args.model,local_files_only=True)
    model=WhisperForConditionalGeneration.from_pretrained(args.model,dtype=dtype,local_files_only=True).to(args.device).eval()
    records=[]
    for i,row in enumerate(rows):
        file=(path.parent/row['audio']).resolve();audio_hash=hashlib.sha256(file.read_bytes()).hexdigest()
        if row.get('sha256') and audio_hash!=row['sha256']:raise ValueError('WAV modificado')
        rate,wave=wavfile.read(file)
        if rate!=16000 or wave.ndim!=1:raise ValueError('se requiere WAV mono de 16 kHz')
        if np.issubdtype(wave.dtype,np.integer):wave=wave.astype('float32')/max(abs(np.iinfo(wave.dtype).min),np.iinfo(wave.dtype).max)
        else:wave=wave.astype('float32')
        inputs=processor(wave,sampling_rate=rate,return_tensors='pt').input_features.to(device=args.device,dtype=dtype)
        if args.device=='cuda':torch.cuda.synchronize()
        start=time.perf_counter()
        with torch.no_grad():ids=model.generate(inputs,language=row['language'],task='transcribe',max_new_tokens=128)
        if args.device=='cuda':torch.cuda.synchronize()
        pred=norm(processor.batch_decode(ids,skip_special_tokens=True)[0]);ref=norm(row['reference']);e,n=errors(ref,pred)
        records.append({'source':row,'sha256_audio':audio_hash,'reference_normalized':ref,'hypothesis':pred,'errors':e,'words':n,
                        'seconds':time.perf_counter()-start,'duration':len(wave)/rate,'tokens':int(ids.shape[-1])})
        print(i+1,'/',len(rows),'ref',ref,'hipótesis',pred,'errores',e,'/',n,flush=True)
    E=sum(r['errors'] for r in records);N=sum(r['words'] for r in records)
    groups={}
    for r in records:
        key=r['source'].get('condition','sin condición');group=groups.setdefault(key,{'errors':0,'words':0,'count':0})
        group['errors']+=r['errors'];group['words']+=r['words'];group['count']+=1
    for group in groups.values():group['wer']=group['errors']/group['words'] if group['words'] else None
    Path(args.out).write_text(json.dumps({'model':'openai/whisper-small@973afd24965f72e36ca33b3055d56a652f456b4d','weights_sha256':weight_hash.hexdigest(),
        'normalization':'NFC, minúsculas, separación de puntuación y símbolos; cifras intactas',
        'device':args.device,'errors':E,'words':N,'wer':E/N if N else None,'groups':groups,'records':records},ensure_ascii=False,indent=2),encoding='utf8')

if __name__=='__main__':main()
