File size: 4,569 Bytes
79b2661
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
"""

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.transforms as T
from typing import Dict, Optional
from pathlib import Path
import io
from config import AudioConfig


def read_audio(source):
    """Decode using the container signature; some corpus .wav files contain FLAC."""
    import numpy as np
    from scipy.io import wavfile

    if isinstance(source, bytes):
        source = io.BytesIO(source)
        header = source.getbuffer()[:12].tobytes()
    else:
        with Path(source).open("rb") as stream:
            header = stream.read(12)
    if header[:4] in (b"RIFF", b"RIFX", b"RF64") and header[8:12] == b"WAVE":
        try:
            sr, data = wavfile.read(source)
        except ValueError:
            if isinstance(source, io.BytesIO):
                source.seek(0)
        else:
            if data.dtype == np.uint8:
                data = (data.astype(np.float32) - 128) / 128
            elif np.issubdtype(data.dtype, np.signedinteger):
                data = data.astype(np.float32) / (-float(np.iinfo(data.dtype).min))
            return torch.from_numpy(data.astype(np.float32).T.copy()), sr
    import soundfile as sf
    data, sr = sf.read(source, dtype="float32", always_2d=True)
    return torch.from_numpy(data.T.copy()), sr


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.ndim not in (1, 2) or wav.numel() == 0 or orig_sr <= 0:
            raise ValueError("Expected nonempty mono or channel-first audio and a positive sample rate.")
        wav = wav.float()
        if not torch.isfinite(wav).all():
            raise ValueError("Input audio contains NaN or infinity.")
        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)
        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)."""
        return self.normalize_waveform(*read_audio(audio_path))

    def load_audio_bytes(self, data: bytes) -> torch.Tensor:
        return self.normalize_waveform(*read_audio(data))

    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)

        if wav.shape[-1] <= self.config.n_fft // 2:
            raise ValueError(f"Audio must contain more than {self.config.n_fft // 2} samples for the centered mel transform.")
        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)