File size: 5,852 Bytes
a1fe2e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#!/usr/bin/env python3
"""End-of-keyword: learned end head vs RULE-BASED energy (volume) detectors, same clips, same metrics.
Conditions: silence (keyword then silence), command (VN command 0-150 ms after keyword), car_command (command mix
through a held-out Aurora car IR + real room noise 5-20 dB SNR). All methods start at the wake frame and are capped.
Rules (causal, 10 ms frame energy E in dB of the received audio):
  drop D   : first frame after wake with E < P - D, P = max E over [wake-500 ms, now] (keyword loudness)
  drop D h3: same but 3 consecutive frames (30 ms hold)
  adapt a  : threshold = F + a*(P-F), F = 10th percentile of E over the 1 s before the keyword (noise floor); 3-frame smoothed E
    EH_V2=1 EH_V3=1 python end_rules.py WAKE_CKPT HEAD N T [max_clips]"""
import json, os, sys
import numpy as np, torch
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
os.environ["FAR_SET"] = "car"; _a = sys.argv; sys.argv = [_a[0], "x"]; import vf_far as FAR; sys.argv = _a
import end_head as EH
from end_head import audio, load_checkpoint, read_manifest, K, SR
CK, HD, N, T = sys.argv[1], sys.argv[2], int(sys.argv[3]), float(sys.argv[4]); MAXC = int(sys.argv[5]) if len(sys.argv) > 5 else 10**9
CAP = 0.25
sys.argv = [sys.argv[0], "runs/en13_ft2_causal_mel80/best.pt", "stream", "/dev/null"]; sys.path.insert(0, K + "/plans_local"); import stream_eval as S
torch.set_num_threads(8)
model, fe, cfg, _, _ = load_checkpoint(CK, torch.device("cpu")); z = torch.load(HD); head = EH.mk_head(z["dim"]); head.load_state_dict(z["head"]); head.eval()
rows = [json.loads(l) for l in open(K + "/data/aurora/manifest_en4_real85.jsonl")]
clips = [r["audio"] for r in rows if r["label"] == "aurora" and r.get("split") == "dev" and "fish_s2" in r["audio"]][:MAXC]
vs = [i.audio for i in read_manifest(K + "/data/aurora/manifest_hp6.jsonl") if i.split == "dev" and i.kind == "negative_speech"]
rng = np.random.default_rng(0)
METH = ["head p>=0.4 cap250", "head lookback150"] + [f"drop {d} dB" for d in (10, 15, 20, 25)] + [f"drop {d} dB h3" for d in (10, 15, 20, 25)] + [f"adapt {a}" for a in (0.2, 0.3, 0.5)] + ["hold 150 ms"]
res = {c: [] for c in ("silence", "command", "car_command")}
for ci, p in enumerate(clips):
    w0 = audio.load(p, SR); se = S.speech_end(w0, drop=40, floor=-60)
    if se is None: continue
    c = audio.load(vs[int(rng.integers(len(vs)))], SR, start=0.0, duration=0.9); gap = rng.uniform(0, 0.15)
    for cond in res:
        w = np.concatenate([np.zeros(SR, np.float32), w0[:int(se * SR)], np.zeros(SR, np.float32)]); kend = 1.0 + se
        if cond != "silence":
            g = int((kend + gap) * SR); cc = c[:len(w) - g]
            ref = np.sqrt(np.mean(w0 ** 2) + 1e-10); rms = np.sqrt(np.mean(cc ** 2) + 1e-10)
            if rms > 1e-4: w[g:g + len(cc)] += cc * ref / rms
        if cond == "car_command": w = FAR.far(w.astype(np.float32), ci).astype(np.float32)
        x = (w + 1e-3 * rng.standard_normal(len(w))).astype(np.float32)
        with torch.no_grad():
            m = fe(torch.from_numpy(x)[None]); m = m.unsqueeze(1) if m.dim() == 3 else m
            f = model.frame_features(m); L = model.classifier(f.unsqueeze(2)).squeeze(2)[0].numpy(); pe = torch.sigmoid(head(EH.feats(model, m)))[0].numpy()
        d = L[1] - L[0]; c_ = np.concatenate([[0.0], np.cumsum(d, dtype=np.float64)]); ks = np.arange(146, len(d)); lo = np.maximum(0, ks + 1 - N)
        t = 1 / (1 + np.exp(-(c_[ks + 1] - c_[lo]) / (ks + 1 - lo))); h = np.flatnonzero(t >= T)
        if not len(h): continue
        fr = ks[h[0]]; fire = (fr + 1) * 0.01; capf = fr + int(CAP * 100)
        nf = len(x) // 160; E = 10 * np.log10(np.array([np.mean(x[i * 160:(i + 1) * 160] ** 2) for i in range(nf)]) + 1e-12)
        Es = np.convolve(E, np.ones(3) / 3, mode="full")[:nf]  # causal 3-frame smoothing
        def first(cond_fn, hold=1):
            run = 0
            for j in range(fr, min(capf, nf - 1) + 1):
                run = run + 1 if cond_fn(j) else 0
                if run >= hold: return (j + 1) * 0.01
            return fire + CAP
        r = []
        g2 = np.flatnonzero(pe[fr:capf + 1] >= 0.4); hd = (fr + g2[0] + 1) * 0.01 if len(g2) else fire + CAP; r.append(hd - kend)
        # lookback: if p_end is already >= 0.4 at the wake, walk back (<=150 ms) to where it last crossed 0.4 (audio is in the ring buffer)
        if pe[fr] >= 0.4:
            j = fr
            while j > fr - 15 and pe[j - 1] >= 0.4: j -= 1
            r.append((j + 1) * 0.01 - kend)
        else: r.append(hd - kend)
        Pk = lambda j: E[max(0, fr - 50):j + 1].max()
        for D in (10, 15, 20, 25): r.append(first(lambda j, D=D: E[j] < Pk(j) - D) - kend)
        for D in (10, 15, 20, 25): r.append(first(lambda j, D=D: E[j] < Pk(j) - D, 3) - kend)
        kst = max(0, fr - 150); F = np.percentile(E[max(0, kst - 100):kst + 1], 10)
        for a in (0.2, 0.3, 0.5): r.append(first(lambda j, a=a: Es[j] < F + a * (Pk(j) - F)) - kend)
        r.append(fire + 0.15 - kend)
        res[cond].append(r)
    if ci % 500 == 0: print(ci, flush=True)
out = {}
for cond, v in res.items():
    v = np.array(v) * 1e3; out[cond] = {}
    for col, name in enumerate(METH):
        q = np.percentile(v[:, col], [10, 50, 90]); s = {"n": len(v), "p10": q[0], "p50": q[1], "p90": q[2], "within50": 100 * np.mean(np.abs(v[:, col]) <= 50),
             "before_end": 100 * np.mean(v[:, col] < 0), "late150": 100 * np.mean(v[:, col] > 150), "mae": np.mean(np.abs(v[:, col]))}
        out[cond][name] = s
        print(f"{cond:12s} {name:20s} n={s['n']} p10 {q[0]:5.0f} p50 {q[1]:5.0f} p90 {q[2]:5.0f} | within50 {s['within50']:3.0f}%  before_end {s['before_end']:3.0f}%  late150 {s['late150']:3.0f}%  MAE {s['mae']:4.0f} ms", flush=True)
json.dump(out, open(K + "/runs/vf_eval/" + os.environ.get("ER_OUT", "end_rules.json"), "w"), indent=1)