|
|
import torchaudio |
|
|
import torchaudio.functional as F |
|
|
import glob |
|
|
from pathlib import Path |
|
|
from multiprocessing import Pool |
|
|
import os |
|
|
from functools import partial |
|
|
|
|
|
import numpy as np |
|
|
import torch |
|
|
import tqdm |
|
|
|
|
|
import torch.multiprocessing |
|
|
|
|
|
class TUTRealLoader: |
|
|
def __init__(self): |
|
|
self._fs = 44100 |
|
|
self._eps = np.spacing(np.float64(1e-16)) |
|
|
self._audio_max_len_samples = 30 * self._fs |
|
|
self._nb_channels = 4 |
|
|
|
|
|
def _load(self, audio_path): |
|
|
waveform, fs = torchaudio.load(audio_path, channels_first=False) |
|
|
audio = waveform[:, :self._nb_channels] + self._eps |
|
|
|
|
|
|
|
|
if audio.shape[0] < self._audio_max_len_samples: |
|
|
audio = torch.nn.functional.pad( |
|
|
audio, |
|
|
(0, 0, 0, self._audio_max_len_samples - audio.shape[0]) |
|
|
) |
|
|
elif audio.shape[0] > self._audio_max_len_samples: |
|
|
audio = audio[:self._audio_max_len_samples, :] |
|
|
|
|
|
return audio, fs |
|
|
|
|
|
RESAMPLE_RATE = 32000 |
|
|
PATH = "original_audios" |
|
|
SAVE_PATH = f"audios_sr={RESAMPLE_RATE}" |
|
|
|
|
|
def resample(path, loader, resample_rate, device): |
|
|
waveform, sample_rate = loader._load(path) |
|
|
waveform = waveform.to(device) |
|
|
if waveform.shape[0] != 4: |
|
|
waveform = waveform.T |
|
|
resampled_waveform = F.resample( |
|
|
waveform, |
|
|
sample_rate, |
|
|
resample_rate, |
|
|
lowpass_filter_width=64, |
|
|
rolloff=0.9475937167399596, |
|
|
resampling_method="sinc_interp_kaiser", |
|
|
beta=14.769656459379492, |
|
|
) |
|
|
return resampled_waveform |
|
|
|
|
|
|
|
|
def resample_and_save(audio, resample_rate, loader, device): |
|
|
resampled_audio = resample(audio, loader, resample_rate, device) |
|
|
assert resampled_audio.shape[0] == 4, "Swap channel dimensions" |
|
|
file_name = Path(audio).stem |
|
|
file_ext = Path(audio).suffix |
|
|
save_file = f"{SAVE_PATH}/{file_name}{file_ext}" |
|
|
if not os.path.exists(save_file): |
|
|
torchaudio.save(save_file, resampled_audio.cpu(), resample_rate, channels_first=True) |
|
|
|
|
|
|
|
|
if __name__ == "__main__": |
|
|
torch.multiprocessing.set_start_method('spawn', force=True) |
|
|
os.makedirs(SAVE_PATH, exist_ok=True) |
|
|
device = torch.device("cpu" if not torch.cuda.is_available() else "cuda") |
|
|
loader = TUTRealLoader() |
|
|
audios = glob.glob(f"{PATH}/*.wav") |
|
|
audios = list(filter(lambda x: not os.path.exists(os.path.join(SAVE_PATH, Path(x).stem + ".wav")), audios)) |
|
|
|
|
|
print(f"Found {len(audios)} to resample") |
|
|
|
|
|
p = Pool(8) |
|
|
resample_and_save_partial = partial(resample_and_save, resample_rate = RESAMPLE_RATE, loader=loader, device = device) |
|
|
r = list(tqdm.tqdm(p.imap(resample_and_save_partial, audios), total=len(audios))) |
|
|
p.close() |
|
|
p.join() |