File size: 8,498 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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
#!/usr/bin/env python3
"""
Extract RawNet3 embeddings for all audio files.

This script extracts RawNet3 speaker embeddings for:
- 100 audio files ending with "R" in exp_2 directory (e.g., F01R.wav)
- 9,800 audio files in output directory

The embeddings are saved in a dictionary format where:
- Key: filename without extension (e.g., "F01R")
- Value: RawNet3 embedding vector (numpy array)

Saved as both pickle (.pkl) and numpy (.npz) formats for flexibility.

Requirements:
- ESPnet-SPK: pip install espnet
- Or RawNet repository: git clone https://github.com/jungjee/RawNet.git
"""

import os
import sys
import numpy as np
from pathlib import Path
import pickle
import warnings

warnings.filterwarnings('ignore')

# Try to import tqdm for progress bars, fallback to basic iteration if not available
try:
    from tqdm import tqdm
except ImportError:
    def tqdm(iterable, desc=None):
        if desc:
            print(f"\nProcessing {desc}...")
        return iterable

# Try to import ESPnet first (preferred method)
try:
    from espnet2.bin.spk_inference import Speech2Embedding
    ESPNET_AVAILABLE = True
    print("ESPnet-SPK is available")
except ImportError:
    ESPNET_AVAILABLE = False
    print("ESPnet-SPK not available. Please install it:")
    print("  pip install espnet")
    print("Or set up the RawNet repository manually.")
    sys.exit(1)


def load_audio(file_path, target_sr=16000):
    """Load audio file and resample to target sample rate if needed."""
    try:
        # Try librosa first (most reliable)
        try:
            import librosa
            audio, sr = librosa.load(file_path, sr=target_sr, mono=True)
            # Audio is already in float32 format normalized to [-1, 1]
            return audio.astype(np.float32)
        except ImportError:
            # Fallback to soundfile
            import soundfile as sf
            audio, sr = sf.read(file_path)
            
            # Convert stereo to mono if needed
            if len(audio.shape) > 1:
                audio = np.mean(audio, axis=1)
            
            # Resample if needed
            if sr != target_sr:
                import scipy.signal
                num_samples = int(len(audio) * target_sr / sr)
                audio = scipy.signal.resample(audio, num_samples)
            
            # Ensure audio is in the correct format (float32, normalized to [-1, 1])
            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)
            
            # Normalize to [-1, 1] if needed
            if np.max(np.abs(audio)) > 1.0:
                audio = audio / np.max(np.abs(audio))
            
            return audio.astype(np.float32)
    except Exception as e:
        print(f"Error loading {file_path}: {e}")
        return None


def extract_embedding_espnet(audio_path, speech2spk_embed):
    """Extract embedding using ESPnet."""
    try:
        audio = load_audio(audio_path)
        if audio is None:
            return None
        
        # ESPnet expects numpy array (raw waveform, 16kHz, float32)
        # The Speech2Embedding object handles the processing
        embedding = speech2spk_embed(audio)
        
        # Convert to numpy array if needed (ESPnet may return numpy or torch tensor)
        if hasattr(embedding, 'cpu'):  # torch.Tensor
            embedding = embedding.cpu().numpy()
        elif not isinstance(embedding, np.ndarray):
            embedding = np.array(embedding)
        
        return embedding.flatten()
    except Exception as e:
        print(f"Error extracting embedding with ESPnet from {audio_path}: {e}")
        import traceback
        traceback.print_exc()
        return None


def main():
    """Main function to extract embeddings for all audio files."""
    
    print("=" * 80)
    print("RawNet3 Embedding Extraction")
    print("=" * 80)
    
    # Initialize model
    if not ESPNET_AVAILABLE:
        print("\nERROR: ESPnet-SPK is not available.")
        print("Please install ESPnet-SPK first:")
        print("  pip install espnet")
        print("\nThis script uses ESPnet-SPK's pre-trained RawNet3 model for easier access.")
        sys.exit(1)
    
    print("\nInitializing ESPnet RawNet3 model...")
    try:
        speech2spk_embed = Speech2Embedding.from_pretrained(
            model_tag="espnet/voxcelebs12_rawnet3"
        )
        print("ESPnet RawNet3 model loaded successfully")
    except Exception as e:
        print(f"\nERROR: Failed to load ESPnet RawNet3 model: {e}")
        print("\nThis may be due to:")
        print("  1. Network issues (model needs to be downloaded from HuggingFace)")
        print("  2. Missing dependencies")
        print("\nPlease ensure you have a stable internet connection and try again.")
        import traceback
        traceback.print_exc()
        sys.exit(1)
    
    # Collect all audio files
    print("\nCollecting audio files...")
    
    from extraction_utils import collect_audio_files, DEFAULT_OUTPUT_DIR
    exp_2_files, output_files = collect_audio_files()
    print(f"Found {len(exp_2_files)} reference files (data/audio/reference/*R.wav)")
    print(f"Found {len(output_files)} comparison files (data/audio/comparison/*.wav)")
    
    total_files = len(exp_2_files) + len(output_files)
    print(f"Total files to process: {total_files}")
    
    if total_files == 0:
        print("ERROR: No audio files found!")
        sys.exit(1)
    
    # Extract embeddings
    print("\nExtracting embeddings...")
    embeddings_dict = {}
    failed_files = []
    
    # Process exp_2 files
    print("\nProcessing exp_2 files...")
    for audio_path in tqdm(exp_2_files, desc="exp_2"):
        # Get filename without extension (e.g., "F01R")
        filename_key = audio_path.stem
        
        try:
            embedding = extract_embedding_espnet(audio_path, speech2spk_embed)
            
            if embedding is not None:
                embeddings_dict[filename_key] = embedding
            else:
                failed_files.append(str(audio_path))
        except Exception as e:
            print(f"\nError processing {audio_path}: {e}")
            failed_files.append(str(audio_path))
    
    # Process output files
    print("\nProcessing output files...")
    for audio_path in tqdm(output_files, desc="output"):
        # Get filename without extension (e.g., "6_F01R_F02R_001")
        filename_key = audio_path.stem
        
        try:
            embedding = extract_embedding_espnet(audio_path, speech2spk_embed)
            
            if embedding is not None:
                embeddings_dict[filename_key] = embedding
            else:
                failed_files.append(str(audio_path))
        except Exception as e:
            print(f"\nError processing {audio_path}: {e}")
            failed_files.append(str(audio_path))
    
    # Save embeddings
    print("\nSaving embeddings...")
    
    DEFAULT_OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
    npz_path = DEFAULT_OUTPUT_DIR / "rawnet3.npz"
    np.savez_compressed(npz_path, **embeddings_dict)
    print(f"Saved embeddings to {npz_path}")
    
    # Print summary
    print("\n" + "=" * 80)
    print("Summary")
    print("=" * 80)
    print(f"Total files processed: {total_files}")
    print(f"Successfully extracted: {len(embeddings_dict)}")
    print(f"Failed: {len(failed_files)}")
    
    if failed_files:
        print(f"\nFailed files (first 10):")
        for f in failed_files[:10]:
            print(f"  {f}")
        if len(failed_files) > 10:
            print(f"  ... and {len(failed_files) - 10} more")
    
    print(f"\nEmbedding dimension: {list(embeddings_dict.values())[0].shape if embeddings_dict else 'N/A'}")
    print(f"\nSaved files:")
    print(f"  - {pickle_path} (Python pickle format)")
    print(f"  - {npz_path} (NumPy compressed format)")
    print("\nTo load embeddings later:")
    print(f"  import pickle")
    print(f"  with open('{pickle_path}', 'rb') as f:")
    print(f"      embeddings = pickle.load(f)")
    print("\nOr:")
    print(f"  import numpy as np")
    print(f"  data = np.load('{npz_path}', allow_pickle=True)")
    print(f"  embeddings = {{k: data[k] for k in data.files}}")


if __name__ == "__main__":
    main()