File size: 10,627 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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
"""
Prosodic Feature Extraction
Extract F0 (fundamental frequency), jitter, shimmer, and other prosodic features.
These features capture micro-variations that distinguish human from AI voices.
"""
import numpy as np
import librosa
from typing import Dict, Optional, Tuple

import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent.parent))
from config import SAMPLE_RATE, F0_MIN, F0_MAX, HOP_LENGTH

# Try to import parselmouth for advanced prosody analysis
try:
    import parselmouth
    from parselmouth.praat import call
    PARSELMOUTH_AVAILABLE = True
except ImportError:
    PARSELMOUTH_AVAILABLE = False


def extract_f0_librosa(
    audio: np.ndarray,
    sr: int = SAMPLE_RATE,
    fmin: float = F0_MIN,
    fmax: float = F0_MAX,
    hop_length: int = HOP_LENGTH
) -> np.ndarray:
    """
    Extract fundamental frequency using librosa's pyin algorithm.
    
    Args:
        audio: Audio waveform
        sr: Sample rate
        fmin: Minimum frequency
        fmax: Maximum frequency
        hop_length: Hop length
        
    Returns:
        F0 contour (with NaN for unvoiced frames)
    """
    f0, voiced_flag, voiced_probs = librosa.pyin(
        audio, fmin=fmin, fmax=fmax, sr=sr, hop_length=hop_length
    )
    return f0


def extract_f0_parselmouth(
    audio: np.ndarray,
    sr: int = SAMPLE_RATE,
    fmin: float = F0_MIN,
    fmax: float = F0_MAX
) -> np.ndarray:
    """
    Extract F0 using Parselmouth/Praat (more accurate for speech).
    
    Args:
        audio: Audio waveform
        sr: Sample rate
        fmin: Minimum frequency
        fmax: Maximum frequency
        
    Returns:
        F0 contour
    """
    if not PARSELMOUTH_AVAILABLE:
        return extract_f0_librosa(audio, sr, fmin, fmax)
    
    # Create Parselmouth Sound object
    sound = parselmouth.Sound(audio, sampling_frequency=sr)
    
    # Extract pitch
    pitch = call(sound, "To Pitch", 0.0, fmin, fmax)
    
    # Get F0 values
    n_frames = call(pitch, "Get number of frames")
    f0 = []
    for i in range(1, n_frames + 1):
        f0_value = call(pitch, "Get value in frame", i, "Hertz")
        f0.append(f0_value if not np.isnan(f0_value) else 0.0)
    
    return np.array(f0)


def extract_f0(
    audio: np.ndarray,
    sr: int = SAMPLE_RATE,
    fmin: float = F0_MIN,
    fmax: float = F0_MAX
) -> np.ndarray:
    """
    Extract fundamental frequency using best available method.
    
    Args:
        audio: Audio waveform
        sr: Sample rate
        fmin: Minimum frequency
        fmax: Maximum frequency
        
    Returns:
        F0 contour
    """
    if PARSELMOUTH_AVAILABLE:
        return extract_f0_parselmouth(audio, sr, fmin, fmax)
    return extract_f0_librosa(audio, sr, fmin, fmax)


def calculate_jitter(f0: np.ndarray) -> Dict[str, float]:
    """
    Calculate jitter (frequency perturbation) from F0 contour.
    
    Jitter measures cycle-to-cycle variations in frequency.
    Human voices have natural micro-perturbations, while AI voices
    are often too smooth or follow rigid mathematical curves.
    
    Args:
        f0: F0 contour (NaN/0 for unvoiced)
        
    Returns:
        Dictionary with jitter metrics
    """
    # Filter out unvoiced frames
    f0_voiced = f0[~np.isnan(f0) & (f0 > 0)]
    
    if len(f0_voiced) < 2:
        return {
            "jitter_local": 0.0,
            "jitter_local_abs": 0.0,
            "jitter_rap": 0.0,
            "jitter_ppq5": 0.0
        }
    
    # Convert to periods
    periods = 1.0 / f0_voiced
    
    # Local jitter (relative)
    diffs = np.abs(np.diff(periods))
    jitter_local = float(np.mean(diffs) / np.mean(periods)) if np.mean(periods) > 0 else 0.0
    
    # Local jitter (absolute) - in seconds
    jitter_local_abs = float(np.mean(diffs))
    
    # RAP (Relative Average Perturbation) - 3-point average
    if len(periods) >= 3:
        rap_diffs = []
        for i in range(1, len(periods) - 1):
            avg = (periods[i-1] + periods[i] + periods[i+1]) / 3
            rap_diffs.append(abs(periods[i] - avg))
        jitter_rap = float(np.mean(rap_diffs) / np.mean(periods)) if np.mean(periods) > 0 else 0.0
    else:
        jitter_rap = jitter_local
    
    # PPQ5 (5-point Period Perturbation Quotient)
    if len(periods) >= 5:
        ppq5_diffs = []
        for i in range(2, len(periods) - 2):
            avg = np.mean(periods[i-2:i+3])
            ppq5_diffs.append(abs(periods[i] - avg))
        jitter_ppq5 = float(np.mean(ppq5_diffs) / np.mean(periods)) if np.mean(periods) > 0 else 0.0
    else:
        jitter_ppq5 = jitter_rap
    
    return {
        "jitter_local": jitter_local,
        "jitter_local_abs": jitter_local_abs,
        "jitter_rap": jitter_rap,
        "jitter_ppq5": jitter_ppq5
    }


def calculate_shimmer(
    audio: np.ndarray,
    sr: int = SAMPLE_RATE,
    f0: Optional[np.ndarray] = None
) -> Dict[str, float]:
    """
    Calculate shimmer (amplitude perturbation).
    
    Shimmer measures cycle-to-cycle variations in amplitude.
    Like jitter, it captures the natural "noise" in human voices.
    
    Args:
        audio: Audio waveform
        sr: Sample rate
        f0: Optional precomputed F0 contour
        
    Returns:
        Dictionary with shimmer metrics
    """
    if PARSELMOUTH_AVAILABLE:
        return _calculate_shimmer_parselmouth(audio, sr)
    
    # Simplified shimmer calculation without Parselmouth
    return _calculate_shimmer_simple(audio, sr)


def _calculate_shimmer_parselmouth(
    audio: np.ndarray,
    sr: int
) -> Dict[str, float]:
    """Calculate shimmer using Parselmouth/Praat."""
    sound = parselmouth.Sound(audio, sampling_frequency=sr)
    
    try:
        point_process = call(sound, "To PointProcess (periodic, cc)", F0_MIN, F0_MAX)
        
        shimmer_local = call(
            [sound, point_process], "Get shimmer (local)", 0.0, 0.0, 
            0.0001, 0.02, 1.3, 1.6
        )
        shimmer_local_db = call(
            [sound, point_process], "Get shimmer (local, dB)", 0.0, 0.0,
            0.0001, 0.02, 1.3, 1.6
        )
        shimmer_apq3 = call(
            [sound, point_process], "Get shimmer (apq3)", 0.0, 0.0,
            0.0001, 0.02, 1.3, 1.6
        )
        shimmer_apq5 = call(
            [sound, point_process], "Get shimmer (apq5)", 0.0, 0.0,
            0.0001, 0.02, 1.3, 1.6
        )
        
        return {
            "shimmer_local": float(shimmer_local) if not np.isnan(shimmer_local) else 0.0,
            "shimmer_local_db": float(shimmer_local_db) if not np.isnan(shimmer_local_db) else 0.0,
            "shimmer_apq3": float(shimmer_apq3) if not np.isnan(shimmer_apq3) else 0.0,
            "shimmer_apq5": float(shimmer_apq5) if not np.isnan(shimmer_apq5) else 0.0
        }
    except Exception:
        return _calculate_shimmer_simple(audio, sr)


def _calculate_shimmer_simple(
    audio: np.ndarray,
    sr: int
) -> Dict[str, float]:
    """Simplified shimmer calculation using amplitude envelope."""
    # Compute amplitude envelope
    envelope = np.abs(librosa.effects.preemphasis(audio))
    
    # Compute frame-level amplitudes
    frame_length = int(sr * 0.025)  # 25ms frames
    hop_length = int(sr * 0.010)    # 10ms hop
    
    amplitudes = []
    for i in range(0, len(envelope) - frame_length, hop_length):
        frame = envelope[i:i + frame_length]
        amplitudes.append(np.max(frame))
    
    amplitudes = np.array(amplitudes)
    
    if len(amplitudes) < 2:
        return {
            "shimmer_local": 0.0,
            "shimmer_local_db": 0.0,
            "shimmer_apq3": 0.0,
            "shimmer_apq5": 0.0
        }
    
    # Local shimmer
    diffs = np.abs(np.diff(amplitudes))
    shimmer_local = float(np.mean(diffs) / np.mean(amplitudes)) if np.mean(amplitudes) > 0 else 0.0
    
    # Shimmer in dB
    shimmer_db = 20 * np.log10(1 + shimmer_local) if shimmer_local > 0 else 0.0
    
    return {
        "shimmer_local": shimmer_local,
        "shimmer_local_db": float(shimmer_db),
        "shimmer_apq3": shimmer_local,  # Simplified
        "shimmer_apq5": shimmer_local   # Simplified
    }


def extract_prosodic_features(
    audio: np.ndarray,
    sr: int = SAMPLE_RATE
) -> Dict[str, float]:
    """
    Extract all prosodic features from audio.
    
    Args:
        audio: Audio waveform
        sr: Sample rate
        
    Returns:
        Dictionary of prosodic features
    """
    features = {}
    
    # Extract F0
    f0 = extract_f0(audio, sr)
    f0_voiced = f0[~np.isnan(f0) & (f0 > 0)]
    
    # F0 statistics
    if len(f0_voiced) > 0:
        features["f0_mean"] = float(np.mean(f0_voiced))
        features["f0_std"] = float(np.std(f0_voiced))
        features["f0_max"] = float(np.max(f0_voiced))
        features["f0_min"] = float(np.min(f0_voiced))
        features["f0_range"] = float(np.max(f0_voiced) - np.min(f0_voiced))
        # Coefficient of variation - key indicator of naturalness
        features["f0_cv"] = float(np.std(f0_voiced) / np.mean(f0_voiced)) if np.mean(f0_voiced) > 0 else 0.0
    else:
        features["f0_mean"] = 0.0
        features["f0_std"] = 0.0
        features["f0_max"] = 0.0
        features["f0_min"] = 0.0
        features["f0_range"] = 0.0
        features["f0_cv"] = 0.0
    
    # Jitter features
    jitter = calculate_jitter(f0)
    features.update(jitter)
    
    # Shimmer features
    shimmer = calculate_shimmer(audio, sr, f0)
    features.update(shimmer)
    
    # Harmonics-to-Noise Ratio (HNR) - simplified version
    features["hnr"] = _calculate_hnr_simple(audio, sr)
    
    return features


def _calculate_hnr_simple(audio: np.ndarray, sr: int) -> float:
    """Calculate simplified Harmonics-to-Noise Ratio."""
    try:
        # Use librosa's harmonic-percussive separation
        harmonic, percussive = librosa.effects.hpss(audio)
        
        harmonic_energy = np.sum(harmonic ** 2)
        noise_energy = np.sum(percussive ** 2)
        
        if noise_energy > 0:
            hnr = 10 * np.log10(harmonic_energy / noise_energy)
            return float(np.clip(hnr, -20, 40))  # Clip to reasonable range
        return 0.0
    except Exception:
        return 0.0


def get_prosodic_feature_vector(
    audio: np.ndarray,
    sr: int = SAMPLE_RATE
) -> np.ndarray:
    """
    Get flattened feature vector from prosodic features.
    
    Args:
        audio: Audio waveform
        sr: Sample rate
        
    Returns:
        1D numpy array of prosodic features
    """
    features = extract_prosodic_features(audio, sr)
    return np.array(list(features.values()))