"""Self-contained spatial feature extraction for HF Space. Extracts 4-channel STFT features (log L, log R, sin IPD, cos IPD) from stereo audio. """ from __future__ import annotations from dataclasses import dataclass from pathlib import Path import numpy as np import soundfile as sf from scipy.signal import resample_poly, stft EPS = 1e-9 @dataclass(frozen=True) class SpatialFeatureConfig: sample_rate: int = 48_000 n_fft: int = 1024 hop_length: int = 512 freq_bins: int = 64 max_frames: int = 960 # ~10s at 48kHz/hop512 def load_audio_stereo(path: str | Path, target_sr: int = 48_000) -> tuple[np.ndarray, int]: audio, sr = sf.read(str(path), dtype="float32", always_2d=True) if audio.shape[1] == 1: audio = np.repeat(audio, 2, axis=1) elif audio.shape[1] > 2: audio = audio[:, :2] if sr != target_sr: channels = [resample_poly(audio[:, i], target_sr, sr) for i in range(2)] min_len = min(len(c) for c in channels) audio = np.stack([c[:min_len] for c in channels], axis=1).astype(np.float32) sr = target_sr return audio, sr def _mel_filterbank(n_fft_bins: int, n_mels: int, sr: int) -> np.ndarray: def hz2mel(hz): return 2595.0 * np.log10(1 + hz / 700.0) def mel2hz(m): return 700.0 * (10 ** (m / 2595.0) - 1) mel_pts = np.linspace(hz2mel(0), hz2mel(sr / 2), n_mels + 2) hz_pts = np.array([mel2hz(m) for m in mel_pts]) bins = np.floor((n_fft_bins * 2) * hz_pts / sr).astype(int) fb = np.zeros((n_mels, n_fft_bins), dtype=np.float32) for i in range(n_mels): lo, c, hi = bins[i], bins[i + 1], bins[i + 2] for j in range(lo, min(c, n_fft_bins)): fb[i, j] = (j - lo) / max(c - lo, 1) for j in range(c, min(hi, n_fft_bins)): fb[i, j] = (hi - j) / max(hi - c, 1) return fb _MEL_CACHE = {} def _resize_freq(m: np.ndarray, target: int, sr: int) -> np.ndarray: if m.shape[0] == target: return m key = (m.shape[0], target, sr) if key not in _MEL_CACHE: _MEL_CACHE[key] = _mel_filterbank(m.shape[0], target, sr) return (_MEL_CACHE[key] @ m).astype(np.float32) def _resize_time(m: np.ndarray, target: int) -> np.ndarray: if m.shape[1] == target: return m if m.shape[1] > target: return m[:, :target] pad = np.zeros((m.shape[0], target - m.shape[1]), dtype=m.dtype) return np.concatenate([m, pad], axis=1) def spatial_tensor_from_audio(audio: np.ndarray, sr: int, cfg: SpatialFeatureConfig | None = None) -> np.ndarray: """Stereo audio (samples, 2) -> (4, freq_bins, max_frames) spatial tensor.""" cfg = cfg or SpatialFeatureConfig(sample_rate=sr) left, right = audio[:, 0], audio[:, 1] _, _, L = stft(left, fs=sr, nperseg=cfg.n_fft, noverlap=cfg.n_fft - cfg.hop_length, boundary=None) _, _, R = stft(right, fs=sr, nperseg=cfg.n_fft, noverlap=cfg.n_fft - cfg.hop_length, boundary=None) t = min(L.shape[1], R.shape[1]) L, R = L[:, :t], R[:, :t] log_l = np.log1p(np.abs(L)).astype(np.float32) log_r = np.log1p(np.abs(R)).astype(np.float32) ipd = np.angle(L * np.conj(R)) sin_ipd = np.sin(ipd).astype(np.float32) cos_ipd = np.cos(ipd).astype(np.float32) channels = [_resize_time(_resize_freq(m, cfg.freq_bins, sr), cfg.max_frames) for m in (log_l, log_r, sin_ipd, cos_ipd)] return np.stack(channels, axis=0).astype(np.float32) def spatial_tensor_from_file(path: str | Path, cfg: SpatialFeatureConfig | None = None) -> np.ndarray: cfg = cfg or SpatialFeatureConfig() audio, sr = load_audio_stereo(path, target_sr=cfg.sample_rate) return spatial_tensor_from_audio(audio, sr, cfg)