RIR-Bench-Hard / scripts /generate_rirs.py
mandipgoswami's picture
Add RIR-Bench-Hard: 2,600 adversarial synthetic RIRs, metadata, splits, eval harness, dataset card (part 8)
9f76cac verified
Raw History Blame Contribute Delete
24.8 kB
"""Generate the RIR-Bench-Hard adversarial room-impulse-response benchmark.
Produces ADVERSARIAL / HARD synthetic RIRs with pyroomacoustics across five
labeled categories that break dereverberation and far-field ASR systems:
1. long_t60 - large halls, long reverberation tails
2. coupled_rooms - two connected volumes -> non-exponential decay
3. near_field - source < 0.3 m from mic, extreme DRR
4. low_drr - far source + asymmetric absorption, very low DRR
5. non_shoebox - non-rectangular (L-shaped / polygonal) rooms, extruded 3D
For every RIR, REAL acoustic metadata is computed (no placeholders):
T60 (Schroeder backward integration, -5..-35 dB line fit),
DRR (direct window +/-2.5 ms around peak vs rest, dB),
C50 (10 log10 E[0-50ms] / E[50ms-end], dB),
EDT (slope 0..-10 dB extrapolated to a T60-equivalent, seconds).
Fully reproducible: every sample uses a fixed per-sample seed.
Outputs:
data/rirs/<category>/<id>.wav (mono, 16 kHz, int16, capped ~4 s)
metadata.csv
metadata.parquet
splits/{train,dev,test_hard}.txt
"""
from __future__ import annotations
import json
import math
import sys
from pathlib import Path
import numpy as np
import pandas as pd
import pyroomacoustics as pra
import soundfile as sf
from scipy.signal import fftconvolve # noqa: F401 (kept for downstream reuse)
BASE = Path(__file__).resolve().parents[1]
DATA = BASE / "data" / "rirs"
SPLITS = BASE / "splits"
FS = 16000
MAX_LEN_S = 4.0
MAX_LEN = int(FS * MAX_LEN_S)
# Target counts per category (balanced). ~2600 total RIRs.
PER_CATEGORY = {
"long_t60": 520,
"coupled_rooms": 520,
"near_field": 520,
"low_drr": 520,
"non_shoebox": 520,
}
GLOBAL_SEED = 20260101
CATEGORIES = list(PER_CATEGORY.keys())
# --------------------------------------------------------------------------
# Metric computation (all operate on a float RIR at sample rate FS)
# --------------------------------------------------------------------------
def _schroeder_db(rir: np.ndarray) -> np.ndarray:
"""Normalized Schroeder backward-integration energy decay curve in dB."""
energy = rir.astype(np.float64) ** 2
edc = np.cumsum(energy[::-1])[::-1]
edc = np.maximum(edc, 1e-20)
edc_db = 10.0 * np.log10(edc / edc[0])
return edc_db
# A reliable slope fit needs both a minimum fit span (so a 1-2 sample drop
# at 16 kHz cannot define a decay rate) and the decay actually reaching the
# lower edge of the fit region. These guards reject near-impulsive responses
# (e.g. extreme near-field RIRs) for which a decay-time estimate is undefined,
# and prevent the extrapolation blow-ups that produce 100+ s artifacts.
_MIN_FIT_SAMPLES = int(0.010 * FS) # >= 10 ms of decay to trust the slope
_T60_CEILING_S = 10.0 # physical sanity cap for the capture window
def measure_t60(rir: np.ndarray, fs: int = FS) -> float:
"""T60 via Schroeder EDC, linear fit on the -5 dB to -35 dB region (T30).
Returns NaN when the response does not decay far enough, or over a long
enough span, to fit a trustworthy slope.
"""
edc_db = _schroeder_db(rir)
if edc_db.min() > -35.0:
# Decay never reaches -35 dB in the captured window -> cannot fit T30.
return float("nan")
i5 = int(np.argmax(edc_db <= -5.0))
i35 = int(np.argmax(edc_db <= -35.0))
if i35 <= i5 or (i35 - i5) < _MIN_FIT_SAMPLES:
return float("nan")
x = np.arange(i5, i35) / fs
y = edc_db[i5:i35]
slope = np.polyfit(x, y, 1)[0] # dB/s, negative
if slope >= -1e-9:
return float("nan")
t60 = -60.0 / slope
if not np.isfinite(t60) or t60 > _T60_CEILING_S:
return float("nan")
return float(t60)
def measure_edt(rir: np.ndarray, fs: int = FS) -> float:
"""Early Decay Time: slope over 0..-10 dB extrapolated to a 60 dB decay.
Returns NaN for near-impulsive responses whose EDC crosses -10 dB in only
a handful of samples (the slope there is dominated by quantization and the
60 dB extrapolation is meaningless).
"""
edc_db = _schroeder_db(rir)
if edc_db.min() > -10.0:
return float("nan")
i0 = int(np.argmax(edc_db <= 0.0))
i10 = int(np.argmax(edc_db <= -10.0))
if i10 <= i0 or (i10 - i0) < _MIN_FIT_SAMPLES:
return float("nan")
x = np.arange(i0, i10) / fs
y = edc_db[i0:i10]
slope = np.polyfit(x, y, 1)[0]
if slope >= -1e-9:
return float("nan")
edt = -60.0 / slope
if not np.isfinite(edt) or edt > _T60_CEILING_S:
return float("nan")
return float(edt)
def measure_drr(rir: np.ndarray, fs: int = FS, win_ms: float = 2.5) -> float:
"""Direct-to-reverberant ratio: energy in +/- win_ms around the peak
vs. the rest of the response, in dB."""
peak = int(np.argmax(np.abs(rir)))
w = int(round(win_ms * 1e-3 * fs))
lo = max(0, peak - w)
hi = min(len(rir), peak + w + 1)
direct = np.sum(rir[lo:hi].astype(np.float64) ** 2)
total = np.sum(rir.astype(np.float64) ** 2)
reverb = max(total - direct, 1e-20)
direct = max(direct, 1e-20)
return float(10.0 * np.log10(direct / reverb))
def measure_c50(rir: np.ndarray, fs: int = FS) -> float:
"""Clarity C50: 10 log10 ( E[0..50ms] / E[50ms..end] ), referenced to the
direct arrival. Capped at +/-60 dB: a late energy that falls below the
1e-6 relative floor of a near-impulsive response yields a numerically
unbounded ratio, which is reported as the +60 dB clarity ceiling rather
than a spurious 200 dB artifact."""
peak = int(np.argmax(np.abs(rir)))
n50 = int(round(0.050 * fs))
early_end = min(len(rir), peak + n50)
early = np.sum(rir[peak:early_end].astype(np.float64) ** 2)
late = np.sum(rir[early_end:].astype(np.float64) ** 2)
total = max(early + late, 1e-20)
# Floor the late energy at 1e-6 of the total so an essentially silent tail
# cannot push clarity past a physically reportable ceiling.
late = max(late, 1e-6 * total)
early = max(early, 1e-20)
c50 = 10.0 * np.log10(early / late)
return float(np.clip(c50, -60.0, 60.0))
# --------------------------------------------------------------------------
# Room builders. Each returns (rir float32, meta dict).
# --------------------------------------------------------------------------
def _finalize_rir(room) -> np.ndarray:
room.compute_rir()
rir = np.asarray(room.rir[0][0], dtype=np.float64)
# Trim leading all-zero propagation delay but keep a small guard so the
# direct peak position is meaningful.
nz = np.flatnonzero(np.abs(rir) > 1e-9)
if nz.size:
start = max(0, nz[0] - 2)
rir = rir[start:]
if len(rir) > MAX_LEN:
rir = rir[:MAX_LEN]
m = np.max(np.abs(rir))
if m > 0:
rir = rir / m
return rir.astype(np.float64)
def build_long_t60(rng: np.random.Generator):
# Large hall. Low absorption -> long T60.
L = rng.uniform(15, 30)
W = rng.uniform(12, 24)
H = rng.uniform(6, 14)
absn = float(rng.uniform(0.02, 0.10))
rt60_target = float(rng.uniform(0.8, 2.5))
# Use Sabine to pick an absorption that lands near the target, then build
# with ray tracing for a realistic long tail.
e_abs, max_order = pra.inverse_sabine(rt60_target, [L, W, H])
room = pra.ShoeBox(
[L, W, H], fs=FS, materials=pra.Material(e_abs),
max_order=min(max_order, 3), ray_tracing=True, air_absorption=True,
)
room.set_ray_tracing(receiver_radius=0.5, n_rays=10000, energy_thres=1e-5)
src = np.array([rng.uniform(1, L - 1), rng.uniform(1, W - 1), rng.uniform(1, H - 1)])
mic = np.array([rng.uniform(1, L - 1), rng.uniform(1, W - 1), rng.uniform(1, H - 1)])
room.add_source(src.tolist())
room.add_microphone(mic.reshape(3, 1))
rir = _finalize_rir(room)
meta = dict(
room_type="shoebox_hall", room_dims=[round(L, 3), round(W, 3), round(H, 3)],
rt60_target=round(rt60_target, 4), source_pos=[round(v, 3) for v in src],
mic_pos=[round(v, 3) for v in mic], absorption=round(e_abs, 5),
n_reflections_order=int(min(max_order, 3)),
)
return rir, meta
def build_coupled_rooms(rng: np.random.Generator):
# Two connected volumes via an L-shaped / barbell polygon with a narrow
# aperture -> non-exponential (double-slope) decay. Asymmetric absorption
# per-wall emphasizes the coupling.
a = rng.uniform(6, 10) # room A side
b = rng.uniform(6, 10) # room B side
neck = rng.uniform(1.0, 2.5) # aperture width
gap = rng.uniform(1.5, 3.0) # corridor length
H = rng.uniform(3.0, 5.0)
y0 = 0.0
# Barbell: box A, narrow neck, box B.
corners = np.array([
[0, 0],
[a, 0],
[a, (b - neck) / 2 + y0],
[a + gap, (b - neck) / 2 + y0],
[a + gap, 0],
[a + gap + b, 0],
[a + gap + b, b],
[a + gap, b],
[a + gap, (b + neck) / 2 + y0],
[a, (b + neck) / 2 + y0],
[a, b],
[0, b],
]).T
absn = float(rng.uniform(0.08, 0.22))
room = pra.Room.from_corners(
corners, fs=FS, materials=pra.Material(absn),
max_order=6, air_absorption=True,
)
room.extrude(H, materials=pra.Material(float(rng.uniform(0.05, 0.2))))
# Source in room A, mic in room B (far side of the coupling aperture).
src = np.array([rng.uniform(0.8, a - 0.8), rng.uniform(0.8, b - 0.8), rng.uniform(1.0, H - 1.0)])
mic = np.array([a + gap + rng.uniform(0.8, b - 0.8), rng.uniform(0.8, b - 0.8), rng.uniform(1.0, H - 1.0)])
room.add_source(src.tolist())
room.add_microphone(mic.reshape(3, 1))
rir = _finalize_rir(room)
meta = dict(
room_type="coupled_barbell",
room_dims=[round(a + gap + b, 3), round(b, 3), round(H, 3)],
rt60_target=None, source_pos=[round(v, 3) for v in src],
mic_pos=[round(v, 3) for v in mic], absorption=round(absn, 5),
n_reflections_order=6,
)
return rir, meta
def build_near_field(rng: np.random.Generator):
# Source extremely close to the mic -> very high DRR. Small/medium room.
L = rng.uniform(3, 6)
W = rng.uniform(3, 6)
H = rng.uniform(2.5, 3.5)
absn = float(rng.uniform(0.1, 0.3))
room = pra.ShoeBox([L, W, H], fs=FS, materials=pra.Material(absn), max_order=12, air_absorption=True)
mic = np.array([rng.uniform(1, L - 1), rng.uniform(1, W - 1), rng.uniform(1, H - 1)])
dist = rng.uniform(0.05, 0.3)
direction = rng.normal(size=3)
direction /= np.linalg.norm(direction)
src = mic + direction * dist
# Keep source inside the room.
src = np.clip(src, [0.1, 0.1, 0.1], [L - 0.1, W - 0.1, H - 0.1])
room.add_source(src.tolist())
room.add_microphone(mic.reshape(3, 1))
rir = _finalize_rir(room)
meta = dict(
room_type="shoebox_small", room_dims=[round(L, 3), round(W, 3), round(H, 3)],
rt60_target=None, source_pos=[round(v, 3) for v in src],
mic_pos=[round(v, 3) for v in mic], absorption=round(absn, 5),
n_reflections_order=12,
)
return rir, meta
def build_low_drr(rng: np.random.Generator):
# Far source in a large, reflective room with asymmetric absorption -> the
# reverberant field dominates the direct path, very low DRR.
L = rng.uniform(10, 18)
W = rng.uniform(8, 14)
H = rng.uniform(4, 8)
# Highly asymmetric wall absorption: one pair reflective, floor absorptive.
absorption = {
"east": float(rng.uniform(0.02, 0.06)),
"west": float(rng.uniform(0.02, 0.06)),
"north": float(rng.uniform(0.4, 0.7)),
"south": float(rng.uniform(0.02, 0.06)),
"floor": float(rng.uniform(0.3, 0.6)),
"ceiling": float(rng.uniform(0.02, 0.06)),
}
mat = {k: pra.Material(v) for k, v in absorption.items()}
room = pra.ShoeBox([L, W, H], fs=FS, materials=mat, max_order=10, ray_tracing=True, air_absorption=True)
room.set_ray_tracing(receiver_radius=0.5, n_rays=8000, energy_thres=1e-5)
# Place source and mic far apart (near opposite walls).
src = np.array([rng.uniform(1, 2.5), rng.uniform(1, W - 1), rng.uniform(1, H - 1)])
mic = np.array([rng.uniform(L - 2.5, L - 1), rng.uniform(1, W - 1), rng.uniform(1, H - 1)])
room.add_source(src.tolist())
room.add_microphone(mic.reshape(3, 1))
rir = _finalize_rir(room)
meta = dict(
room_type="shoebox_asym", room_dims=[round(L, 3), round(W, 3), round(H, 3)],
rt60_target=None, source_pos=[round(v, 3) for v in src],
mic_pos=[round(v, 3) for v in mic],
absorption=round(float(np.mean(list(absorption.values()))), 5),
n_reflections_order=10,
)
return rir, meta
def build_non_shoebox(rng: np.random.Generator):
# Non-rectangular rooms: L-shaped or random convex-ish polygon, extruded.
H = rng.uniform(2.8, 5.0)
absn = float(rng.uniform(0.05, 0.2))
shape = rng.integers(0, 2)
if shape == 0:
# L-shape
a = rng.uniform(6, 12)
b = rng.uniform(6, 12)
c = rng.uniform(2.5, a - 1.0)
d = rng.uniform(2.5, b - 1.0)
corners = np.array([
[0, 0], [a, 0], [a, d], [c, d], [c, b], [0, b],
]).T
xmax, ymax = a, b
else:
# Pentagon/hexagon-ish irregular polygon generated by angular sweep.
n = int(rng.integers(5, 7))
radii = rng.uniform(3.5, 7.0, size=n)
angles = np.sort(rng.uniform(0, 2 * np.pi, size=n))
pts = np.stack([radii * np.cos(angles), radii * np.sin(angles)], axis=0)
pts -= pts.min(axis=1, keepdims=True) # shift to positive quadrant
corners = pts
xmax, ymax = pts[0].max(), pts[1].max()
room = pra.Room.from_corners(corners, fs=FS, materials=pra.Material(absn), max_order=8, air_absorption=True)
room.extrude(H, materials=pra.Material(absn))
def _inside_point():
for _ in range(200):
p = np.array([rng.uniform(0.5, xmax - 0.5), rng.uniform(0.5, ymax - 0.5)])
if room.is_inside(np.array([p[0], p[1], H / 2])):
return p
return np.array([xmax / 2, ymax / 2])
sp = _inside_point()
mp = _inside_point()
src = np.array([sp[0], sp[1], rng.uniform(1.0, H - 1.0)])
mic = np.array([mp[0], mp[1], rng.uniform(1.0, H - 1.0)])
room.add_source(src.tolist())
room.add_microphone(mic.reshape(3, 1))
rir = _finalize_rir(room)
meta = dict(
room_type="l_shape" if shape == 0 else "polygon",
room_dims=[round(float(xmax), 3), round(float(ymax), 3), round(H, 3)],
rt60_target=None, source_pos=[round(float(v), 3) for v in src],
mic_pos=[round(float(v), 3) for v in mic], absorption=round(absn, 5),
n_reflections_order=8,
)
return rir, meta
BUILDERS = {
"long_t60": build_long_t60,
"coupled_rooms": build_coupled_rooms,
"near_field": build_near_field,
"low_drr": build_low_drr,
"non_shoebox": build_non_shoebox,
}
def generate_one(category: str, idx: int):
seed = (GLOBAL_SEED + hash(category) % 100000 + idx * 7919) & 0x7FFFFFFF
rng = np.random.default_rng(seed)
for attempt in range(6):
try:
rir, meta = BUILDERS[category](rng)
except Exception as e: # noqa: BLE001
# Degenerate geometry/placement -> reseed deterministically and retry.
rng = np.random.default_rng((seed + 101 * (attempt + 1)) & 0x7FFFFFFF)
continue
if rir is None or len(rir) < 32 or not np.isfinite(rir).all():
rng = np.random.default_rng((seed + 211 * (attempt + 1)) & 0x7FFFFFFF)
continue
t60 = measure_t60(rir)
drr = measure_drr(rir)
c50 = measure_c50(rir)
edt = measure_edt(rir)
if not np.isfinite([drr, c50]).all():
rng = np.random.default_rng((seed + 317 * (attempt + 1)) & 0x7FFFFFFF)
continue
return rir, meta, dict(t60=t60, drr=drr, c50=c50, edt=edt), seed
return None
def main() -> None:
DATA.mkdir(parents=True, exist_ok=True)
SPLITS.mkdir(parents=True, exist_ok=True)
rows = []
total = sum(PER_CATEGORY.values())
done = 0
for category in CATEGORIES:
(DATA / category).mkdir(parents=True, exist_ok=True)
made = 0
attempt_idx = 0
target = PER_CATEGORY[category]
while made < target:
res = generate_one(category, attempt_idx)
attempt_idx += 1
if res is None:
if attempt_idx > target * 4:
print(f"WARN: {category} stalled at {made}/{target}")
break
continue
rir, meta, metrics, seed = res
rid = f"{category}_{made:04d}"
rel = f"data/rirs/{category}/{rid}.wav"
out = BASE / rel
# int16 WAV, 16 kHz.
pcm = np.clip(rir * 32767.0, -32768, 32767).astype(np.int16)
sf.write(out, pcm, FS, subtype="PCM_16")
rows.append(dict(
id=rid, category=category, filepath=rel, fs=FS,
room_type=meta["room_type"], room_dims=json.dumps(meta["room_dims"]),
rt60_target=meta["rt60_target"],
t60_measured=round(metrics["t60"], 5) if np.isfinite(metrics["t60"]) else None,
drr_db=round(metrics["drr"], 4),
c50_db=round(metrics["c50"], 4),
edt_s=round(metrics["edt"], 5) if np.isfinite(metrics["edt"]) else None,
source_pos=json.dumps(meta["source_pos"]),
mic_pos=json.dumps(meta["mic_pos"]),
absorption=meta["absorption"],
n_reflections_order=meta["n_reflections_order"],
seed=int(seed),
split="", # filled in Step 3
))
made += 1
done += 1
if done % 100 == 0:
print(f" progress {done}/{total} ({category} {made}/{target})")
print(f"category {category}: {made} RIRs")
df = pd.DataFrame(rows)
# ----- Quality control: flag physically implausible metadata ----------
# Every row is KEPT (nothing is silently dropped). A row is marked
# valid=False ONLY when a metric that IS reported is non-physical:
# - c50_db > 60 dB : late-energy underflow (clarity artifact)
# - edt_s > 3*t60 + 1 s : early-decay slope inconsistent with full decay
# - t60 < 0.05 s with a measured decay : no real reverberant tail
# A near-impulsive response (extreme near-field) legitimately has NO
# measurable decay time: its T60/EDT are null, but its DRR and C50 are
# fully physical, so the row stays valid with qc_flag='near_impulsive'.
# Those rows are usable for DRR/C50 evaluation; only decay-time ranges
# exclude them (via dropna), never the benchmark itself.
def _qc(row):
c50 = row["c50_db"]
edt = row["edt_s"]
t60 = row["t60_measured"]
# Non-physical reported values -> invalid.
if c50 is not None and not pd.isna(c50) and c50 >= 60.0:
return False, "c50_nonphysical"
if (not pd.isna(t60)) and t60 < 0.05:
return False, "t60_too_short"
if (not pd.isna(edt)) and (not pd.isna(t60)) and edt > (3.0 * t60 + 1.0):
return False, "edt_inconsistent"
# Undefined decay on a near-impulsive response: valid, but flagged.
if pd.isna(t60) or pd.isna(edt):
return True, "near_impulsive"
return True, "ok"
qc = df.apply(_qc, axis=1, result_type="expand")
df["valid"] = qc[0].astype(bool)
df["qc_flag"] = qc[1].astype(str)
n_flagged = int((~df["valid"]).sum())
print(f"\n=== QC === valid=False on {n_flagged}/{len(df)} rows "
f"(non-physical only); near_impulsive rows stay valid")
print("invalid by category/flag:")
print(df[~df["valid"]].groupby(["category", "qc_flag"]).size().to_string() or " (none)")
print("qc_flag distribution (all rows):")
print(df.groupby("qc_flag").size().to_string())
# ----- Step 3: reproducible splits (valid rows only) ------------------
# Hardness score: high T60 + low DRR are the extremes. Normalize over the
# VALID set and combine. test_hard gets the hardest ~15%; dev ~10%; train
# the rest. Flagged rows get split="" and are excluded from the leaderboard.
valid_mask = df["valid"].to_numpy()
t60 = df["t60_measured"].to_numpy(float)
t60_med = np.nanmedian(t60[valid_mask]) if valid_mask.any() else 0.3
t60_filled = np.where(np.isnan(t60), t60_med, t60)
drr = df["drr_db"].to_numpy(float)
def _z(x, m):
xm = x[m]
s = xm.std()
return (x - xm.mean()) / (s if s > 1e-9 else 1.0)
hardness = _z(t60_filled, valid_mask) - _z(drr, valid_mask)
df["_hardness"] = hardness
rng = np.random.default_rng(GLOBAL_SEED)
df["_rand"] = rng.random(len(df))
split = np.array([""] * len(df), dtype=object)
# Stratify per category so every split sees all five hard types.
for category in CATEGORIES:
cmask = ((df["category"] == category) & df["valid"]).to_numpy()
cidx = np.flatnonzero(cmask)
if len(cidx) == 0:
continue
split[cidx] = "train"
order = cidx[np.argsort(-df["_hardness"].to_numpy()[cidx])] # hardest first
n = len(order)
n_hard = max(1, int(round(0.15 * n)))
n_dev = max(1, int(round(0.10 * n)))
hard_ids = order[:n_hard]
rest = order[n_hard:]
# dev drawn pseudo-randomly from the non-hard remainder (reproducible).
rest_rand = rest[np.argsort(df["_rand"].to_numpy()[rest])]
dev_ids = rest_rand[:n_dev]
split[hard_ids] = "test_hard"
split[dev_ids] = "dev"
df["split"] = split
df = df.drop(columns=["_hardness", "_rand"])
# Write metadata.
cols = [
"id", "category", "filepath", "fs", "room_type", "room_dims",
"rt60_target", "t60_measured", "drr_db", "c50_db", "edt_s",
"source_pos", "mic_pos", "absorption", "n_reflections_order", "seed",
"split", "valid", "qc_flag",
]
df = df[cols]
df.to_csv(BASE / "metadata.csv", index=False)
df.to_parquet(BASE / "metadata.parquet", index=False)
for name in ("train", "dev", "test_hard"):
ids = df.loc[df["split"] == name, "id"].tolist()
(SPLITS / f"{name}.txt").write_text("\n".join(ids) + "\n", encoding="utf-8")
# ----- summary (VALID rows only for all reported ranges) --------------
valid = df[df["valid"]]
def rng_str(col):
s = valid[col].dropna()
return f"{s.min():.3f} .. {s.max():.3f} (median {s.median():.3f})"
print("\n=== GENERATION SUMMARY ===")
print(f"total RIRs: {len(df)} (valid={len(valid)}, flagged={len(df) - len(valid)})")
print("per category (all):")
print(df["category"].value_counts().to_string())
print("flagged per category:")
fl = df[~df["valid"]].groupby("category").size()
print(fl.to_string() if len(fl) else " (none)")
print("splits (valid only):")
print(df["split"].replace("", "unassigned").value_counts().to_string())
print("--- ranges on VALID rows only ---")
print(f"T60 (s): {rng_str('t60_measured')}")
print(f"DRR (dB): {rng_str('drr_db')}")
print(f"C50 (dB): {rng_str('c50_db')}")
print(f"EDT (s): {rng_str('edt_s')}")
# per-category extremes for the card, VALID rows only
def _mnmx(s):
s = s.dropna()
return [round(float(s.min()), 3), round(float(s.max()), 3), round(float(s.median()), 3)]
summary = {}
for category in CATEGORIES:
sub = valid[valid["category"] == category]
allsub = df[df["category"] == category]
summary[category] = dict(
n_total=int(len(allsub)), n_valid=int(len(sub)),
n_flagged=int(len(allsub) - len(sub)),
t60=_mnmx(sub["t60_measured"]), drr=_mnmx(sub["drr_db"]),
c50=_mnmx(sub["c50_db"]), edt=_mnmx(sub["edt_s"]),
n_train=int((sub["split"] == "train").sum()),
n_dev=int((sub["split"] == "dev").sum()),
n_test_hard=int((sub["split"] == "test_hard").sum()),
)
overall = dict(
total=int(len(df)), valid=int(len(valid)), flagged=int(len(df) - len(valid)),
t60=_mnmx(valid["t60_measured"]), drr=_mnmx(valid["drr_db"]),
c50=_mnmx(valid["c50_db"]), edt=_mnmx(valid["edt_s"]),
splits={k: int((valid["split"] == k).sum()) for k in ("train", "dev", "test_hard")},
)
(BASE / "scripts" / "_gen_summary.json").write_text(
json.dumps(dict(overall=overall, per_category=summary), indent=2), encoding="utf-8"
)
print("wrote metadata.csv, metadata.parquet, splits/, scripts/_gen_summary.json")
if __name__ == "__main__":
sys.exit(main())