"""cine-23 demo, the recorded run: load the model train.py trained, score it on the 180 held-out presses it never
heard, then read back a password spelled only from held-out presses. Prints as it goes, with display pauses for
the screen (0.8 s after "testing", 1.0 s before the password, 0.3 s between its letters); the predictions are
computed before the pauses.

    CUDA_VISIBLE_DEVICES= python readback.py RUN_DIR
"""
import json, os, sys, time
import numpy as np
import librosa
import torch
import torch.nn as nn
import torch.nn.functional as F

RUN = sys.argv[1]
KEYS = list("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ")
SR = 44100
torch.set_num_threads(8)


class Net(nn.Module):                                      # the same small CNN as train.py
    def __init__(self, n=36):
        super().__init__()
        c = [1, 32, 64, 128, 192]
        self.convs = nn.ModuleList([nn.Sequential(nn.Conv2d(c[i], c[i + 1], 3, padding=1), nn.BatchNorm2d(c[i + 1]),
                                                  nn.GELU(), nn.Conv2d(c[i + 1], c[i + 1], 3, padding=1),
                                                  nn.BatchNorm2d(c[i + 1]), nn.GELU(), nn.MaxPool2d(2))
                                    for i in range(4)])
        self.drop = nn.Dropout(0.3)
        self.fc = nn.Linear(192, n)

    def forward(self, x):
        x = x[:, None]
        for m in self.convs:
            x = m(x)
        return self.fc(self.drop(x.mean(dim=(2, 3))))


def mel(x):
    m = librosa.feature.melspectrogram(y=x, sr=SR, n_fft=1024, hop_length=225, n_mels=64)
    return librosa.power_to_db(m, ref=np.max).astype(np.float32)[:, :64]


raw = np.load(os.path.join(RUN, "raw_strokes.npy"))
Y = np.load(os.path.join(RUN, "labels.npy"))
test_idx = np.load(os.path.join(RUN, "test_idx.npy"))
res = json.load(open(os.path.join(RUN, "result.json")))
train_mask = np.ones(len(Y), bool); train_mask[test_idx] = False
X = np.stack([mel(s) for s in raw])
mu, sd = X[train_mask].mean(), X[train_mask].std()
net = Net(); net.load_state_dict(torch.load(os.path.join(RUN, "model.pt"))); net.eval()

print(f"trained on {train_mask.sum()} presses", flush=True)
print(f"testing {len(test_idx)} unheard presses...", flush=True)
time.sleep(0.8)                                             # display pause (pacing for the screen)
with torch.no_grad():
    probs = F.softmax(net(torch.tensor((X[test_idx] - mu) / sd)), 1).numpy()
pred = probs.argmax(1)
ok = int((pred == Y[test_idx]).sum())
print(f"  {ok} / {len(test_idx)} right ({100 * ok / len(test_idx):.1f}%)", flush=True)
print("", flush=True)
pw, rows = res["password"], res["pw_test_rows"]
time.sleep(1.0)                                             # display pause
print(f"typed:  {pw}", flush=True)
print("heard:  ", end="", flush=True)
pos = {int(r): j for j, r in enumerate(test_idx)}
for r in rows:
    time.sleep(0.3)
    print(KEYS[pred[pos[r]]].lower(), end="", flush=True)
print("", flush=True)
