File size: 5,437 Bytes
6351b36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
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:
#   <VIPBENCH_ROOT>/
#     code/extraction_utils.py    <- this file
#     data/audio/reference/*.wav
#     data/audio/comparison/*.wav
#     data/embeddings/<model>.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