#!/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()