File size: 2,721 Bytes
0adc059
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
        
        # Pad or trim
        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()