File size: 5,573 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
"""
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, :, :]