senselab.audio.tasks.features_extraction.torchaudio
This module provides the implementation of torchaudio utilities for audio features extraction.
1"""This module provides the implementation of torchaudio utilities for audio features extraction.""" 2 3import os 4from typing import Any, Dict, List, Optional, Sequence 5 6import numpy as np 7import torch 8 9try: 10 import torchaudio 11 12 TORCHAUDIO_AVAILABLE = True 13except ModuleNotFoundError: 14 TORCHAUDIO_AVAILABLE = False 15 16from senselab.audio.data_structures import Audio 17 18 19def extract_spectrogram_from_audios( 20 audios: List[Audio], 21 n_fft: int = 1024, 22 win_length: Optional[int] = None, 23 hop_length: Optional[int] = None, 24) -> List[Dict[str, torch.Tensor]]: 25 """Extract spectrograms from a list of audio objects. 26 27 Args: 28 audios (List[Audio]): List of Audio objects. 29 n_fft (int): Size of FFT, creates n_fft // 2 + 1 bins. Default is 1024. 30 win_length (int): Window size. Default is None, using n_fft. 31 hop_length (int): Length of hop between STFT windows. Default is None, using win_length // 2. 32 33 Returns: 34 List[Dict[str, torch.Tensor]]: List of Dict objects containing spectrograms. 35 """ 36 if not TORCHAUDIO_AVAILABLE: 37 raise ModuleNotFoundError( 38 "`torchaudio` is not installed. " "Please install senselab audio dependencies using `pip install senselab`." 39 ) 40 41 if win_length is None: 42 win_length = n_fft 43 if hop_length is None: 44 hop_length = win_length // 2 45 spectrogram = torchaudio.transforms.Spectrogram( 46 n_fft=n_fft, 47 win_length=win_length, 48 hop_length=hop_length, 49 ) 50 spectrograms = [] 51 for audio in audios: 52 try: 53 spectrograms.append({"spectrogram": spectrogram(audio.waveform).squeeze(0)}) 54 except RuntimeError: 55 spectrograms.append({"spectrogram": np.nan}) 56 return spectrograms 57 58 59def extract_mel_spectrogram_from_audios( 60 audios: List[Audio], 61 n_fft: Optional[int] = 1024, 62 win_length: Optional[int] = None, 63 hop_length: Optional[int] = None, 64 n_mels: int = 128, 65) -> List[Dict[str, torch.Tensor]]: 66 """Extract mel spectrograms from a list of audio objects. 67 68 Args: 69 audios (List[Audio]): List of Audio objects. 70 n_fft (int): Size of FFT, creates n_fft // 2 + 1 bins. Default is 1024. 71 win_length (int): Window size. Default is None, using n_fft. 72 hop_length (int): Length of hop between STFT windows. Default is None, using win_length // 2. 73 n_mels (int): Number of mel filter banks. Default is 128. 74 75 Returns: 76 List[Dict[str, torch.Tensor]]: List of Dict objects containing mel spectrograms. 77 """ 78 if not TORCHAUDIO_AVAILABLE: 79 raise ModuleNotFoundError( 80 "`torchaudio` is not installed. " "Please install senselab audio dependencies using `pip install senselab`." 81 ) 82 83 if win_length is None: 84 win_length = n_fft 85 if hop_length is None: 86 if win_length is not None: 87 hop_length = win_length // 2 88 else: 89 raise ValueError("win_length cannot be None") 90 mel_spectrograms = [] 91 for audio in audios: 92 try: 93 mel_spectrogram = torchaudio.transforms.MelSpectrogram( 94 sample_rate=audio.sampling_rate, 95 n_fft=n_fft, 96 win_length=win_length, 97 hop_length=hop_length, 98 n_mels=n_mels, 99 )(audio.waveform) 100 mel_spectrograms.append({"mel_spectrogram": mel_spectrogram.squeeze(0)}) 101 except RuntimeError: 102 mel_spectrograms.append({"mel_spectrogram": np.nan}) 103 return mel_spectrograms 104 105 106def extract_mfcc_from_audios( 107 audios: List[Audio], 108 n_mfcc: int = 40, 109 n_ftt: Optional[int] = 400, 110 win_length: Optional[int] = None, 111 hop_length: Optional[int] = None, 112 n_mels: int = 128, 113) -> List[Dict[str, torch.Tensor]]: 114 """Extract MFCCs from a list of audio objects. 115 116 Args: 117 audios (List[Audio]): List of Audio objects. 118 n_mfcc (int): Number of MFCCs to return. Default is 40. 119 n_ftt (int): Size of FFT, creates n_ftt // 2 + 1 bins. Default is 400. 120 win_length (int): Window size. Default is None, using n_ftt. 121 hop_length (int): Length of hop between STFT windows. Default is None, using win_length // 2. 122 n_mels (int): Number of mel filter banks. Default is 128. 123 124 Returns: 125 List[Dict[str, torch.Tensor]]: List of Dict objects containing MFCCs. 126 """ 127 if not TORCHAUDIO_AVAILABLE: 128 raise ModuleNotFoundError( 129 "`torchaudio` is not installed. " "Please install senselab audio dependencies using `pip install senselab`." 130 ) 131 132 if win_length is None: 133 win_length = n_ftt 134 if hop_length is None: 135 if win_length is not None: 136 hop_length = win_length // 2 137 else: 138 raise ValueError("win_length cannot be None") 139 mfccs = [] 140 for audio in audios: 141 try: 142 mfcc_transform = torchaudio.transforms.MFCC( 143 sample_rate=audio.sampling_rate, 144 n_mfcc=n_mfcc, 145 melkwargs={"n_fft": n_ftt, "win_length": win_length, "hop_length": hop_length, "n_mels": n_mels}, 146 ) 147 mfccs.append({"mfcc": mfcc_transform(audio.waveform).squeeze(0)}) 148 except RuntimeError: 149 mfccs.append({"mfcc": np.nan}) 150 return mfccs 151 152 153def extract_mel_filter_bank_from_audios( 154 audios: List[Audio], 155 n_mels: int = 128, 156 n_fft: int = 1024, 157 win_length: Optional[int] = None, 158 hop_length: Optional[int] = None, 159) -> List[Dict[str, torch.Tensor]]: 160 """Extract mel filter bank from a list of audio objects. 161 162 Args: 163 audios (List[Audio]): List of Audio objects. 164 n_mels (int): Number of mel filter banks. Default is 128. 165 n_fft (int): Size of FFT, creates n_fft // 2 + 1 bins. Default is 1024. 166 win_length (int): Window size. Default is None, using n_fft. 167 hop_length (int): Length of hop between STFT windows. Default is None, using win_length // 2. 168 169 Returns: 170 List[Dict[str, torch.Tensor]]: List of Dict objects containing mel filter banks. 171 """ 172 if not TORCHAUDIO_AVAILABLE: 173 raise ModuleNotFoundError( 174 "`torchaudio` is not installed. " "Please install senselab audio dependencies using `pip install senselab`." 175 ) 176 177 if win_length is None: 178 win_length = n_fft 179 if hop_length is None: 180 hop_length = win_length // 2 181 n_stft = n_fft // 2 + 1 182 183 spectrograms = extract_spectrogram_from_audios(audios, n_fft, win_length, hop_length) 184 185 mel_filter_banks = [] 186 for i, audio in enumerate(audios): 187 try: 188 melscale_transform = torchaudio.transforms.MelScale( 189 sample_rate=audio.sampling_rate, n_mels=n_mels, n_stft=n_stft 190 ) 191 mel_filter_banks.append({"mel_filter_bank": melscale_transform(spectrograms[i]["spectrogram"]).squeeze(0)}) 192 except RuntimeError: 193 mel_filter_banks.append({"mel_filter_bank": np.nan}) 194 return mel_filter_banks 195 196 197def extract_mel_filter_bank_from_spectrograms( 198 spectrograms: List[Dict[str, torch.Tensor]], 199 sampling_rate: int, 200 n_mels: int = 128, 201) -> List[Dict[str, torch.Tensor]]: 202 """Extract mel filter bank from a list of audio objects. 203 204 Args: 205 spectrograms (List[torch.Tensor]): List of spectrograms. 206 sampling_rate (int): Sampling rate of the audio. 207 n_mels (int): Number of mel filter banks. Default is 128. 208 209 Returns: 210 List[Dict[str, torch.Tensor]]: List of Dict objects containing mel filter banks. 211 """ 212 if not TORCHAUDIO_AVAILABLE: 213 raise ModuleNotFoundError( 214 "`torchaudio` is not installed. " "Please install senselab audio dependencies using `pip install senselab`." 215 ) 216 217 mel_filter_banks = [] 218 for spectrogram in spectrograms: 219 try: 220 melscale_transform = torchaudio.transforms.MelScale( 221 sample_rate=sampling_rate, n_mels=n_mels, n_stft=spectrogram["spectrogram"].shape[0] 222 ) 223 mel_filter_banks.append({"mel_filter_bank": melscale_transform(spectrogram["spectrogram"]).squeeze(0)}) 224 except RuntimeError: 225 mel_filter_banks.append({"mel_filter_bank": np.nan}) 226 return mel_filter_banks 227 228 229def extract_pitch_from_audios( 230 audios: List[Audio], freq_low: int = 80, freq_high: int = 500 231) -> List[Dict[str, torch.Tensor]]: 232 """Extract pitch from a list of audio objects. 233 234 Pitch is detected using the detect_pitch_frequency function from torchaudio. 235 It is implemented using normalized cross-correlation function and median smoothing. 236 237 Args: 238 audios (List[Audio]): List of Audio objects. 239 freq_low (int): Lowest frequency that can be detected (Hz). Should be bigger than 0. 240 (Default is 80). 241 freq_high (int): Highest frequency that can be detected (Hz). 242 (Default is 500). 243 244 Returns: 245 List[Dict[str, torch.Tensor]]: List of Dict objects containing pitches. 246 """ 247 if not TORCHAUDIO_AVAILABLE: 248 raise ModuleNotFoundError( 249 "`torchaudio` is not installed. " "Please install senselab audio dependencies using `pip install senselab`." 250 ) 251 252 if freq_low <= 0: 253 raise ValueError("freq_low should be bigger than 0") 254 255 pitches = [] 256 for audio in audios: 257 try: 258 pitches.append( 259 { 260 "pitch": torchaudio.functional.detect_pitch_frequency( 261 audio.waveform, sample_rate=audio.sampling_rate, freq_low=freq_low, freq_high=freq_high 262 ).squeeze(0) 263 } 264 ) 265 except RuntimeError: 266 pitches.append({"pitch": torch.tensor(torch.nan)}) 267 return pitches 268 269 270def extract_torchaudio_features_from_audios( 271 audios: List[Audio], 272 freq_low: int = 80, 273 freq_high: int = 500, 274 n_fft: int = 1024, 275 n_mels: int = 128, 276 n_mfcc: int = 40, 277 win_length: Optional[int] = None, 278 hop_length: Optional[int] = None, 279) -> List[Dict[str, Any]]: 280 """Extract torchaudio features from a list of audio objects. 281 282 Args: 283 audios (List[Audio]): List of Audio objects. 284 freq_low (int): Lowest detectable frequency (Hz). Must be > 0. 285 Default is 80. 286 freq_high (int): Highest detectable frequency (Hz). 287 Default is 500. 288 n_fft (int): Size of FFT; creates n_fft // 2 + 1 bins. 289 Default is 1024. 290 n_mels (int): Number of mel filter banks. Default is 128. 291 n_mfcc (int): Number of MFCC coefficients. Default is 40. 292 win_length (Optional[int]): Window size. If None, uses n_fft. 293 Default is None. 294 hop_length (Optional[int]): Hop length between STFT windows. If None, uses win_length // 2. 295 Default is None. 296 297 Returns: 298 - List[Dict[str, Any]]: List of Dict objects containing features. 299 300 Raises: 301 - ModuleNotFoundError: If `torchaudio` is not installed. 302 """ 303 if not TORCHAUDIO_AVAILABLE: 304 raise ModuleNotFoundError( 305 "`torchaudio` is not installed. Please install senselab audio dependencies using `pip install senselab`." 306 ) 307 308 wl = n_fft if win_length is None else win_length 309 hl = wl // 2 if hop_length is None else hop_length 310 311 if freq_low <= 0: 312 raise ValueError("freq_low should be bigger than 0") 313 314 results: List[Dict[str, Any]] = [] 315 for sample in audios: 316 sr = sample.sampling_rate 317 try: 318 # Spectrogram 319 spec = torchaudio.transforms.Spectrogram(n_fft=n_fft, win_length=wl, hop_length=hl)(sample.waveform) 320 spec = spec.squeeze(0) # (freq, time) 321 322 # Mel-spectrogram 323 melspec = torchaudio.transforms.MelSpectrogram( 324 sample_rate=sr, n_fft=n_fft, win_length=wl, hop_length=hl, n_mels=n_mels 325 )(sample.waveform) 326 melspec = melspec.squeeze(0) # (mel, time) 327 328 # MFCC 329 mfcc = torchaudio.transforms.MFCC( 330 sample_rate=sr, 331 n_mfcc=n_mfcc, 332 melkwargs={"n_fft": n_fft, "win_length": wl, "hop_length": hl, "n_mels": n_mels}, 333 )(sample.waveform) 334 mfcc = mfcc.squeeze(0) # (n_mfcc, time) 335 336 # Mel filter bank from spectrogram 337 n_stft = n_fft // 2 + 1 338 melfb = torchaudio.transforms.MelScale(sample_rate=sr, n_mels=n_mels, n_stft=n_stft)(spec) 339 melfb = melfb.squeeze(0) # (mel, time) 340 341 # Pitch 342 pitch = torchaudio.functional.detect_pitch_frequency( 343 sample.waveform, sample_rate=sr, freq_low=freq_low, freq_high=freq_high 344 ).squeeze(0) 345 346 results.append( 347 { 348 "pitch": pitch, 349 "mel_filter_bank": melfb, 350 "mfcc": mfcc, 351 "mel_spectrogram": melspec, 352 "spectrogram": spec, 353 } 354 ) 355 except RuntimeError: 356 # Return NaNs with the expected keys if torchaudio raises 357 results.append( 358 { 359 "pitch": torch.tensor(torch.nan), 360 "mel_filter_bank": np.nan, 361 "mfcc": np.nan, 362 "mel_spectrogram": np.nan, 363 "spectrogram": np.nan, 364 } 365 ) 366 367 return results
20def extract_spectrogram_from_audios( 21 audios: List[Audio], 22 n_fft: int = 1024, 23 win_length: Optional[int] = None, 24 hop_length: Optional[int] = None, 25) -> List[Dict[str, torch.Tensor]]: 26 """Extract spectrograms from a list of audio objects. 27 28 Args: 29 audios (List[Audio]): List of Audio objects. 30 n_fft (int): Size of FFT, creates n_fft // 2 + 1 bins. Default is 1024. 31 win_length (int): Window size. Default is None, using n_fft. 32 hop_length (int): Length of hop between STFT windows. Default is None, using win_length // 2. 33 34 Returns: 35 List[Dict[str, torch.Tensor]]: List of Dict objects containing spectrograms. 36 """ 37 if not TORCHAUDIO_AVAILABLE: 38 raise ModuleNotFoundError( 39 "`torchaudio` is not installed. " "Please install senselab audio dependencies using `pip install senselab`." 40 ) 41 42 if win_length is None: 43 win_length = n_fft 44 if hop_length is None: 45 hop_length = win_length // 2 46 spectrogram = torchaudio.transforms.Spectrogram( 47 n_fft=n_fft, 48 win_length=win_length, 49 hop_length=hop_length, 50 ) 51 spectrograms = [] 52 for audio in audios: 53 try: 54 spectrograms.append({"spectrogram": spectrogram(audio.waveform).squeeze(0)}) 55 except RuntimeError: 56 spectrograms.append({"spectrogram": np.nan}) 57 return spectrograms
Extract spectrograms from a list of audio objects.
Arguments:
- audios (List[Audio]): List of Audio objects.
- n_fft (int): Size of FFT, creates n_fft // 2 + 1 bins. Default is 1024.
- win_length (int): Window size. Default is None, using n_fft.
- hop_length (int): Length of hop between STFT windows. Default is None, using win_length // 2.
Returns:
List[Dict[str, torch.Tensor]]: List of Dict objects containing spectrograms.
60def extract_mel_spectrogram_from_audios( 61 audios: List[Audio], 62 n_fft: Optional[int] = 1024, 63 win_length: Optional[int] = None, 64 hop_length: Optional[int] = None, 65 n_mels: int = 128, 66) -> List[Dict[str, torch.Tensor]]: 67 """Extract mel spectrograms from a list of audio objects. 68 69 Args: 70 audios (List[Audio]): List of Audio objects. 71 n_fft (int): Size of FFT, creates n_fft // 2 + 1 bins. Default is 1024. 72 win_length (int): Window size. Default is None, using n_fft. 73 hop_length (int): Length of hop between STFT windows. Default is None, using win_length // 2. 74 n_mels (int): Number of mel filter banks. Default is 128. 75 76 Returns: 77 List[Dict[str, torch.Tensor]]: List of Dict objects containing mel spectrograms. 78 """ 79 if not TORCHAUDIO_AVAILABLE: 80 raise ModuleNotFoundError( 81 "`torchaudio` is not installed. " "Please install senselab audio dependencies using `pip install senselab`." 82 ) 83 84 if win_length is None: 85 win_length = n_fft 86 if hop_length is None: 87 if win_length is not None: 88 hop_length = win_length // 2 89 else: 90 raise ValueError("win_length cannot be None") 91 mel_spectrograms = [] 92 for audio in audios: 93 try: 94 mel_spectrogram = torchaudio.transforms.MelSpectrogram( 95 sample_rate=audio.sampling_rate, 96 n_fft=n_fft, 97 win_length=win_length, 98 hop_length=hop_length, 99 n_mels=n_mels, 100 )(audio.waveform) 101 mel_spectrograms.append({"mel_spectrogram": mel_spectrogram.squeeze(0)}) 102 except RuntimeError: 103 mel_spectrograms.append({"mel_spectrogram": np.nan}) 104 return mel_spectrograms
Extract mel spectrograms from a list of audio objects.
Arguments:
- audios (List[Audio]): List of Audio objects.
- n_fft (int): Size of FFT, creates n_fft // 2 + 1 bins. Default is 1024.
- win_length (int): Window size. Default is None, using n_fft.
- hop_length (int): Length of hop between STFT windows. Default is None, using win_length // 2.
- n_mels (int): Number of mel filter banks. Default is 128.
Returns:
List[Dict[str, torch.Tensor]]: List of Dict objects containing mel spectrograms.
107def extract_mfcc_from_audios( 108 audios: List[Audio], 109 n_mfcc: int = 40, 110 n_ftt: Optional[int] = 400, 111 win_length: Optional[int] = None, 112 hop_length: Optional[int] = None, 113 n_mels: int = 128, 114) -> List[Dict[str, torch.Tensor]]: 115 """Extract MFCCs from a list of audio objects. 116 117 Args: 118 audios (List[Audio]): List of Audio objects. 119 n_mfcc (int): Number of MFCCs to return. Default is 40. 120 n_ftt (int): Size of FFT, creates n_ftt // 2 + 1 bins. Default is 400. 121 win_length (int): Window size. Default is None, using n_ftt. 122 hop_length (int): Length of hop between STFT windows. Default is None, using win_length // 2. 123 n_mels (int): Number of mel filter banks. Default is 128. 124 125 Returns: 126 List[Dict[str, torch.Tensor]]: List of Dict objects containing MFCCs. 127 """ 128 if not TORCHAUDIO_AVAILABLE: 129 raise ModuleNotFoundError( 130 "`torchaudio` is not installed. " "Please install senselab audio dependencies using `pip install senselab`." 131 ) 132 133 if win_length is None: 134 win_length = n_ftt 135 if hop_length is None: 136 if win_length is not None: 137 hop_length = win_length // 2 138 else: 139 raise ValueError("win_length cannot be None") 140 mfccs = [] 141 for audio in audios: 142 try: 143 mfcc_transform = torchaudio.transforms.MFCC( 144 sample_rate=audio.sampling_rate, 145 n_mfcc=n_mfcc, 146 melkwargs={"n_fft": n_ftt, "win_length": win_length, "hop_length": hop_length, "n_mels": n_mels}, 147 ) 148 mfccs.append({"mfcc": mfcc_transform(audio.waveform).squeeze(0)}) 149 except RuntimeError: 150 mfccs.append({"mfcc": np.nan}) 151 return mfccs
Extract MFCCs from a list of audio objects.
Arguments:
- audios (List[Audio]): List of Audio objects.
- n_mfcc (int): Number of MFCCs to return. Default is 40.
- n_ftt (int): Size of FFT, creates n_ftt // 2 + 1 bins. Default is 400.
- win_length (int): Window size. Default is None, using n_ftt.
- hop_length (int): Length of hop between STFT windows. Default is None, using win_length // 2.
- n_mels (int): Number of mel filter banks. Default is 128.
Returns:
List[Dict[str, torch.Tensor]]: List of Dict objects containing MFCCs.
154def extract_mel_filter_bank_from_audios( 155 audios: List[Audio], 156 n_mels: int = 128, 157 n_fft: int = 1024, 158 win_length: Optional[int] = None, 159 hop_length: Optional[int] = None, 160) -> List[Dict[str, torch.Tensor]]: 161 """Extract mel filter bank from a list of audio objects. 162 163 Args: 164 audios (List[Audio]): List of Audio objects. 165 n_mels (int): Number of mel filter banks. Default is 128. 166 n_fft (int): Size of FFT, creates n_fft // 2 + 1 bins. Default is 1024. 167 win_length (int): Window size. Default is None, using n_fft. 168 hop_length (int): Length of hop between STFT windows. Default is None, using win_length // 2. 169 170 Returns: 171 List[Dict[str, torch.Tensor]]: List of Dict objects containing mel filter banks. 172 """ 173 if not TORCHAUDIO_AVAILABLE: 174 raise ModuleNotFoundError( 175 "`torchaudio` is not installed. " "Please install senselab audio dependencies using `pip install senselab`." 176 ) 177 178 if win_length is None: 179 win_length = n_fft 180 if hop_length is None: 181 hop_length = win_length // 2 182 n_stft = n_fft // 2 + 1 183 184 spectrograms = extract_spectrogram_from_audios(audios, n_fft, win_length, hop_length) 185 186 mel_filter_banks = [] 187 for i, audio in enumerate(audios): 188 try: 189 melscale_transform = torchaudio.transforms.MelScale( 190 sample_rate=audio.sampling_rate, n_mels=n_mels, n_stft=n_stft 191 ) 192 mel_filter_banks.append({"mel_filter_bank": melscale_transform(spectrograms[i]["spectrogram"]).squeeze(0)}) 193 except RuntimeError: 194 mel_filter_banks.append({"mel_filter_bank": np.nan}) 195 return mel_filter_banks
Extract mel filter bank from a list of audio objects.
Arguments:
- audios (List[Audio]): List of Audio objects.
- n_mels (int): Number of mel filter banks. Default is 128.
- n_fft (int): Size of FFT, creates n_fft // 2 + 1 bins. Default is 1024.
- win_length (int): Window size. Default is None, using n_fft.
- hop_length (int): Length of hop between STFT windows. Default is None, using win_length // 2.
Returns:
List[Dict[str, torch.Tensor]]: List of Dict objects containing mel filter banks.
198def extract_mel_filter_bank_from_spectrograms( 199 spectrograms: List[Dict[str, torch.Tensor]], 200 sampling_rate: int, 201 n_mels: int = 128, 202) -> List[Dict[str, torch.Tensor]]: 203 """Extract mel filter bank from a list of audio objects. 204 205 Args: 206 spectrograms (List[torch.Tensor]): List of spectrograms. 207 sampling_rate (int): Sampling rate of the audio. 208 n_mels (int): Number of mel filter banks. Default is 128. 209 210 Returns: 211 List[Dict[str, torch.Tensor]]: List of Dict objects containing mel filter banks. 212 """ 213 if not TORCHAUDIO_AVAILABLE: 214 raise ModuleNotFoundError( 215 "`torchaudio` is not installed. " "Please install senselab audio dependencies using `pip install senselab`." 216 ) 217 218 mel_filter_banks = [] 219 for spectrogram in spectrograms: 220 try: 221 melscale_transform = torchaudio.transforms.MelScale( 222 sample_rate=sampling_rate, n_mels=n_mels, n_stft=spectrogram["spectrogram"].shape[0] 223 ) 224 mel_filter_banks.append({"mel_filter_bank": melscale_transform(spectrogram["spectrogram"]).squeeze(0)}) 225 except RuntimeError: 226 mel_filter_banks.append({"mel_filter_bank": np.nan}) 227 return mel_filter_banks
Extract mel filter bank from a list of audio objects.
Arguments:
- spectrograms (List[torch.Tensor]): List of spectrograms.
- sampling_rate (int): Sampling rate of the audio.
- n_mels (int): Number of mel filter banks. Default is 128.
Returns:
List[Dict[str, torch.Tensor]]: List of Dict objects containing mel filter banks.
230def extract_pitch_from_audios( 231 audios: List[Audio], freq_low: int = 80, freq_high: int = 500 232) -> List[Dict[str, torch.Tensor]]: 233 """Extract pitch from a list of audio objects. 234 235 Pitch is detected using the detect_pitch_frequency function from torchaudio. 236 It is implemented using normalized cross-correlation function and median smoothing. 237 238 Args: 239 audios (List[Audio]): List of Audio objects. 240 freq_low (int): Lowest frequency that can be detected (Hz). Should be bigger than 0. 241 (Default is 80). 242 freq_high (int): Highest frequency that can be detected (Hz). 243 (Default is 500). 244 245 Returns: 246 List[Dict[str, torch.Tensor]]: List of Dict objects containing pitches. 247 """ 248 if not TORCHAUDIO_AVAILABLE: 249 raise ModuleNotFoundError( 250 "`torchaudio` is not installed. " "Please install senselab audio dependencies using `pip install senselab`." 251 ) 252 253 if freq_low <= 0: 254 raise ValueError("freq_low should be bigger than 0") 255 256 pitches = [] 257 for audio in audios: 258 try: 259 pitches.append( 260 { 261 "pitch": torchaudio.functional.detect_pitch_frequency( 262 audio.waveform, sample_rate=audio.sampling_rate, freq_low=freq_low, freq_high=freq_high 263 ).squeeze(0) 264 } 265 ) 266 except RuntimeError: 267 pitches.append({"pitch": torch.tensor(torch.nan)}) 268 return pitches
Extract pitch from a list of audio objects.
Pitch is detected using the detect_pitch_frequency function from torchaudio. It is implemented using normalized cross-correlation function and median smoothing.
Arguments:
- audios (List[Audio]): List of Audio objects.
- freq_low (int): Lowest frequency that can be detected (Hz). Should be bigger than 0. (Default is 80).
- freq_high (int): Highest frequency that can be detected (Hz). (Default is 500).
Returns:
List[Dict[str, torch.Tensor]]: List of Dict objects containing pitches.
271def extract_torchaudio_features_from_audios( 272 audios: List[Audio], 273 freq_low: int = 80, 274 freq_high: int = 500, 275 n_fft: int = 1024, 276 n_mels: int = 128, 277 n_mfcc: int = 40, 278 win_length: Optional[int] = None, 279 hop_length: Optional[int] = None, 280) -> List[Dict[str, Any]]: 281 """Extract torchaudio features from a list of audio objects. 282 283 Args: 284 audios (List[Audio]): List of Audio objects. 285 freq_low (int): Lowest detectable frequency (Hz). Must be > 0. 286 Default is 80. 287 freq_high (int): Highest detectable frequency (Hz). 288 Default is 500. 289 n_fft (int): Size of FFT; creates n_fft // 2 + 1 bins. 290 Default is 1024. 291 n_mels (int): Number of mel filter banks. Default is 128. 292 n_mfcc (int): Number of MFCC coefficients. Default is 40. 293 win_length (Optional[int]): Window size. If None, uses n_fft. 294 Default is None. 295 hop_length (Optional[int]): Hop length between STFT windows. If None, uses win_length // 2. 296 Default is None. 297 298 Returns: 299 - List[Dict[str, Any]]: List of Dict objects containing features. 300 301 Raises: 302 - ModuleNotFoundError: If `torchaudio` is not installed. 303 """ 304 if not TORCHAUDIO_AVAILABLE: 305 raise ModuleNotFoundError( 306 "`torchaudio` is not installed. Please install senselab audio dependencies using `pip install senselab`." 307 ) 308 309 wl = n_fft if win_length is None else win_length 310 hl = wl // 2 if hop_length is None else hop_length 311 312 if freq_low <= 0: 313 raise ValueError("freq_low should be bigger than 0") 314 315 results: List[Dict[str, Any]] = [] 316 for sample in audios: 317 sr = sample.sampling_rate 318 try: 319 # Spectrogram 320 spec = torchaudio.transforms.Spectrogram(n_fft=n_fft, win_length=wl, hop_length=hl)(sample.waveform) 321 spec = spec.squeeze(0) # (freq, time) 322 323 # Mel-spectrogram 324 melspec = torchaudio.transforms.MelSpectrogram( 325 sample_rate=sr, n_fft=n_fft, win_length=wl, hop_length=hl, n_mels=n_mels 326 )(sample.waveform) 327 melspec = melspec.squeeze(0) # (mel, time) 328 329 # MFCC 330 mfcc = torchaudio.transforms.MFCC( 331 sample_rate=sr, 332 n_mfcc=n_mfcc, 333 melkwargs={"n_fft": n_fft, "win_length": wl, "hop_length": hl, "n_mels": n_mels}, 334 )(sample.waveform) 335 mfcc = mfcc.squeeze(0) # (n_mfcc, time) 336 337 # Mel filter bank from spectrogram 338 n_stft = n_fft // 2 + 1 339 melfb = torchaudio.transforms.MelScale(sample_rate=sr, n_mels=n_mels, n_stft=n_stft)(spec) 340 melfb = melfb.squeeze(0) # (mel, time) 341 342 # Pitch 343 pitch = torchaudio.functional.detect_pitch_frequency( 344 sample.waveform, sample_rate=sr, freq_low=freq_low, freq_high=freq_high 345 ).squeeze(0) 346 347 results.append( 348 { 349 "pitch": pitch, 350 "mel_filter_bank": melfb, 351 "mfcc": mfcc, 352 "mel_spectrogram": melspec, 353 "spectrogram": spec, 354 } 355 ) 356 except RuntimeError: 357 # Return NaNs with the expected keys if torchaudio raises 358 results.append( 359 { 360 "pitch": torch.tensor(torch.nan), 361 "mel_filter_bank": np.nan, 362 "mfcc": np.nan, 363 "mel_spectrogram": np.nan, 364 "spectrogram": np.nan, 365 } 366 ) 367 368 return results
Extract torchaudio features from a list of audio objects.
Args: audios (List[Audio]): List of Audio objects. freq_low (int): Lowest detectable frequency (Hz). Must be > 0. Default is 80. freq_high (int): Highest detectable frequency (Hz). Default is 500. n_fft (int): Size of FFT; creates n_fft // 2 + 1 bins. Default is 1024. n_mels (int): Number of mel filter banks. Default is 128. n_mfcc (int): Number of MFCC coefficients. Default is 40. win_length (Optional[int]): Window size. If None, uses n_fft. Default is None. hop_length (Optional[int]): Hop length between STFT windows. If None, uses win_length // 2. Default is None.
Returns:
- List[Dict[str, Any]]: List of Dict objects containing features.
Raises:
- ModuleNotFoundError: If
torchaudiois not installed.