Spaces:
Sleeping
Sleeping
Download src/analysis/audio_analyzer.py from Shahzroux/audio-mastering-engine: direct link, hf CLI and curl.
- Browser
- Download file 11.1 kB
-
https://huggingface.co/spaces/Shahzroux/audio-mastering-engine/resolve/main/src/analysis/audio_analyzer.py
- Command line
-
hf download hf://spaces/Shahzroux/audio-mastering-engine/src/analysis/audio_analyzer.py
-
curl -L -o audio_analyzer.py https://huggingface.co/spaces/Shahzroux/audio-mastering-engine/resolve/main/src/analysis/audio_analyzer.py
11.1 kB
| """ | |
| Audio Analysis Module | |
| Extracts comprehensive features from audio files for AI processing | |
| """ | |
| import librosa | |
| import numpy as np | |
| import pyloudnorm as pyln | |
| from scipy import signal | |
| from typing import Dict, Optional | |
| import warnings | |
| warnings.filterwarnings('ignore') | |
| class AudioAnalyzer: | |
| """ | |
| Comprehensive audio analysis for mastering | |
| """ | |
| def __init__(self, sample_rate: int = 44100): | |
| self.sample_rate = sample_rate | |
| self.loudness_meter = pyln.Meter(sample_rate) | |
| def analyze(self, audio_path: str) -> Dict: | |
| """ | |
| Main analysis function - extracts all features | |
| Args: | |
| audio_path: Path to audio file | |
| Returns: | |
| Dictionary containing all audio features | |
| """ | |
| print(f"π΅ Analyzing: {audio_path}") | |
| # Load audio | |
| audio, sr = librosa.load(audio_path, sr=self.sample_rate, mono=False) | |
| # Handle stereo/mono | |
| if len(audio.shape) == 1: | |
| audio_mono = audio | |
| is_stereo = False | |
| else: | |
| audio_mono = librosa.to_mono(audio) | |
| is_stereo = True | |
| features = { | |
| 'file_path': audio_path, | |
| 'is_stereo': is_stereo, | |
| 'sample_rate': sr, | |
| 'duration': len(audio_mono) / sr | |
| } | |
| # Run all analysis | |
| print(" π Analyzing loudness...") | |
| features.update(self._analyze_loudness(audio_mono, audio if is_stereo else None)) | |
| print(" πΌ Analyzing spectrum...") | |
| features.update(self._analyze_spectrum(audio_mono, sr)) | |
| print(" π Analyzing dynamics...") | |
| features.update(self._analyze_dynamics(audio_mono)) | |
| if is_stereo: | |
| print(" π Analyzing stereo field...") | |
| features.update(self._analyze_stereo(audio)) | |
| print(" πΉ Analyzing musical content...") | |
| features.update(self._analyze_musical(audio_mono, sr)) | |
| print("β Analysis complete!\n") | |
| return features | |
| def _analyze_loudness(self, audio_mono, audio_stereo=None) -> Dict: | |
| """Analyze loudness metrics""" | |
| features = {} | |
| # LUFS (integrated loudness) | |
| try: | |
| features['integrated_lufs'] = self.loudness_meter.integrated_loudness(audio_mono) | |
| except: | |
| features['integrated_lufs'] = -70.0 | |
| # Peak level | |
| features['peak_db'] = float(20 * np.log10(np.abs(audio_mono).max() + 1e-10)) | |
| # True peak (for stereo) | |
| if audio_stereo is not None: | |
| features['true_peak_db'] = float(20 * np.log10( | |
| np.abs(audio_stereo).max() + 1e-10 | |
| )) | |
| else: | |
| features['true_peak_db'] = features['peak_db'] | |
| # RMS level | |
| rms = np.sqrt(np.mean(audio_mono ** 2)) | |
| features['rms_db'] = float(20 * np.log10(rms + 1e-10)) | |
| # Crest factor (peak to RMS ratio) | |
| features['crest_factor'] = features['peak_db'] - features['rms_db'] | |
| return features | |
| def _analyze_spectrum(self, audio, sr) -> Dict: | |
| """Analyze frequency spectrum""" | |
| features = {} | |
| # Compute spectrogram | |
| S = np.abs(librosa.stft(audio)) | |
| # Spectral centroid (brightness) | |
| centroid = librosa.feature.spectral_centroid(S=S, sr=sr) | |
| features['spectral_centroid'] = float(np.mean(centroid)) | |
| # Spectral bandwidth | |
| bandwidth = librosa.feature.spectral_bandwidth(S=S, sr=sr) | |
| features['spectral_bandwidth'] = float(np.mean(bandwidth)) | |
| # Spectral rolloff (frequency below which 85% of energy is) | |
| rolloff = librosa.feature.spectral_rolloff(S=S, sr=sr, roll_percent=0.85) | |
| features['spectral_rolloff'] = float(np.mean(rolloff)) | |
| # Frequency band energy distribution | |
| features['bass_energy'] = self._band_energy(audio, sr, 20, 200) | |
| features['low_mid_energy'] = self._band_energy(audio, sr, 200, 500) | |
| features['mid_energy'] = self._band_energy(audio, sr, 500, 2000) | |
| features['high_mid_energy'] = self._band_energy(audio, sr, 2000, 6000) | |
| features['high_energy'] = self._band_energy(audio, sr, 6000, 20000) | |
| # Tonal balance | |
| total_energy = (features['bass_energy'] + features['low_mid_energy'] + | |
| features['mid_energy'] + features['high_mid_energy'] + | |
| features['high_energy']) | |
| features['bass_ratio'] = features['bass_energy'] / (total_energy + 1e-10) | |
| features['mid_ratio'] = features['mid_energy'] / (total_energy + 1e-10) | |
| features['high_ratio'] = features['high_energy'] / (total_energy + 1e-10) | |
| return features | |
| def _analyze_dynamics(self, audio) -> Dict: | |
| """Analyze dynamic range and envelope""" | |
| features = {} | |
| # Dynamic range (simplified DR meter) | |
| rms = librosa.feature.rms(y=audio)[0] | |
| peak = np.abs(audio).max() | |
| rms_db = 20 * np.log10(np.mean(rms) + 1e-10) | |
| peak_db = 20 * np.log10(peak + 1e-10) | |
| features['dynamic_range'] = float(peak_db - rms_db) | |
| # RMS envelope statistics | |
| features['dynamics_std'] = float(np.std(rms)) | |
| features['dynamics_variance'] = float(np.var(rms)) | |
| # Transient vs sustained energy | |
| hop_length = 512 | |
| rms_smooth = np.convolve(rms, np.ones(10)/10, mode='same') | |
| transient_mask = rms > rms_smooth * 1.5 | |
| features['transient_ratio'] = float(np.sum(transient_mask) / len(rms)) | |
| return features | |
| def _analyze_stereo(self, audio_stereo) -> Dict: | |
| """Analyze stereo field""" | |
| features = {} | |
| left = audio_stereo[0] | |
| right = audio_stereo[1] | |
| # Mid/Side calculation | |
| mid = (left + right) / 2 | |
| side = (left - right) / 2 | |
| # Stereo width (based on mid/side energy) | |
| mid_energy = np.sum(mid ** 2) | |
| side_energy = np.sum(side ** 2) | |
| total_energy = mid_energy + side_energy | |
| features['stereo_width'] = float(side_energy / (total_energy + 1e-10)) | |
| # Phase correlation | |
| correlation = np.corrcoef(left, right)[0, 1] | |
| features['phase_correlation'] = float(correlation) | |
| # Balance (L/R energy difference) | |
| left_energy = np.sum(left ** 2) | |
| right_energy = np.sum(right ** 2) | |
| if left_energy + right_energy > 0: | |
| features['lr_balance'] = float( | |
| (left_energy - right_energy) / (left_energy + right_energy) | |
| ) | |
| else: | |
| features['lr_balance'] = 0.0 | |
| return features | |
| def _analyze_musical(self, audio, sr) -> Dict: | |
| """Analyze musical content""" | |
| features = {} | |
| # Tempo detection | |
| try: | |
| tempo, beats = librosa.beat.beat_track(y=audio, sr=sr) | |
| features['tempo'] = float(tempo) | |
| features['beat_strength'] = float(np.mean( | |
| librosa.onset.onset_strength(y=audio, sr=sr) | |
| )) | |
| except: | |
| features['tempo'] = 120.0 | |
| features['beat_strength'] = 0.5 | |
| # Harmonic/Percussive separation | |
| try: | |
| y_harmonic, y_percussive = librosa.effects.hpss(audio) | |
| harmonic_energy = np.sum(y_harmonic ** 2) | |
| percussive_energy = np.sum(y_percussive ** 2) | |
| total = harmonic_energy + percussive_energy | |
| features['harmonic_ratio'] = float(harmonic_energy / (total + 1e-10)) | |
| features['percussive_ratio'] = float(percussive_energy / (total + 1e-10)) | |
| except: | |
| features['harmonic_ratio'] = 0.5 | |
| features['percussive_ratio'] = 0.5 | |
| # Zero crossing rate (indicator of noisiness) | |
| zcr = librosa.feature.zero_crossing_rate(audio) | |
| features['zero_crossing_rate'] = float(np.mean(zcr)) | |
| return features | |
| def _band_energy(self, audio, sr, low_freq, high_freq) -> float: | |
| """Calculate energy in frequency band""" | |
| # Design bandpass filter | |
| nyquist = sr / 2 | |
| low = low_freq / nyquist | |
| high = min(high_freq / nyquist, 0.99) | |
| if low >= high or low <= 0: | |
| return 0.0 | |
| try: | |
| sos = signal.butter(4, [low, high], btype='band', output='sos') | |
| filtered = signal.sosfilt(sos, audio) | |
| energy = float(np.sum(filtered ** 2)) | |
| return energy | |
| except: | |
| return 0.0 | |
| def print_analysis(self, features: Dict): | |
| """Print formatted analysis results""" | |
| print("\n" + "="*60) | |
| print("π AUDIO ANALYSIS REPORT") | |
| print("="*60) | |
| print(f"\nπ FILE INFO:") | |
| print(f" Path: {features['file_path']}") | |
| print(f" Duration: {features['duration']:.2f} seconds") | |
| print(f" Stereo: {'Yes' if features['is_stereo'] else 'No'}") | |
| print(f"\nπ LOUDNESS:") | |
| print(f" Integrated LUFS: {features['integrated_lufs']:.1f} LUFS") | |
| print(f" Peak Level: {features['peak_db']:.1f} dBFS") | |
| print(f" True Peak: {features['true_peak_db']:.1f} dBTP") | |
| print(f" RMS Level: {features['rms_db']:.1f} dBFS") | |
| print(f" Crest Factor: {features['crest_factor']:.1f} dB") | |
| print(f"\nπΌ SPECTRUM:") | |
| print(f" Centroid: {features['spectral_centroid']:.0f} Hz") | |
| print(f" Bass Ratio: {features['bass_ratio']*100:.1f}%") | |
| print(f" Mid Ratio: {features['mid_ratio']*100:.1f}%") | |
| print(f" High Ratio: {features['high_ratio']*100:.1f}%") | |
| print(f"\nπ DYNAMICS:") | |
| print(f" Dynamic Range: {features['dynamic_range']:.1f} dB") | |
| print(f" Transient Content: {features['transient_ratio']*100:.1f}%") | |
| if features['is_stereo']: | |
| print(f"\nπ STEREO:") | |
| print(f" Stereo Width: {features['stereo_width']:.2f}") | |
| print(f" Phase Correlation: {features['phase_correlation']:.2f}") | |
| print(f" L/R Balance: {features['lr_balance']:.3f}") | |
| print(f"\nπΉ MUSICAL:") | |
| print(f" Tempo: {features['tempo']:.1f} BPM") | |
| print(f" Harmonic Content: {features['harmonic_ratio']*100:.1f}%") | |
| print(f" Percussive Content: {features['percussive_ratio']*100:.1f}%") | |
| print("\n" + "="*60 + "\n") | |
| # Example usage | |
| if __name__ == "__main__": | |
| # Test the analyzer | |
| analyzer = AudioAnalyzer() | |
| # Replace with your audio file | |
| audio_file = "path/to/your/audio.wav" | |
| try: | |
| features = analyzer.analyze(audio_file) | |
| analyzer.print_analysis(features) | |
| except Exception as e: | |
| print(f"Error: {e}") | |
| print("\nPlease provide a valid audio file path.") | |