from datasets import load_dataset
from tqdm.auto import tqdm
from speech_collator import SpeechCollator
import json
from torch.utils.data import DataLoader
import torch
from vocex import Vocex
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np

vocex = Vocex.from_pretrained("cdminix/vocex")


dataset = load_dataset("libritts-r-aligned.py")

# Load the speaker2idx and phone2idx dictionaries
with open("data/speaker2idx.json", "r") as f:
    speaker2idx = json.load(f)
    idx2speaker = {v: k for k, v in speaker2idx.items()}
with open("data/phone2idx.json", "r") as f:
    phone2idx = json.load(f)
    idx2phone = {v: k for k, v in phone2idx.items()}

collator = SpeechCollator(
    speaker2idx=speaker2idx,
    phone2idx=phone2idx,
)

dataloader = DataLoader(
    dataset["dev"],
    batch_size=1,
    shuffle=False,
    collate_fn=collator.collate_fn,
    num_workers=4,
)

def resample(x, vpw=5):
    return np.interp(np.linspace(0, 1, vpw), np.linspace(0, 1, len(x)), x)

mean_pitchs = []
std_pitchs = []
mean_energys = []
std_energys = []
mean_durations = []
std_durations = []
mean_dvecs = []
std_dvecs = []

for item in tqdm(dataloader):
    result = vocex.model(item["mel"], inference=True)
    pitch = result["measures"]["pitch"]
    energy = result["measures"]["energy"]
    va = result["measures"]["voice_activity_binary"]
    dvec = result["dvector"]
    mean_pitch = pitch.mean()
    std_pitch = pitch.std()
    mean_energy = energy.mean()
    std_energy = energy.std()
    durations = item["phone_durations"].squeeze().numpy()
    durations = np.log(durations + 1)
    mean_duration = durations.mean()
    std_duration = durations.std()
    mean_pitchs.append(mean_pitch)
    std_pitchs.append(std_pitch)
    mean_energys.append(mean_energy)
    std_energys.append(std_energy)
    mean_durations.append(mean_duration)
    std_durations.append(std_duration)
    mean_dvecs.append(dvec.mean())
    std_dvecs.append(dvec.std())

mean_pitch = [float(np.mean(mean_pitchs)), float(np.std(mean_pitchs))]
std_pitch = [float(np.mean(std_pitchs)), float(np.std(std_pitchs))]
mean_energy = [float(np.mean(mean_energys)), float(np.std(mean_energys))]
std_energy = [float(np.mean(std_energys)), float(np.std(std_energys))]
mean_duration = [float(np.mean(mean_durations)), float(np.std(mean_durations))]
std_duration = [float(np.mean(std_durations)), float(np.std(std_durations))]
mean_dvec = [float(np.mean(mean_dvecs)), float(np.std(mean_dvecs))]
std_dvec = [float(np.mean(std_dvecs)), float(np.std(std_dvecs))]

# save the stats
stats = {
    "mean_pitch": mean_pitch,
    "std_pitch": std_pitch,
    "mean_energy": mean_energy,
    "std_energy": std_energy,
    "mean_duration": mean_duration,
    "std_duration": std_duration,
    "mean_dvec": mean_dvec,
    "std_dvec": std_dvec,
}

with open("data/stats.json", "w") as f:
    json.dump(stats, f)

for item in tqdm(dataloader):
    plt.figure(figsize=(20, 10))
    plt.subplot(4, 1, 1)
    plt.title("Mel spectrogram")
    plt.imshow(item["mel"].squeeze().numpy().T, aspect="auto", origin="lower")
    result = vocex.model(item["mel"], inference=True)
    pitch = result["measures"]["pitch"]
    energy = result["measures"]["energy"]
    va = result["measures"]["voice_activity_binary"]
    mean_pitch = pitch.mean()
    std_pitch = pitch.std()
    pitch = (pitch - pitch.mean()) / pitch.std()
    mean_energy = energy.mean()
    std_energy = energy.std()
    energy = (energy - energy.mean()) / energy.std()
    va = (va - 0.5) * 2
    durations = item["phone_durations"].squeeze().numpy()
    plt.subplot(4, 1, 2)
    sns.lineplot(
        x=np.arange(len(pitch[0])),
        y=pitch[0],
        color="red",
        label="Pitch",
    )
    sns.lineplot(
        x=np.arange(len(energy[0])),
        y=energy[0],
        color="blue",
        label="Energy",
    )
    sns.lineplot(
        x=np.arange(len(va[0])),
        y=va[0],
        color="green",
        label="Voice activity",
    )
    plt.legend()
    dur = [d for d in durations if d > 0]
    current_idx = 0
    vpw = 5 # values per window
    new_repr = np.zeros((len(dur), vpw*3 + 1))
    for i, d in enumerate(dur):
        new_repr[i, 0] = d
        # get values in duration window
        pitch_win = pitch[0, current_idx:current_idx+d]
        energy_win = energy[0, current_idx:current_idx+d]
        va_win = va[0, current_idx:current_idx+d]
        current_idx += d
        # resample to vpw values
        pitch_win = resample(pitch_win, vpw)
        energy_win = resample(energy_win, vpw)
        va_win = resample(va_win, vpw)
        new_repr[i, 1:vpw+1] = pitch_win
        new_repr[i, vpw+1:2*vpw+1] = energy_win
        new_repr[i, 2*vpw+1:3*vpw+1] = va_win
    new_repr[:, 0] = np.log(new_repr[:, 0] + 1)
    mean_dur = new_repr[:, 0].mean()
    std_dur = new_repr[:, 0].std()
    new_repr[:, 0] = (new_repr[:, 0] - mean_dur) / std_dur
    plt.subplot(4, 1, 3)
    # heatmap with log scale
    phones = [idx2phone[int(p)] for i, p in enumerate(item["phones"][0]) if item["phone_durations"][0][i] > 0]
    for p_i, p in enumerate(phones):
        if "[" in p:
            # make empty symbol for phones with []
            phones[p_i] = ""
    sns.heatmap(new_repr.T, cmap="viridis")
    # set xticks while making sure they are in the middle of the phone
    plt.tick_params(axis="x", which="both", bottom=False, top=False, labelbottom=True)
    plt.xticks(np.arange(len(phones))+0.5, np.arange(len(phones)), rotation=0)
    plt.yticks([0.5]+list(np.array([1,2,3])*(vpw)-vpw/2+1), ["Duration", "Pitch", "Energy", "Voice activity"], rotation=0)
    plt.twiny()
    plt.xticks(np.arange(len(phones))+0.5, phones, rotation=0)
    plt.xlim(0, len(phones))
    # allow some space between this plot and the next one
    plt.subplots_adjust(hspace=0.5)
    # reconstruct pitch, energy and va from new_repr
    r_pitch = np.zeros(len(pitch[0]))
    r_energy = np.zeros(len(energy[0]))
    r_va = np.zeros(len(va[0]))
    current_idx = 0
    for i, d in enumerate(dur):
        # get values in duration window
        pitch_win = new_repr[i, 1:vpw+1]
        energy_win = new_repr[i, vpw+1:2*vpw+1]
        va_win = new_repr[i, 2*vpw+1:3*vpw+1]
        # resample to d values
        pitch_win = resample(pitch_win, d)
        energy_win = resample(energy_win, d)
        va_win = resample(va_win, d)
        r_pitch[current_idx:current_idx+d] = pitch_win
        r_energy[current_idx:current_idx+d] = energy_win
        r_va[current_idx:current_idx+d] = va_win
        current_idx += d
    plt.subplot(4, 1, 4)
    sns.lineplot(
        x=np.arange(len(r_pitch)),
        y=r_pitch,
        color="red",
        label="Pitch",
    )
    sns.lineplot(
        x=np.arange(len(r_energy)),
        y=r_energy,
        color="blue",
        label="Energy",
    )
    sns.lineplot(
        x=np.arange(len(r_va)),
        y=r_va,
        color="green",
        label="Voice activity",
    )
    plt.legend()
    plt.savefig("test.png")
    print("Mean pitch:", mean_pitch)
    print("Std pitch:", std_pitch)
    print("Mean energy:", mean_energy)
    print("Std energy:", std_energy)
    print("Mean duration:", mean_dur)
    print("Std duration:", std_dur)
    break