"""Feature extraction into a compact, streamable binary store. Layout (written under ``features/``): * ``train.bin`` — a flat little-endian float32 blob. Audio samples and the flattened mel spectrogram for every clip are appended back to back. * ``train.dat`` — a JSONL index/manifest. One record per clip giving byte offsets and shapes into ``train.bin`` plus ``duration`` and ``sample_rate``. The writer streams one clip at a time, so memory usage is independent of the dataset size (works for datasets far larger than RAM). """ from __future__ import annotations import json from dataclasses import dataclass from pathlib import Path from typing import Iterable, Optional import numpy as np from video_vec2wav2_tokenizer.audio.extractor import load_wav from video_vec2wav2_tokenizer.utils.io import ensure_dir from video_vec2wav2_tokenizer.utils.logging import get_logger logger = get_logger(__name__) _FLOAT_BYTES = 4 # float32 def compute_mel_spectrogram( samples: np.ndarray, sample_rate: int, *, n_mels: int = 80, n_fft: int = 400, hop_length: int = 160, ) -> np.ndarray: """Return a log-mel spectrogram of shape ``(n_mels, n_frames)`` (float32). Uses librosa when available; otherwise falls back to a NumPy STFT + a triangular mel filterbank so the feature path has no hard dependency. """ try: import librosa # type: ignore mel = librosa.feature.melspectrogram( y=samples, sr=sample_rate, n_mels=n_mels, n_fft=n_fft, hop_length=hop_length ) log_mel = librosa.power_to_db(mel, ref=np.max) return log_mel.astype(np.float32) except ImportError: return _numpy_log_mel( samples, sample_rate, n_mels=n_mels, n_fft=n_fft, hop_length=hop_length ) def _hz_to_mel(hz: np.ndarray) -> np.ndarray: return 2595.0 * np.log10(1.0 + hz / 700.0) def _mel_to_hz(mel: np.ndarray) -> np.ndarray: return 700.0 * (10.0 ** (mel / 2595.0) - 1.0) def _mel_filterbank(sr: int, n_fft: int, n_mels: int) -> np.ndarray: n_freqs = n_fft // 2 + 1 fft_freqs = np.linspace(0, sr / 2, n_freqs) mel_min, mel_max = _hz_to_mel(np.array([0.0])), _hz_to_mel(np.array([sr / 2])) mel_points = np.linspace(mel_min[0], mel_max[0], n_mels + 2) hz_points = _mel_to_hz(mel_points) fb = np.zeros((n_mels, n_freqs), dtype=np.float32) for m in range(1, n_mels + 1): f_left, f_center, f_right = hz_points[m - 1], hz_points[m], hz_points[m + 1] left = (fft_freqs - f_left) / max(f_center - f_left, 1e-9) right = (f_right - fft_freqs) / max(f_right - f_center, 1e-9) fb[m - 1] = np.clip(np.minimum(left, right), 0.0, None) return fb def _numpy_log_mel( samples: np.ndarray, sr: int, *, n_mels: int, n_fft: int, hop_length: int ) -> np.ndarray: if samples.size < n_fft: samples = np.pad(samples, (0, n_fft - samples.size)) window = np.hanning(n_fft).astype(np.float32) n_frames = 1 + (len(samples) - n_fft) // hop_length stft = np.empty((n_fft // 2 + 1, n_frames), dtype=np.complex64) for i in range(n_frames): frame = samples[i * hop_length : i * hop_length + n_fft] * window stft[:, i] = np.fft.rfft(frame) power = (np.abs(stft) ** 2).astype(np.float32) fb = _mel_filterbank(sr, n_fft, n_mels) mel = fb @ power log_mel = 10.0 * np.log10(np.maximum(mel, 1e-10)) return log_mel.astype(np.float32) @dataclass(slots=True) class FeatureExtractor: """Stream clips into ``train.bin`` / ``train.dat``.""" sample_rate: int = 16000 n_mels: int = 80 n_fft: int = 400 hop_length: int = 160 split: str = "train" def extract_dataset( self, clip_paths: Iterable[str | Path], features_dir: str | Path, ) -> Path: """Write features for all ``clip_paths``. Returns the manifest path.""" features_dir = ensure_dir(features_dir) bin_path = features_dir / f"{self.split}.bin" dat_path = features_dir / f"{self.split}.dat" offset = 0 n = 0 with bin_path.open("wb") as bin_fh, dat_path.open("w", encoding="utf-8") as dat_fh: for clip_path in clip_paths: clip_path = Path(clip_path) samples, sr = load_wav(clip_path, sample_rate=self.sample_rate) mel = compute_mel_spectrogram( samples, sr, n_mels=self.n_mels, n_fft=self.n_fft, hop_length=self.hop_length ) audio_f32 = samples.astype(" %s", n, bin_path) return dat_path def read_feature_record( bin_path: str | Path, record: dict ) -> tuple[np.ndarray, np.ndarray]: """Read one clip's ``(audio, mel)`` arrays back from the binary store.""" with Path(bin_path).open("rb") as fh: fh.seek(record["audio_offset"]) audio = np.frombuffer( fh.read(record["audio_length"] * _FLOAT_BYTES), dtype="