audio-mastering-engine / src /analysis /audio_analyzer.py
Shahzroux's picture
Update src/analysis/audio_analyzer.py
eddb9d6 verified
Raw History Blame Contribute Delete
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.")