""" Shared utilities for embedding extraction across all models. Provides common audio loading, file collection, and save logic so that each per-model extraction script only needs to define model initialization and a single `model_fn(audio_path) -> np.ndarray` function. """ import sys import numpy as np from pathlib import Path try: from tqdm import tqdm except ImportError: def tqdm(iterable, desc=None, total=None): if desc: print(f"\nProcessing {desc}...") return iterable import os # Resolve the release root. # Priority: VIPBENCH_ROOT env var > parent of this script's directory. # Layout assumed: # / # code/extraction_utils.py <- this file # data/audio/reference/*.wav # data/audio/comparison/*.wav # data/embeddings/.npz <- output def _resolve_root(): env = os.environ.get("VIPBENCH_ROOT") if env: return Path(env).resolve() return Path(__file__).resolve().parent.parent DEFAULT_BASE_DIR = _resolve_root() DEFAULT_OUTPUT_DIR = DEFAULT_BASE_DIR / "data" / "embeddings" def load_audio(file_path, target_sr=16000): """Load audio file as float32 mono at target_sr. Replicates the pattern from extract_rawnet3_embeddings.py. """ try: import librosa audio, sr = librosa.load(file_path, sr=target_sr, mono=True) return audio.astype(np.float32) except ImportError: pass # Fallback to soundfile import soundfile as sf audio, sr = sf.read(file_path) if len(audio.shape) > 1: audio = np.mean(audio, axis=1) if sr != target_sr: import scipy.signal num_samples = int(len(audio) * target_sr / sr) audio = scipy.signal.resample(audio, num_samples) if audio.dtype != np.float32: if audio.dtype == np.int16: audio = audio.astype(np.float32) / 32768.0 elif audio.dtype == np.int32: audio = audio.astype(np.float32) / 2147483648.0 else: audio = audio.astype(np.float32) if np.max(np.abs(audio)) > 1.0: audio = audio / np.max(np.abs(audio)) return audio.astype(np.float32) def collect_audio_files(base_dir=None): """Collect reference and stimulus audio files. Returns ------- ref_files : list[Path] 100 reference clips from exp_2/*R.wav stim_files : list[Path] 9,800 comparison clips from output/*.wav """ base = Path(base_dir) if base_dir else DEFAULT_BASE_DIR ref_files = sorted((base / "data" / "audio" / "reference").glob("*R.wav")) stim_files = sorted((base / "data" / "audio" / "comparison").glob("*.wav")) return ref_files, stim_files def save_embeddings(embeddings_dict, model_name, output_dir=None): """Save embeddings as compressed .npz with same format as rawnet3_embeddings.npz.""" out = Path(output_dir) if output_dir else DEFAULT_OUTPUT_DIR out.mkdir(parents=True, exist_ok=True) path = out / f"{model_name}.npz" np.savez_compressed(path, **embeddings_dict) print(f"Saved {len(embeddings_dict)} embeddings to {path}") return path def extract_all(model_fn, model_name, base_dir=None, output_dir=None): """Run extraction for all audio files using the provided model function. Parameters ---------- model_fn : callable Takes a file path (str or Path) and returns a 1-D numpy array (the embedding). model_name : str Name used for the output file ({model_name}_embeddings.npz). base_dir : str or Path, optional Project root. Defaults to DEFAULT_BASE_DIR. output_dir : str or Path, optional Where to save the .npz. Defaults to DEFAULT_OUTPUT_DIR. """ ref_files, stim_files = collect_audio_files(base_dir) total = len(ref_files) + len(stim_files) print(f"\n{'=' * 60}") print(f"{model_name} Embedding Extraction") print(f"{'=' * 60}") print(f"Reference files: {len(ref_files)}") print(f"Stimulus files: {len(stim_files)}") print(f"Total: {total}") embeddings_dict = {} failed = [] print(f"\nProcessing reference files...") for path in tqdm(ref_files, desc="references"): key = path.stem try: emb = model_fn(path) if emb is not None: embeddings_dict[key] = emb else: failed.append(str(path)) except Exception as e: print(f"\n Error on {path.name}: {e}") failed.append(str(path)) print(f"\nProcessing stimulus files...") for path in tqdm(stim_files, desc="stimuli"): key = path.stem try: emb = model_fn(path) if emb is not None: embeddings_dict[key] = emb else: failed.append(str(path)) except Exception as e: print(f"\n Error on {path.name}: {e}") failed.append(str(path)) # Summary print(f"\n{'=' * 60}") print(f"Summary") print(f"{'=' * 60}") print(f"Extracted: {len(embeddings_dict)} / {total}") print(f"Failed: {len(failed)}") if embeddings_dict: sample = next(iter(embeddings_dict.values())) print(f"Dimension: {sample.shape}") if failed: print(f"\nFailed files (first 10):") for f in failed[:10]: print(f" {f}") save_embeddings(embeddings_dict, model_name, output_dir) return embeddings_dict