training-scripts / eq_fricative_eval_job.py
LogosAccessibleExpression's picture
Upload eq_fricative_eval_job.py with huggingface_hub
c35602b verified
Raw History Blame Contribute Delete
12.4 kB
# /// script
# requires-python = ">=3.10"
# dependencies = [
# "torch",
# "transformers>=4.45",
# "peft",
# "accelerate",
# "jiwer",
# "av",
# "scipy",
# "numpy",
# "requests",
# "huggingface_hub",
# ]
# ///
"""
High-shelf EQ ("fricative boost") sweep — HuggingFace Job script (uv run --script).
Question: does boosting everything above ~3 kHz (where /s ʃ f θ z/ energy lives)
before the log-mel front end make the personal turbo adapter more accurate?
Data: the speaker's recordings made on/after SINCE (the 2026-09-24 batch of 500).
The adapter was trained in June on the May recordings, so these are held out.
Refuses to run unless exactly EXPECTED rows match (guard against pulling the
wrong set).
Each clip is decoded once, then transcribed under every GAINS_DB condition
(0 dB = control). Processing per condition:
RBJ high-shelf biquad, corner SHELF_HZ, Q=0.707 (the shelf reaches half its
gain at SHELF_HZ and ~full gain by ~5 kHz), then RMS re-matched to the
original clip so the only change is spectral tilt, not loudness (the web app
RMS-normalizes to -18 dBFS anyway). A negative gain is a cut: the
dose-response control.
Because every clip appears in every condition, comparisons are PAIRED:
ΔWER vs 0 dB with a paired-bootstrap 95% CI, and clip-level better/worse counts.
Env: USER_ID, ADAPTER, SINCE, EXPECTED, GAINS_DB, SHELF_HZ, RESULTS_REPO
Secrets: HF_TOKEN, SUPABASE_SERVICE_ROLE_KEY
"""
import csv, io, json, os, re, time
from concurrent.futures import ThreadPoolExecutor
import av
import jiwer
import numpy as np
import requests
import torch
from scipy.signal import lfilter
USER_ID = os.environ["USER_ID"]
ADAPTER = os.environ.get("ADAPTER", "LogosAccessibleExpression/logos-turbo-lora-d43df745")
BASE = os.environ.get("BASE", "openai/whisper-large-v3-turbo")
SINCE = os.environ.get("SINCE", "2026-09-01")
EXPECTED = int(os.environ.get("EXPECTED", "500"))
GAINS_DB = [float(g) for g in os.environ.get("GAINS_DB", "-6,0,3,6,9,12").split(",")]
SHELF_HZ = float(os.environ.get("SHELF_HZ", "3000"))
BATCH = int(os.environ.get("BATCH", "16"))
RESULTS_REPO = os.environ.get("RESULTS_REPO", "")
SUPABASE_URL = os.environ.get("SUPABASE_URL", "https://hehlulmegluxmtlupwgp.supabase.co")
SB_KEY = os.environ["SUPABASE_SERVICE_ROLE_KEY"]
SR = 16000
assert 0.0 in GAINS_DB, "0 dB control condition is required"
hdrs = {"apikey": SB_KEY, "Authorization": f"Bearer {SB_KEY}"}
# ---------------------------------------------------------------- data
recs = requests.get(
f"{SUPABASE_URL}/rest/v1/training_recordings", headers=hdrs, timeout=30,
params={"select": "id,audio_url,phrase_id,recorded_at",
"user_id": f"eq.{USER_ID}", "recorded_at": f"gte.{SINCE}"}).json()
phrases = requests.get(f"{SUPABASE_URL}/rest/v1/training_phrases", headers=hdrs,
timeout=30, params={"select": "id,text"}).json()
phrase_map = {p["id"]: p["text"] for p in phrases}
recs = [r for r in recs if r["phrase_id"] in phrase_map]
if len(recs) != EXPECTED:
raise SystemExit(f"refusing: expected {EXPECTED} labeled recordings since {SINCE}, found {len(recs)}")
print(f"{len(recs)} held-out recordings since {SINCE}", flush=True)
def decode(rec):
"""Fetch and decode any container (webm/opus or wav) to 16 kHz mono float32."""
r = requests.get(rec["audio_url"].replace("/object/public/", "/object/"),
headers=hdrs, timeout=60)
r.raise_for_status()
with av.open(io.BytesIO(r.content)) as c:
st = c.streams.audio[0]
info = {"codec": st.codec_context.name, "src_rate": st.rate,
"bit_rate": st.bit_rate or c.bit_rate}
rs = av.AudioResampler(format="flt", layout="mono", rate=SR)
chunks = [f.to_ndarray().reshape(-1) for fr in c.decode(st) for f in rs.resample(fr)]
chunks += [f.to_ndarray().reshape(-1) for f in rs.resample(None)]
return np.concatenate(chunks).astype(np.float32), info
with ThreadPoolExecutor(16) as ex:
decoded = list(ex.map(decode, recs))
clips = [{"id": r["id"], "ref": phrase_map[r["phrase_id"]], "audio": a, **info}
for r, (a, info) in zip(recs, decoded)]
codecs = {}
for c in clips:
k = f'{c["codec"]}@{c["src_rate"]}Hz'
codecs[k] = codecs.get(k, 0) + 1
print("source formats:", codecs, flush=True)
print("bit rates (kbps):", sorted({round((c["bit_rate"] or 0) / 1000) for c in clips}), flush=True)
# ---------------------------------------------------------------- DSP
def high_shelf(gain_db, f0=SHELF_HZ, fs=SR):
"""RBJ Audio-EQ-Cookbook high shelf, shelf slope S=1."""
A = 10 ** (gain_db / 40)
w0 = 2 * np.pi * f0 / fs
cw, sw = np.cos(w0), np.sin(w0)
alpha = sw / 2 * np.sqrt(2) # S=1
sA = 2 * np.sqrt(A) * alpha
b = [A * ((A + 1) + (A - 1) * cw + sA),
-2 * A * ((A - 1) + (A + 1) * cw),
A * ((A + 1) + (A - 1) * cw - sA)]
a = [(A + 1) - (A - 1) * cw + sA,
2 * ((A - 1) - (A + 1) * cw),
(A + 1) - (A - 1) * cw - sA]
return np.array(b) / a[0], np.array(a) / a[0]
def apply_eq(x, gain_db):
if gain_db == 0:
return x
b, a = high_shelf(gain_db)
y = lfilter(b, a, x).astype(np.float32)
rms_x, rms_y = np.sqrt(np.mean(x ** 2)), np.sqrt(np.mean(y ** 2))
return y * (rms_x / rms_y) if rms_y > 0 else y
def band_balance_db(x):
"""Fricative band (4.5-7.5 kHz) re 1 kHz band, on the louder half of frames
(speech, not silence) — same measure used for the badge mic investigation."""
n = 512
frames = np.lib.stride_tricks.sliding_window_view(x, n)[::256] * np.hanning(n)
if len(frames) == 0:
return float("nan")
P = np.abs(np.fft.rfft(frames, axis=1)) ** 2
e = P.sum(1)
P = P[e >= np.median(e)].mean(0)
f = np.fft.rfftfreq(n, 1 / SR)
band = lambda lo, hi: P[(f >= lo) & (f < hi)].mean()
return float(10 * np.log10(band(4500, 7500) / band(800, 1250) + 1e-20))
for g in GAINS_DB: # print the actual filter so the log documents what was applied
b, a = high_shelf(g)
from scipy.signal import freqz
_, h = freqz(b, a, worN=[500, 1000, 2000, 3000, 4000, 5000, 6000, 7500], fs=SR)
print(f"shelf {g:+.0f} dB @ {SHELF_HZ:.0f} Hz → gain at 0.5/1/2/3/4/5/6/7.5 kHz:",
" ".join(f"{20*np.log10(abs(v)):+.1f}" for v in h), flush=True)
# ---------------------------------------------------------------- model
from peft import PeftModel
from transformers import WhisperForConditionalGeneration, WhisperProcessor
print(f"loading {BASE} + {ADAPTER}", flush=True)
processor = WhisperProcessor.from_pretrained(BASE)
model = WhisperForConditionalGeneration.from_pretrained(BASE, torch_dtype=torch.float16)
model = PeftModel.from_pretrained(model, ADAPTER).merge_and_unload().to("cuda").eval()
def transcribe(audios):
feats = processor.feature_extractor(audios, sampling_rate=SR, return_tensors="pt")
with torch.no_grad():
out = model.generate(input_features=feats.input_features.to("cuda", torch.float16),
language="en", task="transcribe", max_new_tokens=128)
return [t.strip() for t in processor.batch_decode(out, skip_special_tokens=True)]
# ---------------------------------------------------------------- scoring
norm = jiwer.Compose([jiwer.ToLowerCase(), jiwer.RemovePunctuation(),
jiwer.RemoveMultipleSpaces(), jiwer.Strip()])
# Spelling proxy for words carrying a fricative (/s z f v θ ð ʃ ʒ tʃ dʒ/).
FRIC = re.compile(r"[szfvxj]|ch|th|ph|sh|c[eiy]|g[eiy]")
def score(ref, hyp):
r, h = norm(ref) or "<empty>", norm(hyp) or ""
o = jiwer.process_words(r, h if h else "<none>")
hits_fric = n_fric = 0
refw = o.references[0]
for ch in o.alignments[0]:
for w in refw[ch.ref_start_idx:ch.ref_end_idx]:
if FRIC.search(w):
n_fric += 1
hits_fric += ch.type == "equal"
return {"S": o.substitutions, "D": o.deletions, "I": o.insertions,
"N": len(refw), "fric_hit": hits_fric, "fric_n": n_fric}
t0 = time.time()
per = {g: [] for g in GAINS_DB}
for g in GAINS_DB:
audios = [apply_eq(c["audio"], g) for c in clips]
hyps = []
for i in range(0, len(audios), BATCH):
hyps += transcribe(audios[i:i + BATCH])
for c, a, h in zip(clips, audios, hyps):
per[g].append({"id": c["id"], "ref": c["ref"], "hyp": h,
"band_db": band_balance_db(a), **score(c["ref"], h)})
E = sum(x["S"] + x["D"] + x["I"] for x in per[g]); N = sum(x["N"] for x in per[g])
print(f"[{g:+.0f} dB] corpus WER {E/N:.4f} ({time.time()-t0:.0f}s)", flush=True)
# ---------------------------------------------------------------- stats
rng = np.random.default_rng(0)
B = 5000
idx = rng.integers(0, len(clips), size=(B, len(clips)))
err = {g: np.array([x["S"] + x["D"] + x["I"] for x in per[g]]) for g in GAINS_DB}
Nw = np.array([x["N"] for x in per[0.0]])
def corpus(e, ix=None):
return e.sum() / Nw.sum() if ix is None else e[ix].sum(1) / Nw[ix].sum(1)
summary = []
for g in GAINS_DB:
rows = per[g]
d = corpus(err[g], idx) - corpus(err[0.0], idx)
fh = sum(x["fric_hit"] for x in rows); fn = sum(x["fric_n"] for x in rows)
summary.append({
"gain_db": g,
"wer": corpus(err[g]),
"S": int(sum(x["S"] for x in rows)), "D": int(sum(x["D"] for x in rows)),
"I": int(sum(x["I"] for x in rows)), "N": int(Nw.sum()),
"exact_match": float(np.mean(err[g] == 0)),
"fricative_word_recall": fh / fn if fn else float("nan"),
"delta_wer_vs_0": corpus(err[g]) - corpus(err[0.0]),
"delta_ci95": [float(np.percentile(d, 2.5)), float(np.percentile(d, 97.5))],
"p_boost_better": float(np.mean(d < 0)),
"clips_better": int(np.sum(err[g] < err[0.0])),
"clips_worse": int(np.sum(err[g] > err[0.0])),
"median_band_db": float(np.nanmedian([x["band_db"] for x in rows])),
})
print("\n================ RESULTS ================")
print(f"adapter {ADAPTER} | {len(clips)} held-out clips | shelf @ {SHELF_HZ:.0f} Hz, RMS-matched")
print(f"{'gain':>5} {'WER':>7} {'ΔWER':>8} {'95% CI':>18} {'S/D/I':>12} {'exact':>6} "
f"{'fricW':>6} {'+/-clips':>9} {'band':>6}")
for s in summary:
print(f"{s['gain_db']:+5.0f} {s['wer']:7.4f} {s['delta_wer_vs_0']:+8.4f} "
f"[{s['delta_ci95'][0]:+.4f},{s['delta_ci95'][1]:+.4f}] "
f"{s['S']:>4}/{s['D']}/{s['I']:<4} {s['exact_match']:6.3f} "
f"{s['fricative_word_recall']:6.3f} {s['clips_better']:>4}/{s['clips_worse']:<4} "
f"{s['median_band_db']:6.1f}")
print("ΔWER < 0 = boost helps. CI straddling 0 = no detectable effect.")
best = min(summary, key=lambda s: s["wer"])
if best["gain_db"] != 0:
print(f"\nclips that changed at {best['gain_db']:+.0f} dB (up to 15):")
shown = 0
for a, b in zip(per[0.0], per[best["gain_db"]]):
if a["hyp"] != b["hyp"] and shown < 15:
shown += 1
print(f" ref: {a['ref']!r}\n 0dB: {a['hyp']!r}\n {best['gain_db']:+.0f}dB: {b['hyp']!r}")
# ---------------------------------------------------------------- persist
# Job logs expire; results go to a PRIVATE dataset repo.
if RESULTS_REPO:
from huggingface_hub import HfApi
api = HfApi(token=os.environ["HF_TOKEN"])
api.create_repo(RESULTS_REPO, repo_type="dataset", private=True, exist_ok=True)
stamp = time.strftime("%Y%m%d-%H%M%S")
buf = io.StringIO()
w = csv.DictWriter(buf, fieldnames=["gain_db", "id", "ref", "hyp", "S", "D", "I", "N",
"fric_hit", "fric_n", "band_db"])
w.writeheader()
for g in GAINS_DB:
for x in per[g]:
w.writerow({"gain_db": g, **x})
meta = {"adapter": ADAPTER, "base": BASE, "since": SINCE, "n_clips": len(clips),
"shelf_hz": SHELF_HZ, "gains_db": GAINS_DB, "rms_matched": True,
"source_formats": codecs, "summary": summary}
api.upload_file(path_or_fileobj=json.dumps(meta, indent=2).encode(),
path_in_repo=f"{stamp}/summary.json", repo_id=RESULTS_REPO, repo_type="dataset")
api.upload_file(path_or_fileobj=buf.getvalue().encode(),
path_in_repo=f"{stamp}/per_clip.csv", repo_id=RESULTS_REPO, repo_type="dataset")
print(f"results → https://huggingface.co/datasets/{RESULTS_REPO}/tree/main/{stamp}")