| |
| """ |
| Evaluate event detection by comparing the model output against the pre-rendered |
| GT binaural file (gt_*.wav) already present in each eval output folder. |
| |
| Unlike evaluate_event_detection.py, this script requires NO stem reconstruction, |
| NO 5-channel WAV, and NO dataset initialisation — the GT file is already in each |
| sample directory alongside the model output. |
| |
| Interpretation |
| -------------- |
| The GT file encodes exactly the sources the model should output for the given |
| command (speech + any distractors that should be kept). At the distractor time |
| window: |
| |
| • SI-SNR / NXCorr (output vs GT) |
| High → model output matches GT → model behaved correctly |
| Low → model output diverges from GT → model failed |
| |
| • CLAP audio-audio similarity (output crop vs GT crop) |
| High → output sounds like GT at that window → correct behaviour |
| Low → output diverges from GT at that window → failure |
| |
| CSV output: event_detection_scores_gt.csv (compare vs event_detection_scores.csv) |
| |
| Bulk usage: |
| python evaluate_event_detection_gt.py \\ |
| --eval_outputs_dir experiments_final/combined_v1/eval_outputs_test_3k/outputs \\ |
| --output_csv experiments_final/combined_v1/eval_outputs_test_3k/event_detection_scores_gt.csv \\ |
| [--use_cuda] [--batch_size 256] [--num_workers 6] |
| """ |
|
|
| import csv |
| import sys |
| import json |
| import argparse |
| 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 |
|
|
| |
| SISNR_THRESHOLD_DB = -10.0 |
| NXCORR_THRESHOLD = 0.10 |
| CLAP_THRESHOLD = 0.25 |
|
|
| |
| CSV_FIELDS = [ |
| "sample_name", |
| "mixture_id", |
| "command_type", |
| "target_sources", |
| "distractor_key", |
| "distractor_name", |
| "distractor_start_s", |
| "distractor_end_s", |
| "gt_label", |
| "si_snr_db", |
| "nxcorr", |
| "clap_sim", |
| "clap_label", |
| "error", |
| ] |
|
|
| |
| _DEFAULT_SAMPLE_DIR = ( |
| PROJECT_ROOT |
| / "experiments_final/combined_v1/eval_outputs_test_3k/outputs" |
| / "000_airport_1dist_005_rep1_v0_no_input" |
| ) |
|
|
|
|
| |
| |
| |
|
|
| def load_mono(path: Path) -> torch.Tensor: |
| """Load any-channel WAV and mix down to mono. Returns (1, T).""" |
| audio, sr = torchaudio.load(str(path)) |
| assert sr == SR, f"Expected {SR} Hz, got {sr} Hz in {path}" |
| return audio.mean(dim=0, keepdim=True) |
|
|
|
|
| def crop_to_window(audio: torch.Tensor, start_s: float, end_s: float) -> torch.Tensor: |
| """Crop (1, T) to [start_s, end_s) in seconds.""" |
| return audio[:, int(start_s * SR): int(end_s * SR)] |
|
|
|
|
| |
| |
| |
|
|
| def si_snr(estimate: torch.Tensor, reference: torch.Tensor) -> float: |
| """SI-SNR in dB between estimate and reference (1-D tensors).""" |
| 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: |
| """Peak normalized cross-correlation in [0, 1] between two 1-D tensors.""" |
| 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() |
|
|
|
|
| def binary_decision(score: float, threshold: float, higher_means_correct: bool) -> str: |
| correct = score > threshold if higher_means_correct else score < threshold |
| return "CORRECT ✓" if correct else "WRONG ✗" |
|
|
|
|
| |
| |
| |
|
|
| def _prep_clap_tensor(audio: torch.Tensor, target_len: int, use_cuda: bool) -> torch.Tensor: |
| """Replicate CLAP's load_audio_into_tensor pad/trim logic from a (1,T) 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): |
| """ |
| Batch CLAP audio-audio similarity: model output crop vs GT crop. |
| |
| crops : list of (model_crop (1,T), gt_crop (1,T), row_dict) |
| Fills row["clap_sim"] in-place. No temp files. |
| """ |
| 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: |
| model_prep = [_prep_clap_tensor(mc, target_len, use_cuda) for mc, gc, row in crops] |
| gt_prep = [_prep_clap_tensor(gc, target_len, use_cuda) for mc, gc, row in crops] |
| batch = torch.stack(model_prep + gt_prep, dim=0) |
|
|
| all_embs = clap_model._get_audio_embeddings(batch) |
|
|
| for i, (mc, gc, row) in enumerate(crops): |
| a = torch.tensor(all_embs[i]).unsqueeze(0) |
| b = torch.tensor(all_embs[n + i]).unsqueeze(0) |
| row["clap_sim"] = f"{F.cosine_similarity(a, b).item():.6f}" |
|
|
| except Exception as e: |
| for _, _, row in crops: |
| row["error"] = (row.get("error") or "").rstrip() + f" clap_batch:{e}" |
|
|
|
|
| |
| |
| |
|
|
| 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) -> tuple: |
| """ |
| Compute signal metrics (SI-SNR, NXCorr) for one sample using the GT wav |
| as the reference. CLAP is handled later in batch by flush_clap_batch. |
| |
| Returns (rows, crops) where crops contains (model_crop, gt_crop, row_dict). |
| """ |
| 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", "") |
|
|
| |
| output_files = sorted(sample_dir.glob("output_*.wav")) |
| if not output_files: |
| return ([_error_row(sample_dir.name, mixture_id, command_type, |
| target_sources, error="Output WAV not found")], []) |
|
|
| |
| gt_files = sorted(sample_dir.glob("gt_*.wav")) |
| if not gt_files: |
| return ([_error_row(sample_dir.name, mixture_id, command_type, |
| target_sources, error="GT WAV not found")], []) |
|
|
| model_out_mono = load_mono(output_files[0]) |
| gt_mono = load_mono(gt_files[0]) |
| gt_filename = gt_files[0].name |
|
|
| |
| 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, error="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, |
| "si_snr_db": "", |
| "nxcorr": "", |
| "clap_sim": "", |
| "clap_label": gt_filename, |
| "error": "", |
| } |
|
|
| model_crop = crop_to_window(model_out_mono, t_start, t_end) |
| gt_crop = crop_to_window(gt_mono, t_start, t_end) |
| model_1d = model_crop.squeeze(0) |
| gt_1d = gt_crop.squeeze(0) |
|
|
| try: |
| row["si_snr_db"] = f"{si_snr(model_1d, gt_1d):.4f}" |
| except Exception as e: |
| row["error"] += f"si_snr:{e} " |
|
|
| try: |
| row["nxcorr"] = f"{normalized_xcorr(model_1d, gt_1d):.6f}" |
| except Exception as e: |
| row["error"] += f"nxcorr:{e} " |
|
|
| rows.append(row) |
| crops.append((model_crop, gt_crop, row)) |
|
|
| return rows, crops |
|
|
|
|
| |
| |
| |
|
|
| def main(): |
| parser = argparse.ArgumentParser( |
| description="Evaluate event detection: model output vs GT wav.") |
| parser.add_argument("--use_cuda", action="store_true") |
| parser.add_argument("--eval_outputs_dir", type=str, default=None, |
| help="Bulk mode: directory containing eval sample subfolders") |
| parser.add_argument("--output_csv", type=str, default=None, |
| help="Path to write scores CSV") |
| parser.add_argument("--batch_size", type=int, default=256, |
| help="Audio crops per CLAP batch (default 256)") |
| parser.add_argument("--num_workers", type=int, default=6, |
| help="Worker threads for signal metrics (default 6)") |
| args = parser.parse_args() |
|
|
| bulk_mode = args.eval_outputs_dir is not None |
|
|
| print("Initializing CLAP model ...") |
| from msclap import CLAP |
| clap_model = CLAP(version="2023", use_cuda=args.use_cuda) |
|
|
| |
| |
| |
| if not bulk_mode: |
| sample_dir = _DEFAULT_SAMPLE_DIR |
|
|
| output_files = sorted(sample_dir.glob("output_*.wav")) |
| gt_files = sorted(sample_dir.glob("gt_*.wav")) |
|
|
| if not output_files or not gt_files: |
| print("ERROR: output or GT wav not found in", sample_dir) |
| return |
|
|
| with open(sample_dir / "metadata.json") as f: |
| meta = json.load(f) |
|
|
| model_out_mono = load_mono(output_files[0]) |
| gt_mono = load_mono(gt_files[0]) |
|
|
| audio_meta = meta.get("audio_metadata", {}) |
| distractor_info = {k: v for k, v in audio_meta.items() |
| if k.startswith("distractor_")} |
|
|
| print(f"\n{'═'*60}") |
| print(f"Sample : {sample_dir.name}") |
| print(f"Output : {output_files[0].name}") |
| print(f"GT : {gt_files[0].name}") |
| print(f"Command : {meta['command_variant']['command_type']}") |
| print(f"Targets : {meta['command_variant']['target_sources']}") |
| print(f"{'═'*60}") |
|
|
| 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 meta["command_variant"]["target_sources"] |
| else "REMOVED") |
|
|
| print(f"\n{'─'*60}") |
| print(f"Distractor : {name} ({t_start:.3f}s – {t_end:.3f}s) gt_label={gt_label}") |
| print() |
|
|
| model_crop = crop_to_window(model_out_mono, t_start, t_end) |
| gt_crop = crop_to_window(gt_mono, t_start, t_end) |
|
|
| sisnr_score = si_snr(model_crop.squeeze(0), gt_crop.squeeze(0)) |
| nxcorr_score = normalized_xcorr(model_crop.squeeze(0), gt_crop.squeeze(0)) |
|
|
| print(f" SI-SNR (output vs GT) : {sisnr_score:+7.2f} dB " |
| f"→ {binary_decision(sisnr_score, SISNR_THRESHOLD_DB, True)}") |
| print(f" NXCorr (output vs GT) : {nxcorr_score:8.4f} " |
| f"→ {binary_decision(nxcorr_score, NXCORR_THRESHOLD, True)}") |
|
|
| target_len = clap_model.args.duration * clap_model.args.sampling_rate |
| use_cuda = getattr(clap_model, "use_cuda", False) and torch.cuda.is_available() |
|
|
| try: |
| batch = torch.stack([ |
| _prep_clap_tensor(model_crop, target_len, use_cuda), |
| _prep_clap_tensor(gt_crop, target_len, use_cuda), |
| ], dim=0) |
| embs = clap_model._get_audio_embeddings(batch) |
| sim = F.cosine_similarity( |
| torch.tensor(embs[0]).unsqueeze(0), |
| torch.tensor(embs[1]).unsqueeze(0), |
| ).item() |
| print(f" CLAP (output vs GT) : {sim:8.4f} " |
| f"→ {binary_decision(sim, CLAP_THRESHOLD, True)}") |
| except Exception as e: |
| print(f" CLAP (output vs GT) : FAILED — {e}") |
|
|
| print(f"\n{'═'*60}\nDone.") |
| return |
|
|
| |
| |
| |
| 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_gt.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("Reference: GT wav in each sample folder (no stem reconstruction)") |
|
|
| output_csv.parent.mkdir(parents=True, exist_ok=True) |
|
|
| def _process_one(sd): |
| try: |
| return process_sample_signal_only(sd) |
| except Exception as e: |
| return [_error_row(sd.name, "", "", "", error=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() |
|
|