"""Coseno ECAPA entre referencia LJSpeech y salidas F5; no es verificación de identidad."""
import argparse,json
from pathlib import Path
import numpy as np
from scipy.io import wavfile
from scipy.signal import resample_poly
import torch,torchaudio
if not hasattr(torchaudio,'list_audio_backends'):torchaudio.list_audio_backends=lambda:[]
from hyperpyyaml import load_hyperpyyaml
from vocoder_lab import sha

def load16(path):
    sr,x=wavfile.read(path)
    if x.ndim!=1 or x.dtype!=np.int16:raise ValueError('se espera WAV mono int16')
    x=x.astype(np.float32)/32768
    if sr==22050:x=resample_poly(x,320,441)
    elif sr!=16000:raise ValueError('frecuencia no soportada')
    return torch.from_numpy(x)[None,:]

def main():
    p=argparse.ArgumentParser();p.add_argument('--generated',required=True);p.add_argument('--reference',required=True)
    p.add_argument('--model',required=True);p.add_argument('--out',required=True);p.add_argument('--device',default='cpu');args=p.parse_args()
    torch.set_num_threads(2);root=Path(args.generated);model=Path(args.model)
    rows=[json.loads(x) for x in (root/'manifest.jsonl').read_text(encoding='utf8').splitlines() if x.strip()]
    if not rows:raise ValueError('manifiesto vacío')
    if sha(model/'embedding_model.ckpt')!='0575cb64845e6b9a10db9bcb74d5ac32b326b8dc90352671d345e2ee3d0126a2':raise ValueError('pesos ECAPA distintos de la revisión fijada')
    with (model/'hyperparams.yaml').open(encoding='utf8') as f:hp=load_hyperpyyaml(f)
    features=hp['compute_features'].to(args.device).eval();norm=hp['mean_var_norm'].to(args.device).eval()
    embed=hp['embedding_model'].to(args.device).eval()
    embed.load_state_dict(torch.load(model/'embedding_model.ckpt',map_location=args.device,weights_only=True))
    def vector(path):
        x=load16(path).to(args.device);length=torch.ones(1,device=args.device)
        with torch.no_grad():return embed(norm(features(x),length),length).reshape(-1)
    reference=vector(args.reference);result=[]
    for row in rows:
        path=root/row['audio']
        if sha(path)!=row['sha256']:raise ValueError('audio modificado')
        cos=torch.nn.functional.cosine_similarity(reference,vector(path),dim=0).item()
        result.append({'id':row['id'],'cosine':cos});print(row['id'],round(cos,4),flush=True)
    output={'reference_sha256':sha(args.reference),'model_sha256':sha(model/'embedding_model.ckpt'),
       'n':len(result),'mean_cosine':float(np.mean([x['cosine'] for x in result])),
       'warning':'Un locutor, similitud no calibrada y sin inferencia de identidad ni calidad perceptual.', 'rows':result}
    Path(args.out).write_text(json.dumps(output,ensure_ascii=False,indent=2),encoding='utf8');print('media',output['mean_cosine'],flush=True)

if __name__=='__main__':main()
