LogosAccessibleExpression commited on
Commit
c35602b
·
verified ·
1 Parent(s): 90fb2d4

Upload eq_fricative_eval_job.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. eq_fricative_eval_job.py +280 -0
eq_fricative_eval_job.py ADDED
@@ -0,0 +1,280 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # requires-python = ">=3.10"
3
+ # dependencies = [
4
+ # "torch",
5
+ # "transformers>=4.45",
6
+ # "peft",
7
+ # "accelerate",
8
+ # "jiwer",
9
+ # "av",
10
+ # "scipy",
11
+ # "numpy",
12
+ # "requests",
13
+ # "huggingface_hub",
14
+ # ]
15
+ # ///
16
+ """
17
+ High-shelf EQ ("fricative boost") sweep — HuggingFace Job script (uv run --script).
18
+
19
+ Question: does boosting everything above ~3 kHz (where /s ʃ f θ z/ energy lives)
20
+ before the log-mel front end make the personal turbo adapter more accurate?
21
+
22
+ Data: the speaker's recordings made on/after SINCE (the 2026-09-24 batch of 500).
23
+ The adapter was trained in June on the May recordings, so these are held out.
24
+ Refuses to run unless exactly EXPECTED rows match (guard against pulling the
25
+ wrong set).
26
+
27
+ Each clip is decoded once, then transcribed under every GAINS_DB condition
28
+ (0 dB = control). Processing per condition:
29
+ RBJ high-shelf biquad, corner SHELF_HZ, Q=0.707 (the shelf reaches half its
30
+ gain at SHELF_HZ and ~full gain by ~5 kHz), then RMS re-matched to the
31
+ original clip so the only change is spectral tilt, not loudness (the web app
32
+ RMS-normalizes to -18 dBFS anyway). A negative gain is a cut: the
33
+ dose-response control.
34
+
35
+ Because every clip appears in every condition, comparisons are PAIRED:
36
+ ΔWER vs 0 dB with a paired-bootstrap 95% CI, and clip-level better/worse counts.
37
+
38
+ Env: USER_ID, ADAPTER, SINCE, EXPECTED, GAINS_DB, SHELF_HZ, RESULTS_REPO
39
+ Secrets: HF_TOKEN, SUPABASE_SERVICE_ROLE_KEY
40
+ """
41
+ import csv, io, json, os, re, time
42
+ from concurrent.futures import ThreadPoolExecutor
43
+
44
+ import av
45
+ import jiwer
46
+ import numpy as np
47
+ import requests
48
+ import torch
49
+ from scipy.signal import lfilter
50
+
51
+ USER_ID = os.environ["USER_ID"]
52
+ ADAPTER = os.environ.get("ADAPTER", "LogosAccessibleExpression/logos-turbo-lora-d43df745")
53
+ BASE = os.environ.get("BASE", "openai/whisper-large-v3-turbo")
54
+ SINCE = os.environ.get("SINCE", "2026-09-01")
55
+ EXPECTED = int(os.environ.get("EXPECTED", "500"))
56
+ GAINS_DB = [float(g) for g in os.environ.get("GAINS_DB", "-6,0,3,6,9,12").split(",")]
57
+ SHELF_HZ = float(os.environ.get("SHELF_HZ", "3000"))
58
+ BATCH = int(os.environ.get("BATCH", "16"))
59
+ RESULTS_REPO = os.environ.get("RESULTS_REPO", "")
60
+ SUPABASE_URL = os.environ.get("SUPABASE_URL", "https://hehlulmegluxmtlupwgp.supabase.co")
61
+ SB_KEY = os.environ["SUPABASE_SERVICE_ROLE_KEY"]
62
+ SR = 16000
63
+ assert 0.0 in GAINS_DB, "0 dB control condition is required"
64
+
65
+ hdrs = {"apikey": SB_KEY, "Authorization": f"Bearer {SB_KEY}"}
66
+
67
+ # ---------------------------------------------------------------- data
68
+ recs = requests.get(
69
+ f"{SUPABASE_URL}/rest/v1/training_recordings", headers=hdrs, timeout=30,
70
+ params={"select": "id,audio_url,phrase_id,recorded_at",
71
+ "user_id": f"eq.{USER_ID}", "recorded_at": f"gte.{SINCE}"}).json()
72
+ phrases = requests.get(f"{SUPABASE_URL}/rest/v1/training_phrases", headers=hdrs,
73
+ timeout=30, params={"select": "id,text"}).json()
74
+ phrase_map = {p["id"]: p["text"] for p in phrases}
75
+ recs = [r for r in recs if r["phrase_id"] in phrase_map]
76
+ if len(recs) != EXPECTED:
77
+ raise SystemExit(f"refusing: expected {EXPECTED} labeled recordings since {SINCE}, found {len(recs)}")
78
+ print(f"{len(recs)} held-out recordings since {SINCE}", flush=True)
79
+
80
+
81
+ def decode(rec):
82
+ """Fetch and decode any container (webm/opus or wav) to 16 kHz mono float32."""
83
+ r = requests.get(rec["audio_url"].replace("/object/public/", "/object/"),
84
+ headers=hdrs, timeout=60)
85
+ r.raise_for_status()
86
+ with av.open(io.BytesIO(r.content)) as c:
87
+ st = c.streams.audio[0]
88
+ info = {"codec": st.codec_context.name, "src_rate": st.rate,
89
+ "bit_rate": st.bit_rate or c.bit_rate}
90
+ rs = av.AudioResampler(format="flt", layout="mono", rate=SR)
91
+ chunks = [f.to_ndarray().reshape(-1) for fr in c.decode(st) for f in rs.resample(fr)]
92
+ chunks += [f.to_ndarray().reshape(-1) for f in rs.resample(None)]
93
+ return np.concatenate(chunks).astype(np.float32), info
94
+
95
+
96
+ with ThreadPoolExecutor(16) as ex:
97
+ decoded = list(ex.map(decode, recs))
98
+ clips = [{"id": r["id"], "ref": phrase_map[r["phrase_id"]], "audio": a, **info}
99
+ for r, (a, info) in zip(recs, decoded)]
100
+ codecs = {}
101
+ for c in clips:
102
+ k = f'{c["codec"]}@{c["src_rate"]}Hz'
103
+ codecs[k] = codecs.get(k, 0) + 1
104
+ print("source formats:", codecs, flush=True)
105
+ print("bit rates (kbps):", sorted({round((c["bit_rate"] or 0) / 1000) for c in clips}), flush=True)
106
+
107
+ # ---------------------------------------------------------------- DSP
108
+ def high_shelf(gain_db, f0=SHELF_HZ, fs=SR):
109
+ """RBJ Audio-EQ-Cookbook high shelf, shelf slope S=1."""
110
+ A = 10 ** (gain_db / 40)
111
+ w0 = 2 * np.pi * f0 / fs
112
+ cw, sw = np.cos(w0), np.sin(w0)
113
+ alpha = sw / 2 * np.sqrt(2) # S=1
114
+ sA = 2 * np.sqrt(A) * alpha
115
+ b = [A * ((A + 1) + (A - 1) * cw + sA),
116
+ -2 * A * ((A - 1) + (A + 1) * cw),
117
+ A * ((A + 1) + (A - 1) * cw - sA)]
118
+ a = [(A + 1) - (A - 1) * cw + sA,
119
+ 2 * ((A - 1) - (A + 1) * cw),
120
+ (A + 1) - (A - 1) * cw - sA]
121
+ return np.array(b) / a[0], np.array(a) / a[0]
122
+
123
+
124
+ def apply_eq(x, gain_db):
125
+ if gain_db == 0:
126
+ return x
127
+ b, a = high_shelf(gain_db)
128
+ y = lfilter(b, a, x).astype(np.float32)
129
+ rms_x, rms_y = np.sqrt(np.mean(x ** 2)), np.sqrt(np.mean(y ** 2))
130
+ return y * (rms_x / rms_y) if rms_y > 0 else y
131
+
132
+
133
+ def band_balance_db(x):
134
+ """Fricative band (4.5-7.5 kHz) re 1 kHz band, on the louder half of frames
135
+ (speech, not silence) — same measure used for the badge mic investigation."""
136
+ n = 512
137
+ frames = np.lib.stride_tricks.sliding_window_view(x, n)[::256] * np.hanning(n)
138
+ if len(frames) == 0:
139
+ return float("nan")
140
+ P = np.abs(np.fft.rfft(frames, axis=1)) ** 2
141
+ e = P.sum(1)
142
+ P = P[e >= np.median(e)].mean(0)
143
+ f = np.fft.rfftfreq(n, 1 / SR)
144
+ band = lambda lo, hi: P[(f >= lo) & (f < hi)].mean()
145
+ return float(10 * np.log10(band(4500, 7500) / band(800, 1250) + 1e-20))
146
+
147
+
148
+ for g in GAINS_DB: # print the actual filter so the log documents what was applied
149
+ b, a = high_shelf(g)
150
+ from scipy.signal import freqz
151
+ _, h = freqz(b, a, worN=[500, 1000, 2000, 3000, 4000, 5000, 6000, 7500], fs=SR)
152
+ print(f"shelf {g:+.0f} dB @ {SHELF_HZ:.0f} Hz → gain at 0.5/1/2/3/4/5/6/7.5 kHz:",
153
+ " ".join(f"{20*np.log10(abs(v)):+.1f}" for v in h), flush=True)
154
+
155
+ # ---------------------------------------------------------------- model
156
+ from peft import PeftModel
157
+ from transformers import WhisperForConditionalGeneration, WhisperProcessor
158
+
159
+ print(f"loading {BASE} + {ADAPTER}", flush=True)
160
+ processor = WhisperProcessor.from_pretrained(BASE)
161
+ model = WhisperForConditionalGeneration.from_pretrained(BASE, torch_dtype=torch.float16)
162
+ model = PeftModel.from_pretrained(model, ADAPTER).merge_and_unload().to("cuda").eval()
163
+
164
+
165
+ def transcribe(audios):
166
+ feats = processor.feature_extractor(audios, sampling_rate=SR, return_tensors="pt")
167
+ with torch.no_grad():
168
+ out = model.generate(input_features=feats.input_features.to("cuda", torch.float16),
169
+ language="en", task="transcribe", max_new_tokens=128)
170
+ return [t.strip() for t in processor.batch_decode(out, skip_special_tokens=True)]
171
+
172
+ # ---------------------------------------------------------------- scoring
173
+ norm = jiwer.Compose([jiwer.ToLowerCase(), jiwer.RemovePunctuation(),
174
+ jiwer.RemoveMultipleSpaces(), jiwer.Strip()])
175
+ # Spelling proxy for words carrying a fricative (/s z f v θ ð ʃ ʒ tʃ dʒ/).
176
+ FRIC = re.compile(r"[szfvxj]|ch|th|ph|sh|c[eiy]|g[eiy]")
177
+
178
+
179
+ def score(ref, hyp):
180
+ r, h = norm(ref) or "<empty>", norm(hyp) or ""
181
+ o = jiwer.process_words(r, h if h else "<none>")
182
+ hits_fric = n_fric = 0
183
+ refw = o.references[0]
184
+ for ch in o.alignments[0]:
185
+ for w in refw[ch.ref_start_idx:ch.ref_end_idx]:
186
+ if FRIC.search(w):
187
+ n_fric += 1
188
+ hits_fric += ch.type == "equal"
189
+ return {"S": o.substitutions, "D": o.deletions, "I": o.insertions,
190
+ "N": len(refw), "fric_hit": hits_fric, "fric_n": n_fric}
191
+
192
+
193
+ t0 = time.time()
194
+ per = {g: [] for g in GAINS_DB}
195
+ for g in GAINS_DB:
196
+ audios = [apply_eq(c["audio"], g) for c in clips]
197
+ hyps = []
198
+ for i in range(0, len(audios), BATCH):
199
+ hyps += transcribe(audios[i:i + BATCH])
200
+ for c, a, h in zip(clips, audios, hyps):
201
+ per[g].append({"id": c["id"], "ref": c["ref"], "hyp": h,
202
+ "band_db": band_balance_db(a), **score(c["ref"], h)})
203
+ E = sum(x["S"] + x["D"] + x["I"] for x in per[g]); N = sum(x["N"] for x in per[g])
204
+ print(f"[{g:+.0f} dB] corpus WER {E/N:.4f} ({time.time()-t0:.0f}s)", flush=True)
205
+
206
+ # ---------------------------------------------------------------- stats
207
+ rng = np.random.default_rng(0)
208
+ B = 5000
209
+ idx = rng.integers(0, len(clips), size=(B, len(clips)))
210
+ err = {g: np.array([x["S"] + x["D"] + x["I"] for x in per[g]]) for g in GAINS_DB}
211
+ Nw = np.array([x["N"] for x in per[0.0]])
212
+
213
+
214
+ def corpus(e, ix=None):
215
+ return e.sum() / Nw.sum() if ix is None else e[ix].sum(1) / Nw[ix].sum(1)
216
+
217
+
218
+ summary = []
219
+ for g in GAINS_DB:
220
+ rows = per[g]
221
+ d = corpus(err[g], idx) - corpus(err[0.0], idx)
222
+ fh = sum(x["fric_hit"] for x in rows); fn = sum(x["fric_n"] for x in rows)
223
+ summary.append({
224
+ "gain_db": g,
225
+ "wer": corpus(err[g]),
226
+ "S": int(sum(x["S"] for x in rows)), "D": int(sum(x["D"] for x in rows)),
227
+ "I": int(sum(x["I"] for x in rows)), "N": int(Nw.sum()),
228
+ "exact_match": float(np.mean(err[g] == 0)),
229
+ "fricative_word_recall": fh / fn if fn else float("nan"),
230
+ "delta_wer_vs_0": corpus(err[g]) - corpus(err[0.0]),
231
+ "delta_ci95": [float(np.percentile(d, 2.5)), float(np.percentile(d, 97.5))],
232
+ "p_boost_better": float(np.mean(d < 0)),
233
+ "clips_better": int(np.sum(err[g] < err[0.0])),
234
+ "clips_worse": int(np.sum(err[g] > err[0.0])),
235
+ "median_band_db": float(np.nanmedian([x["band_db"] for x in rows])),
236
+ })
237
+
238
+ print("\n================ RESULTS ================")
239
+ print(f"adapter {ADAPTER} | {len(clips)} held-out clips | shelf @ {SHELF_HZ:.0f} Hz, RMS-matched")
240
+ print(f"{'gain':>5} {'WER':>7} {'ΔWER':>8} {'95% CI':>18} {'S/D/I':>12} {'exact':>6} "
241
+ f"{'fricW':>6} {'+/-clips':>9} {'band':>6}")
242
+ for s in summary:
243
+ print(f"{s['gain_db']:+5.0f} {s['wer']:7.4f} {s['delta_wer_vs_0']:+8.4f} "
244
+ f"[{s['delta_ci95'][0]:+.4f},{s['delta_ci95'][1]:+.4f}] "
245
+ f"{s['S']:>4}/{s['D']}/{s['I']:<4} {s['exact_match']:6.3f} "
246
+ f"{s['fricative_word_recall']:6.3f} {s['clips_better']:>4}/{s['clips_worse']:<4} "
247
+ f"{s['median_band_db']:6.1f}")
248
+ print("ΔWER < 0 = boost helps. CI straddling 0 = no detectable effect.")
249
+
250
+ best = min(summary, key=lambda s: s["wer"])
251
+ if best["gain_db"] != 0:
252
+ print(f"\nclips that changed at {best['gain_db']:+.0f} dB (up to 15):")
253
+ shown = 0
254
+ for a, b in zip(per[0.0], per[best["gain_db"]]):
255
+ if a["hyp"] != b["hyp"] and shown < 15:
256
+ shown += 1
257
+ print(f" ref: {a['ref']!r}\n 0dB: {a['hyp']!r}\n {best['gain_db']:+.0f}dB: {b['hyp']!r}")
258
+
259
+ # ---------------------------------------------------------------- persist
260
+ # Job logs expire; results go to a PRIVATE dataset repo.
261
+ if RESULTS_REPO:
262
+ from huggingface_hub import HfApi
263
+ api = HfApi(token=os.environ["HF_TOKEN"])
264
+ api.create_repo(RESULTS_REPO, repo_type="dataset", private=True, exist_ok=True)
265
+ stamp = time.strftime("%Y%m%d-%H%M%S")
266
+ buf = io.StringIO()
267
+ w = csv.DictWriter(buf, fieldnames=["gain_db", "id", "ref", "hyp", "S", "D", "I", "N",
268
+ "fric_hit", "fric_n", "band_db"])
269
+ w.writeheader()
270
+ for g in GAINS_DB:
271
+ for x in per[g]:
272
+ w.writerow({"gain_db": g, **x})
273
+ meta = {"adapter": ADAPTER, "base": BASE, "since": SINCE, "n_clips": len(clips),
274
+ "shelf_hz": SHELF_HZ, "gains_db": GAINS_DB, "rms_matched": True,
275
+ "source_formats": codecs, "summary": summary}
276
+ api.upload_file(path_or_fileobj=json.dumps(meta, indent=2).encode(),
277
+ path_in_repo=f"{stamp}/summary.json", repo_id=RESULTS_REPO, repo_type="dataset")
278
+ api.upload_file(path_or_fileobj=buf.getvalue().encode(),
279
+ path_in_repo=f"{stamp}/per_clip.csv", repo_id=RESULTS_REPO, repo_type="dataset")
280
+ print(f"results → https://huggingface.co/datasets/{RESULTS_REPO}/tree/main/{stamp}")