# SPDX-License-Identifier: Apache-2.0 """Audio front end, a clean-room numpy port of transformers ``Gemma4AudioFeatureExtractor`` (as configured by the snapshot's preprocessor_config.json): 16 kHz mono, truncate to 30 s, right-pad to a multiple of 128 samples, semicausal left pad of 160, 321-sample frames every 160 samples (last sample dropped, no preemphasis), periodic Hann(320), |rfft_512|, 128 HTK mel filters (0-8 kHz, no norm), log(mel + 1e-3); frames whose window reaches into the padding are zeroed and masked.""" from __future__ import annotations import math from typing import Tuple import numpy as np from .. import model_spec as S _CACHE = {} def _mel_filters() -> np.ndarray: if "mel" not in _CACHE: def h2m(f): return 2595.0 * np.log10(1.0 + f / 700.0) def m2h(m): return 700.0 * (np.power(10, m / 2595.0) - 1.0) nbins = S.A_FFT // 2 + 1 mel = np.linspace(h2m(0.0), h2m(8000.0), S.A_MEL + 2) ff = m2h(mel) fft_freqs = np.linspace(0, S.A_SR // 2, nbins) diff = np.diff(ff) slopes = ff[None, :] - fft_freqs[:, None] down = -slopes[:, :-2] / diff[:-1] up = slopes[:, 2:] / diff[1:] _CACHE["mel"] = np.maximum(np.zeros(1), np.minimum(down, up)) # [257, 128] float64 win = np.hanning(S.A_FRAME + 1)[:-1] # periodic Hann _CACHE["win"] = win.astype(np.float32) return _CACHE["mel"] def resample(wave: np.ndarray, sr: int) -> np.ndarray: """-> 16 kHz float32 (polyphase, scipy if available, else linear interpolation).""" wave = np.asarray(wave, dtype=np.float32) if wave.ndim == 2: wave = wave.mean(axis=0 if wave.shape[0] < wave.shape[1] else 1) if sr == S.A_SR: return wave try: from scipy.signal import resample_poly g = math.gcd(int(sr), S.A_SR) return resample_poly(wave, S.A_SR // g, int(sr) // g).astype(np.float32) except ImportError: n = int(round(len(wave) * S.A_SR / sr)) return np.interp(np.arange(n) * (sr / S.A_SR), np.arange(len(wave)), wave).astype(np.float32) def log_mel(wave: np.ndarray, max_samples: int = S.A_MAX_SAMPLES) -> Tuple[np.ndarray, np.ndarray]: """16 kHz mono float waveform -> (features [T, 128] float32 (zero where masked), mask [T] bool).""" mel = _mel_filters() win = _CACHE["win"] x = np.asarray(wave, dtype=np.float32).reshape(-1)[:max_samples] n = len(x) padded = int(math.ceil(max(n, 1) / S.A_PAD_MULT) * S.A_PAD_MULT) xp = np.zeros(padded, dtype=np.float32) xp[:n] = x am = np.zeros(padded, dtype=np.int32) am[:n] = 1 pl = S.A_FRAME // 2 xp = np.pad(xp, (pl, 0)) am = np.pad(am, (pl, 0)) size = S.A_FRAME + 1 nf = (len(xp) - size) // S.A_HOP + 1 if nf <= 0: return np.zeros((0, S.A_MEL), np.float32), np.zeros((0,), bool) idx = np.arange(nf)[:, None] * S.A_HOP + np.arange(size)[None, :] frames = xp[idx][:, :-1] * win spec = np.abs(np.fft.rfft(frames, n=S.A_FFT, axis=-1)) lm = np.log(spec @ mel + S.A_MEL_FLOOR).astype(np.float32) mask = am[np.arange(nf) * S.A_HOP + size - 1].astype(bool) return lm * mask[:, None], mask def n_tokens(mask: np.ndarray) -> int: m = np.asarray(mask) for _ in range(2): m = m[::2][: (len(m) + 2 - 3) // 2 + 1] return int(m.sum())