← zidingz.com

fidelity.py

← Gallery · core.py · scenes.py · render.py · fidelity.py · export_live.py

"""Ablation: degrade a clean recording in one controlled way at a time and measure how much
each feature the scenes consume moves away from the clean-reference value.
fidelity.py REF_AUDIO [INTERFERER_AUDIO] -> prints a table and writes out/fidelity.json"""
import sys, os, json, subprocess, numpy as np
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import core, scenes
from scipy import signal, ndimage
SR = core.SR
rng = np.random.default_rng(0)

def ff(x, af=None, codec=None):
    """Round-trip x through an ffmpeg audio filter and/or a lossy codec."""
    raw = x.astype(np.float32).tobytes(); base = ["ffmpeg", "-v", "error", "-f", "f32le", "-ar", str(SR), "-ac", "1", "-i", "-"]
    if codec:
        tmp = f"/tmp/_fid.{codec[0]}"
        subprocess.run(base + (["-af", af] if af else []) + codec[1] + ["-y", tmp], input=raw, check=True)
        out = subprocess.run(["ffmpeg", "-v", "error", "-i", tmp, "-ac", "1", "-ar", str(SR), "-f", "f32le", "-"], capture_output=True, check=True).stdout
    else:
        out = subprocess.run(base + ["-af", af, "-ar", str(SR), "-f", "f32le", "-"], input=raw, capture_output=True, check=True).stdout
    y = np.frombuffer(out, np.float32).copy(); n = len(x)
    return np.pad(y, (0, max(0, n - len(y))))[:n]

def noise(x, snr_db, colour="white"):
    n = rng.standard_normal(len(x)).astype(np.float32)
    if colour == "pink": n = signal.lfilter([0.049922, -0.095993, 0.050612, -0.004408], [1, -2.494956, 2.017265, -0.522189], n)
    p = np.mean(x ** 2); return x + n * np.sqrt(p / 10 ** (snr_db / 10) / np.mean(n ** 2))

def wow(x, depth, f=0.55):
    """Speed wobble: instantaneous speed 1 + depth*sin(2 pi f t). 78 rpm = 1.3 Hz once-per-rev; warps add slower terms."""
    t = np.arange(len(x)) / SR
    return np.interp(t + depth / (2 * np.pi * f) * (1 - np.cos(2 * np.pi * f * t)), t, x).astype(np.float32)

def reverb(x, rt60):
    n = int(rt60 * SR); h = rng.standard_normal(n) * 10 ** (-3 * np.arange(n) / n); h[0] = 0; h *= 0.5 / np.sqrt((h ** 2).sum()); h[0] = 1
    return signal.fftconvolve(x, h)[:len(x)].astype(np.float32)

def feats(x):
    A = core.Analysis(x)
    env = scenes.key_env(A, thr=0.3, release=0.35, top=7, dyn=0.75)
    r, _ = core.ridge(A.W, 36 * core.BPS, 75 * core.BPS, max_jump=4, jump_cost=1.2)
    f = ndimage.gaussian_filter1d(A.flux, 1)
    pk, _ = signal.find_peaks(f, height=0.25, distance=4, prominence=0.12)
    return dict(env=env, chroma=A.chroma_h, flux=A.flux, onsets=pk, ridge=r, loud=A.loud)

def compare(R, F):
    T = min(R["env"].shape[1], F["env"].shape[1]); o = {}
    a, b = R["env"][:, :T], F["env"][:, :T]
    o["env_r"] = float(np.corrcoef(a.ravel(), b.ravel())[0, 1])
    A_, B_ = a > 0.1, b > 0.1; act = (A_ | B_).sum(0) > 0
    o["keys_jaccard"] = float(((A_ & B_).sum(0)[act] / (A_ | B_).sum(0)[act]).mean())
    c1, c2 = R["chroma"][:, :T], F["chroma"][:, :T]
    o["chroma_cos"] = float(((c1 * c2).sum(0) / (np.linalg.norm(c1, axis=0) * np.linalg.norm(c2, axis=0) + 1e-9)).mean())
    hit = sum(np.any(np.abs(F["onsets"] - p) <= 2) for p in R["onsets"]); prec = sum(np.any(np.abs(R["onsets"] - p) <= 2) for p in F["onsets"])
    rc, pr = hit / max(len(R["onsets"]), 1), prec / max(len(F["onsets"]), 1)
    o["onset_f1"] = float(2 * rc * pr / max(rc + pr, 1e-9))
    o["ridge_agree"] = float((np.abs(R["ridge"][:T] - F["ridge"][:T]) <= core.BPS).mean())
    return o

if __name__ == "__main__":
    x = core.load(sys.argv[1]); R = feats(x)
    V = {"identical (sanity)": x.copy()}
    for fc in (8000, 5000, 3000): V[f"low-pass {fc} Hz"] = ff(x, f"lowpass=f={fc}:p=2,lowpass=f={fc}:p=2")
    V["sample rate 11.025 kHz"] = ff(x, "aresample=11025")
    V["sample rate 8 kHz"] = ff(x, "aresample=8000")
    V["8-bit quantisation"] = np.round(x / np.abs(x).max() * 127) / 127 * np.abs(x).max()
    for s in (40, 30, 20, 10): V[f"white noise, SNR {s} dB"] = noise(x, s)
    V["pink noise, SNR 20 dB"] = noise(x, 20, "pink")
    V["MP3 32 kbps"] = ff(x, codec=("mp3", ["-c:a", "libmp3lame", "-b:a", "32k"]))
    V["Opus 12 kbps"] = ff(x, codec=("opus", ["-c:a", "libopus", "-b:a", "12k"]))
    for d in (0.003, 0.01): V[f"wow ±{d*100:.1f}% speed"] = wow(x, d)
    for rt in (1.0, 2.5): V[f"added hall reverb, RT60 {rt} s"] = reverb(x, rt)
    V["heavy compression 8:1"] = ff(x, "acompressor=threshold=-30dB:ratio=8:attack=5:release=80:makeup=6")
    if len(sys.argv) > 2:
        y = core.load(sys.argv[2], 60, len(x) / SR + 1)[:len(x)]; y = np.pad(y, (0, len(x) - len(y)))
        for g in (-12, 0):
            V[f"other music mixed in at {g:+d} dB"] = x + y * np.sqrt(np.mean(x ** 2) / np.mean(y ** 2)) * 10 ** (g / 20)
    V["78 rpm simulation (5.5 kHz, SNR 25 dB pink, wow 0.3%)"] = noise(wow(ff(x, "highpass=f=80,lowpass=f=5500:p=2,lowpass=f=5500:p=2"), 0.003), 25, "pink")
    rows = []
    print(f"{'variant':52s} env_r  keysJ  chroma onsetF1 ridge")
    for name, y in V.items():
        o = compare(R, feats(y.astype(np.float32))); rows.append({"variant": name, **o})
        print(f"{name:52s} {o['env_r']:.2f}   {o['keys_jaccard']:.2f}   {o['chroma_cos']:.2f}   {o['onset_f1']:.2f}    {o['ridge_agree']:.2f}", flush=True)
    json.dump({"reference": os.path.basename(sys.argv[1]), "n_onsets": int(len(R["onsets"])), "rows": rows}, open("out/fidelity.json", "w"), indent=1)