"""cine-23 demo: train a keystroke-from-sound classifier on the Durham paper's own public recordings
(JBFH-Dev/Keystroke-Datasets, MIT; MBPWavs = an iPhone 13 mini beside a 16-inch M1 Pro MacBook Pro, 36 keys x 25
presses), test it on presses it never heard, then spell a password from held-out presses only.

CPU only (CUDA_VISIBLE_DEVICES=""), the moss-sfx env (torch, librosa):
    CUDA_VISIBLE_DEVICES= tools/audio/envs/moss-sfx/bin/python train.py /tmp/c23/data OUT_DIR

Follows the paper where it says how (3.1-3.3): keystrokes isolated by an STFT energy threshold, fixed length 14400
samples (0.33 s); 64 mel bands, window 1024; time shift up to 40 % and SpecAugment-style masking of 10 % of each axis
as augmentation. The model is a small CNN of ours (not the paper's CoAtNet). Split: per key, 20 presses train, 5 test
(seeded), so the test set is 180 presses, as in the paper's Table 4.
"""
import json, os, sys, time
import numpy as np
import librosa
import torch
import torch.nn as nn
import torch.nn.functional as F

DATA, OUT = sys.argv[1], sys.argv[2]
os.makedirs(OUT, exist_ok=True)
KEYS = list("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ")
SR, LEN, N_PER = 44100, 14400, 25
torch.manual_seed(23); np.random.seed(23)
torch.set_num_threads(min(16, os.cpu_count() or 4))
log = open(os.path.join(OUT, "train_log.txt"), "w")


def say(*a):
    s = " ".join(str(x) for x in a)
    print(s); log.write(s + "\n"); log.flush()


def isolate(sig, n=N_PER):
    """the paper's isolator idea: STFT energy over a threshold marks a keystroke; we search the threshold that yields
    exactly n strokes (the file holds n presses), each LEN samples starting a little before the onset"""
    size, scan = 1024, 225
    energy = np.abs(np.sum(librosa.stft(sig, n_fft=size, hop_length=scan), axis=0)).astype(float)
    lo, hi = float(np.percentile(energy, 50)), float(energy.max())
    best = None
    for _ in range(60):
        th = (lo + hi) / 2
        on, last = [], -10 ** 9
        for i in np.where(energy > th)[0]:
            s = i * scan
            if s - last > SR * 0.12:                        # a new stroke at least 0.12 s after the last onset
                on.append(s); last = s
        if len(on) == n:
            best = on; break
        if len(on) > n:
            lo = th
        else:
            hi = th
        best = on
    strokes = []
    for s in best[:n]:
        a = max(0, s - 2400)
        x = sig[a:a + LEN]
        if len(x) < LEN:
            x = np.pad(x, (0, LEN - len(x)))
        strokes.append(x)
    return strokes, len(best)


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]


say("loading", DATA)
X, Y, RAW, counts = [], [], [], {}
for k, key in enumerate(KEYS):
    sig, sr = librosa.load(os.path.join(DATA, f"{key}.wav"), sr=SR, mono=True)
    st, found = isolate(sig)
    counts[key] = found
    for s in st:
        RAW.append(s); X.append(mel(s)); Y.append(k)
X, Y = np.stack(X), np.array(Y)
say("strokes", len(Y), "per key found:", counts)
np.save(os.path.join(OUT, "raw_strokes.npy"), np.stack(RAW).astype(np.float32))
np.save(os.path.join(OUT, "labels.npy"), Y)

rng = np.random.default_rng(23)
test_idx, train_idx = [], []
for k in range(len(KEYS)):
    idx = np.where(Y == k)[0]
    rng.shuffle(idx)
    test_idx += list(idx[:5]); train_idx += list(idx[5:])
test_idx, train_idx = np.array(test_idx), np.array(train_idx)
mu, sd = X[train_idx].mean(), X[train_idx].std()
Xn = (X - mu) / sd


def augment(b):
    b = b.clone()
    n, h, w = b.shape
    for i in range(n):
        sh = int(np.random.uniform(-0.4, 0.4) * w)          # time shift up to 40 %
        b[i] = torch.roll(b[i], sh, dims=1)
        f0 = np.random.randint(0, h - 6); b[i, f0:f0 + 6, :] = 0      # mask ~10 % of the mel bands
        t0 = np.random.randint(0, w - 6); b[i, :, t0:t0 + 6] = 0      # and ~10 % of the time frames
    return b


class Net(nn.Module):
    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))))


net = Net()
Xt = torch.tensor(Xn)
Yt = torch.tensor(Y)
EPOCHS = int(os.environ.get("EPOCHS", "160"))
opt = torch.optim.AdamW(net.parameters(), lr=2e-3, weight_decay=1e-3)
sched = torch.optim.lr_scheduler.OneCycleLR(opt, max_lr=3e-3, total_steps=EPOCHS * int(np.ceil(len(train_idx) / 64)))
curve = []
t0 = time.time()
for ep in range(1, EPOCHS + 1):
    net.train()
    perm = np.random.permutation(train_idx)
    tl, tc = 0.0, 0
    for i in range(0, len(perm), 64):
        bi = perm[i:i + 64]
        xb, yb = augment(Xt[bi]), Yt[bi]
        out = net(xb)
        loss = F.cross_entropy(out, yb, label_smoothing=0.05)
        opt.zero_grad(); loss.backward(); opt.step(); sched.step()
        tl += loss.item() * len(bi); tc += (out.argmax(1) == yb).sum().item()
    if ep % 5 == 0 or ep == 1:
        net.eval()
        with torch.no_grad():
            te = (net(Xt[test_idx]).argmax(1) == Yt[test_idx]).float().mean().item()
        curve.append((ep, tl / len(train_idx), tc / len(train_idx), te))
        say(f"epoch {ep:4d}  loss {tl / len(train_idx):.3f}  train acc {tc / len(train_idx):.3f}  "
            f"test acc {te:.3f}  ({time.time() - t0:.0f} s)")

net.eval()
with torch.no_grad():
    probs = F.softmax(net(Xt[test_idx]), 1).numpy()
pred = probs.argmax(1)
acc = float((pred == Y[test_idx]).mean())
wrong = [(KEYS[Y[i]], KEYS[p]) for i, p in zip(test_idx, pred) if KEYS[Y[i]] != KEYS[p]]
say(f"TEST: {int((pred == Y[test_idx]).sum())}/{len(test_idx)} held-out presses correct = {acc * 100:.1f} %")
say("wrong (true -> guessed):", wrong)
torch.save(net.state_dict(), os.path.join(OUT, "model.pt"))

# a password spelled only from held-out presses (each press used once), read back by the model
PW = os.environ.get("PW", "kestrel42")
used, picks = set(), []
for ch in PW.upper():
    k = KEYS.index(ch)
    cand = [j for j, i in enumerate(test_idx) if Y[i] == k and j not in used]
    j = cand[0]; used.add(j); picks.append(j)
read = "".join(KEYS[pred[j]] for j in picks).lower()
conf = [float(probs[j].max()) for j in picks]
say(f"PASSWORD typed (held-out presses): {PW}")
say(f"PASSWORD read back from sound:     {read}   confidences {[round(c, 2) for c in conf]}")
json.dump({"keys": KEYS, "test_presses": len(test_idx), "correct": int((pred == Y[test_idx]).sum()), "accuracy": acc,
           "wrong": wrong, "curve": curve, "epochs": EPOCHS, "password": PW, "read": read, "conf": conf,
           "pw_test_rows": [int(test_idx[j]) for j in picks], "isolated_per_key": counts,
           "train_presses": len(train_idx), "seconds": round(time.time() - t0, 1)},
          open(os.path.join(OUT, "result.json"), "w"), indent=1)
np.save(os.path.join(OUT, "test_idx.npy"), test_idx)
np.save(os.path.join(OUT, "test_probs.npy"), probs)
