Download data/audio_processor.py from ViuAI/Murli-V1.6-Code: direct link, hf CLI and curl.
- Browser
- Download file 7.32 kB
-
https://huggingface.co/ViuAI/Murli-V1.6-Code/resolve/main/data/audio_processor.py
- Command line
-
hf download hf://ViuAI/Murli-V1.6-Code/data/audio_processor.py
-
curl -L -o audio_processor.py https://huggingface.co/ViuAI/Murli-V1.6-Code/resolve/main/data/audio_processor.py
7.32 kB
| """ | |
| Murli V1.6 Audio, Log-Mel Spectrogram, Pitch (F0), and Energy Extractor. | |
| Matches 24kHz / 100-bin HTK Mel specification cleanly with NaN guards and multi-container byte decoding. | |
| """ | |
| import io | |
| import math | |
| from typing import Tuple | |
| import numpy as np | |
| import torch | |
| import torch.nn as nn | |
| import torch.nn.functional as F | |
| try: | |
| import soundfile as sf | |
| except ImportError: | |
| sf = None | |
| from scipy.io import wavfile | |
| from config import AudioConfig | |
| def _decode_pcm_with_scipy(src) -> Tuple[torch.Tensor, int]: | |
| sr, data = wavfile.read(src) | |
| arr = np.asarray(data) | |
| if arr.dtype == np.uint8: | |
| arr = (arr.astype(np.float32) - 128.0) / 128.0 | |
| elif np.issubdtype(arr.dtype, np.integer): | |
| arr = arr.astype(np.float32) / float(-int(np.iinfo(arr.dtype).min)) | |
| else: | |
| arr = arr.astype(np.float32) | |
| if arr.ndim == 1: | |
| arr = arr[:, None] | |
| return torch.from_numpy(arr.T.copy()), int(sr) | |
| def read_audio_bytes(raw_bytes: bytes) -> Tuple[torch.Tensor, int]: | |
| """Decode WAV/FLAC/OGG audio bytes cleanly into float32 tensor [C, N] and sample rate.""" | |
| if sf is not None: | |
| data, sr = sf.read(io.BytesIO(raw_bytes), dtype="float32", always_2d=True) | |
| return torch.from_numpy(data.T.copy()), int(sr) | |
| return _decode_pcm_with_scipy(io.BytesIO(raw_bytes)) | |
| def read_audio_file(path: str) -> Tuple[torch.Tensor, int]: | |
| if sf is not None: | |
| data, sr = sf.read(path, dtype="float32", always_2d=True) | |
| return torch.from_numpy(data.T.copy()), int(sr) | |
| return _decode_pcm_with_scipy(path) | |
| def _hz_to_mel_htk(f: np.ndarray) -> np.ndarray: | |
| return 2595.0 * np.log10(1.0 + f / 700.0) | |
| def _mel_to_hz_htk(m: np.ndarray) -> np.ndarray: | |
| return 700.0 * (10.0 ** (m / 2595.0) - 1.0) | |
| def build_mel_filterbank(cfg: AudioConfig) -> torch.Tensor: | |
| if cfg.mel_scale == "slaney": | |
| from librosa.filters import mel | |
| return torch.from_numpy(mel(sr=cfg.sample_rate, n_fft=cfg.n_fft, n_mels=cfg.n_mels, | |
| fmin=cfg.f_min, fmax=cfg.f_max, htk=False, norm="slaney")) | |
| n_freqs = cfg.n_fft // 2 + 1 | |
| freqs = np.linspace(0.0, cfg.sample_rate / 2.0, n_freqs) | |
| m_min = _hz_to_mel_htk(np.array([cfg.f_min]))[0] | |
| m_max = _hz_to_mel_htk(np.array([cfg.f_max]))[0] | |
| m_pts = np.linspace(m_min, m_max, cfg.n_mels + 2) | |
| f_pts = _mel_to_hz_htk(m_pts) | |
| fb = np.zeros((cfg.n_mels, n_freqs), dtype=np.float32) | |
| for m in range(cfg.n_mels): | |
| f_left, f_center, f_right = f_pts[m], f_pts[m + 1], f_pts[m + 2] | |
| left_slope = (freqs - f_left) / max(f_center - f_left, 1e-6) | |
| right_slope = (f_right - freqs) / max(f_right - f_center, 1e-6) | |
| fb[m] = np.maximum(0.0, np.minimum(left_slope, right_slope)) | |
| return torch.from_numpy(fb) | |
| class AudioProcessor(nn.Module): | |
| """Extracts 100-bin log-mel spectrograms, frame-level log-F0, and normalized frame energy.""" | |
| def __init__(self, cfg: AudioConfig = AudioConfig()): | |
| super().__init__() | |
| self.cfg = cfg | |
| self.register_buffer("window", torch.hann_window(cfg.win_length), persistent=False) | |
| self.register_buffer("mel_fb", build_mel_filterbank(cfg), persistent=False) | |
| def normalize_waveform(self, wav: torch.Tensor, sr: int) -> torch.Tensor: | |
| if wav.dim() == 2: | |
| wav = wav.mean(dim=0) | |
| if sr <= 0 or wav.ndim != 1 or not wav.numel() or not torch.isfinite(wav).all(): | |
| raise ValueError("Expected finite nonempty audio with a positive sample rate") | |
| if sr != self.cfg.sample_rate: | |
| from scipy.signal import resample_poly | |
| factor = math.gcd(sr, self.cfg.sample_rate) | |
| samples = resample_poly(wav.detach().float().cpu().numpy(), self.cfg.sample_rate // factor, sr // factor) | |
| wav = torch.from_numpy(samples).float().to(wav.device) | |
| wav = wav.float() | |
| peak = wav.abs().max().item() | |
| if peak <= 1e-4 or wav.max() == wav.min(): | |
| raise ValueError("Silent or constant waveform") | |
| return wav / peak * 0.95 | |
| def extract_features(self, wav: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: | |
| """ | |
| Args: | |
| wav: 1D normalized 24kHz float32 waveform [N] | |
| Returns: | |
| mel: [100, T] log-mel spectrogram | |
| log_f0: [T] normalized log-F0 curve (0 on unvoiced) | |
| energy: [T] log-RMS frame energy | |
| """ | |
| if wav.numel() < self.cfg.n_fft: | |
| wav = F.pad(wav, (0, self.cfg.n_fft - wav.numel())) | |
| pad = self.cfg.n_fft // 2 if self.cfg.center else (self.cfg.n_fft - self.cfg.hop_length) // 2 | |
| wav_padded = F.pad(wav.unsqueeze(0), (pad, pad), mode="reflect").squeeze(0) | |
| stft = torch.stft( | |
| wav_padded, | |
| n_fft=self.cfg.n_fft, | |
| hop_length=self.cfg.hop_length, | |
| win_length=self.cfg.win_length, | |
| window=self.window.to(wav.device), | |
| center=False, | |
| return_complex=True, | |
| ) | |
| mag = stft.abs() | |
| mel = torch.matmul(self.mel_fb.to(wav.device), mag).clamp(min=self.cfg.mel_min_clip).log() | |
| t_frames = mel.shape[-1] | |
| raw_energy = torch.log(mag.pow(2).mean(dim=0).sqrt().clamp(min=1e-5)) | |
| # Center & scale log-RMS energy to match normalized mel/F0 scale (~[-2.5, +1.5]) | |
| energy = (raw_energy + 5.0) / 2.5 | |
| # Lightweight frame-wise autocorrelation pitch (F0) estimator | |
| start = (self.cfg.n_fft - self.cfg.win_length) // 2 | |
| frames = wav_padded[start:].unfold(0, self.cfg.win_length, self.cfg.hop_length)[:t_frames] | |
| frames = frames - frames.mean(dim=-1, keepdim=True) | |
| min_lag = max(1, math.ceil(self.cfg.sample_rate / self.cfg.f0_max)) | |
| max_lag = min(self.cfg.win_length // 2, int(self.cfg.sample_rate / self.cfg.f0_min)) | |
| if max_lag < min_lag: | |
| raise ValueError("Pitch range has no representable period at this window size") | |
| # Normalize the correlation by the energy of the overlapping samples at each lag. | |
| ac = torch.fft.irfft(torch.fft.rfft(frames, n=self.cfg.win_length * 2).abs().square(), | |
| n=self.cfg.win_length * 2) | |
| lags = torch.arange(min_lag - 1, max_lag + 2, device=frames.device) | |
| power = F.pad(frames.square().cumsum(-1), (1, 0)) | |
| left = power[:, self.cfg.win_length - lags] | |
| right = power[:, -1:] - power[:, lags] | |
| correlation = ac[:, lags] / (left * right).clamp_min(1e-12).sqrt() | |
| scores = correlation[:, 1:-1] | |
| peaks = (scores >= correlation[:, :-2]) & (scores >= correlation[:, 2:]) | |
| peak_scores = scores.masked_fill(~peaks, -1.0) | |
| strongest = peak_scores.amax(dim=1, keepdim=True) | |
| # Pick the earliest near-equal peak instead of a multiple of the fundamental period. | |
| voiced = peak_scores >= (strongest * 0.95).clamp_min(0.35) | |
| period = voiced.long().argmax(dim=1) + min_lag | |
| hz = torch.where(voiced.any(dim=1), self.cfg.sample_rate / period.float(), 0.0) | |
| # Reference at 40 Hz (< f0_min=50 Hz) so all voiced frames remain >= 0.223 and never collide with unvoiced 0.0 | |
| log_f0 = torch.where(hz > 0, torch.log(hz.clamp(min=1.0)) - math.log(40.0), torch.zeros_like(hz)) | |
| return mel, log_f0, energy | |