from __future__ import annotations import math from pathlib import Path import numpy as np PAPER_SAMPLE_RATE = 16_000 PAPER_DURATION_SECONDS = 6.0 PAPER_FRAME_LENGTH = 400 PAPER_HOP_LENGTH = 160 PAPER_FFT_LENGTH = 512 PAPER_TIME_FRAMES = 598 PAPER_FREQUENCY_BINS = 257 PAPER_SPECTROGRAM_SHAPE = (PAPER_TIME_FRAMES, PAPER_FREQUENCY_BINS, 2) def adjust_stft_width(stft: np.ndarray, target_width: int = 601) -> np.ndarray: if stft.ndim != 2 or stft.shape[1] <= 0: raise ValueError(f"STFT must be rank 2 with a non-empty time axis, got {stft.shape}") if target_width <= 0: raise ValueError("target_width must be positive") if stft.shape[1] == target_width: return stft if stft.shape[1] > target_width: return stft[:, :target_width] repeats = int(math.ceil(target_width / stft.shape[1])) return np.tile(stft, (1, repeats))[:, :target_width] def repeat_or_trim_waveform(waveform: np.ndarray, target_samples: int) -> np.ndarray: values = np.asarray(waveform, dtype=np.float32).reshape(-1) if target_samples <= 0: raise ValueError("target_samples must be positive") if values.size == 0: raise ValueError("Decoded audio waveform is empty") if values.size >= target_samples: return values[:target_samples] repeats = int(math.ceil(target_samples / values.size)) return np.tile(values, repeats)[:target_samples] def audio_to_complex_spectrogram( audio_path: str | Path, sr: int = PAPER_SAMPLE_RATE, duration: float = PAPER_DURATION_SECONDS, ) -> np.ndarray: import librosa if sr != PAPER_SAMPLE_RATE or duration != PAPER_DURATION_SECONDS: raise ValueError( "The paper-faithful contract is fixed at 16 kHz and 6.0 seconds; " f"got sr={sr}, duration={duration}" ) waveform, _ = librosa.load(str(audio_path), sr=sr, mono=True) waveform = repeat_or_trim_waveform(waveform, target_samples=int(round(sr * duration))) return waveform_to_complex_spectrogram(waveform) def waveform_to_complex_spectrogram(waveform: np.ndarray) -> np.ndarray: values = repeat_or_trim_waveform( np.asarray(waveform, dtype=np.float32), target_samples=int(PAPER_SAMPLE_RATE * PAPER_DURATION_SECONDS), ) frames = np.lib.stride_tricks.sliding_window_view(values, PAPER_FRAME_LENGTH)[ ::PAPER_HOP_LENGTH ] if frames.shape != (PAPER_TIME_FRAMES, PAPER_FRAME_LENGTH): raise ValueError(f"Unexpected framed waveform shape: {frames.shape}") window = np.hanning(PAPER_FRAME_LENGTH + 1)[:-1].astype(np.float32) stft = np.fft.rfft( frames * window[None, :], n=PAPER_FFT_LENGTH, axis=1, ) if stft.shape != (PAPER_TIME_FRAMES, PAPER_FREQUENCY_BINS): raise ValueError(f"Unexpected STFT shape: {stft.shape}") result = np.empty(PAPER_SPECTROGRAM_SHAPE, dtype=np.float32) result[:, :, 0] = stft.real.astype(np.float32, copy=False) result[:, :, 1] = stft.imag.astype(np.float32, copy=False) result = np.sign(result) * (np.abs(result) ** 0.3) if not np.isfinite(result).all(): raise ValueError("Spectrogram contains non-finite values") return result