File size: 24,539 Bytes
c22b544 | 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 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 | #!/usr/bin/env python3
"""
Complement-based GT evaluation: is the output closer to GT or its complement?
For each sample and each distractor time window, construct GT and complement
from spatially-rendered stems (no background noise in either):
REMOVED distractor:
GT = rendered speech only (distractor absent)
complement = rendered speech + distractor (distractor present)
PRESENT distractor:
GT = rendered speech + distractor (distractor present)
complement = rendered speech only (distractor absent)
success = sim(output, GT) > sim(output, complement)
This isolates the distractor-handling decision — background noise cannot
inflate accuracy because neither GT nor complement contains it.
Three metrics: SI-SNR, NXCorr, CLAP audio-audio similarity.
CSV output: event_detection_scores_complement.csv
Usage:
python evaluate_event_detection_complement.py \\
--eval_outputs_dir experiments_final/combined_v1/eval_outputs_test_3k/outputs \\
--mixtures_dir data/audio_mixtures_old \\
--output_csv experiments_final/combined_v1/eval_outputs_test_3k/event_detection_scores_complement.csv \\
[--use_cuda] [--batch_size 32] [--num_workers 6]
"""
import os
import csv
import sys
import json
import copy
import argparse
import threading
import concurrent.futures
from pathlib import Path
import numpy as np
import torch
import torch.nn.functional as F
import torchaudio
PROJECT_ROOT = Path(__file__).parent
sys.path.insert(0, str(PROJECT_ROOT))
SR = 44100
# ── CSV columns ────────────────────────────────────────────────────────────────
CSV_FIELDS = [
"sample_name",
"mixture_id",
"command_type",
"target_sources",
"distractor_key",
"distractor_name",
"distractor_start_s",
"distractor_end_s",
"gt_label", # REMOVED / PRESENT (from target_sources)
# Output vs GT (rendered stems)
"out_si_snr_db",
"out_nxcorr",
"out_clap_sim",
# Output vs complement (rendered stems)
"comp_si_snr_db",
"comp_nxcorr",
"comp_clap_sim",
# Per-metric binary success (1 = output closer to GT than complement)
"success_sisnr",
"success_nxcorr",
"success_clap",
"error",
]
_DEFAULT_SAMPLE_DIR = (
PROJECT_ROOT
/ "experiments_final/combined_v1/eval_outputs_test_3k/outputs"
/ "000_airport_1dist_005_rep1_v0_no_input"
)
_DEFAULT_WAV_5CH = (
PROJECT_ROOT
/ "data/audio_mixtures_old/test/airport_1dist_005_rep1_v0.wav"
)
# ═══════════════════════════════════════════════════════════════════════════════
# Audio helpers
# ═══════════════════════════════════════════════════════════════════════════════
def load_mono(path: Path) -> torch.Tensor:
audio, sr = torchaudio.load(str(path))
assert sr == SR, f"Expected {SR} Hz, got {sr} in {path}"
return audio.mean(dim=0, keepdim=True)
def crop_to_window(audio: torch.Tensor, start_s: float, end_s: float) -> torch.Tensor:
return audio[:, int(start_s * SR): int(end_s * SR)]
# ═══════════════════════════════════════════════════════════════════════════════
# Signal metrics
# ═══════════════════════════════════════════════════════════════════════════════
def si_snr(estimate: torch.Tensor, reference: torch.Tensor) -> float:
from torchmetrics.functional import scale_invariant_signal_noise_ratio
est = estimate.reshape(1, -1).float()
ref = reference.reshape(1, -1).float()
L = min(est.shape[-1], ref.shape[-1])
return scale_invariant_signal_noise_ratio(est[..., :L], ref[..., :L]).item()
def normalized_xcorr(a: torch.Tensor, b: torch.Tensor) -> float:
a = a.reshape(1, 1, -1).float()
b = b.reshape(1, 1, -1).float()
if a.shape[-1] < b.shape[-1]:
a, b = b, a
xcorr = F.conv1d(a, b)
norm = (a.norm() * b.norm()).clamp(min=1e-8)
return (xcorr.abs().max() / norm).item()
# ═══════════════════════════════════════════════════════════════════════════════
# Stem reconstruction (speech + distractors, spatially rendered)
# ═══════════════════════════════════════════════════════════════════════════════
# _load_frozen_simulator mutates a shared simulator instance, so concurrent
# calls from ThreadPoolExecutor cause race conditions. Serialise access.
_SIMULATOR_LOCK = threading.Lock()
def reconstruct_all_stems_mono(
wav_5ch_path: Path,
eval_metadata: dict,
dataset,
) -> dict:
"""
Reconstruct spatially-rendered, SNR-scaled mono stems for ALL sources
(speech + each distractor).
Returns {label: (1, T) mono tensor} where label is "speech" or a
distractor name like "dog".
"""
channels, file_sr = torchaudio.load(str(wav_5ch_path))
assert file_sr == SR
speech_np = channels[0].numpy()
distractor_names = eval_metadata.get("distractors", [])
distractor_np = {name: channels[2 + i].numpy()
for i, name in enumerate(distractor_names)}
snr_info = eval_metadata["snr_info"]
speech_scaled = speech_np * snr_info["speech"]["scaling_factor"]
dist_scaled = {name: stem * snr_info[name]["scaling_factor"]
for name, stem in distractor_np.items()}
spatial_labels = eval_metadata["spatial_labels"]
ordered_stems = [speech_scaled if lbl == "speech" else dist_scaled[lbl]
for lbl in spatial_labels]
event_audio = np.stack(ordered_stems, axis=0) # (N_sources, T)
meta_copy = dict(eval_metadata)
sofa_rel = meta_copy.get("sofa", "")
if sofa_rel and not os.path.isabs(sofa_rel):
meta_copy["sofa"] = str(PROJECT_ROOT / sofa_rel)
# Lock: _load_frozen_simulator mutates shared simulator state (source_positions,
# hrtf_indices, etc.). Must hold lock through simulate() too since the sim
# object is shared and not safely deepcopy-able (contains SOFA data).
with _SIMULATOR_LOCK:
sim = dataset._load_frozen_simulator(meta_copy, spatial_labels)
gt_audio = sim.simulate(event_audio)[..., :event_audio.shape[1]] # (N, 2, T)
result = {}
for i, label in enumerate(spatial_labels):
binaural = torch.from_numpy(gt_audio[i]).float() # (2, T)
result[label] = binaural.mean(dim=0, keepdim=True) # (1, T)
return result
# ═══════════════════════════════════════════════════════════════════════════════
# Batched CLAP (3N tensors per batch: output, GT, complement)
# ═══════════════════════════════════════════════════════════════════════════════
def _prep_clap_tensor(audio: torch.Tensor, target_len: int, use_cuda: bool) -> torch.Tensor:
x = audio.reshape(-1).float()
if x.shape[0] >= target_len:
x = x[:target_len]
else:
reps = int(np.ceil(target_len / x.shape[0]))
x = x.repeat(reps)[:target_len]
t = x.reshape(1, -1)
return t.cuda() if use_cuda else t
def flush_clap_batch(crops, clap_model):
"""
crops: list of (out_crop (1,T), gt_crop (1,T), comp_crop (1,T), row_dict)
Fills row["out_clap_sim"], row["comp_clap_sim"], row["success_clap"].
Batch layout: [out_0..out_N, gt_0..gt_N, comp_0..comp_N] → (3N, 1, L)
"""
if not crops:
return
target_len = clap_model.args.duration * clap_model.args.sampling_rate
use_cuda = getattr(clap_model, "use_cuda", False) and torch.cuda.is_available()
n = len(crops)
try:
out_prep = [_prep_clap_tensor(oc, target_len, use_cuda) for oc, gc, cc, _ in crops]
gt_prep = [_prep_clap_tensor(gc, target_len, use_cuda) for oc, gc, cc, _ in crops]
comp_prep = [_prep_clap_tensor(cc, target_len, use_cuda) for oc, gc, cc, _ in crops]
batch = torch.stack(out_prep + gt_prep + comp_prep, dim=0) # (3N, 1, L)
all_embs = clap_model._get_audio_embeddings(batch) # (3N, D)
for i, (oc, gc, cc, row) in enumerate(crops):
e_out = torch.tensor(all_embs[i]).unsqueeze(0)
e_gt = torch.tensor(all_embs[n + i]).unsqueeze(0)
e_comp = torch.tensor(all_embs[2 * n + i]).unsqueeze(0)
out_sim = F.cosine_similarity(e_out, e_gt).item()
comp_sim = F.cosine_similarity(e_out, e_comp).item()
row["out_clap_sim"] = f"{out_sim:.6f}"
row["comp_clap_sim"] = f"{comp_sim:.6f}"
row["success_clap"] = "1" if out_sim > comp_sim else "0"
except Exception as e:
for _, _, _, row in crops:
row["error"] = (row.get("error") or "").rstrip() + f" clap_batch:{e}"
# ═══════════════════════════════════════════════════════════════════════════════
# Per-sample processing
# ═══════════════════════════════════════════════════════════════════════════════
def _error_row(sample_name, mixture_id, command_type, target_sources, error):
row = {f: "" for f in CSV_FIELDS}
row["sample_name"] = sample_name
row["mixture_id"] = mixture_id
row["command_type"] = command_type
row["target_sources"] = target_sources
row["error"] = error
return row
def process_sample_signal_only(
sample_dir: Path,
mixtures_dir: Path,
dataset,
) -> tuple:
"""
Compute SI-SNR and NXCorr for output vs GT and output vs complement.
CLAP is deferred to flush_clap_batch.
Returns (rows, crops) where crops = (out_crop, gt_crop, comp_crop, row).
"""
with open(sample_dir / "metadata.json") as f:
meta = json.load(f)
command_type = meta["command_variant"]["command_type"]
target_sources_list = meta["command_variant"]["target_sources"]
target_sources = "|".join(target_sources_list)
mixture_id = meta.get("mixture_id", "")
split = meta.get("split", "test")
# ── Locate model output ──────────────────────────────────────────────────
output_files = sorted(sample_dir.glob("output_*.wav"))
if not output_files:
return ([_error_row(sample_dir.name, mixture_id, command_type,
target_sources, "Output WAV not found")], [])
# ── Locate 5-channel WAV ─────────────────────────────────────────────────
wav_5ch = mixtures_dir / split / f"{mixture_id}.wav"
if not wav_5ch.exists():
return ([_error_row(sample_dir.name, mixture_id, command_type,
target_sources, f"5ch WAV not found: {wav_5ch}")], [])
out_mono = load_mono(output_files[0])
# ── Reconstruct all rendered stems ───────────────────────────────────────
try:
stems = reconstruct_all_stems_mono(wav_5ch, meta, dataset)
except Exception as e:
return ([_error_row(sample_dir.name, mixture_id, command_type,
target_sources, f"stem reconstruction: {e}")], [])
if "speech" not in stems:
return ([_error_row(sample_dir.name, mixture_id, command_type,
target_sources, "speech stem missing")], [])
speech_mono = stems["speech"] # (1, T)
# ── Score each distractor ────────────────────────────────────────────────
audio_meta = meta.get("audio_metadata", {})
distractor_info = {k: v for k, v in audio_meta.items()
if k.startswith("distractor_")}
if not distractor_info:
return ([_error_row(sample_dir.name, mixture_id, command_type,
target_sources, "no distractor metadata")], [])
rows = []
crops = []
for dist_key in sorted(distractor_info.keys()):
info = distractor_info[dist_key]
name = info["name"]
t_start = info["mixture_start"]
t_end = info["mixture_end"]
gt_label = "PRESENT" if name in target_sources_list else "REMOVED"
row = {
"sample_name": sample_dir.name,
"mixture_id": mixture_id,
"command_type": command_type,
"target_sources": target_sources,
"distractor_key": dist_key,
"distractor_name": name,
"distractor_start_s": f"{t_start:.4f}",
"distractor_end_s": f"{t_end:.4f}",
"gt_label": gt_label,
"out_si_snr_db": "",
"out_nxcorr": "",
"out_clap_sim": "",
"comp_si_snr_db": "",
"comp_nxcorr": "",
"comp_clap_sim": "",
"success_sisnr": "",
"success_nxcorr": "",
"success_clap": "",
"error": "",
}
if name not in stems:
row["error"] = f"stem missing for '{name}'"
rows.append(row)
continue
# Crop rendered stems to distractor window
speech_crop = crop_to_window(speech_mono, t_start, t_end)
dist_crop = crop_to_window(stems[name], t_start, t_end)
out_crop = crop_to_window(out_mono, t_start, t_end)
# Build GT and complement
if gt_label == "REMOVED":
gt_crop = speech_crop # should be speech only
comp_crop = speech_crop + dist_crop # wrong answer: distractor present
else: # PRESENT
gt_crop = speech_crop + dist_crop # should have distractor
comp_crop = speech_crop # wrong answer: distractor absent
out_1d = out_crop.squeeze(0)
gt_1d = gt_crop.squeeze(0)
comp_1d = comp_crop.squeeze(0)
try:
out_s = si_snr(out_1d, gt_1d)
comp_s = si_snr(out_1d, comp_1d)
row["out_si_snr_db"] = f"{out_s:.4f}"
row["comp_si_snr_db"] = f"{comp_s:.4f}"
row["success_sisnr"] = "1" if out_s > comp_s else "0"
except Exception as e:
row["error"] += f"si_snr:{e} "
try:
out_x = normalized_xcorr(out_1d, gt_1d)
comp_x = normalized_xcorr(out_1d, comp_1d)
row["out_nxcorr"] = f"{out_x:.6f}"
row["comp_nxcorr"] = f"{comp_x:.6f}"
row["success_nxcorr"] = "1" if out_x > comp_x else "0"
except Exception as e:
row["error"] += f"nxcorr:{e} "
rows.append(row)
crops.append((out_crop, gt_crop, comp_crop, row))
return rows, crops
# ═══════════════════════════════════════════════════════════════════════════════
# Main
# ═══════════════════════════════════════════════════════════════════════════════
def main():
parser = argparse.ArgumentParser(
description="Complement-based eval: success = output closer to GT than complement.")
parser.add_argument("--use_cuda", action="store_true")
parser.add_argument("--eval_outputs_dir", type=str, default=None)
parser.add_argument("--mixtures_dir", type=str, default=None,
help="Path to audio_mixtures directory (contains train/test/)")
parser.add_argument("--output_csv", type=str, default=None)
parser.add_argument("--batch_size", type=int, default=32)
parser.add_argument("--num_workers", type=int, default=6)
args = parser.parse_args()
bulk_mode = args.eval_outputs_dir is not None
# ── Shared initialization ────────────────────────────────────────────────
mixtures_dir = Path(args.mixtures_dir) if args.mixtures_dir else _DEFAULT_WAV_5CH.parent.parent
print("Initializing dataset (for spatial rendering) ...")
from src.training.datasets.audio_mixtures_spatial import AudioMixturesSpatialDataset
dataset = AudioMixturesSpatialDataset(
mixtures_dir=str(mixtures_dir),
hrtf_dir=str(PROJECT_ROOT / "data" / "hrtf"),
dset="test",
sr=SR,
)
print("Initializing CLAP model ...")
from msclap import CLAP
clap_model = CLAP(version="2023", use_cuda=args.use_cuda)
# ── Single-sample mode ────────────────────────────────────────────────────
if not bulk_mode:
sample_dir = _DEFAULT_SAMPLE_DIR
wav_5ch = _DEFAULT_WAV_5CH
output_files = sorted(sample_dir.glob("output_*.wav"))
if not output_files:
print("ERROR: missing output wav in", sample_dir)
return
with open(sample_dir / "metadata.json") as f:
meta = json.load(f)
out_mono = load_mono(output_files[0])
stems = reconstruct_all_stems_mono(wav_5ch, meta, dataset)
if "speech" not in stems:
print("ERROR: speech stem reconstruction failed")
return
speech_mono = stems["speech"]
target_src_list = meta["command_variant"]["target_sources"]
dist_info = {k: v for k, v in meta.get("audio_metadata", {}).items()
if k.startswith("distractor_")}
print(f"\n{'═'*65}")
print(f"Sample : {sample_dir.name}")
print(f"Output : {output_files[0].name}")
print(f"Command : {meta['command_variant']['command_type']}")
print(f"Targets : {target_src_list}")
print(f"Stems : {list(stems.keys())}")
print(f"{'═'*65}")
target_len = clap_model.args.duration * clap_model.args.sampling_rate
use_cuda = getattr(clap_model, "use_cuda", False) and torch.cuda.is_available()
for dist_key in sorted(dist_info.keys()):
info = dist_info[dist_key]
name = info["name"]
t_start = info["mixture_start"]
t_end = info["mixture_end"]
gt_label = "PRESENT" if name in target_src_list else "REMOVED"
if name not in stems:
print(f"\n [SKIP] no stem for '{name}'")
continue
speech_crop = crop_to_window(speech_mono, t_start, t_end)
dist_crop = crop_to_window(stems[name], t_start, t_end)
out_crop = crop_to_window(out_mono, t_start, t_end)
if gt_label == "REMOVED":
gt_crop = speech_crop
comp_crop = speech_crop + dist_crop
else:
gt_crop = speech_crop + dist_crop
comp_crop = speech_crop
out_1d, gt_1d, comp_1d = out_crop.squeeze(0), gt_crop.squeeze(0), comp_crop.squeeze(0)
out_sisnr = si_snr(out_1d, gt_1d)
comp_sisnr = si_snr(out_1d, comp_1d)
out_nx = normalized_xcorr(out_1d, gt_1d)
comp_nx = normalized_xcorr(out_1d, comp_1d)
batch = torch.stack([
_prep_clap_tensor(out_crop, target_len, use_cuda),
_prep_clap_tensor(gt_crop, target_len, use_cuda),
_prep_clap_tensor(comp_crop, target_len, use_cuda),
], dim=0)
embs = clap_model._get_audio_embeddings(batch)
out_sim = F.cosine_similarity(
torch.tensor(embs[0]).unsqueeze(0),
torch.tensor(embs[1]).unsqueeze(0)).item()
comp_sim = F.cosine_similarity(
torch.tensor(embs[0]).unsqueeze(0),
torch.tensor(embs[2]).unsqueeze(0)).item()
tick = lambda a, b: "✓ SUCCESS" if a > b else "✗ FAILED "
print(f"\n Distractor : {name} ({t_start:.3f}s – {t_end:.3f}s) [{gt_label}]")
print(f" SI-SNR out→GT={out_sisnr:+7.2f}dB out→comp={comp_sisnr:+7.2f}dB → {tick(out_sisnr, comp_sisnr)}")
print(f" NXCorr out→GT={out_nx:7.4f} out→comp={comp_nx:7.4f} → {tick(out_nx, comp_nx)}")
print(f" CLAP out→GT={out_sim:7.4f} out→comp={comp_sim:7.4f} → {tick(out_sim, comp_sim)}")
print(f"\n{'═'*65}\nDone.")
return
# ── Bulk mode ─────────────────────────────────────────────────────────────
eval_outputs_dir = Path(args.eval_outputs_dir)
output_csv = Path(args.output_csv) if args.output_csv else \
eval_outputs_dir.parent / "event_detection_scores_complement.csv"
sample_dirs = sorted([d for d in eval_outputs_dir.iterdir() if d.is_dir()])
total = len(sample_dirs)
batch_size = args.batch_size
num_workers = args.num_workers
print(f"\nBulk mode: {total} samples batch_size={batch_size} num_workers={num_workers}")
print(f"Output: {output_csv}")
print("Metric: success = output closer to GT than complement (no background noise bias)")
output_csv.parent.mkdir(parents=True, exist_ok=True)
def _process_one(sd):
try:
return process_sample_signal_only(sd, mixtures_dir, dataset)
except Exception as e:
return [_error_row(sd.name, "", "", "", str(e))], []
with open(output_csv, "w", newline="") as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=CSV_FIELDS)
writer.writeheader()
csvfile.flush()
for chunk_start in range(0, total, batch_size):
chunk = sample_dirs[chunk_start: chunk_start + batch_size]
end = min(chunk_start + batch_size, total)
print(f"[{chunk_start+1:4d}–{end:4d}/{total}] signal metrics ...", flush=True)
with concurrent.futures.ThreadPoolExecutor(max_workers=num_workers) as ex:
results = list(ex.map(_process_one, chunk))
chunk_rows, chunk_crops = [], []
for rows, crops in results:
chunk_rows.extend(rows)
chunk_crops.extend(crops)
print(f" CLAP batch ({len(chunk_crops)} crops) ...", flush=True)
flush_clap_batch(chunk_crops, clap_model)
for row in chunk_rows:
writer.writerow({f: row.get(f, "") for f in CSV_FIELDS})
csvfile.flush()
print(f"\nDone. Scores written to {output_csv}")
if __name__ == "__main__":
main()
|