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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
from os.path import join
|
| 3 |
+
import torch
|
| 4 |
+
import pytorch_lightning as pl
|
| 5 |
+
from torch.utils.data import Dataset
|
| 6 |
+
from torch.utils.data import DataLoader
|
| 7 |
+
from glob import glob
|
| 8 |
+
from torchaudio import load
|
| 9 |
+
import numpy as np
|
| 10 |
+
import torch.nn.functional as F
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def get_window(window_type, window_length):
|
| 14 |
+
if window_type == 'sqrthann':
|
| 15 |
+
return torch.sqrt(torch.hann_window(window_length, periodic=True))
|
| 16 |
+
elif window_type == 'hann':
|
| 17 |
+
return torch.hann_window(window_length, periodic=True)
|
| 18 |
+
else:
|
| 19 |
+
raise NotImplementedError(f"Window type {window_type} not implemented!")
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class Specs(Dataset):
|
| 23 |
+
def __init__(self, data_dir, subset, dummy, shuffle_spec, num_frames,
|
| 24 |
+
format='default', normalize="noisy", spec_transform=None,
|
| 25 |
+
stft_kwargs=None, **ignored_kwargs):
|
| 26 |
+
|
| 27 |
+
# Read file paths according to file naming format.
|
| 28 |
+
if format == "default":
|
| 29 |
+
self.clean_files = []
|
| 30 |
+
self.clean_files += sorted(glob(join(data_dir, subset, "clean", "*.wav")))
|
| 31 |
+
self.clean_files += sorted(glob(join(data_dir, subset, "clean", "**", "*.wav")))
|
| 32 |
+
self.noisy_files = []
|
| 33 |
+
self.noisy_files += sorted(glob(join(data_dir, subset, "noisy", "*.wav")))
|
| 34 |
+
self.noisy_files += sorted(glob(join(data_dir, subset, "noisy", "**", "*.wav")))
|
| 35 |
+
elif format == "reverb":
|
| 36 |
+
self.clean_files = []
|
| 37 |
+
self.clean_files += sorted(glob(join(data_dir, subset, "anechoic", "*.wav")))
|
| 38 |
+
self.clean_files += sorted(glob(join(data_dir, subset, "anechoic", "**", "*.wav")))
|
| 39 |
+
self.noisy_files = []
|
| 40 |
+
self.noisy_files += sorted(glob(join(data_dir, subset, "reverb", "*.wav")))
|
| 41 |
+
self.noisy_files += sorted(glob(join(data_dir, subset, "reverb", "**", "*.wav")))
|
| 42 |
+
else:
|
| 43 |
+
# Feel free to add your own directory format
|
| 44 |
+
raise NotImplementedError(f"Directory format {format} unknown!")
|
| 45 |
+
|
| 46 |
+
self.dummy = dummy
|
| 47 |
+
self.num_frames = num_frames
|
| 48 |
+
self.shuffle_spec = shuffle_spec
|
| 49 |
+
self.normalize = normalize
|
| 50 |
+
self.spec_transform = spec_transform
|
| 51 |
+
|
| 52 |
+
assert all(k in stft_kwargs.keys() for k in ["n_fft", "hop_length", "center", "window"]), "misconfigured STFT kwargs"
|
| 53 |
+
self.stft_kwargs = stft_kwargs
|
| 54 |
+
self.hop_length = self.stft_kwargs["hop_length"]
|
| 55 |
+
assert self.stft_kwargs.get("center", None) == True, "'center' must be True for current implementation"
|
| 56 |
+
|
| 57 |
+
def __getitem__(self, i):
|
| 58 |
+
x, _ = load(self.clean_files[i])
|
| 59 |
+
y, _ = load(self.noisy_files[i])
|
| 60 |
+
|
| 61 |
+
# formula applies for center=True
|
| 62 |
+
target_len = (self.num_frames - 1) * self.hop_length
|
| 63 |
+
current_len = x.size(-1)
|
| 64 |
+
pad = max(target_len - current_len, 0)
|
| 65 |
+
if pad == 0:
|
| 66 |
+
# extract random part of the audio file
|
| 67 |
+
if self.shuffle_spec:
|
| 68 |
+
start = int(np.random.uniform(0, current_len-target_len))
|
| 69 |
+
else:
|
| 70 |
+
start = int((current_len-target_len)/2)
|
| 71 |
+
x = x[..., start:start+target_len]
|
| 72 |
+
y = y[..., start:start+target_len]
|
| 73 |
+
else:
|
| 74 |
+
# pad audio if the length T is smaller than num_frames
|
| 75 |
+
x = F.pad(x, (pad//2, pad//2+(pad%2)), mode='constant')
|
| 76 |
+
y = F.pad(y, (pad//2, pad//2+(pad%2)), mode='constant')
|
| 77 |
+
|
| 78 |
+
# normalize w.r.t to the noisy or the clean signal or not at all
|
| 79 |
+
# to ensure same clean signal power in x and y.
|
| 80 |
+
if self.normalize == "noisy":
|
| 81 |
+
normfac = y.abs().max()
|
| 82 |
+
elif self.normalize == "clean":
|
| 83 |
+
normfac = x.abs().max()
|
| 84 |
+
elif self.normalize == "not":
|
| 85 |
+
normfac = 1.0
|
| 86 |
+
x = x / normfac
|
| 87 |
+
y = y / normfac
|
| 88 |
+
|
| 89 |
+
X = torch.stft(x, **self.stft_kwargs)
|
| 90 |
+
Y = torch.stft(y, **self.stft_kwargs)
|
| 91 |
+
|
| 92 |
+
X, Y = self.spec_transform(X), self.spec_transform(Y)
|
| 93 |
+
return X, Y
|
| 94 |
+
|
| 95 |
+
def __len__(self):
|
| 96 |
+
if self.dummy:
|
| 97 |
+
# for debugging shrink the data set size
|
| 98 |
+
return int(len(self.clean_files)/200)
|
| 99 |
+
else:
|
| 100 |
+
return len(self.clean_files)
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
class SpecsDataModule(pl.LightningDataModule):
|
| 104 |
+
@staticmethod
|
| 105 |
+
def add_argparse_args(parser):
|
| 106 |
+
parser.add_argument("--base_dir", type=str, required=True, help="The base directory of the dataset. Should contain `train`, `valid` and `test` subdirectories, each of which contain `clean` and `noisy` subdirectories.")
|
| 107 |
+
parser.add_argument("--format", type=str, choices=("default", "reverb"), default="default", help="Read file paths according to file naming format.")
|
| 108 |
+
parser.add_argument("--batch_size", type=int, default=8, help="The batch size. 8 by default.")
|
| 109 |
+
parser.add_argument("--n_fft", type=int, default=510, help="Number of FFT bins. 510 by default.") # to assure 256 freq bins
|
| 110 |
+
parser.add_argument("--hop_length", type=int, default=128, help="Window hop length. 128 by default.")
|
| 111 |
+
parser.add_argument("--num_frames", type=int, default=256, help="Number of frames for the dataset. 256 by default.")
|
| 112 |
+
parser.add_argument("--window", type=str, choices=("sqrthann", "hann"), default="hann", help="The window function to use for the STFT. 'hann' by default.")
|
| 113 |
+
parser.add_argument("--num_workers", type=int, default=16, help="Number of workers to use for DataLoaders. 4 by default.")
|
| 114 |
+
parser.add_argument("--dummy", action="store_true", help="Use reduced dummy dataset for prototyping.")
|
| 115 |
+
parser.add_argument("--spec_factor", type=float, default=0.15, help="Factor to multiply complex STFT coefficients by. 0.15 by default.")
|
| 116 |
+
parser.add_argument("--spec_abs_exponent", type=float, default=0.5, help="Exponent e for the transformation abs(z)**e * exp(1j*angle(z)). 0.5 by default.")
|
| 117 |
+
parser.add_argument("--normalize", type=str, choices=("clean", "noisy", "not"), default="noisy", help="Normalize the input waveforms by the clean signal, the noisy signal, or not at all.")
|
| 118 |
+
parser.add_argument("--transform_type", type=str, choices=("exponent", "log", "none"), default="exponent", help="Spectogram transformation for input representation.")
|
| 119 |
+
return parser
|
| 120 |
+
|
| 121 |
+
def __init__(
|
| 122 |
+
self, base_dir, format='default', batch_size=8,
|
| 123 |
+
n_fft=510, hop_length=128, num_frames=256, window='hann',
|
| 124 |
+
num_workers=4, dummy=False, spec_factor=0.15, spec_abs_exponent=0.5,
|
| 125 |
+
gpu=True, normalize='noisy', transform_type="exponent", **kwargs
|
| 126 |
+
):
|
| 127 |
+
super().__init__()
|
| 128 |
+
self.base_dir = base_dir
|
| 129 |
+
self.format = format
|
| 130 |
+
self.batch_size = batch_size
|
| 131 |
+
self.n_fft = n_fft
|
| 132 |
+
self.hop_length = hop_length
|
| 133 |
+
self.num_frames = num_frames
|
| 134 |
+
self.window = get_window(window, self.n_fft)
|
| 135 |
+
self.windows = {}
|
| 136 |
+
self.num_workers = num_workers
|
| 137 |
+
self.dummy = dummy
|
| 138 |
+
self.spec_factor = spec_factor
|
| 139 |
+
self.spec_abs_exponent = spec_abs_exponent
|
| 140 |
+
self.gpu = gpu
|
| 141 |
+
self.normalize = normalize
|
| 142 |
+
self.transform_type = transform_type
|
| 143 |
+
self.kwargs = kwargs
|
| 144 |
+
|
| 145 |
+
def setup(self, stage=None):
|
| 146 |
+
specs_kwargs = dict(
|
| 147 |
+
stft_kwargs=self.stft_kwargs, num_frames=self.num_frames,
|
| 148 |
+
spec_transform=self.spec_fwd, **self.kwargs
|
| 149 |
+
)
|
| 150 |
+
if stage == 'fit' or stage is None:
|
| 151 |
+
self.train_set = Specs(data_dir=self.base_dir, subset='train',
|
| 152 |
+
dummy=self.dummy, shuffle_spec=True, format=self.format,
|
| 153 |
+
normalize=self.normalize, **specs_kwargs)
|
| 154 |
+
self.valid_set = Specs(data_dir=self.base_dir, subset='valid',
|
| 155 |
+
dummy=self.dummy, shuffle_spec=False, format=self.format,
|
| 156 |
+
normalize=self.normalize, **specs_kwargs)
|
| 157 |
+
if stage == 'test' or stage is None:
|
| 158 |
+
self.test_set = Specs(data_dir=self.base_dir, subset='test',
|
| 159 |
+
dummy=self.dummy, shuffle_spec=False, format=self.format,
|
| 160 |
+
normalize=self.normalize, **specs_kwargs)
|
| 161 |
+
|
| 162 |
+
def spec_fwd(self, spec):
|
| 163 |
+
if self.transform_type == "exponent":
|
| 164 |
+
if self.spec_abs_exponent != 1:
|
| 165 |
+
# only do this calculation if spec_exponent != 1, otherwise it's quite a bit of wasted computation
|
| 166 |
+
# and introduced numerical error
|
| 167 |
+
e = self.spec_abs_exponent
|
| 168 |
+
spec = spec.abs()**e * torch.exp(1j * spec.angle())
|
| 169 |
+
spec = spec * self.spec_factor
|
| 170 |
+
elif self.transform_type == "log":
|
| 171 |
+
spec = torch.log(1 + spec.abs()) * torch.exp(1j * spec.angle())
|
| 172 |
+
spec = spec * self.spec_factor
|
| 173 |
+
elif self.transform_type == "none":
|
| 174 |
+
spec = spec
|
| 175 |
+
return spec
|
| 176 |
+
|
| 177 |
+
def spec_back(self, spec):
|
| 178 |
+
if self.transform_type == "exponent":
|
| 179 |
+
spec = spec / self.spec_factor
|
| 180 |
+
if self.spec_abs_exponent != 1:
|
| 181 |
+
e = self.spec_abs_exponent
|
| 182 |
+
spec = spec.abs()**(1/e) * torch.exp(1j * spec.angle())
|
| 183 |
+
elif self.transform_type == "log":
|
| 184 |
+
spec = spec / self.spec_factor
|
| 185 |
+
spec = (torch.exp(spec.abs()) - 1) * torch.exp(1j * spec.angle())
|
| 186 |
+
elif self.transform_type == "none":
|
| 187 |
+
spec = spec
|
| 188 |
+
return spec
|
| 189 |
+
|
| 190 |
+
@property
|
| 191 |
+
def stft_kwargs(self):
|
| 192 |
+
return {**self.istft_kwargs, "return_complex": True}
|
| 193 |
+
|
| 194 |
+
@property
|
| 195 |
+
def istft_kwargs(self):
|
| 196 |
+
return dict(
|
| 197 |
+
n_fft=self.n_fft, hop_length=self.hop_length,
|
| 198 |
+
window=self.window, center=True
|
| 199 |
+
)
|
| 200 |
+
|
| 201 |
+
def _get_window(self, x):
|
| 202 |
+
"""
|
| 203 |
+
Retrieve an appropriate window for the given tensor x, matching the device.
|
| 204 |
+
Caches the retrieved windows so that only one window tensor will be allocated per device.
|
| 205 |
+
"""
|
| 206 |
+
window = self.windows.get(x.device, None)
|
| 207 |
+
if window is None:
|
| 208 |
+
window = self.window.to(x.device)
|
| 209 |
+
self.windows[x.device] = window
|
| 210 |
+
return window
|
| 211 |
+
|
| 212 |
+
def stft(self, sig):
|
| 213 |
+
window = self._get_window(sig)
|
| 214 |
+
return torch.stft(sig, **{**self.stft_kwargs, "window": window})
|
| 215 |
+
|
| 216 |
+
def istft(self, spec, length=None):
|
| 217 |
+
window = self._get_window(spec)
|
| 218 |
+
return torch.istft(spec, **{**self.istft_kwargs, "window": window, "length": length})
|
| 219 |
+
|
| 220 |
+
def train_dataloader(self):
|
| 221 |
+
return DataLoader(
|
| 222 |
+
self.train_set, batch_size=self.batch_size,
|
| 223 |
+
num_workers=self.num_workers, pin_memory=self.gpu, shuffle=True
|
| 224 |
+
)
|
| 225 |
+
|
| 226 |
+
def val_dataloader(self):
|
| 227 |
+
return DataLoader(
|
| 228 |
+
self.valid_set, batch_size=self.batch_size,
|
| 229 |
+
num_workers=self.num_workers, pin_memory=self.gpu, shuffle=False
|
| 230 |
+
)
|
| 231 |
+
|
| 232 |
+
def test_dataloader(self):
|
| 233 |
+
return DataLoader(
|
| 234 |
+
self.test_set, batch_size=self.batch_size,
|
| 235 |
+
num_workers=self.num_workers, pin_memory=self.gpu, shuffle=False
|
| 236 |
+
)
|