Download features/prosody.py from devmm03/vs: direct link, hf CLI and curl.
- Browser
- Download file 10.6 kB
-
https://huggingface.co/spaces/devmm03/vs/resolve/main/features/prosody.py
- Command line
-
hf download hf://spaces/devmm03/vs/features/prosody.py
-
curl -L -o prosody.py https://huggingface.co/spaces/devmm03/vs/resolve/main/features/prosody.py
10.6 kB
| """ | |
| 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())) | |