"""CTC mechanism demo and optional offline Whisper transcription of PCM16 WAV."""
import argparse
import itertools
import json
from pathlib import Path
import platform

import torch
from torch.nn import functional as F
from deep_learning import ctc_collapse
from deep_learning_apps import read_pcm16


def edit_distance(reference, hypothesis):
    row = list(range(len(hypothesis)+1))
    for i, expected in enumerate(reference,1):
        new = [i]
        for j,actual in enumerate(hypothesis,1):
            new.append(min(new[-1]+1,row[j]+1,row[j-1]+(expected!=actual)))
        row = new
    return row[-1]


def error_rate(reference, hypothesis, unit="character"):
    # Only whitespace is normalized; punctuation and case remain significant.
    ref=reference.split() if unit=="word" else list("".join(reference.split()))
    hyp=hypothesis.split() if unit=="word" else list("".join(hypothesis.split()))
    if not ref:
        raise ValueError("Nonempty reference needed for an error rate")
    return {"unit":unit,"edits":edit_distance(ref,hyp),"reference_units":len(ref),
            "rate":edit_distance(ref,hyp)/len(ref),
            "normalization":"word: whitespace split; character: remove whitespace only"}


def ctc_demo():
    probabilities=torch.tensor([[.4,.6],[.7,.3],[.5,.5]],dtype=torch.float64)
    paths=[]
    for path in itertools.product(range(2),repeat=3):
        if ctc_collapse(path)==[1]:
            mass=float(probabilities[torch.arange(3),torch.tensor(path)].prod())
            paths.append({"path":list(path),"probability":mass})
    loss=F.ctc_loss(probabilities.log()[:,None,:],torch.tensor([1]),
                    torch.tensor([3]),torch.tensor([1]),reduction="sum")
    return {"blank":0,"target":[1],"valid_paths":paths,
            "target_probability":sum(p["probability"] for p in paths),
            "negative_log_probability":float(loss),
            "repeated_letter_example":ctc_collapse([1,1,0,1,2,2]),
            "note":"Artificial frame probabilities; not a trained speech recognizer"}


def main():
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--model-dir",type=Path)
    parser.add_argument("--audio",type=Path)
    parser.add_argument("--language",default="chinese")
    parser.add_argument("--reference")
    parser.add_argument("--unit",choices=["character","word"],default="character")
    parser.add_argument("--output",type=Path,default=Path("artifacts/deep/speech/report.json"))
    args=parser.parse_args()
    torch.set_num_threads(1)
    if args.model_dir is None and args.audio is None:
        result=ctc_demo()
    else:
        if args.model_dir is None or args.audio is None:
            parser.error("Provide both --model-dir and --audio")
        from transformers import AutoProcessor, AutoModelForSpeechSeq2Seq
        import transformers
        if not args.model_dir.is_dir():
            raise FileNotFoundError("Prepare the complete local model folder first")
        waveform=read_pcm16(args.audio)
        if not 0<len(waveform)<=30*16000:
            raise ValueError("Use a nonempty clip of at most 30 seconds")
        processor=AutoProcessor.from_pretrained(args.model_dir,local_files_only=True)
        model=AutoModelForSpeechSeq2Seq.from_pretrained(
            args.model_dir,local_files_only=True).eval()
        features=processor(waveform.numpy(),sampling_rate=16000,return_tensors="pt",
                            return_attention_mask=True)
        with torch.inference_mode():
            tokens=model.generate(**features,language=args.language,task="transcribe",
                                  max_new_tokens=225)
        text=processor.batch_decode(tokens,skip_special_tokens=True)[0]
        result={"text":text,"audio":str(args.audio),"local_model":str(args.model_dir),
                "language":args.language,"task":"transcribe","sample_rate":16000,
                "seconds":len(waveform)/16000,
                "environment":{"python":platform.python_version(),"torch":torch.__version__,
                               "transformers":transformers.__version__,"device":"cpu"}}
        if args.reference is not None:
            result["evaluation"]=error_rate(args.reference,text,args.unit)
    args.output.parent.mkdir(parents=True,exist_ok=True)
    args.output.write_text(json.dumps(result,ensure_ascii=False,indent=2),encoding="utf-8")
    print(json.dumps(result,ensure_ascii=False,indent=2))


if __name__=="__main__":
    main()
