#!/usr/bin/env python3 """ Evaluate whether a model successfully removed a distractor event from its output. Two detection methods: A) Signal-level : SI-SNR and normalized cross-correlation between the model output and the reconstructed, spatialized distractor stem. B) CLAP-level : cosine similarity between the CLAP audio embedding of the model output crop and the CLAP text embedding of the distractor class label. Detection is performed only over the time window where the distractor is active in the mixture (from mixture_start / mixture_end in audio_metadata). Modes ----- Single-sample (default, for debugging): python evaluate_event_detection.py [--use_cuda] Bulk (score all samples, write raw CSV — no thresholding): python evaluate_event_detection.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/event_detection_scores.csv \\ [--use_cuda] [--batch_size 32] [--num_workers 4] Bulk-mode speedups vs single-sample mode: * Text embeddings are pre-computed once for all ~30 distractor classes. * Audio embeddings are batched: batch_size audio crops → one CLAP forward pass. * Signal metrics (stem reconstruction + SI-SNR/NXCorr) run in parallel via num_workers threads, overlapping with CLAP GPU work. """ import os import csv import sys import json import argparse import tempfile import concurrent.futures from pathlib import Path import numpy as np import torch import torch.nn.functional as F import torchaudio # ── Project root & import path ──────────────────────────────────────────────── PROJECT_ROOT = Path(__file__).parent sys.path.insert(0, str(PROJECT_ROOT)) # ── Default single-sample paths (used when --eval_outputs_dir is not given) ── _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" ) SR = 44100 # ── Decision thresholds (only used in single-sample mode for display) ──────── SISNR_THRESHOLD_DB = -10.0 NXCORR_THRESHOLD = 0.10 CLAP_THRESHOLD = 0.25 # ── CLAP text labels per distractor class ──────────────────────────────────── # Covers all classes appearing in test_3k, OOD_backgrounds, OOD_both, OOD_distractors. DISTRACTOR_CLAP_LABELS = { # ── original / in-distribution classes (unchanged) ─────────────────────── "dog": "dog barking", "cat": "cat meowing", "baby_cry": "baby crying", "birds_chirping": "birds chirping", "cricket": "cricket chirping", "cock_a_doodle_doo": "rooster crowing", "speech": "person speaking", "singing": "person singing", "music": "music playing", "gunshot": "gunshot", "glass_breaking": "glass breaking", "computer_typing": "keyboard typing", "toilet_flush": "toilet flushing", "hammer": "hammering", "siren": "siren wailing", "alarm_clock": "alarm clock ringing", "car_horn": "car horn honking", "ocean": "ocean waves", "thunderstorm": "thunderstorm", "door_knock": "door knocking", "footsteps": "footsteps walking", # ── OOD_backgrounds classes ─────────────────────────────────────────────── "applause": "crowd applauding and clapping", "boom": "loud boom or explosion", "car_alarm": "car alarm sounding", "cellphone_buzz_vibrating_alert": "cellphone buzzing vibration alert", "cough": "person coughing", "drill": "power drill running", "engine": "engine running", "fire_alarm": "fire alarm beeping", "fireworks": "fireworks exploding", "helicopter": "helicopter flying overhead", "jackhammer": "jackhammer drilling", "ringtone": "phone ringing", "slam": "door slamming shut", "sneeze": "person sneezing", # ── OOD_both and OOD_distractors classes ───────────────────────────────── "aircraft": "aircraft flying overhead", "breathing": "heavy breathing", "bus": "bus engine and doors", "buzzer": "electric buzzer sounding", "chainsaw": "chainsaw cutting", "cheering": "crowd cheering", "ding_dong": "doorbell ding dong", "doorbell": "doorbell ringing", "frog": "frog croaking", "hair_dryer": "hair dryer blowing", "howl": "animal howling", "lawn_mower": "lawn mower running", "moo": "cow mooing", "pour": "liquid pouring", "printer": "printer printing", "sink_filling_or_washing": "water running in sink", "skateboard": "skateboard rolling", "snoring": "person snoring", "squeak": "squeaking sound", "telephone_bell_ringing": "telephone bell ringing", "thump_thud": "heavy thump or thud", "tick_tock": "clock ticking", "train_horn": "train horn blowing", "velcro_hook_and_loop_fastener": "velcro ripping apart", } # ── 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 if distractor not in target_sources, else PRESENT "si_snr_db", "nxcorr", "clap_sim", "clap_label", "error", ] # ═══════════════════════════════════════════════════════════════════════════════ # Audio helpers # ═══════════════════════════════════════════════════════════════════════════════ 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. Returns (1, N).""" return audio[:, int(start_s * SR): int(end_s * SR)] # ═══════════════════════════════════════════════════════════════════════════════ # Metrics (accept pre-cropped 1-D tensors) # ═══════════════════════════════════════════════════════════════════════════════ def si_snr(estimate: torch.Tensor, reference: torch.Tensor) -> float: """ Scale-Invariant SNR in dB between estimate and reference (both 1-D). Higher → estimate contains more of reference (distractor more present). """ 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. Higher → signals more similar (distractor more present). """ 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 clap_audio_similarity( model_crop_mono: torch.Tensor, stem_crop_mono: torch.Tensor, clap_model, # pre-initialized CLAP instance ) -> float: """ Cosine similarity between CLAP audio embeddings of the model output crop and the reconstructed distractor stem crop. Higher → distractor more present in the model output. Used only in single-sample mode; bulk mode uses flush_clap_batch instead. """ tmp_model = tmp_stem = None try: with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as f: tmp_model = f.name with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as f: tmp_stem = f.name torchaudio.save(tmp_model, model_crop_mono.float(), SR) torchaudio.save(tmp_stem, stem_crop_mono.float(), SR) embs = clap_model.get_audio_embeddings([tmp_model, tmp_stem]) # (2, D) sim = F.cosine_similarity( torch.tensor(embs[0]).unsqueeze(0), torch.tensor(embs[1]).unsqueeze(0), ).item() finally: for p in [tmp_model, tmp_stem]: if p: try: os.unlink(p) except Exception: pass return sim def binary_decision(score: float, threshold: float, higher_means_present: bool) -> str: present = score > threshold if higher_means_present else score < threshold return "PRESENT" if present else "REMOVED" # ═══════════════════════════════════════════════════════════════════════════════ # Distractor stem reconstruction # ═══════════════════════════════════════════════════════════════════════════════ def reconstruct_distractor_stems_mono( wav_5ch_path: Path, eval_metadata: dict, dataset, # pre-initialized AudioMixturesSpatialDataset ) -> dict: """ Reconstruct each distractor's spatially-rendered, SNR-scaled mono stem. Uses the frozen spatial + SNR metadata in eval_metadata (from metadata.json) so the reconstruction exactly matches what the model received as input. Returns ------- dict {distractor_name: (1, T) mono tensor} """ # ── Load 5-channel audio ────────────────────────────────────────────────── 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)} # ── Apply frozen SNR scaling ────────────────────────────────────────────── 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()} # ── Build ordered source array matching spatial_labels ──────────────────── 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) # ── Patch sofa path to absolute so simulator can find the file ──────────── 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) # ── Load frozen simulator and spatialize ────────────────────────────────── sim = dataset._load_frozen_simulator(meta_copy, spatial_labels) gt_audio = sim.simulate(event_audio)[..., :event_audio.shape[1]] # (N, 2, T) # ── Extract each distractor → binaural → mono ───────────────────────────── result = {} for i, label in enumerate(spatial_labels): if label != "speech": binaural = torch.from_numpy(gt_audio[i]).float() # (2, T) result[label] = binaural.mean(dim=0, keepdim=True) # (1, T) return result # ═══════════════════════════════════════════════════════════════════════════════ # Bulk-mode helpers # ═══════════════════════════════════════════════════════════════════════════════ def _prep_clap_tensor(audio: torch.Tensor, target_len: int, use_cuda: bool) -> torch.Tensor: """ Replicate CLAP's load_audio_into_tensor logic directly from a (1,T) tensor. Returns (1, target_len) — no file I/O. """ 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-infer CLAP audio embeddings for model output crops AND distractor stem crops, then fill clap_sim (audio-audio cosine similarity) into each row dict in-place. crops : list of (model_crop (1,T), stem_crop (1,T), row_dict) No temp files — tensors are pre-processed in memory and passed directly to clap_model._get_audio_embeddings(), bypassing all file I/O. """ if not crops: return target_len = clap_model.args.duration * clap_model.args.sampling_rate # 7 * 44100 use_cuda = getattr(clap_model, "use_cuda", False) and torch.cuda.is_available() n = len(crops) try: # Pre-process all clips: (1, target_len) each, then stack to (2N, 1, target_len) model_prep = [_prep_clap_tensor(mc, target_len, use_cuda) for mc, sc, row in crops] stem_prep = [_prep_clap_tensor(sc, target_len, use_cuda) for mc, sc, row in crops] batch = torch.stack(model_prep + stem_prep, dim=0) # (2N, 1, target_len) # One GPU forward pass — no file I/O all_embs = clap_model._get_audio_embeddings(batch) # (2N, D) numpy array for i, (model_crop, stem_crop, row) in enumerate(crops): a = torch.tensor(all_embs[i]).unsqueeze(0) # model output emb b = torch.tensor(all_embs[n + i]).unsqueeze(0) # distractor stem emb 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 process_sample_signal_only( sample_dir: Path, mixtures_dir: Path, dataset, ) -> tuple: """ Compute signal-level metrics (SI-SNR, NXCorr) for one eval sample. CLAP is intentionally skipped here — handled later in batch by flush_clap_batch. Returns ------- rows : list of row dicts (clap_sim left empty) crops : list of (audio_crop (1,T), clap_label, row_dict) — one per valid distractor """ # ── Load metadata ───────────────────────────────────────────────────────── 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 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, error=f"5ch WAV not found: {wav_5ch}")], []) # ── Find model output WAV (filename includes action+target, not command_type) ─ 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")], []) output_file = output_files[0] model_out_mono = load_mono(output_file) # (1, T) # ── Identify distractors ────────────────────────────────────────────────── 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")], []) # ── Reconstruct distractor stems ───────────────────────────────────────── try: stems = reconstruct_distractor_stems_mono(wav_5ch, meta, dataset) except Exception as e: return ([_error_row(sample_dir.name, mixture_id, command_type, target_sources, error=f"stem reconstruction: {e}")], []) # ── Score each distractor (signal metrics only) ─────────────────────────── 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": name, # audio-audio mode: stores distractor name for reference "error": "", } if name not in stems: row["error"] = f"stem missing for '{name}'" rows.append(row) continue dist_crop = crop_to_window(stems[name], t_start, t_end) model_crop = crop_to_window(model_out_mono, t_start, t_end) dist_1d = dist_crop.squeeze(0) model_1d = model_crop.squeeze(0) try: row["si_snr_db"] = f"{si_snr(model_1d, dist_1d):.4f}" except Exception as e: row["error"] += f"si_snr:{e} " try: row["nxcorr"] = f"{normalized_xcorr(model_1d, dist_1d):.6f}" except Exception as e: row["error"] += f"nxcorr:{e} " rows.append(row) crops.append((model_crop, dist_crop, row)) return rows, crops # ═══════════════════════════════════════════════════════════════════════════════ # Per-sample processing (single-sample mode — calls CLAP inline) # ═══════════════════════════════════════════════════════════════════════════════ def process_sample( sample_dir: Path, mixtures_dir: Path, dataset, clap_model, ) -> list: """ Process one eval output folder (single-sample / debugging path). Calls CLAP inline per distractor. Bulk mode uses process_sample_signal_only + flush_clap_batch instead for efficiency. """ 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") 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, error=f"5ch WAV not found: {wav_5ch}")] 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")] output_file = output_files[0] model_out_mono = load_mono(output_file) 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")] try: stems = reconstruct_distractor_stems_mono(wav_5ch, meta, dataset) except Exception as e: return [_error_row(sample_dir.name, mixture_id, command_type, target_sources, error=f"stem reconstruction: {e}")] rows = [] 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": name, # audio-audio mode: stores distractor name for reference "error": "", } if name not in stems: row["error"] = f"stem missing for '{name}'" rows.append(row) continue dist_crop = crop_to_window(stems[name], t_start, t_end) model_crop = crop_to_window(model_out_mono, t_start, t_end) dist_1d = dist_crop.squeeze(0) model_1d = model_crop.squeeze(0) try: row["si_snr_db"] = f"{si_snr(model_1d, dist_1d):.4f}" except Exception as e: row["error"] += f"si_snr:{e} " try: row["nxcorr"] = f"{normalized_xcorr(model_1d, dist_1d):.6f}" except Exception as e: row["error"] += f"nxcorr:{e} " if clap_model is not None: try: row["clap_sim"] = f"{clap_audio_similarity(model_crop, dist_crop, clap_model):.6f}" except Exception as e: row["error"] += f"clap:{e} " rows.append(row) return rows 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 # ═══════════════════════════════════════════════════════════════════════════════ # Main # ═══════════════════════════════════════════════════════════════════════════════ def main(): parser = argparse.ArgumentParser(description="Evaluate distractor event detection.") parser.add_argument("--use_cuda", action="store_true", help="Run CLAP embeddings on GPU") parser.add_argument("--eval_outputs_dir", type=str, default=None, help="Bulk mode: directory containing eval sample subfolders") parser.add_argument("--mixtures_dir", type=str, default=None, help="Bulk mode: path to audio_mixtures directory (contains train/test/)") parser.add_argument("--output_csv", type=str, default=None, help="Bulk mode: path to write scores CSV") parser.add_argument("--batch_size", type=int, default=32, help="Number of audio crops per CLAP batch (default 32)") parser.add_argument("--num_workers", type=int, default=4, help="Worker threads for signal metric computation (default 4)") args = parser.parse_args() bulk_mode = args.eval_outputs_dir is not None # ── Shared initialization (done once) ──────────────────────────────────── mixtures_dir = Path(args.mixtures_dir) if args.mixtures_dir else _DEFAULT_WAV_5CH.parent.parent print("Initializing dataset ...") 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 model_out_mono = load_mono(sample_dir / f"output_no_input.wav") gt_speech_mono = load_mono(sample_dir / "gt_speech.wav") with open(sample_dir / "metadata.json") as f: meta = json.load(f) 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"Command : {meta['command_variant']['command_type']}") print(f"Targets : {meta['command_variant']['target_sources']}") print(f"Distractors : {meta.get('distractors', [])}") print(f"{'═'*60}") stems = reconstruct_distractor_stems_mono(wav_5ch, meta, dataset) 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"] print(f"\n{'─'*60}") print(f"Distractor : {name} ({t_start:.3f}s – {t_end:.3f}s)") print() if name not in stems: print(f" [SKIP] no stem for '{name}'") continue dist_crop = crop_to_window(stems[name], t_start, t_end) model_crop = crop_to_window(model_out_mono, t_start, t_end) dist_1d = dist_crop.squeeze(0) model_1d = model_crop.squeeze(0) sisnr_score = si_snr(model_1d, dist_1d) nxcorr_score = normalized_xcorr(model_1d, dist_1d) sisnr_dec = binary_decision(sisnr_score, SISNR_THRESHOLD_DB, True) nxcorr_dec = binary_decision(nxcorr_score, NXCORR_THRESHOLD, True) print(f" Method A (SI-SNR) : {sisnr_score:+7.2f} dB " f"[threshold {SISNR_THRESHOLD_DB:+.0f} dB] → " f"{'REMOVED ✓' if sisnr_dec == 'REMOVED' else 'PRESENT ✗'}") print(f" Method A (NXCorr) : {nxcorr_score:8.4f} " f"[threshold {NXCORR_THRESHOLD:.2f}] → " f"{'REMOVED ✓' if nxcorr_dec == 'REMOVED' else 'PRESENT ✗'}") print(f"\n Running CLAP (audio vs stem) ...") try: clap_score = clap_audio_similarity(model_crop, dist_crop, clap_model) clap_dec = binary_decision(clap_score, CLAP_THRESHOLD, True) print(f" Method B (CLAP) : {clap_score:8.4f} " f"[threshold {CLAP_THRESHOLD:.2f}] → " f"{'REMOVED ✓' if clap_dec == 'REMOVED' else 'PRESENT ✗'}") except Exception as e: print(f" Method B (CLAP) : FAILED — {e}") print(f"\n{'═'*60}\nDone.") return # ════════════════════════════════════════════════════════════════════════ # BULK MODE — batched signal metrics + batched CLAP # ════════════════════════════════════════════════════════════════════════ 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.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("CLAP mode: audio-audio (model output vs distractor stem)") output_csv.parent.mkdir(parents=True, exist_ok=True) def _process_one_signal(sd): """Thread worker: signal metrics only, no CLAP.""" try: return process_sample_signal_only(sd, mixtures_dir, dataset) 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) # ── Parallel signal metrics ─────────────────────────────────────── with concurrent.futures.ThreadPoolExecutor(max_workers=num_workers) as ex: results = list(ex.map(_process_one_signal, chunk)) chunk_rows = [] chunk_crops = [] for rows, crops in results: chunk_rows.extend(rows) chunk_crops.extend(crops) # ── Batched CLAP (audio-audio) ──────────────────────────────────── print(f" CLAP batch ({len(chunk_crops)} crops) ...", flush=True) flush_clap_batch(chunk_crops, clap_model) # ── Write chunk to CSV ──────────────────────────────────────────── 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()