Download features/mfcc.py from devmm03/vs: direct link, hf CLI and curl.
- Browser
- Download file 5.57 kB
-
https://huggingface.co/spaces/devmm03/vs/resolve/main/features/mfcc.py
- Command line
-
hf download hf://spaces/devmm03/vs/features/mfcc.py
-
curl -L -o mfcc.py https://huggingface.co/spaces/devmm03/vs/resolve/main/features/mfcc.py
5.57 kB
| """ | |
| MFCC and Mel-Spectrogram Feature Extraction | |
| Extract Mel-frequency cepstral coefficients and spectrograms for voice analysis. | |
| """ | |
| import numpy as np | |
| import librosa | |
| from typing import Dict, Tuple, Optional | |
| import sys | |
| from pathlib import Path | |
| sys.path.insert(0, str(Path(__file__).parent.parent)) | |
| from config import SAMPLE_RATE, N_FFT, HOP_LENGTH, N_MELS, N_MFCC | |
| def extract_mel_spectrogram( | |
| audio: np.ndarray, | |
| sr: int = SAMPLE_RATE, | |
| n_fft: int = N_FFT, | |
| hop_length: int = HOP_LENGTH, | |
| n_mels: int = N_MELS, | |
| to_db: bool = True | |
| ) -> np.ndarray: | |
| """ | |
| Extract Mel-spectrogram from audio. | |
| The Mel-spectrogram is a 2D representation that can reveal: | |
| - Vertical stripes: temporal glitches in AI voices | |
| - Horizontal ringing: vocoder artifacts | |
| - Unnatural smoothness in AI-generated audio | |
| Args: | |
| audio: Audio waveform | |
| sr: Sample rate | |
| n_fft: FFT window size | |
| hop_length: Hop length | |
| n_mels: Number of Mel bands | |
| to_db: Convert to decibels | |
| Returns: | |
| Mel-spectrogram array (n_mels, time) | |
| """ | |
| mel_spec = librosa.feature.melspectrogram( | |
| y=audio, sr=sr, n_fft=n_fft, hop_length=hop_length, n_mels=n_mels | |
| ) | |
| if to_db: | |
| mel_spec = librosa.power_to_db(mel_spec, ref=np.max) | |
| return mel_spec | |
| def extract_mfcc( | |
| audio: np.ndarray, | |
| sr: int = SAMPLE_RATE, | |
| n_fft: int = N_FFT, | |
| hop_length: int = HOP_LENGTH, | |
| n_mfcc: int = N_MFCC | |
| ) -> np.ndarray: | |
| """ | |
| Extract Mel-frequency cepstral coefficients. | |
| MFCCs are essentially a "thumbprint" of the vocal tract, | |
| capturing the spectral envelope of the audio. | |
| Args: | |
| audio: Audio waveform | |
| sr: Sample rate | |
| n_fft: FFT window size | |
| hop_length: Hop length | |
| n_mfcc: Number of MFCCs to extract | |
| Returns: | |
| MFCC array (n_mfcc, time) | |
| """ | |
| mfcc = librosa.feature.mfcc( | |
| y=audio, sr=sr, n_fft=n_fft, hop_length=hop_length, n_mfcc=n_mfcc | |
| ) | |
| return mfcc | |
| def extract_delta_mfcc( | |
| mfcc: np.ndarray, | |
| order: int = 1 | |
| ) -> np.ndarray: | |
| """ | |
| Extract delta (derivative) MFCCs. | |
| Delta MFCCs capture the dynamics of the spectral features, | |
| which can differ between human and AI voices. | |
| Args: | |
| mfcc: MFCC array | |
| order: Derivative order (1 for delta, 2 for delta-delta) | |
| Returns: | |
| Delta MFCC array | |
| """ | |
| return librosa.feature.delta(mfcc, order=order) | |
| def extract_mfcc_with_deltas( | |
| audio: np.ndarray, | |
| sr: int = SAMPLE_RATE, | |
| n_mfcc: int = N_MFCC | |
| ) -> np.ndarray: | |
| """ | |
| Extract MFCCs with first and second-order deltas. | |
| Args: | |
| audio: Audio waveform | |
| sr: Sample rate | |
| n_mfcc: Number of MFCCs | |
| Returns: | |
| Stacked array of MFCCs, delta, and delta-delta (3*n_mfcc, time) | |
| """ | |
| mfcc = extract_mfcc(audio, sr, n_mfcc=n_mfcc) | |
| delta = extract_delta_mfcc(mfcc, order=1) | |
| delta2 = extract_delta_mfcc(mfcc, order=2) | |
| return np.vstack([mfcc, delta, delta2]) | |
| def extract_mfcc_features( | |
| audio: np.ndarray, | |
| sr: int = SAMPLE_RATE, | |
| n_mfcc: int = N_MFCC | |
| ) -> Dict[str, float]: | |
| """ | |
| Extract MFCC-based features with statistics. | |
| Args: | |
| audio: Audio waveform | |
| sr: Sample rate | |
| n_mfcc: Number of MFCCs | |
| Returns: | |
| Dictionary of MFCC statistics | |
| """ | |
| mfcc = extract_mfcc(audio, sr, n_mfcc=n_mfcc) | |
| delta = extract_delta_mfcc(mfcc, order=1) | |
| features = {} | |
| # Statistics for each MFCC coefficient | |
| for i in range(n_mfcc): | |
| features[f"mfcc_{i}_mean"] = float(np.mean(mfcc[i])) | |
| features[f"mfcc_{i}_std"] = float(np.std(mfcc[i])) | |
| features[f"delta_mfcc_{i}_mean"] = float(np.mean(delta[i])) | |
| features[f"delta_mfcc_{i}_std"] = float(np.std(delta[i])) | |
| # Global MFCC statistics | |
| features["mfcc_mean_energy"] = float(np.mean(np.sum(mfcc**2, axis=0))) | |
| features["mfcc_std_energy"] = float(np.std(np.sum(mfcc**2, axis=0))) | |
| return features | |
| def get_mfcc_feature_vector( | |
| audio: np.ndarray, | |
| sr: int = SAMPLE_RATE, | |
| n_mfcc: int = N_MFCC | |
| ) -> np.ndarray: | |
| """ | |
| Get flattened feature vector from MFCC features. | |
| Args: | |
| audio: Audio waveform | |
| sr: Sample rate | |
| n_mfcc: Number of MFCCs | |
| Returns: | |
| 1D numpy array of MFCC-based features | |
| """ | |
| features = extract_mfcc_features(audio, sr, n_mfcc) | |
| return np.array(list(features.values())) | |
| def prepare_spectrogram_for_cnn( | |
| audio: np.ndarray, | |
| sr: int = SAMPLE_RATE, | |
| target_shape: Tuple[int, int] = (128, 128) | |
| ) -> np.ndarray: | |
| """ | |
| Prepare Mel-spectrogram for CNN input. | |
| Args: | |
| audio: Audio waveform | |
| sr: Sample rate | |
| target_shape: Target (height, width) for the spectrogram | |
| Returns: | |
| Normalized spectrogram array with shape (1, height, width) | |
| """ | |
| mel_spec = extract_mel_spectrogram(audio, sr, n_mels=target_shape[0]) | |
| # Resize to target width if needed | |
| if mel_spec.shape[1] > target_shape[1]: | |
| mel_spec = mel_spec[:, :target_shape[1]] | |
| elif mel_spec.shape[1] < target_shape[1]: | |
| padding = target_shape[1] - mel_spec.shape[1] | |
| mel_spec = np.pad(mel_spec, ((0, 0), (0, padding)), mode='constant') | |
| # Normalize to [0, 1] | |
| mel_spec = (mel_spec - mel_spec.min()) / (mel_spec.max() - mel_spec.min() + 1e-8) | |
| # Add channel dimension | |
| return mel_spec[np.newaxis, :, :] | |