File size: 3,680 Bytes
5be0f71
 
 
 
 
 
 
 
 
b62c0da
5be0f71
 
 
 
 
 
b62c0da
 
 
5be0f71
 
 
 
 
 
 
 
 
 
b62c0da
 
5be0f71
 
b62c0da
 
 
 
 
 
 
 
 
 
 
 
5be0f71
b62c0da
 
 
 
 
 
 
5be0f71
b62c0da
 
 
5be0f71
 
b62c0da
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5be0f71
 
b62c0da
 
5be0f71
 
 
b62c0da
5be0f71
 
b62c0da
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
"""
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)