"""Atención Whisper small sobre voz SAPI de m24-l27 y control de silencio."""
import json, os
from pathlib import Path
import numpy as np
from scipy.io import wavfile
import torch
from transformers import WhisperProcessor, WhisperForConditionalGeneration

torch.manual_seed(28)
device='cuda' if torch.cuda.is_available() and os.environ.get('WHISPER_CPU')!='1' else 'cpu';dtype=torch.float16 if device=='cuda' else torch.float32
root=Path(os.environ.get('WHISPER_SMALL_PATH','asr-models/whisper-small'))
processor=WhisperProcessor.from_pretrained(root,local_files_only=True)
model=WhisperForConditionalGeneration.from_pretrained(root,attn_implementation='eager',torch_dtype=dtype,local_files_only=True).to(device).eval()
sr,wave=wavfile.read(os.environ.get('WHISPER_AUDIO','sapi-example.wav'));assert sr==16000
wave=wave.astype(np.float32)/32768
features=processor(wave,sampling_rate=sr,return_tensors='pt').input_features.to(device=device,dtype=dtype)
with torch.no_grad():
    generated=model.generate(features,language='english',task='transcribe',return_timestamps=True,max_new_tokens=64)
    encoder=model.get_encoder()(features,output_attentions=False,return_dict=True)
    prompt=processor.get_decoder_prompt_ids(language='english',task='transcribe',no_timestamps=False)
    prefix=[model.config.decoder_start_token_id]+[token for _,token in prompt]
    decoder_ids=torch.cat([torch.tensor([prefix],device=device),generated[:,:-1]],dim=1)
    result=model(encoder_outputs=encoder,decoder_input_ids=decoder_ids,output_attentions=True,return_dict=True)
print('generado:',processor.batch_decode(generated,decode_with_timestamps=True)[0],flush=True)
attention=result.cross_attentions[-1][0].float().mean(0).cpu().numpy()
count=min(attention.shape[1],int(np.ceil(len(wave)/sr*50)))
mel=features[0,:,:2*count:2].float().cpu().numpy()
rows=[]
for index,token in enumerate(generated[0].tolist()):
    weights=attention[len(prefix)-1+index,:count]
    rows.append({'token':processor.tokenizer.decode([token],decode_with_timestamps=True),'token_id':token,
                 'weights':np.round(weights,6).tolist(),'mass_in_clip':float(weights.sum())})
path=Path(os.environ.get('WHISPER_ATTENTION_OUTPUT','attention-data.json'))
partial=path.with_suffix('.partial.json')
partial.write_text(json.dumps({'sample_rate':sr,'duration':len(wave)/sr,'generated':processor.batch_decode(generated,decode_with_timestamps=True)[0],'rows':rows,'mel':np.round(mel,4).tolist()},ensure_ascii=False),encoding='utf-8')
print('atención parcial guardada:',partial,flush=True)
cached=os.environ.get('WHISPER_SILENCE_SOURCE')
if cached:
    control=json.loads(Path(cached).read_text(encoding='utf-8'))
    silence_text,prompted_text=control['silence'],control['prompted_silence']
else:
    silence=np.zeros(sr*8,dtype=np.float32)
    sil_features=processor(silence,sampling_rate=sr,return_tensors='pt').input_features.to(device=device,dtype=dtype)
    with torch.no_grad():
        blank=model.generate(sil_features,language='english',task='transcribe',return_timestamps=True,max_new_tokens=64)
        silence_prompt=processor.get_prompt_ids('Thank you for watching.',return_tensors='pt').to(device)
        prompted=model.generate(sil_features,language='english',task='transcribe',return_timestamps=True,max_new_tokens=64,prompt_ids=silence_prompt)
    silence_text=processor.batch_decode(blank,decode_with_timestamps=True)[0]
    prompted_text=processor.batch_decode(prompted,decode_with_timestamps=True)[0]
print('silencio:',silence_text,flush=True)
print('silencio con prompt:',prompted_text,flush=True)
path=Path(os.environ.get('WHISPER_ATTENTION_OUTPUT','attention-data.json'))
path.write_text(json.dumps({'sample_rate':sr,'duration':len(wave)/sr,'generated':processor.batch_decode(generated,decode_with_timestamps=True)[0],
    'rows':rows,'mel':np.round(mel,4).tolist(),'silence':silence_text,'prompted_silence':prompted_text},ensure_ascii=False),encoding='utf-8')
print('guardado:',path,flush=True)
