Download data/audio_processor.py from ViuAI/TTS_10M: direct link, hf CLI and curl.
- Browser
- Download file 3.68 kB
-
https://huggingface.co/ViuAI/TTS_10M/resolve/main/data/audio_processor.py
- Command line
-
hf download hf://ViuAI/TTS_10M/data/audio_processor.py
-
curl -L -o audio_processor.py https://huggingface.co/ViuAI/TTS_10M/resolve/main/data/audio_processor.py
3.68 kB
| """ | |
| Audio Processor & Mel-Spectrogram Extractor. | |
| Specifically matched with Vocos 24kHz Neural Vocoder standards. | |
| Guarantees mathematically locked parameters to prevent robotic beeps or distortion. | |
| """ | |
| import torch | |
| import torchaudio | |
| import torchaudio.transforms as T | |
| from typing import Dict, Optional | |
| from config import AudioConfig | |
| class AudioProcessor: | |
| def __init__(self, config: Optional[AudioConfig] = None): | |
| self.config = config or AudioConfig() | |
| self._resamplers: Dict[int, T.Resample] = {} | |
| # Exact 24kHz Mel Spectrogram Transform matching vocos.feature_extractors.MelSpectrogramFeatures | |
| self.mel_spectrogram = T.MelSpectrogram( | |
| sample_rate=self.config.sample_rate, | |
| n_fft=self.config.n_fft, | |
| win_length=self.config.win_length, | |
| hop_length=self.config.hop_length, | |
| f_min=self.config.f_min, | |
| f_max=self.config.f_max, | |
| n_mels=self.config.n_mels, | |
| power=1.0, # magnitude spectrogram | |
| center=True, | |
| norm=self.config.mel_norm, | |
| mel_scale=self.config.mel_scale, | |
| ) | |
| def _get_resampler(self, orig_sr: int) -> T.Resample: | |
| if orig_sr not in self._resamplers: | |
| self._resamplers[orig_sr] = T.Resample( | |
| orig_freq=orig_sr, new_freq=self.config.sample_rate | |
| ) | |
| return self._resamplers[orig_sr] | |
| def normalize_waveform(self, wav: torch.Tensor, orig_sr: int) -> torch.Tensor: | |
| """Converts waveform to 24kHz mono and peak-normalizes with headroom.""" | |
| if wav.dim() == 1: | |
| wav = wav.unsqueeze(0) | |
| elif wav.dim() == 2 and wav.shape[0] > 1: | |
| wav = torch.mean(wav, dim=0, keepdim=True) | |
| elif wav.dim() == 2 and wav.shape[1] > 1 and wav.shape[0] == 1: | |
| pass | |
| wav = wav.float() | |
| if orig_sr != self.config.sample_rate: | |
| wav = self._get_resampler(orig_sr)(wav) | |
| max_val = torch.max(torch.abs(wav)) | |
| if max_val > 1e-6: | |
| wav = (wav / max_val) * 0.95 | |
| return wav.squeeze(0) # (num_samples,) | |
| def load_audio(self, audio_path: str) -> torch.Tensor: | |
| """Loads and normalizes audio to 24kHz mono (bulletproof across torchaudio/torchcodec versions).""" | |
| if audio_path.lower().endswith(".wav"): | |
| import numpy as np | |
| from scipy.io import wavfile | |
| sr, data = wavfile.read(audio_path) | |
| if np.issubdtype(data.dtype, np.integer): | |
| if data.dtype == np.uint8: | |
| data = (data.astype(np.float32) - 128.0) / 128.0 | |
| else: | |
| max_int = float(np.iinfo(data.dtype).max) | |
| data = data.astype(np.float32) / max_int | |
| else: | |
| data = data.astype(np.float32) | |
| wav = torch.from_numpy(data) | |
| # scipy wavfile returns (N,) for mono or (N, C) for multi-channel | |
| if wav.dim() == 2: | |
| wav = wav.transpose(0, 1) # (C, N) | |
| return self.normalize_waveform(wav, sr) | |
| wav, sr = torchaudio.load(audio_path) | |
| return self.normalize_waveform(wav, sr) | |
| def wav_to_mel(self, wav: torch.Tensor) -> torch.Tensor: | |
| """ | |
| Converts 1D waveform (num_samples,) to (n_mels, T_mel) log-mel spectrogram. | |
| Uses exact Vocos safe_log compression to prevent mismatch and NaNs. | |
| """ | |
| if wav.dim() == 1: | |
| wav = wav.unsqueeze(0) # (1, num_samples) | |
| mel = self.mel_spectrogram(wav) | |
| log_mel = torch.log(torch.clamp(mel, min=self.config.mel_min_clip)) | |
| return log_mel.squeeze(0) # (n_mels, T_mel) | |