File size: 6,104 Bytes
0468ff5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
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()))