""" Spectral Feature Extraction Extract spectral centroid, rolloff, bandwidth, and other spectral features. """ import numpy as np import librosa from typing import Dict, 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, ROLLOFF_PERCENT def extract_spectral_centroid( audio: np.ndarray, sr: int = SAMPLE_RATE, n_fft: int = N_FFT, hop_length: int = HOP_LENGTH ) -> np.ndarray: """ Extract spectral centroid - the "center of mass" of the spectrum. AI voices often have a more static/stable centroid compared to human voices which show more natural variation. Args: audio: Audio waveform sr: Sample rate n_fft: FFT window size hop_length: Hop length Returns: Spectral centroid values over time """ centroid = librosa.feature.spectral_centroid( y=audio, sr=sr, n_fft=n_fft, hop_length=hop_length ) return centroid[0] def extract_spectral_rolloff( audio: np.ndarray, sr: int = SAMPLE_RATE, n_fft: int = N_FFT, hop_length: int = HOP_LENGTH, roll_percent: float = ROLLOFF_PERCENT ) -> np.ndarray: """ Extract spectral rolloff - frequency below which a percentage of energy lies. AI-generated audio often shows sharp cutoffs around certain frequencies (e.g., vocoder artifacts). Args: audio: Audio waveform sr: Sample rate n_fft: FFT window size hop_length: Hop length roll_percent: Energy percentage threshold (0.85 = 85%) Returns: Spectral rolloff frequencies over time """ rolloff = librosa.feature.spectral_rolloff( y=audio, sr=sr, n_fft=n_fft, hop_length=hop_length, roll_percent=roll_percent ) return rolloff[0] def extract_spectral_bandwidth( audio: np.ndarray, sr: int = SAMPLE_RATE, n_fft: int = N_FFT, hop_length: int = HOP_LENGTH ) -> np.ndarray: """ Extract spectral bandwidth - weighted standard deviation of frequencies. Args: audio: Audio waveform sr: Sample rate n_fft: FFT window size hop_length: Hop length Returns: Spectral bandwidth values over time """ bandwidth = librosa.feature.spectral_bandwidth( y=audio, sr=sr, n_fft=n_fft, hop_length=hop_length ) return bandwidth[0] def extract_spectral_flatness( audio: np.ndarray, n_fft: int = N_FFT, hop_length: int = HOP_LENGTH ) -> np.ndarray: """ Extract spectral flatness - measure of how noise-like vs tonal the sound is. AI voices may show different flatness patterns than human voices. Args: audio: Audio waveform n_fft: FFT window size hop_length: Hop length Returns: Spectral flatness values over time """ flatness = librosa.feature.spectral_flatness( y=audio, n_fft=n_fft, hop_length=hop_length ) return flatness[0] def extract_spectral_contrast( audio: np.ndarray, sr: int = SAMPLE_RATE, n_fft: int = N_FFT, hop_length: int = HOP_LENGTH, n_bands: int = 6 ) -> np.ndarray: """ Extract spectral contrast - difference between peaks and valleys in spectrum. Args: audio: Audio waveform sr: Sample rate n_fft: FFT window size hop_length: Hop length n_bands: Number of frequency bands Returns: Spectral contrast matrix (n_bands+1, time) """ contrast = librosa.feature.spectral_contrast( y=audio, sr=sr, n_fft=n_fft, hop_length=hop_length, n_bands=n_bands ) return contrast def extract_zero_crossing_rate( audio: np.ndarray, hop_length: int = HOP_LENGTH ) -> np.ndarray: """ Extract zero-crossing rate - rate at which signal changes sign. Args: audio: Audio waveform hop_length: Hop length Returns: Zero-crossing rate values over time """ zcr = librosa.feature.zero_crossing_rate(y=audio, hop_length=hop_length) return zcr[0] def extract_spectral_features( audio: np.ndarray, sr: int = SAMPLE_RATE, n_fft: int = N_FFT, hop_length: int = HOP_LENGTH ) -> Dict[str, np.ndarray]: """ Extract all spectral features from audio. Args: audio: Audio waveform sr: Sample rate n_fft: FFT window size hop_length: Hop length Returns: Dictionary of spectral features with statistics """ # Extract raw features centroid = extract_spectral_centroid(audio, sr, n_fft, hop_length) rolloff = extract_spectral_rolloff(audio, sr, n_fft, hop_length) bandwidth = extract_spectral_bandwidth(audio, sr, n_fft, hop_length) flatness = extract_spectral_flatness(audio, n_fft, hop_length) zcr = extract_zero_crossing_rate(audio, hop_length) # Compute statistics for each feature features = {} for name, values in [ ("centroid", centroid), ("rolloff", rolloff), ("bandwidth", bandwidth), ("flatness", flatness), ("zcr", zcr) ]: features[f"{name}_mean"] = float(np.mean(values)) features[f"{name}_std"] = float(np.std(values)) features[f"{name}_max"] = float(np.max(values)) features[f"{name}_min"] = float(np.min(values)) # Variation coefficient (indicator of stability) if np.mean(values) != 0: features[f"{name}_cv"] = float(np.std(values) / np.mean(values)) else: features[f"{name}_cv"] = 0.0 return features def get_spectral_feature_vector( audio: np.ndarray, sr: int = SAMPLE_RATE ) -> np.ndarray: """ Get flattened feature vector from spectral features. Args: audio: Audio waveform sr: Sample rate Returns: 1D numpy array of spectral features """ features = extract_spectral_features(audio, sr) return np.array(list(features.values()))