"""Extrae matrices de atención Tacotron2; usa pesos SpeechBrain locales."""
import argparse,hashlib,json,time
from pathlib import Path
import numpy as np
import torch,torchaudio

# SpeechBrain 1.0.3 inspecciona una API que torchaudio 2.11 retiró. Aquí no
# se cargan archivos con torchaudio; no se altera la instalación compartida.
if not hasattr(torchaudio,'list_audio_backends'):torchaudio.list_audio_backends=lambda:[]
from hyperpyyaml import load_hyperpyyaml
from speechbrain.utils.text_to_sequence import symbols

TEXTS=[
    'The small bird sings by the window.',
    'The little little little bird sings and sings and sings again.',
    'The rain fell softly on the road while the quiet little bird kept singing over and over again.'
]

def sha(path):
    h=hashlib.sha256()
    with Path(path).open('rb') as f:
        for b in iter(lambda:f.read(1024*1024),b''):h.update(b)
    return h.hexdigest()

def main():
    p=argparse.ArgumentParser();p.add_argument('--model',required=True);p.add_argument('--out',required=True)
    p.add_argument('--vocoder',help='Directorio opcional de HiFi-GAN SpeechBrain para generar los WAV')
    p.add_argument('--device',default='cpu');args=p.parse_args();torch.set_num_threads(2);torch.manual_seed(2929)
    root=Path(args.model);out=Path(args.out);out.mkdir(parents=True,exist_ok=True)
    if sha(root/'model.ckpt')!='02d1aa3fc1cc8fb0981895c765e9d0017416bb78861b5450e458dda92e567856':raise ValueError('pesos Tacotron distintos de la revisión fijada')
    with (root/'hyperparams.yaml').open(encoding='utf8') as f:hp=load_hyperpyyaml(f)
    model=hp['model'].to(args.device).eval();model.load_state_dict(torch.load(root/'model.ckpt',map_location=args.device,weights_only=True))
    records=[];mels=[]
    for i,text in enumerate(TEXTS):
        ids=hp['text_to_sequence'](text,['english_cleaners']);x=torch.tensor(ids,device=args.device)[None,:];length=torch.tensor([len(ids)],device=args.device)
        start=time.perf_counter()
        with torch.no_grad():mel,mel_len,alignment=model.infer(x,length)
        if args.device=='cuda':torch.cuda.synchronize()
        mat=alignment[0,:int(mel_len[0]),:len(ids)].detach().cpu().numpy()
        if mat.shape[1]!=len(ids) or not np.isfinite(mat).all():raise ValueError('alineamiento inválido')
        if args.vocoder:mels.append(mel[...,:int(mel_len[0])].detach())
        np.save(out/f'alignment-{i}.npy',mat)
        positions=np.argmax(mat,axis=1);visited=int(np.unique(positions).size);movement=np.diff(positions)
        records.append({'text':text,'tokens':[symbols[j] for j in ids],'frames':len(mat),'tokens_visited':visited,
                        'argmax_backward_steps':int(np.sum(movement<0)),
                        'argmax_forward_jumps_gt_one':int(np.sum(movement>1)),
                        'max_frame_weight_mean':float(mat.max(axis=1).mean()),'seconds':time.perf_counter()-start,
                        'matrix':f'alignment-{i}.npy'})
        print(i,'texto',len(ids),'tramas',len(mat),'visitados',visited,'segundos',records[-1]['seconds'],flush=True)
    if args.vocoder:
        from scipy.io import wavfile
        voc=Path(args.vocoder);weights=voc/'generator.ckpt'
        if sha(weights)!='1a389f24ffdc3769e0b9c0331f9d803ad0b78185e0da4f2d094e29eedbc11640':raise ValueError('pesos HiFi-GAN distintos de la revisión fijada')
        with (voc/'hyperparams.yaml').open(encoding='utf8') as f:voc_hp=load_hyperpyyaml(f)
        generator=voc_hp['generator'].to(args.device).eval()
        generator.load_state_dict(torch.load(weights,map_location=args.device,weights_only=True));generator.remove_weight_norm()
        for i,mel in enumerate(mels):
            with torch.no_grad():wave=generator.inference(mel)[0,0]
            offset=generator.inference_padding*256;wave=wave[offset:offset+mel.shape[-1]*256].detach().cpu().numpy()
            if not len(wave) or not np.isfinite(wave).all():raise ValueError('WAV generado inválido')
            wav=out/f'tacotron-{i}.wav';wavfile.write(wav,22050,np.rint(np.clip(wave,-1,1)*32767).astype(np.int16))
            records[i]['audio']=wav.name;records[i]['audio_sha256']=sha(wav);records[i]['hifigan_sha256']=sha(weights)
    (out/'manifest.json').write_text(json.dumps({'revision':'d01e530d6d8e1b388c04b882305867addbed4389',
        'weights_sha256':sha(root/'model.ckpt'),'seed':2929,'examples':records},ensure_ascii=False,indent=2),encoding='utf8')

if __name__=='__main__':main()
