File size: 2,014 Bytes
7e7a152 | 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 | """Canonical waveform preprocessing, extracted without numerical changes."""
import numpy as np
import torch
from scipy import signal
def prepare_staqa_waveform(
wav: np.ndarray,
sample_rate: int,
*,
target_sample_rate: int = 32_000,
target_length: int = 320_000,
normalize: bool = True,
) -> torch.Tensor:
"""Return the canonical two-channel, fixed-length StAQA waveform."""
if (
isinstance(sample_rate, bool)
or not isinstance(sample_rate, int)
or sample_rate <= 0
):
raise ValueError("sample_rate must be a positive integer")
if target_sample_rate <= 0:
raise ValueError("target_sample_rate must be positive")
if target_length <= 0:
raise ValueError("target_length must be positive")
waveform = np.asarray(wav).T.astype(np.float32)
if waveform.ndim != 2:
raise ValueError(
"StAQA waveform must be [samples, channels], "
f"got shape {tuple(np.asarray(wav).shape)}"
)
if waveform.shape[0] == 1:
waveform = np.repeat(waveform, 2, axis=0)
elif waveform.shape[0] > 2:
waveform = waveform[:2]
if int(sample_rate) != int(target_sample_rate):
waveform = signal.resample_poly(
waveform,
int(target_sample_rate),
int(sample_rate),
axis=-1,
).astype(np.float32)
if normalize:
for channel in range(waveform.shape[0]):
rms = float(np.sqrt(np.mean(waveform[channel] ** 2)))
if rms > 0:
waveform[channel] = waveform[channel] * 10 ** (
(-14.0 - 20 * np.log10(rms)) / 20
)
if waveform.shape[1] >= target_length:
waveform = waveform[:, :target_length]
else:
pad = np.zeros(
(waveform.shape[0], target_length - waveform.shape[1]),
dtype=np.float32,
)
waveform = np.concatenate([waveform, pad], axis=1)
return torch.from_numpy(waveform)
|