File size: 4,324 Bytes
79b2661
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
695c9f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
111
112
113
"""

Anti-Beep and Audio Quality Guardian.

Detects flat tones, robotic beeps, NaNs, clipping, or collapsed spectrograms in real-time.

"""

import os
import torch
from typing import Tuple


class AudioSanityGuardian:
    @staticmethod
    def check_spectrogram(mel: torch.Tensor) -> Tuple[bool, str]:
        """

        Validates Mel-spectrogram before vocoding.

        mel: (n_mels, T) or (B, n_mels, T)

        """
        if mel.ndim not in (2, 3) or mel.numel() == 0:
            return False, "Expected a nonempty mel spectrogram."
        if torch.isnan(mel).any() or torch.isinf(mel).any():
            return False, "CRITICAL ERROR: Spectrogram contains NaN or Inf values!"

        # Check standard deviation across frequency bins
        freq_std = torch.std(mel, dim=-2, unbiased=False).mean().item()
        if freq_std < 0.05:
            return False, f"WARNING: Collapsed spectrum detected (freq std={freq_std:.4f} < 0.05). Risk of beep tone!"

        # Check standard deviation across time frames (catches constant sustained buzz/tone)
        if mel.shape[-1] > 1:
            time_std = torch.std(mel, dim=-1).mean().item()
            if time_std < 0.02:
                return False, f"WARNING: Constant static spectrum across time (time std={time_std:.4f} < 0.02). Risk of sustained tone!"

        return True, "Spectrogram is healthy and diverse."

    @staticmethod
    def check_audio_waveform(waveform: torch.Tensor, sample_rate: int = 24000) -> Tuple[bool, str]:
        """

        Validates output 24kHz waveform.

        waveform: (num_samples,) or (1, num_samples)

        """
        if waveform.dim() > 1:
            waveform = waveform.squeeze(0)

        if waveform.numel() == 0:
            return False, "WARNING: Audio waveform is empty!"

        if torch.isnan(waveform).any() or torch.isinf(waveform).any():
            return False, "CRITICAL ERROR: Waveform contains NaN/Inf values!"

        max_amp = torch.max(torch.abs(waveform)).item()
        if max_amp < 1e-4:
            return False, "WARNING: Audio is completely silent!"

        if max_amp > 1.0:
            return False, "Waveform exceeds the PCM range and will clip on export."

        # Check for pure sinusoidal tone / beep by inspecting peak energy ratio in FFT
        fft = torch.fft.rfft(waveform.float())
        power = torch.abs(fft) ** 2
        total_energy = power.sum().item()
        max_energy = power.max().item()

        if total_energy > 0 and (max_energy / total_energy) > 0.85:
            return False, "WARNING: Strong single-frequency tone detected (Peak energy > 85%). This is a robot beep!"

        return True, "Passed finite-value, silence and single-tone checks."


def save_audio(file_path: str, waveform: torch.Tensor, sample_rate: int = 24000):
    """

    Saves audio waveform to 16-bit PCM WAV using scipy (bulletproof across all platforms).

    waveform: (num_samples,) or (1, num_samples) in [-1.0, 1.0]

    """
    import numpy as np
    from scipy.io import wavfile

    parent_dir = os.path.dirname(file_path)
    if parent_dir:
        os.makedirs(parent_dir, exist_ok=True)

    if isinstance(waveform, torch.Tensor):
        waveform = waveform.detach().cpu().squeeze().numpy()

    if waveform.size == 0 or not np.isfinite(waveform).all():
        raise ValueError("Cannot write an empty or non-finite waveform.")
    waveform = np.clip(waveform, -1.0, 1.0)
    int16_audio = (waveform * 32767.0).astype(np.int16)

    wavfile.write(file_path, sample_rate, int16_audio)


def debuzz_waveform(

    waveform,

    sample_rate: int = 24000,

    cutoff_hz: float = 8500.0,

    mix: float = 0.35,

):
    """

    Applies a gentle zero-phase high-frequency softening blend to reduce

    light metallic Vocos buzz without dulling speech clarity.

    """
    import numpy as np
    from scipy.signal import butter, sosfiltfilt

    arr = np.asarray(waveform, dtype=np.float32)
    if arr.size < 32 or mix <= 0.0 or cutoff_hz >= sample_rate * 0.45:
        return arr

    sos = butter(4, cutoff_hz, btype="low", fs=sample_rate, output="sos")
    smoothed = sosfiltfilt(sos, arr).astype(np.float32)
    return ((1.0 - mix) * arr + mix * smoothed).astype(np.float32)