torchaudio 2.9.1__cp310-cp310-macosx_11_0_arm64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. torchaudio/.dylibs/libc++.1.0.dylib +0 -0
  2. torchaudio/__init__.py +204 -0
  3. torchaudio/_extension/__init__.py +61 -0
  4. torchaudio/_extension/utils.py +133 -0
  5. torchaudio/_internal/__init__.py +10 -0
  6. torchaudio/_internal/module_utils.py +171 -0
  7. torchaudio/_torchcodec.py +340 -0
  8. torchaudio/compliance/__init__.py +5 -0
  9. torchaudio/compliance/kaldi.py +813 -0
  10. torchaudio/datasets/__init__.py +47 -0
  11. torchaudio/datasets/cmuarctic.py +157 -0
  12. torchaudio/datasets/cmudict.py +186 -0
  13. torchaudio/datasets/commonvoice.py +86 -0
  14. torchaudio/datasets/dr_vctk.py +121 -0
  15. torchaudio/datasets/fluentcommands.py +108 -0
  16. torchaudio/datasets/gtzan.py +1118 -0
  17. torchaudio/datasets/iemocap.py +147 -0
  18. torchaudio/datasets/librilight_limited.py +111 -0
  19. torchaudio/datasets/librimix.py +133 -0
  20. torchaudio/datasets/librispeech.py +174 -0
  21. torchaudio/datasets/librispeech_biasing.py +189 -0
  22. torchaudio/datasets/libritts.py +168 -0
  23. torchaudio/datasets/ljspeech.py +107 -0
  24. torchaudio/datasets/musdb_hq.py +139 -0
  25. torchaudio/datasets/quesst14.py +136 -0
  26. torchaudio/datasets/snips.py +157 -0
  27. torchaudio/datasets/speechcommands.py +183 -0
  28. torchaudio/datasets/tedlium.py +218 -0
  29. torchaudio/datasets/utils.py +54 -0
  30. torchaudio/datasets/vctk.py +143 -0
  31. torchaudio/datasets/voxceleb1.py +309 -0
  32. torchaudio/datasets/yesno.py +89 -0
  33. torchaudio/functional/__init__.py +130 -0
  34. torchaudio/functional/_alignment.py +128 -0
  35. torchaudio/functional/filtering.py +1685 -0
  36. torchaudio/functional/functional.py +2505 -0
  37. torchaudio/lib/__init__.py +0 -0
  38. torchaudio/lib/_torchaudio.so +0 -0
  39. torchaudio/lib/libtorchaudio.so +0 -0
  40. torchaudio/models/__init__.py +85 -0
  41. torchaudio/models/_hdemucs.py +1008 -0
  42. torchaudio/models/conformer.py +293 -0
  43. torchaudio/models/conv_tasnet.py +330 -0
  44. torchaudio/models/decoder/__init__.py +64 -0
  45. torchaudio/models/decoder/_ctc_decoder.py +568 -0
  46. torchaudio/models/decoder/_cuda_ctc_decoder.py +187 -0
  47. torchaudio/models/deepspeech.py +84 -0
  48. torchaudio/models/emformer.py +884 -0
  49. torchaudio/models/rnnt.py +816 -0
  50. torchaudio/models/rnnt_decoder.py +339 -0
  51. torchaudio/models/squim/__init__.py +11 -0
  52. torchaudio/models/squim/objective.py +326 -0
  53. torchaudio/models/squim/subjective.py +150 -0
  54. torchaudio/models/tacotron2.py +1046 -0
  55. torchaudio/models/wav2letter.py +72 -0
  56. torchaudio/models/wav2vec2/__init__.py +45 -0
  57. torchaudio/models/wav2vec2/components.py +1167 -0
  58. torchaudio/models/wav2vec2/model.py +1579 -0
  59. torchaudio/models/wav2vec2/utils/__init__.py +7 -0
  60. torchaudio/models/wav2vec2/utils/import_fairseq.py +213 -0
  61. torchaudio/models/wav2vec2/utils/import_huggingface.py +134 -0
  62. torchaudio/models/wav2vec2/wavlm_attention.py +214 -0
  63. torchaudio/models/wavernn.py +409 -0
  64. torchaudio/pipelines/__init__.py +102 -0
  65. torchaudio/pipelines/_source_separation_pipeline.py +109 -0
  66. torchaudio/pipelines/_squim_pipeline.py +156 -0
  67. torchaudio/pipelines/_tts/__init__.py +16 -0
  68. torchaudio/pipelines/_tts/impl.py +385 -0
  69. torchaudio/pipelines/_tts/interface.py +255 -0
  70. torchaudio/pipelines/_tts/utils.py +230 -0
  71. torchaudio/pipelines/_wav2vec2/__init__.py +0 -0
  72. torchaudio/pipelines/_wav2vec2/aligner.py +87 -0
  73. torchaudio/pipelines/_wav2vec2/impl.py +1699 -0
  74. torchaudio/pipelines/_wav2vec2/utils.py +346 -0
  75. torchaudio/pipelines/rnnt_pipeline.py +380 -0
  76. torchaudio/transforms/__init__.py +78 -0
  77. torchaudio/transforms/_multi_channel.py +467 -0
  78. torchaudio/transforms/_transforms.py +2138 -0
  79. torchaudio/utils/__init__.py +4 -0
  80. torchaudio/utils/download.py +89 -0
  81. torchaudio/version.py +2 -0
  82. torchaudio-2.9.1.dist-info/METADATA +133 -0
  83. torchaudio-2.9.1.dist-info/RECORD +86 -0
  84. torchaudio-2.9.1.dist-info/WHEEL +5 -0
  85. torchaudio-2.9.1.dist-info/licenses/LICENSE +25 -0
  86. torchaudio-2.9.1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,2138 @@
1
+ # -*- coding: utf-8 -*-
2
+
3
+ import math
4
+ import warnings
5
+ from typing import Callable, Optional, Sequence, Tuple, Union
6
+
7
+ import torch
8
+ from torch import Tensor
9
+ from torch.nn.modules.lazy import LazyModuleMixin
10
+ from torch.nn.parameter import UninitializedParameter
11
+
12
+ from torchaudio import functional as F
13
+ from torchaudio.functional.functional import (
14
+ _apply_sinc_resample_kernel,
15
+ _check_convolve_mode,
16
+ _fix_waveform_shape,
17
+ _get_sinc_resample_kernel,
18
+ _rnnt_loss,
19
+ _stretch_waveform,
20
+ )
21
+
22
+ __all__ = []
23
+
24
+
25
+ class Spectrogram(torch.nn.Module):
26
+ r"""Create a spectrogram from a audio signal.
27
+
28
+ .. devices:: CPU CUDA
29
+
30
+ .. properties:: Autograd TorchScript
31
+
32
+ Args:
33
+ n_fft (int, optional): Size of FFT, creates ``n_fft // 2 + 1`` bins. (Default: ``400``)
34
+ win_length (int or None, optional): Window size. (Default: ``n_fft``)
35
+ hop_length (int or None, optional): Length of hop between STFT windows. (Default: ``win_length // 2``)
36
+ pad (int, optional): Two sided padding of signal. (Default: ``0``)
37
+ window_fn (Callable[..., Tensor], optional): A function to create a window tensor
38
+ that is applied/multiplied to each frame/window. (Default: ``torch.hann_window``)
39
+ power (float or None, optional): Exponent for the magnitude spectrogram,
40
+ (must be > 0) e.g., 1 for magnitude, 2 for power, etc.
41
+ If None, then the complex spectrum is returned instead. (Default: ``2``)
42
+ normalized (bool or str, optional): Whether to normalize by magnitude after stft. If input is str, choices are
43
+ ``"window"`` and ``"frame_length"``, if specific normalization type is desirable. ``True`` maps to
44
+ ``"window"``. (Default: ``False``)
45
+ wkwargs (dict or None, optional): Arguments for window function. (Default: ``None``)
46
+ center (bool, optional): whether to pad :attr:`waveform` on both sides so
47
+ that the :math:`t`-th frame is centered at time :math:`t \times \text{hop\_length}`.
48
+ (Default: ``True``)
49
+ pad_mode (string, optional): controls the padding method used when
50
+ :attr:`center` is ``True``. (Default: ``"reflect"``)
51
+ onesided (bool, optional): controls whether to return half of results to
52
+ avoid redundancy (Default: ``True``)
53
+ return_complex (bool, optional):
54
+ Deprecated and not used.
55
+
56
+ Example
57
+ >>> waveform, sample_rate = torchaudio.load("test.wav", normalize=True)
58
+ >>> transform = torchaudio.transforms.Spectrogram(n_fft=800)
59
+ >>> spectrogram = transform(waveform)
60
+
61
+ """
62
+ __constants__ = ["n_fft", "win_length", "hop_length", "pad", "power", "normalized"]
63
+
64
+ def __init__(
65
+ self,
66
+ n_fft: int = 400,
67
+ win_length: Optional[int] = None,
68
+ hop_length: Optional[int] = None,
69
+ pad: int = 0,
70
+ window_fn: Callable[..., Tensor] = torch.hann_window,
71
+ power: Optional[float] = 2.0,
72
+ normalized: Union[bool, str] = False,
73
+ wkwargs: Optional[dict] = None,
74
+ center: bool = True,
75
+ pad_mode: str = "reflect",
76
+ onesided: bool = True,
77
+ return_complex: Optional[bool] = None,
78
+ ) -> None:
79
+ super(Spectrogram, self).__init__()
80
+ torch._C._log_api_usage_once("torchaudio.transforms.Spectrogram")
81
+ self.n_fft = n_fft
82
+ # number of FFT bins. the returned STFT result will have n_fft // 2 + 1
83
+ # number of frequencies due to onesided=True in torch.stft
84
+ self.win_length = win_length if win_length is not None else n_fft
85
+ self.hop_length = hop_length if hop_length is not None else self.win_length // 2
86
+ window = window_fn(self.win_length) if wkwargs is None else window_fn(self.win_length, **wkwargs)
87
+ self.register_buffer("window", window)
88
+ self.pad = pad
89
+ self.power = power
90
+ self.normalized = normalized
91
+ self.center = center
92
+ self.pad_mode = pad_mode
93
+ self.onesided = onesided
94
+ if return_complex is not None:
95
+ warnings.warn(
96
+ "`return_complex` argument is now deprecated and is not effective."
97
+ "`torchaudio.transforms.Spectrogram(power=None)` always returns a tensor with "
98
+ "complex dtype. Please remove the argument in the function call."
99
+ )
100
+
101
+ def forward(self, waveform: Tensor) -> Tensor:
102
+ r"""
103
+ Args:
104
+ waveform (Tensor): Tensor of audio of dimension (..., time).
105
+
106
+ Returns:
107
+ Tensor: Dimension (..., freq, time), where freq is
108
+ ``n_fft // 2 + 1`` where ``n_fft`` is the number of
109
+ Fourier bins, and time is the number of window hops (n_frame).
110
+ """
111
+ return F.spectrogram(
112
+ waveform,
113
+ self.pad,
114
+ self.window,
115
+ self.n_fft,
116
+ self.hop_length,
117
+ self.win_length,
118
+ self.power,
119
+ self.normalized,
120
+ self.center,
121
+ self.pad_mode,
122
+ self.onesided,
123
+ )
124
+
125
+
126
+ class InverseSpectrogram(torch.nn.Module):
127
+ r"""Create an inverse spectrogram to recover an audio signal from a spectrogram.
128
+
129
+ .. devices:: CPU CUDA
130
+
131
+ .. properties:: Autograd TorchScript
132
+
133
+ Args:
134
+ n_fft (int, optional): Size of FFT, creates ``n_fft // 2 + 1`` bins. (Default: ``400``)
135
+ win_length (int or None, optional): Window size. (Default: ``n_fft``)
136
+ hop_length (int or None, optional): Length of hop between STFT windows. (Default: ``win_length // 2``)
137
+ pad (int, optional): Two sided padding of signal. (Default: ``0``)
138
+ window_fn (Callable[..., Tensor], optional): A function to create a window tensor
139
+ that is applied/multiplied to each frame/window. (Default: ``torch.hann_window``)
140
+ normalized (bool or str, optional): Whether the stft output was normalized by magnitude. If input is str,
141
+ choices are ``"window"`` and ``"frame_length"``, dependent on normalization mode. ``True`` maps to
142
+ ``"window"``. (Default: ``False``)
143
+ wkwargs (dict or None, optional): Arguments for window function. (Default: ``None``)
144
+ center (bool, optional): whether the signal in spectrogram was padded on both sides so
145
+ that the :math:`t`-th frame is centered at time :math:`t \times \text{hop\_length}`.
146
+ (Default: ``True``)
147
+ pad_mode (string, optional): controls the padding method used when
148
+ :attr:`center` is ``True``. (Default: ``"reflect"``)
149
+ onesided (bool, optional): controls whether spectrogram was used to return half of results to
150
+ avoid redundancy (Default: ``True``)
151
+
152
+ Example
153
+ >>> batch, freq, time = 2, 257, 100
154
+ >>> length = 25344
155
+ >>> spectrogram = torch.randn(batch, freq, time, dtype=torch.cdouble)
156
+ >>> transform = transforms.InverseSpectrogram(n_fft=512)
157
+ >>> waveform = transform(spectrogram, length)
158
+ """
159
+ __constants__ = ["n_fft", "win_length", "hop_length", "pad", "power", "normalized"]
160
+
161
+ def __init__(
162
+ self,
163
+ n_fft: int = 400,
164
+ win_length: Optional[int] = None,
165
+ hop_length: Optional[int] = None,
166
+ pad: int = 0,
167
+ window_fn: Callable[..., Tensor] = torch.hann_window,
168
+ normalized: Union[bool, str] = False,
169
+ wkwargs: Optional[dict] = None,
170
+ center: bool = True,
171
+ pad_mode: str = "reflect",
172
+ onesided: bool = True,
173
+ ) -> None:
174
+ super(InverseSpectrogram, self).__init__()
175
+ self.n_fft = n_fft
176
+ # number of FFT bins. the returned STFT result will have n_fft // 2 + 1
177
+ # number of frequencies due to onesided=True in torch.stft
178
+ self.win_length = win_length if win_length is not None else n_fft
179
+ self.hop_length = hop_length if hop_length is not None else self.win_length // 2
180
+ window = window_fn(self.win_length) if wkwargs is None else window_fn(self.win_length, **wkwargs)
181
+ self.register_buffer("window", window)
182
+ self.pad = pad
183
+ self.normalized = normalized
184
+ self.center = center
185
+ self.pad_mode = pad_mode
186
+ self.onesided = onesided
187
+
188
+ def forward(self, spectrogram: Tensor, length: Optional[int] = None) -> Tensor:
189
+ r"""
190
+ Args:
191
+ spectrogram (Tensor): Complex tensor of audio of dimension (..., freq, time).
192
+ length (int or None, optional): The output length of the waveform.
193
+
194
+ Returns:
195
+ Tensor: Dimension (..., time), Least squares estimation of the original signal.
196
+ """
197
+ return F.inverse_spectrogram(
198
+ spectrogram,
199
+ length,
200
+ self.pad,
201
+ self.window,
202
+ self.n_fft,
203
+ self.hop_length,
204
+ self.win_length,
205
+ self.normalized,
206
+ self.center,
207
+ self.pad_mode,
208
+ self.onesided,
209
+ )
210
+
211
+
212
+ class GriffinLim(torch.nn.Module):
213
+ r"""Compute waveform from a linear scale magnitude spectrogram using the Griffin-Lim transformation.
214
+
215
+ .. devices:: CPU CUDA
216
+
217
+ .. properties:: Autograd TorchScript
218
+
219
+ Implementation ported from
220
+ *librosa* :cite:`brian_mcfee-proc-scipy-2015`, *A fast Griffin-Lim algorithm* :cite:`6701851`
221
+ and *Signal estimation from modified short-time Fourier transform* :cite:`1172092`.
222
+
223
+ Args:
224
+ n_fft (int, optional): Size of FFT, creates ``n_fft // 2 + 1`` bins. (Default: ``400``)
225
+ n_iter (int, optional): Number of iteration for phase recovery process. (Default: ``32``)
226
+ win_length (int or None, optional): Window size. (Default: ``n_fft``)
227
+ hop_length (int or None, optional): Length of hop between STFT windows. (Default: ``win_length // 2``)
228
+ window_fn (Callable[..., Tensor], optional): A function to create a window tensor
229
+ that is applied/multiplied to each frame/window. (Default: ``torch.hann_window``)
230
+ power (float, optional): Exponent for the magnitude spectrogram,
231
+ (must be > 0) e.g., 1 for magnitude, 2 for power, etc. (Default: ``2``)
232
+ wkwargs (dict or None, optional): Arguments for window function. (Default: ``None``)
233
+ momentum (float, optional): The momentum parameter for fast Griffin-Lim.
234
+ Setting this to 0 recovers the original Griffin-Lim method.
235
+ Values near 1 can lead to faster convergence, but above 1 may not converge. (Default: ``0.99``)
236
+ length (int, optional): Array length of the expected output. (Default: ``None``)
237
+ rand_init (bool, optional): Initializes phase randomly if True and to zero otherwise. (Default: ``True``)
238
+
239
+ Example
240
+ >>> batch, freq, time = 2, 257, 100
241
+ >>> spectrogram = torch.randn(batch, freq, time)
242
+ >>> transform = transforms.GriffinLim(n_fft=512)
243
+ >>> waveform = transform(spectrogram)
244
+ """
245
+ __constants__ = ["n_fft", "n_iter", "win_length", "hop_length", "power", "length", "momentum", "rand_init"]
246
+
247
+ def __init__(
248
+ self,
249
+ n_fft: int = 400,
250
+ n_iter: int = 32,
251
+ win_length: Optional[int] = None,
252
+ hop_length: Optional[int] = None,
253
+ window_fn: Callable[..., Tensor] = torch.hann_window,
254
+ power: float = 2.0,
255
+ wkwargs: Optional[dict] = None,
256
+ momentum: float = 0.99,
257
+ length: Optional[int] = None,
258
+ rand_init: bool = True,
259
+ ) -> None:
260
+ super(GriffinLim, self).__init__()
261
+
262
+ if not (0 <= momentum < 1):
263
+ raise ValueError("momentum must be in the range [0, 1). Found: {}".format(momentum))
264
+
265
+ self.n_fft = n_fft
266
+ self.n_iter = n_iter
267
+ self.win_length = win_length if win_length is not None else n_fft
268
+ self.hop_length = hop_length if hop_length is not None else self.win_length // 2
269
+ window = window_fn(self.win_length) if wkwargs is None else window_fn(self.win_length, **wkwargs)
270
+ self.register_buffer("window", window)
271
+ self.length = length
272
+ self.power = power
273
+ self.momentum = momentum
274
+ self.rand_init = rand_init
275
+
276
+ def forward(self, specgram: Tensor) -> Tensor:
277
+ r"""
278
+ Args:
279
+ specgram (Tensor):
280
+ A magnitude-only STFT spectrogram of dimension (..., freq, frames)
281
+ where freq is ``n_fft // 2 + 1``.
282
+
283
+ Returns:
284
+ Tensor: waveform of (..., time), where time equals the ``length`` parameter if given.
285
+ """
286
+ return F.griffinlim(
287
+ specgram,
288
+ self.window,
289
+ self.n_fft,
290
+ self.hop_length,
291
+ self.win_length,
292
+ self.power,
293
+ self.n_iter,
294
+ self.momentum,
295
+ self.length,
296
+ self.rand_init,
297
+ )
298
+
299
+
300
+ class AmplitudeToDB(torch.nn.Module):
301
+ r"""Turn a tensor from the power/amplitude scale to the decibel scale.
302
+
303
+ .. devices:: CPU CUDA
304
+
305
+ .. properties:: Autograd TorchScript
306
+
307
+ This output depends on the maximum value in the input tensor, and so
308
+ may return different values for an audio clip split into snippets vs. a
309
+ a full clip.
310
+
311
+ Args:
312
+ stype (str, optional): scale of input tensor (``"power"`` or ``"magnitude"``). The
313
+ power being the elementwise square of the magnitude. (Default: ``"power"``)
314
+ top_db (float or None, optional): minimum negative cut-off in decibels. A reasonable
315
+ number is 80. (Default: ``None``)
316
+
317
+ Example
318
+ >>> waveform, sample_rate = torchaudio.load("test.wav", normalize=True)
319
+ >>> transform = transforms.AmplitudeToDB(stype="amplitude", top_db=80)
320
+ >>> waveform_db = transform(waveform)
321
+ """
322
+ __constants__ = ["multiplier", "amin", "ref_value", "db_multiplier"]
323
+
324
+ def __init__(self, stype: str = "power", top_db: Optional[float] = None) -> None:
325
+ super(AmplitudeToDB, self).__init__()
326
+ self.stype = stype
327
+ if top_db is not None and top_db < 0:
328
+ raise ValueError("top_db must be positive value")
329
+ self.top_db = top_db
330
+ self.multiplier = 10.0 if stype == "power" else 20.0
331
+ self.amin = 1e-10
332
+ self.ref_value = 1.0
333
+ self.db_multiplier = math.log10(max(self.amin, self.ref_value))
334
+
335
+ def forward(self, x: Tensor) -> Tensor:
336
+ r"""Numerically stable implementation from Librosa.
337
+
338
+ https://librosa.org/doc/latest/generated/librosa.amplitude_to_db.html
339
+
340
+ Args:
341
+ x (Tensor): Input tensor before being converted to decibel scale.
342
+
343
+ Returns:
344
+ Tensor: Output tensor in decibel scale.
345
+ """
346
+ return F.amplitude_to_DB(x, self.multiplier, self.amin, self.db_multiplier, self.top_db)
347
+
348
+
349
+ class MelScale(torch.nn.Module):
350
+ r"""Turn a normal STFT into a mel frequency STFT with triangular filter banks.
351
+
352
+ .. devices:: CPU CUDA
353
+
354
+ .. properties:: Autograd TorchScript
355
+
356
+ Args:
357
+ n_mels (int, optional): Number of mel filterbanks. (Default: ``128``)
358
+ sample_rate (int, optional): Sample rate of audio signal. (Default: ``16000``)
359
+ f_min (float, optional): Minimum frequency. (Default: ``0.``)
360
+ f_max (float or None, optional): Maximum frequency. (Default: ``sample_rate // 2``)
361
+ n_stft (int, optional): Number of bins in STFT. See ``n_fft`` in :class:`Spectrogram`. (Default: ``201``)
362
+ norm (str or None, optional): If ``"slaney"``, divide the triangular mel weights by the width of the mel band
363
+ (area normalization). (Default: ``None``)
364
+ mel_scale (str, optional): Scale to use: ``htk`` or ``slaney``. (Default: ``htk``)
365
+
366
+ Example
367
+ >>> waveform, sample_rate = torchaudio.load("test.wav", normalize=True)
368
+ >>> spectrogram_transform = transforms.Spectrogram(n_fft=1024)
369
+ >>> spectrogram = spectrogram_transform(waveform)
370
+ >>> melscale_transform = transforms.MelScale(sample_rate=sample_rate, n_stft=1024 // 2 + 1)
371
+ >>> melscale_spectrogram = melscale_transform(spectrogram)
372
+
373
+ See also:
374
+ :py:func:`torchaudio.functional.melscale_fbanks` - The function used to
375
+ generate the filter banks.
376
+ """
377
+ __constants__ = ["n_mels", "sample_rate", "f_min", "f_max"]
378
+
379
+ def __init__(
380
+ self,
381
+ n_mels: int = 128,
382
+ sample_rate: int = 16000,
383
+ f_min: float = 0.0,
384
+ f_max: Optional[float] = None,
385
+ n_stft: int = 201,
386
+ norm: Optional[str] = None,
387
+ mel_scale: str = "htk",
388
+ ) -> None:
389
+ super(MelScale, self).__init__()
390
+ self.n_mels = n_mels
391
+ self.sample_rate = sample_rate
392
+ self.f_max = f_max if f_max is not None else float(sample_rate // 2)
393
+ self.f_min = f_min
394
+ self.norm = norm
395
+ self.mel_scale = mel_scale
396
+
397
+ if f_min > self.f_max:
398
+ raise ValueError("Require f_min: {} <= f_max: {}".format(f_min, self.f_max))
399
+
400
+ fb = F.melscale_fbanks(n_stft, self.f_min, self.f_max, self.n_mels, self.sample_rate, self.norm, self.mel_scale)
401
+ self.register_buffer("fb", fb)
402
+
403
+ def forward(self, specgram: Tensor) -> Tensor:
404
+ r"""
405
+ Args:
406
+ specgram (Tensor): A spectrogram STFT of dimension (..., freq, time).
407
+
408
+ Returns:
409
+ Tensor: Mel frequency spectrogram of size (..., ``n_mels``, time).
410
+ """
411
+
412
+ # (..., time, freq) dot (freq, n_mels) -> (..., n_mels, time)
413
+ mel_specgram = torch.matmul(specgram.transpose(-1, -2), self.fb).transpose(-1, -2)
414
+
415
+ return mel_specgram
416
+
417
+
418
+ class InverseMelScale(torch.nn.Module):
419
+ r"""Estimate a STFT in normal frequency domain from mel frequency domain.
420
+
421
+ .. devices:: CPU CUDA
422
+
423
+ It minimizes the euclidian norm between the input mel-spectrogram and the product between
424
+ the estimated spectrogram and the filter banks using `torch.linalg.lstsq`.
425
+
426
+ Args:
427
+ n_stft (int): Number of bins in STFT. See ``n_fft`` in :class:`Spectrogram`.
428
+ n_mels (int, optional): Number of mel filterbanks. (Default: ``128``)
429
+ sample_rate (int, optional): Sample rate of audio signal. (Default: ``16000``)
430
+ f_min (float, optional): Minimum frequency. (Default: ``0.``)
431
+ f_max (float or None, optional): Maximum frequency. (Default: ``sample_rate // 2``)
432
+ norm (str or None, optional): If "slaney", divide the triangular mel weights by the width of the mel band
433
+ (area normalization). (Default: ``None``)
434
+ mel_scale (str, optional): Scale to use: ``htk`` or ``slaney``. (Default: ``htk``)
435
+ driver (str, optional): Name of the LAPACK/MAGMA method to be used for `torch.lstsq`.
436
+ For CPU inputs the valid values are ``"gels"``, ``"gelsy"``, ``"gelsd"``, ``"gelss"``.
437
+ For CUDA input, the only valid driver is ``"gels"``, which assumes that A is full-rank.
438
+ (Default: ``"gels``)
439
+
440
+ Example
441
+ >>> waveform, sample_rate = torchaudio.load("test.wav", normalize=True)
442
+ >>> mel_spectrogram_transform = transforms.MelSpectrogram(sample_rate, n_fft=1024)
443
+ >>> mel_spectrogram = mel_spectrogram_transform(waveform)
444
+ >>> inverse_melscale_transform = transforms.InverseMelScale(n_stft=1024 // 2 + 1)
445
+ >>> spectrogram = inverse_melscale_transform(mel_spectrogram)
446
+ """
447
+ __constants__ = [
448
+ "n_stft",
449
+ "n_mels",
450
+ "sample_rate",
451
+ "f_min",
452
+ "f_max",
453
+ ]
454
+
455
+ def __init__(
456
+ self,
457
+ n_stft: int,
458
+ n_mels: int = 128,
459
+ sample_rate: int = 16000,
460
+ f_min: float = 0.0,
461
+ f_max: Optional[float] = None,
462
+ norm: Optional[str] = None,
463
+ mel_scale: str = "htk",
464
+ driver: str = "gels",
465
+ ) -> None:
466
+ super(InverseMelScale, self).__init__()
467
+ self.n_mels = n_mels
468
+ self.sample_rate = sample_rate
469
+ self.f_max = f_max or float(sample_rate // 2)
470
+ self.f_min = f_min
471
+ self.driver = driver
472
+
473
+ if f_min > self.f_max:
474
+ raise ValueError("Require f_min: {} <= f_max: {}".format(f_min, self.f_max))
475
+
476
+ if driver not in ["gels", "gelsy", "gelsd", "gelss"]:
477
+ raise ValueError(f'driver must be one of ["gels", "gelsy", "gelsd", "gelss"]. Found {driver}.')
478
+
479
+ fb = F.melscale_fbanks(n_stft, self.f_min, self.f_max, self.n_mels, self.sample_rate, norm, mel_scale)
480
+ self.register_buffer("fb", fb)
481
+
482
+ def forward(self, melspec: Tensor) -> Tensor:
483
+ r"""
484
+ Args:
485
+ melspec (Tensor): A Mel frequency spectrogram of dimension (..., ``n_mels``, time)
486
+
487
+ Returns:
488
+ Tensor: Linear scale spectrogram of size (..., freq, time)
489
+ """
490
+ # pack batch
491
+ shape = melspec.size()
492
+ melspec = melspec.view(-1, shape[-2], shape[-1])
493
+
494
+ n_mels, time = shape[-2], shape[-1]
495
+ freq, _ = self.fb.size() # (freq, n_mels)
496
+ if self.n_mels != n_mels:
497
+ raise ValueError("Expected an input with {} mel bins. Found: {}".format(self.n_mels, n_mels))
498
+
499
+ specgram = torch.relu(torch.linalg.lstsq(self.fb.transpose(-1, -2)[None], melspec, driver=self.driver).solution)
500
+
501
+ # unpack batch
502
+ specgram = specgram.view(shape[:-2] + (freq, time))
503
+ return specgram
504
+
505
+
506
+ class MelSpectrogram(torch.nn.Module):
507
+ r"""Create MelSpectrogram for a raw audio signal.
508
+
509
+ .. devices:: CPU CUDA
510
+
511
+ .. properties:: Autograd TorchScript
512
+
513
+ This is a composition of :py:func:`torchaudio.transforms.Spectrogram`
514
+ and :py:func:`torchaudio.transforms.MelScale`.
515
+
516
+ Sources
517
+ * https://gist.github.com/kastnerkyle/179d6e9a88202ab0a2fe
518
+ * https://timsainb.github.io/spectrograms-mfccs-and-inversion-in-python.html
519
+ * http://haythamfayek.com/2016/04/21/speech-processing-for-machine-learning.html
520
+
521
+ Args:
522
+ sample_rate (int, optional): Sample rate of audio signal. (Default: ``16000``)
523
+ n_fft (int, optional): Size of FFT, creates ``n_fft // 2 + 1`` bins. (Default: ``400``)
524
+ win_length (int or None, optional): Window size. (Default: ``n_fft``)
525
+ hop_length (int or None, optional): Length of hop between STFT windows. (Default: ``win_length // 2``)
526
+ f_min (float, optional): Minimum frequency. (Default: ``0.``)
527
+ f_max (float or None, optional): Maximum frequency. (Default: ``None``)
528
+ pad (int, optional): Two sided padding of signal. (Default: ``0``)
529
+ n_mels (int, optional): Number of mel filterbanks. (Default: ``128``)
530
+ window_fn (Callable[..., Tensor], optional): A function to create a window tensor
531
+ that is applied/multiplied to each frame/window. (Default: ``torch.hann_window``)
532
+ power (float, optional): Exponent for the magnitude spectrogram,
533
+ (must be > 0) e.g., 1 for magnitude, 2 for power, etc. (Default: ``2``)
534
+ normalized (bool, optional): Whether to normalize by magnitude after stft. (Default: ``False``)
535
+ wkwargs (Dict[..., ...] or None, optional): Arguments for window function. (Default: ``None``)
536
+ center (bool, optional): whether to pad :attr:`waveform` on both sides so
537
+ that the :math:`t`-th frame is centered at time :math:`t \times \text{hop\_length}`.
538
+ (Default: ``True``)
539
+ pad_mode (string, optional): controls the padding method used when
540
+ :attr:`center` is ``True``. (Default: ``"reflect"``)
541
+ onesided: Deprecated and unused.
542
+ norm (str or None, optional): If "slaney", divide the triangular mel weights by the width of the mel band
543
+ (area normalization). (Default: ``None``)
544
+ mel_scale (str, optional): Scale to use: ``htk`` or ``slaney``. (Default: ``htk``)
545
+
546
+ Example
547
+ >>> waveform, sample_rate = torchaudio.load("test.wav", normalize=True)
548
+ >>> transform = transforms.MelSpectrogram(sample_rate)
549
+ >>> mel_specgram = transform(waveform) # (channel, n_mels, time)
550
+
551
+ See also:
552
+ :py:func:`torchaudio.functional.melscale_fbanks` - The function used to
553
+ generate the filter banks.
554
+ """
555
+ __constants__ = ["sample_rate", "n_fft", "win_length", "hop_length", "pad", "n_mels", "f_min"]
556
+
557
+ def __init__(
558
+ self,
559
+ sample_rate: int = 16000,
560
+ n_fft: int = 400,
561
+ win_length: Optional[int] = None,
562
+ hop_length: Optional[int] = None,
563
+ f_min: float = 0.0,
564
+ f_max: Optional[float] = None,
565
+ pad: int = 0,
566
+ n_mels: int = 128,
567
+ window_fn: Callable[..., Tensor] = torch.hann_window,
568
+ power: float = 2.0,
569
+ normalized: bool = False,
570
+ wkwargs: Optional[dict] = None,
571
+ center: bool = True,
572
+ pad_mode: str = "reflect",
573
+ onesided: Optional[bool] = None,
574
+ norm: Optional[str] = None,
575
+ mel_scale: str = "htk",
576
+ ) -> None:
577
+ super(MelSpectrogram, self).__init__()
578
+ torch._C._log_api_usage_once("torchaudio.transforms.MelSpectrogram")
579
+
580
+ if onesided is not None:
581
+ warnings.warn(
582
+ "Argument 'onesided' has been deprecated and has no influence on the behavior of this module."
583
+ )
584
+
585
+ self.sample_rate = sample_rate
586
+ self.n_fft = n_fft
587
+ self.win_length = win_length if win_length is not None else n_fft
588
+ self.hop_length = hop_length if hop_length is not None else self.win_length // 2
589
+ self.pad = pad
590
+ self.power = power
591
+ self.normalized = normalized
592
+ self.n_mels = n_mels # number of mel frequency bins
593
+ self.f_max = f_max
594
+ self.f_min = f_min
595
+ self.spectrogram = Spectrogram(
596
+ n_fft=self.n_fft,
597
+ win_length=self.win_length,
598
+ hop_length=self.hop_length,
599
+ pad=self.pad,
600
+ window_fn=window_fn,
601
+ power=self.power,
602
+ normalized=self.normalized,
603
+ wkwargs=wkwargs,
604
+ center=center,
605
+ pad_mode=pad_mode,
606
+ onesided=True,
607
+ )
608
+ self.mel_scale = MelScale(
609
+ self.n_mels, self.sample_rate, self.f_min, self.f_max, self.n_fft // 2 + 1, norm, mel_scale
610
+ )
611
+
612
+ def forward(self, waveform: Tensor) -> Tensor:
613
+ r"""
614
+ Args:
615
+ waveform (Tensor): Tensor of audio of dimension (..., time).
616
+
617
+ Returns:
618
+ Tensor: Mel frequency spectrogram of size (..., ``n_mels``, time).
619
+ """
620
+ specgram = self.spectrogram(waveform)
621
+ mel_specgram = self.mel_scale(specgram)
622
+ return mel_specgram
623
+
624
+
625
+ class MFCC(torch.nn.Module):
626
+ r"""Create the Mel-frequency cepstrum coefficients from an audio signal.
627
+
628
+ .. devices:: CPU CUDA
629
+
630
+ .. properties:: Autograd TorchScript
631
+
632
+ By default, this calculates the MFCC on the DB-scaled Mel spectrogram.
633
+ This is not the textbook implementation, but is implemented here to
634
+ give consistency with librosa.
635
+
636
+ This output depends on the maximum value in the input spectrogram, and so
637
+ may return different values for an audio clip split into snippets vs. a
638
+ a full clip.
639
+
640
+ Args:
641
+ sample_rate (int, optional): Sample rate of audio signal. (Default: ``16000``)
642
+ n_mfcc (int, optional): Number of mfc coefficients to retain. (Default: ``40``)
643
+ dct_type (int, optional): type of DCT (discrete cosine transform) to use. (Default: ``2``)
644
+ norm (str, optional): norm to use. (Default: ``"ortho"``)
645
+ log_mels (bool, optional): whether to use log-mel spectrograms instead of db-scaled. (Default: ``False``)
646
+ melkwargs (dict or None, optional): arguments for MelSpectrogram. (Default: ``None``)
647
+
648
+ Example
649
+ >>> waveform, sample_rate = torchaudio.load("test.wav", normalize=True)
650
+ >>> transform = transforms.MFCC(
651
+ >>> sample_rate=sample_rate,
652
+ >>> n_mfcc=13,
653
+ >>> melkwargs={"n_fft": 400, "hop_length": 160, "n_mels": 23, "center": False},
654
+ >>> )
655
+ >>> mfcc = transform(waveform)
656
+
657
+ See also:
658
+ :py:func:`torchaudio.functional.melscale_fbanks` - The function used to
659
+ generate the filter banks.
660
+ """
661
+ __constants__ = ["sample_rate", "n_mfcc", "dct_type", "top_db", "log_mels"]
662
+
663
+ def __init__(
664
+ self,
665
+ sample_rate: int = 16000,
666
+ n_mfcc: int = 40,
667
+ dct_type: int = 2,
668
+ norm: str = "ortho",
669
+ log_mels: bool = False,
670
+ melkwargs: Optional[dict] = None,
671
+ ) -> None:
672
+ super(MFCC, self).__init__()
673
+ supported_dct_types = [2]
674
+ if dct_type not in supported_dct_types:
675
+ raise ValueError("DCT type not supported: {}".format(dct_type))
676
+ self.sample_rate = sample_rate
677
+ self.n_mfcc = n_mfcc
678
+ self.dct_type = dct_type
679
+ self.norm = norm
680
+ self.top_db = 80.0
681
+ self.amplitude_to_DB = AmplitudeToDB("power", self.top_db)
682
+
683
+ melkwargs = melkwargs or {}
684
+ self.MelSpectrogram = MelSpectrogram(sample_rate=self.sample_rate, **melkwargs)
685
+
686
+ if self.n_mfcc > self.MelSpectrogram.n_mels:
687
+ raise ValueError("Cannot select more MFCC coefficients than # mel bins")
688
+ dct_mat = F.create_dct(self.n_mfcc, self.MelSpectrogram.n_mels, self.norm)
689
+ self.register_buffer("dct_mat", dct_mat)
690
+ self.log_mels = log_mels
691
+
692
+ def forward(self, waveform: Tensor) -> Tensor:
693
+ r"""
694
+ Args:
695
+ waveform (Tensor): Tensor of audio of dimension (..., time).
696
+
697
+ Returns:
698
+ Tensor: specgram_mel_db of size (..., ``n_mfcc``, time).
699
+ """
700
+ mel_specgram = self.MelSpectrogram(waveform)
701
+ if self.log_mels:
702
+ log_offset = 1e-6
703
+ mel_specgram = torch.log(mel_specgram + log_offset)
704
+ else:
705
+ mel_specgram = self.amplitude_to_DB(mel_specgram)
706
+
707
+ # (..., time, n_mels) dot (n_mels, n_mfcc) -> (..., n_nfcc, time)
708
+ mfcc = torch.matmul(mel_specgram.transpose(-1, -2), self.dct_mat).transpose(-1, -2)
709
+ return mfcc
710
+
711
+
712
+ class LFCC(torch.nn.Module):
713
+ r"""Create the linear-frequency cepstrum coefficients from an audio signal.
714
+
715
+ .. devices:: CPU CUDA
716
+
717
+ .. properties:: Autograd TorchScript
718
+
719
+ By default, this calculates the LFCC on the DB-scaled linear filtered spectrogram.
720
+ This is not the textbook implementation, but is implemented here to
721
+ give consistency with librosa.
722
+
723
+ This output depends on the maximum value in the input spectrogram, and so
724
+ may return different values for an audio clip split into snippets vs. a
725
+ a full clip.
726
+
727
+ Args:
728
+ sample_rate (int, optional): Sample rate of audio signal. (Default: ``16000``)
729
+ n_filter (int, optional): Number of linear filters to apply. (Default: ``128``)
730
+ n_lfcc (int, optional): Number of lfc coefficients to retain. (Default: ``40``)
731
+ f_min (float, optional): Minimum frequency. (Default: ``0.``)
732
+ f_max (float or None, optional): Maximum frequency. (Default: ``None``)
733
+ dct_type (int, optional): type of DCT (discrete cosine transform) to use. (Default: ``2``)
734
+ norm (str, optional): norm to use. (Default: ``"ortho"``)
735
+ log_lf (bool, optional): whether to use log-lf spectrograms instead of db-scaled. (Default: ``False``)
736
+ speckwargs (dict or None, optional): arguments for Spectrogram. (Default: ``None``)
737
+
738
+ Example
739
+ >>> waveform, sample_rate = torchaudio.load("test.wav", normalize=True)
740
+ >>> transform = transforms.LFCC(
741
+ >>> sample_rate=sample_rate,
742
+ >>> n_lfcc=13,
743
+ >>> speckwargs={"n_fft": 400, "hop_length": 160, "center": False},
744
+ >>> )
745
+ >>> lfcc = transform(waveform)
746
+
747
+ See also:
748
+ :py:func:`torchaudio.functional.linear_fbanks` - The function used to
749
+ generate the filter banks.
750
+ """
751
+ __constants__ = ["sample_rate", "n_filter", "n_lfcc", "dct_type", "top_db", "log_lf"]
752
+
753
+ def __init__(
754
+ self,
755
+ sample_rate: int = 16000,
756
+ n_filter: int = 128,
757
+ f_min: float = 0.0,
758
+ f_max: Optional[float] = None,
759
+ n_lfcc: int = 40,
760
+ dct_type: int = 2,
761
+ norm: str = "ortho",
762
+ log_lf: bool = False,
763
+ speckwargs: Optional[dict] = None,
764
+ ) -> None:
765
+ super(LFCC, self).__init__()
766
+ supported_dct_types = [2]
767
+ if dct_type not in supported_dct_types:
768
+ raise ValueError("DCT type not supported: {}".format(dct_type))
769
+ self.sample_rate = sample_rate
770
+ self.f_min = f_min
771
+ self.f_max = f_max if f_max is not None else float(sample_rate // 2)
772
+ self.n_filter = n_filter
773
+ self.n_lfcc = n_lfcc
774
+ self.dct_type = dct_type
775
+ self.norm = norm
776
+ self.top_db = 80.0
777
+ self.amplitude_to_DB = AmplitudeToDB("power", self.top_db)
778
+
779
+ speckwargs = speckwargs or {}
780
+ self.Spectrogram = Spectrogram(**speckwargs)
781
+
782
+ if self.n_lfcc > self.Spectrogram.n_fft:
783
+ raise ValueError("Cannot select more LFCC coefficients than # fft bins")
784
+
785
+ filter_mat = F.linear_fbanks(
786
+ n_freqs=self.Spectrogram.n_fft // 2 + 1,
787
+ f_min=self.f_min,
788
+ f_max=self.f_max,
789
+ n_filter=self.n_filter,
790
+ sample_rate=self.sample_rate,
791
+ )
792
+ self.register_buffer("filter_mat", filter_mat)
793
+
794
+ dct_mat = F.create_dct(self.n_lfcc, self.n_filter, self.norm)
795
+ self.register_buffer("dct_mat", dct_mat)
796
+ self.log_lf = log_lf
797
+
798
+ def forward(self, waveform: Tensor) -> Tensor:
799
+ r"""
800
+ Args:
801
+ waveform (Tensor): Tensor of audio of dimension (..., time).
802
+
803
+ Returns:
804
+ Tensor: Linear Frequency Cepstral Coefficients of size (..., ``n_lfcc``, time).
805
+ """
806
+ specgram = self.Spectrogram(waveform)
807
+
808
+ # (..., time, freq) dot (freq, n_filter) -> (..., n_filter, time)
809
+ specgram = torch.matmul(specgram.transpose(-1, -2), self.filter_mat).transpose(-1, -2)
810
+
811
+ if self.log_lf:
812
+ log_offset = 1e-6
813
+ specgram = torch.log(specgram + log_offset)
814
+ else:
815
+ specgram = self.amplitude_to_DB(specgram)
816
+
817
+ # (..., time, n_filter) dot (n_filter, n_lfcc) -> (..., n_lfcc, time)
818
+ lfcc = torch.matmul(specgram.transpose(-1, -2), self.dct_mat).transpose(-1, -2)
819
+ return lfcc
820
+
821
+
822
+ class MuLawEncoding(torch.nn.Module):
823
+ r"""Encode signal based on mu-law companding.
824
+
825
+ .. devices:: CPU CUDA
826
+
827
+ .. properties:: TorchScript
828
+
829
+ For more info see the
830
+ `Wikipedia Entry <https://en.wikipedia.org/wiki/%CE%9C-law_algorithm>`_
831
+
832
+ This algorithm assumes the signal has been scaled to between -1 and 1 and
833
+ returns a signal encoded with values from 0 to quantization_channels - 1
834
+
835
+ Args:
836
+ quantization_channels (int, optional): Number of channels. (Default: ``256``)
837
+
838
+ Example
839
+ >>> waveform, sample_rate = torchaudio.load("test.wav", normalize=True)
840
+ >>> transform = torchaudio.transforms.MuLawEncoding(quantization_channels=512)
841
+ >>> mulawtrans = transform(waveform)
842
+
843
+ """
844
+ __constants__ = ["quantization_channels"]
845
+
846
+ def __init__(self, quantization_channels: int = 256) -> None:
847
+ super(MuLawEncoding, self).__init__()
848
+ self.quantization_channels = quantization_channels
849
+
850
+ def forward(self, x: Tensor) -> Tensor:
851
+ r"""
852
+ Args:
853
+ x (Tensor): A signal to be encoded.
854
+
855
+ Returns:
856
+ Tensor: An encoded signal.
857
+ """
858
+ return F.mu_law_encoding(x, self.quantization_channels)
859
+
860
+
861
+ class MuLawDecoding(torch.nn.Module):
862
+ r"""Decode mu-law encoded signal.
863
+
864
+ .. devices:: CPU CUDA
865
+
866
+ .. properties:: TorchScript
867
+
868
+ For more info see the
869
+ `Wikipedia Entry <https://en.wikipedia.org/wiki/%CE%9C-law_algorithm>`_
870
+
871
+ This expects an input with values between 0 and ``quantization_channels - 1``
872
+ and returns a signal scaled between -1 and 1.
873
+
874
+ Args:
875
+ quantization_channels (int, optional): Number of channels. (Default: ``256``)
876
+
877
+ Example
878
+ >>> waveform, sample_rate = torchaudio.load("test.wav", normalize=True)
879
+ >>> transform = torchaudio.transforms.MuLawDecoding(quantization_channels=512)
880
+ >>> mulawtrans = transform(waveform)
881
+ """
882
+ __constants__ = ["quantization_channels"]
883
+
884
+ def __init__(self, quantization_channels: int = 256) -> None:
885
+ super(MuLawDecoding, self).__init__()
886
+ self.quantization_channels = quantization_channels
887
+
888
+ def forward(self, x_mu: Tensor) -> Tensor:
889
+ r"""
890
+ Args:
891
+ x_mu (Tensor): A mu-law encoded signal which needs to be decoded.
892
+
893
+ Returns:
894
+ Tensor: The signal decoded.
895
+ """
896
+ return F.mu_law_decoding(x_mu, self.quantization_channels)
897
+
898
+
899
+ class Resample(torch.nn.Module):
900
+ r"""Resample a signal from one frequency to another. A resampling method can be given.
901
+
902
+ .. devices:: CPU CUDA
903
+
904
+ .. properties:: Autograd TorchScript
905
+
906
+ Note:
907
+ If resampling on waveforms of higher precision than float32, there may be a small loss of precision
908
+ because the kernel is cached once as float32. If high precision resampling is important for your application,
909
+ the functional form will retain higher precision, but run slower because it does not cache the kernel.
910
+ Alternatively, you could rewrite a transform that caches a higher precision kernel.
911
+
912
+ Args:
913
+ orig_freq (int, optional): The original frequency of the signal. (Default: ``16000``)
914
+ new_freq (int, optional): The desired frequency. (Default: ``16000``)
915
+ resampling_method (str, optional): The resampling method to use.
916
+ Options: [``sinc_interp_hann``, ``sinc_interp_kaiser``] (Default: ``"sinc_interp_hann"``)
917
+ lowpass_filter_width (int, optional): Controls the sharpness of the filter, more == sharper
918
+ but less efficient. (Default: ``6``)
919
+ rolloff (float, optional): The roll-off frequency of the filter, as a fraction of the Nyquist.
920
+ Lower values reduce anti-aliasing, but also reduce some of the highest frequencies. (Default: ``0.99``)
921
+ beta (float or None, optional): The shape parameter used for kaiser window.
922
+ dtype (torch.device, optional):
923
+ Determnines the precision that resampling kernel is pre-computed and cached. If not provided,
924
+ kernel is computed with ``torch.float64`` then cached as ``torch.float32``.
925
+ If you need higher precision, provide ``torch.float64``, and the pre-computed kernel is computed and
926
+ cached as ``torch.float64``. If you use resample with lower precision, then instead of providing this
927
+ providing this argument, please use ``Resample.to(dtype)``, so that the kernel generation is still
928
+ carried out on ``torch.float64``.
929
+
930
+ Example
931
+ >>> waveform, sample_rate = torchaudio.load("test.wav", normalize=True)
932
+ >>> transform = transforms.Resample(sample_rate, sample_rate/10)
933
+ >>> waveform = transform(waveform)
934
+ """
935
+
936
+ def __init__(
937
+ self,
938
+ orig_freq: int = 16000,
939
+ new_freq: int = 16000,
940
+ resampling_method: str = "sinc_interp_hann",
941
+ lowpass_filter_width: int = 6,
942
+ rolloff: float = 0.99,
943
+ beta: Optional[float] = None,
944
+ *,
945
+ dtype: Optional[torch.dtype] = None,
946
+ ) -> None:
947
+ super().__init__()
948
+
949
+ self.orig_freq = orig_freq
950
+ self.new_freq = new_freq
951
+ self.gcd = math.gcd(int(self.orig_freq), int(self.new_freq))
952
+ self.resampling_method = resampling_method
953
+ self.lowpass_filter_width = lowpass_filter_width
954
+ self.rolloff = rolloff
955
+ self.beta = beta
956
+
957
+ if self.orig_freq != self.new_freq:
958
+ kernel, self.width = _get_sinc_resample_kernel(
959
+ self.orig_freq,
960
+ self.new_freq,
961
+ self.gcd,
962
+ self.lowpass_filter_width,
963
+ self.rolloff,
964
+ self.resampling_method,
965
+ beta,
966
+ dtype=dtype,
967
+ )
968
+ self.register_buffer("kernel", kernel)
969
+
970
+ def forward(self, waveform: Tensor) -> Tensor:
971
+ r"""
972
+ Args:
973
+ waveform (Tensor): Tensor of audio of dimension (..., time).
974
+
975
+ Returns:
976
+ Tensor: Output signal of dimension (..., time).
977
+ """
978
+ if self.orig_freq == self.new_freq:
979
+ return waveform
980
+ return _apply_sinc_resample_kernel(waveform, self.orig_freq, self.new_freq, self.gcd, self.kernel, self.width)
981
+
982
+
983
+ class ComputeDeltas(torch.nn.Module):
984
+ r"""Compute delta coefficients of a tensor, usually a spectrogram.
985
+
986
+ .. devices:: CPU CUDA
987
+
988
+ .. properties:: Autograd TorchScript
989
+
990
+ See `torchaudio.functional.compute_deltas` for more details.
991
+
992
+ Args:
993
+ win_length (int, optional): The window length used for computing delta. (Default: ``5``)
994
+ mode (str, optional): Mode parameter passed to padding. (Default: ``"replicate"``)
995
+ """
996
+ __constants__ = ["win_length"]
997
+
998
+ def __init__(self, win_length: int = 5, mode: str = "replicate") -> None:
999
+ super(ComputeDeltas, self).__init__()
1000
+ self.win_length = win_length
1001
+ self.mode = mode
1002
+
1003
+ def forward(self, specgram: Tensor) -> Tensor:
1004
+ r"""
1005
+ Args:
1006
+ specgram (Tensor): Tensor of audio of dimension (..., freq, time).
1007
+
1008
+ Returns:
1009
+ Tensor: Tensor of deltas of dimension (..., freq, time).
1010
+ """
1011
+ return F.compute_deltas(specgram, win_length=self.win_length, mode=self.mode)
1012
+
1013
+
1014
+ class TimeStretch(torch.nn.Module):
1015
+ r"""Stretch stft in time without modifying pitch for a given rate.
1016
+
1017
+ .. devices:: CPU CUDA
1018
+
1019
+ .. properties:: Autograd TorchScript
1020
+
1021
+ Proposed in *SpecAugment* :cite:`specaugment`.
1022
+
1023
+ Args:
1024
+ hop_length (int or None, optional): Length of hop between STFT windows.
1025
+ (Default: ``n_fft // 2``, where ``n_fft == (n_freq - 1) * 2``)
1026
+ n_freq (int, optional): number of filter banks from stft. (Default: ``201``)
1027
+ fixed_rate (float or None, optional): rate to speed up or slow down by.
1028
+ If None is provided, rate must be passed to the forward method. (Default: ``None``)
1029
+
1030
+ .. note::
1031
+
1032
+ The expected input is raw, complex-valued spectrogram.
1033
+
1034
+ Example
1035
+ >>> spectrogram = torchaudio.transforms.Spectrogram(power=None)
1036
+ >>> stretch = torchaudio.transforms.TimeStretch()
1037
+ >>>
1038
+ >>> original = spectrogram(waveform)
1039
+ >>> stretched_1_2 = stretch(original, 1.2)
1040
+ >>> stretched_0_9 = stretch(original, 0.9)
1041
+
1042
+ .. image:: https://download.pytorch.org/torchaudio/doc-assets/specaugment_time_stretch.png
1043
+ :width: 600
1044
+ :alt: The visualization of stretched spectrograms.
1045
+ """
1046
+ __constants__ = ["fixed_rate"]
1047
+
1048
+ def __init__(self, hop_length: Optional[int] = None, n_freq: int = 201, fixed_rate: Optional[float] = None) -> None:
1049
+ super(TimeStretch, self).__init__()
1050
+
1051
+ self.fixed_rate = fixed_rate
1052
+
1053
+ n_fft = (n_freq - 1) * 2
1054
+ hop_length = hop_length if hop_length is not None else n_fft // 2
1055
+ self.register_buffer("phase_advance", torch.linspace(0, math.pi * hop_length, n_freq)[..., None])
1056
+
1057
+ def forward(self, complex_specgrams: Tensor, overriding_rate: Optional[float] = None) -> Tensor:
1058
+ r"""
1059
+ Args:
1060
+ complex_specgrams (Tensor):
1061
+ A tensor of dimension `(..., freq, num_frame)` with complex dtype.
1062
+ overriding_rate (float or None, optional): speed up to apply to this batch.
1063
+ If no rate is passed, use ``self.fixed_rate``. (Default: ``None``)
1064
+
1065
+ Returns:
1066
+ Tensor:
1067
+ Stretched spectrogram. The resulting tensor is of the corresponding complex dtype
1068
+ as the input spectrogram, and the number of frames is changed to ``ceil(num_frame / rate)``.
1069
+ """
1070
+ if not torch.is_complex(complex_specgrams):
1071
+ warnings.warn(
1072
+ "The input to TimeStretch must be complex type. "
1073
+ "Providing non-complex tensor produces invalid results.",
1074
+ stacklevel=4,
1075
+ )
1076
+
1077
+ if overriding_rate is None:
1078
+ if self.fixed_rate is None:
1079
+ raise ValueError("If no fixed_rate is specified, must pass a valid rate to the forward method.")
1080
+ rate = self.fixed_rate
1081
+ else:
1082
+ rate = overriding_rate
1083
+ return F.phase_vocoder(complex_specgrams, rate, self.phase_advance)
1084
+
1085
+
1086
+ class Fade(torch.nn.Module):
1087
+ r"""Add a fade in and/or fade out to an waveform.
1088
+
1089
+ .. devices:: CPU CUDA
1090
+
1091
+ .. properties:: Autograd TorchScript
1092
+
1093
+ Args:
1094
+ fade_in_len (int, optional): Length of fade-in (time frames). (Default: ``0``)
1095
+ fade_out_len (int, optional): Length of fade-out (time frames). (Default: ``0``)
1096
+ fade_shape (str, optional): Shape of fade. Must be one of: "quarter_sine",
1097
+ ``"half_sine"``, ``"linear"``, ``"logarithmic"``, ``"exponential"``.
1098
+ (Default: ``"linear"``)
1099
+
1100
+ Example
1101
+ >>> waveform, sample_rate = torchaudio.load("test.wav", normalize=True)
1102
+ >>> transform = transforms.Fade(fade_in_len=sample_rate, fade_out_len=2 * sample_rate, fade_shape="linear")
1103
+ >>> faded_waveform = transform(waveform)
1104
+ """
1105
+
1106
+ def __init__(self, fade_in_len: int = 0, fade_out_len: int = 0, fade_shape: str = "linear") -> None:
1107
+ super(Fade, self).__init__()
1108
+ self.fade_in_len = fade_in_len
1109
+ self.fade_out_len = fade_out_len
1110
+ self.fade_shape = fade_shape
1111
+
1112
+ def forward(self, waveform: Tensor) -> Tensor:
1113
+ r"""
1114
+ Args:
1115
+ waveform (Tensor): Tensor of audio of dimension `(..., time)`.
1116
+
1117
+ Returns:
1118
+ Tensor: Tensor of audio of dimension `(..., time)`.
1119
+ """
1120
+ waveform_length = waveform.size()[-1]
1121
+ device = waveform.device
1122
+ return self._fade_in(waveform_length, device) * self._fade_out(waveform_length, device) * waveform
1123
+
1124
+ def _fade_in(self, waveform_length: int, device: torch.device) -> Tensor:
1125
+ fade = torch.linspace(0, 1, self.fade_in_len, device=device)
1126
+ ones = torch.ones(waveform_length - self.fade_in_len, device=device)
1127
+
1128
+ if self.fade_shape == "linear":
1129
+ fade = fade
1130
+
1131
+ if self.fade_shape == "exponential":
1132
+ fade = torch.pow(2, (fade - 1)) * fade
1133
+
1134
+ if self.fade_shape == "logarithmic":
1135
+ fade = torch.log10(0.1 + fade) + 1
1136
+
1137
+ if self.fade_shape == "quarter_sine":
1138
+ fade = torch.sin(fade * math.pi / 2)
1139
+
1140
+ if self.fade_shape == "half_sine":
1141
+ fade = torch.sin(fade * math.pi - math.pi / 2) / 2 + 0.5
1142
+
1143
+ return torch.cat((fade, ones)).clamp_(0, 1)
1144
+
1145
+ def _fade_out(self, waveform_length: int, device: torch.device) -> Tensor:
1146
+ fade = torch.linspace(0, 1, self.fade_out_len, device=device)
1147
+ ones = torch.ones(waveform_length - self.fade_out_len, device=device)
1148
+
1149
+ if self.fade_shape == "linear":
1150
+ fade = -fade + 1
1151
+
1152
+ if self.fade_shape == "exponential":
1153
+ fade = torch.pow(2, -fade) * (1 - fade)
1154
+
1155
+ if self.fade_shape == "logarithmic":
1156
+ fade = torch.log10(1.1 - fade) + 1
1157
+
1158
+ if self.fade_shape == "quarter_sine":
1159
+ fade = torch.sin(fade * math.pi / 2 + math.pi / 2)
1160
+
1161
+ if self.fade_shape == "half_sine":
1162
+ fade = torch.sin(fade * math.pi + math.pi / 2) / 2 + 0.5
1163
+
1164
+ return torch.cat((ones, fade)).clamp_(0, 1)
1165
+
1166
+
1167
+ class _AxisMasking(torch.nn.Module):
1168
+ r"""Apply masking to a spectrogram.
1169
+
1170
+ Args:
1171
+ mask_param (int): Maximum possible length of the mask.
1172
+ axis (int): What dimension the mask is applied on (assuming the tensor is 3D).
1173
+ For frequency masking, axis = 1.
1174
+ For time masking, axis = 2.
1175
+ iid_masks (bool): Applies iid masks to each of the examples in the batch dimension.
1176
+ This option is applicable only when the dimension of the input tensor is >= 3.
1177
+ p (float, optional): maximum proportion of columns that can be masked. (Default: 1.0)
1178
+ """
1179
+ __constants__ = ["mask_param", "axis", "iid_masks", "p"]
1180
+
1181
+ def __init__(self, mask_param: int, axis: int, iid_masks: bool, p: float = 1.0) -> None:
1182
+ super(_AxisMasking, self).__init__()
1183
+ self.mask_param = mask_param
1184
+ self.axis = axis
1185
+ self.iid_masks = iid_masks
1186
+ self.p = p
1187
+
1188
+ def forward(self, specgram: Tensor, mask_value: Union[float, torch.Tensor] = 0.0) -> Tensor:
1189
+ r"""
1190
+ Args:
1191
+ specgram (Tensor): Tensor of dimension `(..., freq, time)`.
1192
+ mask_value (float): Value to assign to the masked columns.
1193
+
1194
+ Returns:
1195
+ Tensor: Masked spectrogram of dimensions `(..., freq, time)`.
1196
+ """
1197
+ # if iid_masks flag marked and specgram has a batch dimension
1198
+ # self.axis + specgram.dim() - 3 gives the time/frequency dimension (last two dimensions)
1199
+ # for input tensor for which the dimension is not 3.
1200
+ if self.iid_masks:
1201
+ return F.mask_along_axis_iid(
1202
+ specgram, self.mask_param, mask_value, self.axis + specgram.dim() - 3, p=self.p
1203
+ )
1204
+ else:
1205
+ return F.mask_along_axis(specgram, self.mask_param, mask_value, self.axis + specgram.dim() - 3, p=self.p)
1206
+
1207
+
1208
+ class FrequencyMasking(_AxisMasking):
1209
+ r"""Apply masking to a spectrogram in the frequency domain.
1210
+
1211
+ .. devices:: CPU CUDA
1212
+
1213
+ .. properties:: Autograd TorchScript
1214
+
1215
+ Proposed in *SpecAugment* :cite:`specaugment`.
1216
+
1217
+ Args:
1218
+ freq_mask_param (int): maximum possible length of the mask.
1219
+ Indices uniformly sampled from [0, freq_mask_param).
1220
+ iid_masks (bool, optional): whether to apply different masks to each
1221
+ example/channel in the batch. (Default: ``False``)
1222
+ This option is applicable only when the input tensor >= 3D.
1223
+
1224
+ Example
1225
+ >>> spectrogram = torchaudio.transforms.Spectrogram()
1226
+ >>> masking = torchaudio.transforms.FrequencyMasking(freq_mask_param=80)
1227
+ >>>
1228
+ >>> original = spectrogram(waveform)
1229
+ >>> masked = masking(original)
1230
+
1231
+ .. image:: https://download.pytorch.org/torchaudio/doc-assets/specaugment_freq_masking1.png
1232
+ :alt: The original spectrogram
1233
+
1234
+ .. image:: https://download.pytorch.org/torchaudio/doc-assets/specaugment_freq_masking2.png
1235
+ :alt: The spectrogram masked along frequency axis
1236
+ """
1237
+
1238
+ def __init__(self, freq_mask_param: int, iid_masks: bool = False) -> None:
1239
+ super(FrequencyMasking, self).__init__(freq_mask_param, 1, iid_masks)
1240
+
1241
+
1242
+ class TimeMasking(_AxisMasking):
1243
+ r"""Apply masking to a spectrogram in the time domain.
1244
+
1245
+ .. devices:: CPU CUDA
1246
+
1247
+ .. properties:: Autograd TorchScript
1248
+
1249
+ Proposed in *SpecAugment* :cite:`specaugment`.
1250
+
1251
+ Args:
1252
+ time_mask_param (int): maximum possible length of the mask.
1253
+ Indices uniformly sampled from [0, time_mask_param).
1254
+ iid_masks (bool, optional): whether to apply different masks to each
1255
+ example/channel in the batch. (Default: ``False``)
1256
+ This option is applicable only when the input tensor >= 3D.
1257
+ p (float, optional): maximum proportion of time steps that can be masked.
1258
+ Must be within range [0.0, 1.0]. (Default: 1.0)
1259
+
1260
+ Example
1261
+ >>> spectrogram = torchaudio.transforms.Spectrogram()
1262
+ >>> masking = torchaudio.transforms.TimeMasking(time_mask_param=80)
1263
+ >>>
1264
+ >>> original = spectrogram(waveform)
1265
+ >>> masked = masking(original)
1266
+
1267
+ .. image:: https://download.pytorch.org/torchaudio/doc-assets/specaugment_time_masking1.png
1268
+ :alt: The original spectrogram
1269
+
1270
+ .. image:: https://download.pytorch.org/torchaudio/doc-assets/specaugment_time_masking2.png
1271
+ :alt: The spectrogram masked along time axis
1272
+ """
1273
+
1274
+ def __init__(self, time_mask_param: int, iid_masks: bool = False, p: float = 1.0) -> None:
1275
+ if not 0.0 <= p <= 1.0:
1276
+ raise ValueError(f"The value of p must be between 0.0 and 1.0 ({p} given).")
1277
+ super(TimeMasking, self).__init__(time_mask_param, 2, iid_masks, p=p)
1278
+
1279
+
1280
+ class SpecAugment(torch.nn.Module):
1281
+ r"""Apply time and frequency masking to a spectrogram.
1282
+ Args:
1283
+ n_time_masks (int): Number of time masks. If its value is zero, no time masking will be applied.
1284
+ time_mask_param (int): Maximum possible length of the time mask.
1285
+ n_freq_masks (int): Number of frequency masks. If its value is zero, no frequency masking will be applied.
1286
+ freq_mask_param (int): Maximum possible length of the frequency mask.
1287
+ iid_masks (bool, optional): Applies iid masks to each of the examples in the batch dimension.
1288
+ This option is applicable only when the input tensor is 4D. (Default: ``True``)
1289
+ p (float, optional): maximum proportion of time steps that can be masked.
1290
+ Must be within range [0.0, 1.0]. (Default: 1.0)
1291
+ zero_masking (bool, optional): If ``True``, use 0 as the mask value,
1292
+ else use mean of the input tensor. (Default: ``False``)
1293
+ """
1294
+ __constants__ = [
1295
+ "n_time_masks",
1296
+ "time_mask_param",
1297
+ "n_freq_masks",
1298
+ "freq_mask_param",
1299
+ "iid_masks",
1300
+ "p",
1301
+ "zero_masking",
1302
+ ]
1303
+
1304
+ def __init__(
1305
+ self,
1306
+ n_time_masks: int,
1307
+ time_mask_param: int,
1308
+ n_freq_masks: int,
1309
+ freq_mask_param: int,
1310
+ iid_masks: bool = True,
1311
+ p: float = 1.0,
1312
+ zero_masking: bool = False,
1313
+ ) -> None:
1314
+ super(SpecAugment, self).__init__()
1315
+ self.n_time_masks = n_time_masks
1316
+ self.time_mask_param = time_mask_param
1317
+ self.n_freq_masks = n_freq_masks
1318
+ self.freq_mask_param = freq_mask_param
1319
+ self.iid_masks = iid_masks
1320
+ self.p = p
1321
+ self.zero_masking = zero_masking
1322
+
1323
+ def forward(self, specgram: Tensor) -> Tensor:
1324
+ r"""
1325
+ Args:
1326
+ specgram (Tensor): Tensor of shape `(..., freq, time)`.
1327
+ Returns:
1328
+ Tensor: Masked spectrogram of shape `(..., freq, time)`.
1329
+ """
1330
+ if self.zero_masking:
1331
+ mask_value = 0.0
1332
+ else:
1333
+ mask_value = specgram.mean()
1334
+ time_dim = specgram.dim() - 1
1335
+ freq_dim = time_dim - 1
1336
+
1337
+ if specgram.dim() > 2 and self.iid_masks is True:
1338
+ for _ in range(self.n_time_masks):
1339
+ specgram = F.mask_along_axis_iid(specgram, self.time_mask_param, mask_value, time_dim, p=self.p)
1340
+ for _ in range(self.n_freq_masks):
1341
+ specgram = F.mask_along_axis_iid(specgram, self.freq_mask_param, mask_value, freq_dim, p=self.p)
1342
+ else:
1343
+ for _ in range(self.n_time_masks):
1344
+ specgram = F.mask_along_axis(specgram, self.time_mask_param, mask_value, time_dim, p=self.p)
1345
+ for _ in range(self.n_freq_masks):
1346
+ specgram = F.mask_along_axis(specgram, self.freq_mask_param, mask_value, freq_dim, p=self.p)
1347
+
1348
+ return specgram
1349
+
1350
+
1351
+ class Loudness(torch.nn.Module):
1352
+ r"""Measure audio loudness according to the ITU-R BS.1770-4 recommendation.
1353
+
1354
+ .. devices:: CPU CUDA
1355
+
1356
+ .. properties:: TorchScript
1357
+
1358
+ Args:
1359
+ sample_rate (int): Sample rate of audio signal.
1360
+
1361
+ Example
1362
+ >>> waveform, sample_rate = torchaudio.load("test.wav", normalize=True)
1363
+ >>> transform = transforms.Loudness(sample_rate)
1364
+ >>> loudness = transform(waveform)
1365
+
1366
+ Reference:
1367
+ - https://www.itu.int/rec/R-REC-BS.1770-4-201510-I/en
1368
+ """
1369
+ __constants__ = ["sample_rate"]
1370
+
1371
+ def __init__(self, sample_rate: int):
1372
+ super(Loudness, self).__init__()
1373
+ self.sample_rate = sample_rate
1374
+
1375
+ def forward(self, wavefrom: Tensor):
1376
+ r"""
1377
+ Args:
1378
+ waveform(torch.Tensor): audio waveform of dimension `(..., channels, time)`
1379
+
1380
+ Returns:
1381
+ Tensor: loudness estimates (LKFS)
1382
+ """
1383
+ return F.loudness(wavefrom, self.sample_rate)
1384
+
1385
+
1386
+ class Vol(torch.nn.Module):
1387
+ r"""Adjust volume of waveform.
1388
+
1389
+ .. devices:: CPU CUDA
1390
+
1391
+ .. properties:: Autograd TorchScript
1392
+
1393
+ Args:
1394
+ gain (float): Interpreted according to the given gain_type:
1395
+ If ``gain_type`` = ``amplitude``, ``gain`` is a positive amplitude ratio.
1396
+ If ``gain_type`` = ``power``, ``gain`` is a power (voltage squared).
1397
+ If ``gain_type`` = ``db``, ``gain`` is in decibels.
1398
+ gain_type (str, optional): Type of gain. One of: ``amplitude``, ``power``, ``db`` (Default: ``amplitude``)
1399
+
1400
+ Example
1401
+ >>> waveform, sample_rate = torchaudio.load("test.wav", normalize=True)
1402
+ >>> transform = transforms.Vol(gain=0.5, gain_type="amplitude")
1403
+ >>> quieter_waveform = transform(waveform)
1404
+ """
1405
+
1406
+ def __init__(self, gain: float, gain_type: str = "amplitude"):
1407
+ super(Vol, self).__init__()
1408
+ self.gain = gain
1409
+ self.gain_type = gain_type
1410
+
1411
+ if gain_type in ["amplitude", "power"] and gain < 0:
1412
+ raise ValueError("If gain_type = amplitude or power, gain must be positive.")
1413
+
1414
+ def forward(self, waveform: Tensor) -> Tensor:
1415
+ r"""
1416
+ Args:
1417
+ waveform (Tensor): Tensor of audio of dimension `(..., time)`.
1418
+
1419
+ Returns:
1420
+ Tensor: Tensor of audio of dimension `(..., time)`.
1421
+ """
1422
+ if self.gain_type == "amplitude":
1423
+ waveform = waveform * self.gain
1424
+
1425
+ if self.gain_type == "db":
1426
+ waveform = F.gain(waveform, self.gain)
1427
+
1428
+ if self.gain_type == "power":
1429
+ waveform = F.gain(waveform, 10 * math.log10(self.gain))
1430
+
1431
+ return torch.clamp(waveform, -1, 1)
1432
+
1433
+
1434
+ class SlidingWindowCmn(torch.nn.Module):
1435
+ r"""
1436
+ Apply sliding-window cepstral mean (and optionally variance) normalization per utterance.
1437
+
1438
+ .. devices:: CPU CUDA
1439
+
1440
+ .. properties:: Autograd TorchScript
1441
+
1442
+ Args:
1443
+ cmn_window (int, optional): Window in frames for running average CMN computation (int, default = 600)
1444
+ min_cmn_window (int, optional): Minimum CMN window used at start of decoding (adds latency only at start).
1445
+ Only applicable if center == false, ignored if center==true (int, default = 100)
1446
+ center (bool, optional): If true, use a window centered on the current frame
1447
+ (to the extent possible, modulo end effects). If false, window is to the left. (bool, default = false)
1448
+ norm_vars (bool, optional): If true, normalize variance to one. (bool, default = false)
1449
+
1450
+ Example
1451
+ >>> waveform, sample_rate = torchaudio.load("test.wav", normalize=True)
1452
+ >>> transform = transforms.SlidingWindowCmn(cmn_window=1000)
1453
+ >>> cmn_waveform = transform(waveform)
1454
+ """
1455
+
1456
+ def __init__(
1457
+ self, cmn_window: int = 600, min_cmn_window: int = 100, center: bool = False, norm_vars: bool = False
1458
+ ) -> None:
1459
+ super().__init__()
1460
+ self.cmn_window = cmn_window
1461
+ self.min_cmn_window = min_cmn_window
1462
+ self.center = center
1463
+ self.norm_vars = norm_vars
1464
+
1465
+ def forward(self, specgram: Tensor) -> Tensor:
1466
+ r"""
1467
+ Args:
1468
+ specgram (Tensor): Tensor of spectrogram of dimension `(..., time, freq)`.
1469
+
1470
+ Returns:
1471
+ Tensor: Tensor of spectrogram of dimension `(..., time, freq)`.
1472
+ """
1473
+ cmn_specgram = F.sliding_window_cmn(specgram, self.cmn_window, self.min_cmn_window, self.center, self.norm_vars)
1474
+ return cmn_specgram
1475
+
1476
+
1477
+ class Vad(torch.nn.Module):
1478
+ r"""Voice Activity Detector. Similar to SoX implementation.
1479
+
1480
+ .. devices:: CPU CUDA
1481
+
1482
+ .. properties:: TorchScript
1483
+
1484
+ Attempts to trim silence and quiet background sounds from the ends of recordings of speech.
1485
+ The algorithm currently uses a simple cepstral power measurement to detect voice,
1486
+ so may be fooled by other things, especially music.
1487
+
1488
+ The effect can trim only from the front of the audio,
1489
+ so in order to trim from the back, the reverse effect must also be used.
1490
+
1491
+ Args:
1492
+ sample_rate (int): Sample rate of audio signal.
1493
+ trigger_level (float, optional): The measurement level used to trigger activity detection.
1494
+ This may need to be changed depending on the noise level, signal level,
1495
+ and other characteristics of the input audio. (Default: 7.0)
1496
+ trigger_time (float, optional): The time constant (in seconds)
1497
+ used to help ignore short bursts of sound. (Default: 0.25)
1498
+ search_time (float, optional): The amount of audio (in seconds)
1499
+ to search for quieter/shorter bursts of audio to include prior
1500
+ to the detected trigger point. (Default: 1.0)
1501
+ allowed_gap (float, optional): The allowed gap (in seconds) between
1502
+ quiteter/shorter bursts of audio to include prior
1503
+ to the detected trigger point. (Default: 0.25)
1504
+ pre_trigger_time (float, optional): The amount of audio (in seconds) to preserve
1505
+ before the trigger point and any found quieter/shorter bursts. (Default: 0.0)
1506
+ boot_time (float, optional) The algorithm (internally) uses adaptive noise
1507
+ estimation/reduction in order to detect the start of the wanted audio.
1508
+ This option sets the time for the initial noise estimate. (Default: 0.35)
1509
+ noise_up_time (float, optional) Time constant used by the adaptive noise estimator
1510
+ for when the noise level is increasing. (Default: 0.1)
1511
+ noise_down_time (float, optional) Time constant used by the adaptive noise estimator
1512
+ for when the noise level is decreasing. (Default: 0.01)
1513
+ noise_reduction_amount (float, optional) Amount of noise reduction to use in
1514
+ the detection algorithm (e.g. 0, 0.5, ...). (Default: 1.35)
1515
+ measure_freq (float, optional) Frequency of the algorithm’s
1516
+ processing/measurements. (Default: 20.0)
1517
+ measure_duration: (float or None, optional) Measurement duration.
1518
+ (Default: Twice the measurement period; i.e. with overlap.)
1519
+ measure_smooth_time (float, optional) Time constant used to smooth
1520
+ spectral measurements. (Default: 0.4)
1521
+ hp_filter_freq (float, optional) "Brick-wall" frequency of high-pass filter applied
1522
+ at the input to the detector algorithm. (Default: 50.0)
1523
+ lp_filter_freq (float, optional) "Brick-wall" frequency of low-pass filter applied
1524
+ at the input to the detector algorithm. (Default: 6000.0)
1525
+ hp_lifter_freq (float, optional) "Brick-wall" frequency of high-pass lifter used
1526
+ in the detector algorithm. (Default: 150.0)
1527
+ lp_lifter_freq (float, optional) "Brick-wall" frequency of low-pass lifter used
1528
+ in the detector algorithm. (Default: 2000.0)
1529
+
1530
+ Example
1531
+ >>> waveform, sample_rate = torchaudio.load("test.wav", normalize=True)
1532
+ >>> waveform_reversed, sample_rate = apply_effects_tensor(waveform, sample_rate, [["reverse"]])
1533
+ >>> transform = transforms.Vad(sample_rate=sample_rate, trigger_level=7.5)
1534
+ >>> waveform_reversed_front_trim = transform(waveform_reversed)
1535
+ >>> waveform_end_trim, sample_rate = apply_effects_tensor(
1536
+ >>> waveform_reversed_front_trim, sample_rate, [["reverse"]]
1537
+ >>> )
1538
+
1539
+ Reference:
1540
+ - http://sox.sourceforge.net/sox.html
1541
+ """
1542
+
1543
+ def __init__(
1544
+ self,
1545
+ sample_rate: int,
1546
+ trigger_level: float = 7.0,
1547
+ trigger_time: float = 0.25,
1548
+ search_time: float = 1.0,
1549
+ allowed_gap: float = 0.25,
1550
+ pre_trigger_time: float = 0.0,
1551
+ boot_time: float = 0.35,
1552
+ noise_up_time: float = 0.1,
1553
+ noise_down_time: float = 0.01,
1554
+ noise_reduction_amount: float = 1.35,
1555
+ measure_freq: float = 20.0,
1556
+ measure_duration: Optional[float] = None,
1557
+ measure_smooth_time: float = 0.4,
1558
+ hp_filter_freq: float = 50.0,
1559
+ lp_filter_freq: float = 6000.0,
1560
+ hp_lifter_freq: float = 150.0,
1561
+ lp_lifter_freq: float = 2000.0,
1562
+ ) -> None:
1563
+ super().__init__()
1564
+
1565
+ self.sample_rate = sample_rate
1566
+ self.trigger_level = trigger_level
1567
+ self.trigger_time = trigger_time
1568
+ self.search_time = search_time
1569
+ self.allowed_gap = allowed_gap
1570
+ self.pre_trigger_time = pre_trigger_time
1571
+ self.boot_time = boot_time
1572
+ self.noise_up_time = noise_up_time
1573
+ self.noise_down_time = noise_down_time
1574
+ self.noise_reduction_amount = noise_reduction_amount
1575
+ self.measure_freq = measure_freq
1576
+ self.measure_duration = measure_duration
1577
+ self.measure_smooth_time = measure_smooth_time
1578
+ self.hp_filter_freq = hp_filter_freq
1579
+ self.lp_filter_freq = lp_filter_freq
1580
+ self.hp_lifter_freq = hp_lifter_freq
1581
+ self.lp_lifter_freq = lp_lifter_freq
1582
+
1583
+ def forward(self, waveform: Tensor) -> Tensor:
1584
+ r"""
1585
+ Args:
1586
+ waveform (Tensor): Tensor of audio of dimension `(channels, time)` or `(time)`
1587
+ Tensor of shape `(channels, time)` is treated as a multi-channel recording
1588
+ of the same event and the resulting output will be trimmed to the earliest
1589
+ voice activity in any channel.
1590
+ """
1591
+ return F.vad(
1592
+ waveform=waveform,
1593
+ sample_rate=self.sample_rate,
1594
+ trigger_level=self.trigger_level,
1595
+ trigger_time=self.trigger_time,
1596
+ search_time=self.search_time,
1597
+ allowed_gap=self.allowed_gap,
1598
+ pre_trigger_time=self.pre_trigger_time,
1599
+ boot_time=self.boot_time,
1600
+ noise_up_time=self.noise_up_time,
1601
+ noise_down_time=self.noise_down_time,
1602
+ noise_reduction_amount=self.noise_reduction_amount,
1603
+ measure_freq=self.measure_freq,
1604
+ measure_duration=self.measure_duration,
1605
+ measure_smooth_time=self.measure_smooth_time,
1606
+ hp_filter_freq=self.hp_filter_freq,
1607
+ lp_filter_freq=self.lp_filter_freq,
1608
+ hp_lifter_freq=self.hp_lifter_freq,
1609
+ lp_lifter_freq=self.lp_lifter_freq,
1610
+ )
1611
+
1612
+
1613
+ class SpectralCentroid(torch.nn.Module):
1614
+ r"""Compute the spectral centroid for each channel along the time axis.
1615
+
1616
+ .. devices:: CPU CUDA
1617
+
1618
+ .. properties:: Autograd TorchScript
1619
+
1620
+ The spectral centroid is defined as the weighted average of the
1621
+ frequency values, weighted by their magnitude.
1622
+
1623
+ Args:
1624
+ sample_rate (int): Sample rate of audio signal.
1625
+ n_fft (int, optional): Size of FFT, creates ``n_fft // 2 + 1`` bins. (Default: ``400``)
1626
+ win_length (int or None, optional): Window size. (Default: ``n_fft``)
1627
+ hop_length (int or None, optional): Length of hop between STFT windows. (Default: ``win_length // 2``)
1628
+ pad (int, optional): Two sided padding of signal. (Default: ``0``)
1629
+ window_fn (Callable[..., Tensor], optional): A function to create a window tensor
1630
+ that is applied/multiplied to each frame/window. (Default: ``torch.hann_window``)
1631
+ wkwargs (dict or None, optional): Arguments for window function. (Default: ``None``)
1632
+
1633
+ Example
1634
+ >>> waveform, sample_rate = torchaudio.load("test.wav", normalize=True)
1635
+ >>> transform = transforms.SpectralCentroid(sample_rate)
1636
+ >>> spectral_centroid = transform(waveform) # (channel, time)
1637
+ """
1638
+ __constants__ = ["sample_rate", "n_fft", "win_length", "hop_length", "pad"]
1639
+
1640
+ def __init__(
1641
+ self,
1642
+ sample_rate: int,
1643
+ n_fft: int = 400,
1644
+ win_length: Optional[int] = None,
1645
+ hop_length: Optional[int] = None,
1646
+ pad: int = 0,
1647
+ window_fn: Callable[..., Tensor] = torch.hann_window,
1648
+ wkwargs: Optional[dict] = None,
1649
+ ) -> None:
1650
+ super(SpectralCentroid, self).__init__()
1651
+ self.sample_rate = sample_rate
1652
+ self.n_fft = n_fft
1653
+ self.win_length = win_length if win_length is not None else n_fft
1654
+ self.hop_length = hop_length if hop_length is not None else self.win_length // 2
1655
+ window = window_fn(self.win_length) if wkwargs is None else window_fn(self.win_length, **wkwargs)
1656
+ self.register_buffer("window", window)
1657
+ self.pad = pad
1658
+
1659
+ def forward(self, waveform: Tensor) -> Tensor:
1660
+ r"""
1661
+ Args:
1662
+ waveform (Tensor): Tensor of audio of dimension `(..., time)`.
1663
+
1664
+ Returns:
1665
+ Tensor: Spectral Centroid of size `(..., time)`.
1666
+ """
1667
+
1668
+ return F.spectral_centroid(
1669
+ waveform, self.sample_rate, self.pad, self.window, self.n_fft, self.hop_length, self.win_length
1670
+ )
1671
+
1672
+
1673
+ class PitchShift(LazyModuleMixin, torch.nn.Module):
1674
+ r"""Shift the pitch of a waveform by ``n_steps`` steps.
1675
+
1676
+ .. devices:: CPU CUDA
1677
+
1678
+ .. properties:: TorchScript
1679
+
1680
+ Args:
1681
+ waveform (Tensor): The input waveform of shape `(..., time)`.
1682
+ sample_rate (int): Sample rate of `waveform`.
1683
+ n_steps (int): The (fractional) steps to shift `waveform`.
1684
+ bins_per_octave (int, optional): The number of steps per octave (Default : ``12``).
1685
+ n_fft (int, optional): Size of FFT, creates ``n_fft // 2 + 1`` bins (Default: ``512``).
1686
+ win_length (int or None, optional): Window size. If None, then ``n_fft`` is used. (Default: ``None``).
1687
+ hop_length (int or None, optional): Length of hop between STFT windows. If None, then ``win_length // 4``
1688
+ is used (Default: ``None``).
1689
+ window (Tensor or None, optional): Window tensor that is applied/multiplied to each frame/window.
1690
+ If None, then ``torch.hann_window(win_length)`` is used (Default: ``None``).
1691
+
1692
+ Example
1693
+ >>> waveform, sample_rate = torchaudio.load("test.wav", normalize=True)
1694
+ >>> transform = transforms.PitchShift(sample_rate, 4)
1695
+ >>> waveform_shift = transform(waveform) # (channel, time)
1696
+ """
1697
+ __constants__ = ["sample_rate", "n_steps", "bins_per_octave", "n_fft", "win_length", "hop_length"]
1698
+
1699
+ kernel: UninitializedParameter
1700
+ width: int
1701
+
1702
+ def __init__(
1703
+ self,
1704
+ sample_rate: int,
1705
+ n_steps: int,
1706
+ bins_per_octave: int = 12,
1707
+ n_fft: int = 512,
1708
+ win_length: Optional[int] = None,
1709
+ hop_length: Optional[int] = None,
1710
+ window_fn: Callable[..., Tensor] = torch.hann_window,
1711
+ wkwargs: Optional[dict] = None,
1712
+ ) -> None:
1713
+ super().__init__()
1714
+ self.n_steps = n_steps
1715
+ self.bins_per_octave = bins_per_octave
1716
+ self.sample_rate = sample_rate
1717
+ self.n_fft = n_fft
1718
+ self.win_length = win_length if win_length is not None else n_fft
1719
+ self.hop_length = hop_length if hop_length is not None else self.win_length // 4
1720
+ window = window_fn(self.win_length) if wkwargs is None else window_fn(self.win_length, **wkwargs)
1721
+ self.register_buffer("window", window)
1722
+ rate = 2.0 ** (-float(n_steps) / bins_per_octave)
1723
+ self.orig_freq = int(sample_rate / rate)
1724
+ self.gcd = math.gcd(int(self.orig_freq), int(sample_rate))
1725
+
1726
+ if self.orig_freq != sample_rate:
1727
+ self.width = -1
1728
+ self.kernel = UninitializedParameter(device=None, dtype=None)
1729
+
1730
+ def initialize_parameters(self, input):
1731
+ if self.has_uninitialized_params():
1732
+ if self.orig_freq != self.sample_rate:
1733
+ with torch.no_grad():
1734
+ kernel, self.width = _get_sinc_resample_kernel(
1735
+ self.orig_freq,
1736
+ self.sample_rate,
1737
+ self.gcd,
1738
+ dtype=input.dtype,
1739
+ device=input.device,
1740
+ )
1741
+ self.kernel.materialize(kernel.shape)
1742
+ self.kernel.copy_(kernel)
1743
+
1744
+ def forward(self, waveform: Tensor) -> Tensor:
1745
+ r"""
1746
+ Args:
1747
+ waveform (Tensor): Tensor of audio of dimension `(..., time)`.
1748
+
1749
+ Returns:
1750
+ Tensor: The pitch-shifted audio of shape `(..., time)`.
1751
+ """
1752
+ shape = waveform.size()
1753
+
1754
+ waveform_stretch = _stretch_waveform(
1755
+ waveform,
1756
+ self.n_steps,
1757
+ self.bins_per_octave,
1758
+ self.n_fft,
1759
+ self.win_length,
1760
+ self.hop_length,
1761
+ self.window,
1762
+ )
1763
+
1764
+ if self.orig_freq != self.sample_rate:
1765
+ waveform_shift = _apply_sinc_resample_kernel(
1766
+ waveform_stretch,
1767
+ self.orig_freq,
1768
+ self.sample_rate,
1769
+ self.gcd,
1770
+ self.kernel,
1771
+ self.width,
1772
+ )
1773
+ else:
1774
+ waveform_shift = waveform_stretch
1775
+
1776
+ return _fix_waveform_shape(
1777
+ waveform_shift,
1778
+ shape,
1779
+ )
1780
+
1781
+
1782
+ class RNNTLoss(torch.nn.Module):
1783
+ """Compute the RNN Transducer loss from *Sequence Transduction with Recurrent Neural Networks*
1784
+ :cite:`graves2012sequence`.
1785
+
1786
+ .. devices:: CPU CUDA
1787
+
1788
+ .. properties:: Autograd TorchScript
1789
+
1790
+ The RNN Transducer loss extends the CTC loss by defining a distribution over output
1791
+ sequences of all lengths, and by jointly modelling both input-output and output-output
1792
+ dependencies.
1793
+
1794
+ Args:
1795
+ blank (int, optional): blank label (Default: ``-1``)
1796
+ clamp (float, optional): clamp for gradients (Default: ``-1``)
1797
+ reduction (string, optional): Specifies the reduction to apply to the output:
1798
+ ``"none"`` | ``"mean"`` | ``"sum"``. (Default: ``"mean"``)
1799
+ fused_log_softmax (bool): set to False if calling log_softmax outside of loss (Default: ``True``)
1800
+
1801
+ Example
1802
+ >>> # Hypothetical values
1803
+ >>> logits = torch.tensor([[[[0.1, 0.6, 0.1, 0.1, 0.1],
1804
+ >>> [0.1, 0.1, 0.6, 0.1, 0.1],
1805
+ >>> [0.1, 0.1, 0.2, 0.8, 0.1]],
1806
+ >>> [[0.1, 0.6, 0.1, 0.1, 0.1],
1807
+ >>> [0.1, 0.1, 0.2, 0.1, 0.1],
1808
+ >>> [0.7, 0.1, 0.2, 0.1, 0.1]]]],
1809
+ >>> dtype=torch.float32,
1810
+ >>> requires_grad=True)
1811
+ >>> targets = torch.tensor([[1, 2]], dtype=torch.int)
1812
+ >>> logit_lengths = torch.tensor([2], dtype=torch.int)
1813
+ >>> target_lengths = torch.tensor([2], dtype=torch.int)
1814
+ >>> transform = transforms.RNNTLoss(blank=0)
1815
+ >>> loss = transform(logits, targets, logit_lengths, target_lengths)
1816
+ >>> loss.backward()
1817
+ """
1818
+
1819
+ def __init__(
1820
+ self,
1821
+ blank: int = -1,
1822
+ clamp: float = -1.0,
1823
+ reduction: str = "mean",
1824
+ fused_log_softmax: bool = True,
1825
+ ):
1826
+ super().__init__()
1827
+ self.blank = blank
1828
+ self.clamp = clamp
1829
+ self.reduction = reduction
1830
+ self.fused_log_softmax = fused_log_softmax
1831
+
1832
+ def forward(
1833
+ self,
1834
+ logits: Tensor,
1835
+ targets: Tensor,
1836
+ logit_lengths: Tensor,
1837
+ target_lengths: Tensor,
1838
+ ):
1839
+ """
1840
+ Args:
1841
+ logits (Tensor): Tensor of dimension `(batch, max seq length, max target length + 1, class)`
1842
+ containing output from joiner
1843
+ targets (Tensor): Tensor of dimension `(batch, max target length)` containing targets with zero padded
1844
+ logit_lengths (Tensor): Tensor of dimension `(batch)` containing lengths of each sequence from encoder
1845
+ target_lengths (Tensor): Tensor of dimension `(batch)` containing lengths of targets for each sequence
1846
+ Returns:
1847
+ Tensor: Loss with the reduction option applied. If ``reduction`` is ``"none"``, then size (batch),
1848
+ otherwise scalar.
1849
+ """
1850
+ return _rnnt_loss(
1851
+ logits,
1852
+ targets,
1853
+ logit_lengths,
1854
+ target_lengths,
1855
+ self.blank,
1856
+ self.clamp,
1857
+ self.reduction,
1858
+ self.fused_log_softmax,
1859
+ )
1860
+
1861
+
1862
+ class Convolve(torch.nn.Module):
1863
+ r"""
1864
+ Convolves inputs along their last dimension using the direct method.
1865
+ Note that, in contrast to :class:`torch.nn.Conv1d`, which actually applies the valid cross-correlation
1866
+ operator, this module applies the true `convolution`_ operator.
1867
+
1868
+ .. devices:: CPU CUDA
1869
+
1870
+ .. properties:: Autograd TorchScript
1871
+
1872
+ Args:
1873
+ mode (str, optional): Must be one of ("full", "valid", "same").
1874
+
1875
+ * "full": Returns the full convolution result, with shape `(..., N + M - 1)`, where
1876
+ `N` and `M` are the trailing dimensions of the two inputs. (Default)
1877
+ * "valid": Returns the segment of the full convolution result corresponding to where
1878
+ the two inputs overlap completely, with shape `(..., max(N, M) - min(N, M) + 1)`.
1879
+ * "same": Returns the center segment of the full convolution result, with shape `(..., N)`.
1880
+
1881
+ .. _convolution:
1882
+ https://en.wikipedia.org/wiki/Convolution
1883
+ """
1884
+
1885
+ def __init__(self, mode: str = "full") -> None:
1886
+ _check_convolve_mode(mode)
1887
+
1888
+ super().__init__()
1889
+ self.mode = mode
1890
+
1891
+ def forward(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
1892
+ r"""
1893
+ Args:
1894
+ x (torch.Tensor): First convolution operand, with shape `(..., N)`.
1895
+ y (torch.Tensor): Second convolution operand, with shape `(..., M)`
1896
+ (leading dimensions must be broadcast-able with those of ``x``).
1897
+
1898
+ Returns:
1899
+ torch.Tensor: Result of convolving ``x`` and ``y``, with shape `(..., L)`, where
1900
+ the leading dimensions match those of ``x`` and `L` is dictated by ``mode``.
1901
+ """
1902
+ return F.convolve(x, y, mode=self.mode)
1903
+
1904
+
1905
+ class FFTConvolve(torch.nn.Module):
1906
+ r"""
1907
+ Convolves inputs along their last dimension using FFT. For inputs with large last dimensions, this module
1908
+ is generally much faster than :class:`Convolve`.
1909
+ Note that, in contrast to :class:`torch.nn.Conv1d`, which actually applies the valid cross-correlation
1910
+ operator, this module applies the true `convolution`_ operator.
1911
+ Also note that this module can only output float tensors (int tensor inputs will be cast to float).
1912
+
1913
+ .. devices:: CPU CUDA
1914
+
1915
+ .. properties:: Autograd TorchScript
1916
+
1917
+ Args:
1918
+ mode (str, optional): Must be one of ("full", "valid", "same").
1919
+
1920
+ * "full": Returns the full convolution result, with shape `(..., N + M - 1)`, where
1921
+ `N` and `M` are the trailing dimensions of the two inputs. (Default)
1922
+ * "valid": Returns the segment of the full convolution result corresponding to where
1923
+ the two inputs overlap completely, with shape `(..., max(N, M) - min(N, M) + 1)`.
1924
+ * "same": Returns the center segment of the full convolution result, with shape `(..., N)`.
1925
+
1926
+ .. _convolution:
1927
+ https://en.wikipedia.org/wiki/Convolution
1928
+ """
1929
+
1930
+ def __init__(self, mode: str = "full") -> None:
1931
+ _check_convolve_mode(mode)
1932
+
1933
+ super().__init__()
1934
+ self.mode = mode
1935
+
1936
+ def forward(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
1937
+ r"""
1938
+ Args:
1939
+ x (torch.Tensor): First convolution operand, with shape `(..., N)`.
1940
+ y (torch.Tensor): Second convolution operand, with shape `(..., M)`
1941
+ (leading dimensions must be broadcast-able with those of ``x``).
1942
+
1943
+ Returns:
1944
+ torch.Tensor: Result of convolving ``x`` and ``y``, with shape `(..., L)`, where
1945
+ the leading dimensions match those of ``x`` and `L` is dictated by ``mode``.
1946
+ """
1947
+ return F.fftconvolve(x, y, mode=self.mode)
1948
+
1949
+
1950
+ def _source_target_sample_rate(orig_freq: int, speed: float) -> Tuple[int, int]:
1951
+ source_sample_rate = int(speed * orig_freq)
1952
+ target_sample_rate = int(orig_freq)
1953
+ gcd = math.gcd(source_sample_rate, target_sample_rate)
1954
+ return source_sample_rate // gcd, target_sample_rate // gcd
1955
+
1956
+
1957
+ class Speed(torch.nn.Module):
1958
+ r"""Adjusts waveform speed.
1959
+
1960
+ .. devices:: CPU CUDA
1961
+
1962
+ .. properties:: Autograd TorchScript
1963
+
1964
+ Args:
1965
+ orig_freq (int): Original frequency of the signals in ``waveform``.
1966
+ factor (float): Factor by which to adjust speed of input. Values greater than 1.0
1967
+ compress ``waveform`` in time, whereas values less than 1.0 stretch ``waveform`` in time.
1968
+ """
1969
+
1970
+ def __init__(self, orig_freq, factor) -> None:
1971
+ super().__init__()
1972
+
1973
+ self.orig_freq = orig_freq
1974
+ self.factor = factor
1975
+
1976
+ self.source_sample_rate, self.target_sample_rate = _source_target_sample_rate(orig_freq, factor)
1977
+ self.resampler = Resample(orig_freq=self.source_sample_rate, new_freq=self.target_sample_rate)
1978
+
1979
+ def forward(self, waveform, lengths: Optional[torch.Tensor] = None) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
1980
+ r"""
1981
+ Args:
1982
+ waveform (torch.Tensor): Input signals, with shape `(..., time)`.
1983
+ lengths (torch.Tensor or None, optional): Valid lengths of signals in ``waveform``, with shape `(...)`.
1984
+ If ``None``, all elements in ``waveform`` are treated as valid. (Default: ``None``)
1985
+
1986
+ Returns:
1987
+ (torch.Tensor, torch.Tensor or None):
1988
+ torch.Tensor
1989
+ Speed-adjusted waveform, with shape `(..., new_time).`
1990
+ torch.Tensor or None
1991
+ If ``lengths`` is not ``None``, valid lengths of signals in speed-adjusted waveform,
1992
+ with shape `(...)`; otherwise, ``None``.
1993
+ """
1994
+
1995
+ if lengths is None:
1996
+ out_lengths = None
1997
+ else:
1998
+ out_lengths = torch.ceil(lengths * self.target_sample_rate / self.source_sample_rate).to(lengths.dtype)
1999
+
2000
+ return self.resampler(waveform), out_lengths
2001
+
2002
+
2003
+ class SpeedPerturbation(torch.nn.Module):
2004
+ r"""Applies the speed perturbation augmentation introduced in
2005
+ *Audio augmentation for speech recognition* :cite:`ko15_interspeech`. For a given input,
2006
+ the module samples a speed-up factor from ``factors`` uniformly at random and adjusts
2007
+ the speed of the input by that factor.
2008
+
2009
+ .. devices:: CPU CUDA
2010
+
2011
+ .. properties:: Autograd TorchScript
2012
+
2013
+ Args:
2014
+ orig_freq (int): Original frequency of the signals in ``waveform``.
2015
+ factors (Sequence[float]): Factors by which to adjust speed of input. Values greater than 1.0
2016
+ compress ``waveform`` in time, whereas values less than 1.0 stretch ``waveform`` in time.
2017
+
2018
+ Example
2019
+ >>> speed_perturb = SpeedPerturbation(16000, [0.9, 1.1, 1.0, 1.0, 1.0])
2020
+ >>> # waveform speed will be adjusted by factor 0.9 with 20% probability,
2021
+ >>> # 1.1 with 20% probability, and 1.0 (i.e. kept the same) with 60% probability.
2022
+ >>> speed_perturbed_waveform = speed_perturb(waveform, lengths)
2023
+ """
2024
+
2025
+ def __init__(self, orig_freq: int, factors: Sequence[float]) -> None:
2026
+ super().__init__()
2027
+
2028
+ self.speeders = torch.nn.ModuleList([Speed(orig_freq=orig_freq, factor=factor) for factor in factors])
2029
+
2030
+ def forward(
2031
+ self, waveform: torch.Tensor, lengths: Optional[torch.Tensor] = None
2032
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
2033
+ r"""
2034
+ Args:
2035
+ waveform (torch.Tensor): Input signals, with shape `(..., time)`.
2036
+ lengths (torch.Tensor or None, optional): Valid lengths of signals in ``waveform``, with shape `(...)`.
2037
+ If ``None``, all elements in ``waveform`` are treated as valid. (Default: ``None``)
2038
+
2039
+ Returns:
2040
+ (torch.Tensor, torch.Tensor or None):
2041
+ torch.Tensor
2042
+ Speed-adjusted waveform, with shape `(..., new_time).`
2043
+ torch.Tensor or None
2044
+ If ``lengths`` is not ``None``, valid lengths of signals in speed-adjusted waveform,
2045
+ with shape `(...)`; otherwise, ``None``.
2046
+ """
2047
+
2048
+ idx = int(torch.randint(len(self.speeders), ()))
2049
+ # NOTE: we do this because TorchScript doesn't allow for
2050
+ # indexing ModuleList instances with non-literals.
2051
+ for speeder_idx, speeder in enumerate(self.speeders):
2052
+ if idx == speeder_idx:
2053
+ return speeder(waveform, lengths)
2054
+ raise RuntimeError("Speeder not found; execution should have never reached here.")
2055
+
2056
+
2057
+ class AddNoise(torch.nn.Module):
2058
+ r"""Scales and adds noise to waveform per signal-to-noise ratio.
2059
+ See :meth:`torchaudio.functional.add_noise` for more details.
2060
+
2061
+ .. devices:: CPU CUDA
2062
+
2063
+ .. properties:: Autograd TorchScript
2064
+ """
2065
+
2066
+ def forward(
2067
+ self, waveform: torch.Tensor, noise: torch.Tensor, snr: torch.Tensor, lengths: Optional[torch.Tensor] = None
2068
+ ) -> torch.Tensor:
2069
+ r"""
2070
+ Args:
2071
+ waveform (torch.Tensor): Input waveform, with shape `(..., L)`.
2072
+ noise (torch.Tensor): Noise, with shape `(..., L)` (same shape as ``waveform``).
2073
+ snr (torch.Tensor): Signal-to-noise ratios in dB, with shape `(...,)`.
2074
+ lengths (torch.Tensor or None, optional): Valid lengths of signals in ``waveform`` and ``noise``,
2075
+ with shape `(...,)` (leading dimensions must match those of ``waveform``). If ``None``, all
2076
+ elements in ``waveform`` and ``noise`` are treated as valid. (Default: ``None``)
2077
+
2078
+ Returns:
2079
+ torch.Tensor: Result of scaling and adding ``noise`` to ``waveform``, with shape `(..., L)`
2080
+ (same shape as ``waveform``).
2081
+ """
2082
+ return F.add_noise(waveform, noise, snr, lengths)
2083
+
2084
+
2085
+ class Preemphasis(torch.nn.Module):
2086
+ r"""Pre-emphasizes a waveform along its last dimension.
2087
+ See :meth:`torchaudio.functional.preemphasis` for more details.
2088
+
2089
+ .. devices:: CPU CUDA
2090
+
2091
+ .. properties:: Autograd TorchScript
2092
+
2093
+ Args:
2094
+ coeff (float, optional): Pre-emphasis coefficient. Typically between 0.0 and 1.0.
2095
+ (Default: 0.97)
2096
+ """
2097
+
2098
+ def __init__(self, coeff: float = 0.97) -> None:
2099
+ super().__init__()
2100
+ self.coeff = coeff
2101
+
2102
+ def forward(self, waveform: torch.Tensor) -> torch.Tensor:
2103
+ r"""
2104
+ Args:
2105
+ waveform (torch.Tensor): Waveform, with shape `(..., N)`.
2106
+
2107
+ Returns:
2108
+ torch.Tensor: Pre-emphasized waveform, with shape `(..., N)`.
2109
+ """
2110
+ return F.preemphasis(waveform, coeff=self.coeff)
2111
+
2112
+
2113
+ class Deemphasis(torch.nn.Module):
2114
+ r"""De-emphasizes a waveform along its last dimension.
2115
+ See :meth:`torchaudio.functional.deemphasis` for more details.
2116
+
2117
+ .. devices:: CPU CUDA
2118
+
2119
+ .. properties:: Autograd TorchScript
2120
+
2121
+ Args:
2122
+ coeff (float, optional): De-emphasis coefficient. Typically between 0.0 and 1.0.
2123
+ (Default: 0.97)
2124
+ """
2125
+
2126
+ def __init__(self, coeff: float = 0.97) -> None:
2127
+ super().__init__()
2128
+ self.coeff = coeff
2129
+
2130
+ def forward(self, waveform: torch.Tensor) -> torch.Tensor:
2131
+ r"""
2132
+ Args:
2133
+ waveform (torch.Tensor): Waveform, with shape `(..., N)`.
2134
+
2135
+ Returns:
2136
+ torch.Tensor: De-emphasized waveform, with shape `(..., N)`.
2137
+ """
2138
+ return F.functional.deemphasis(waveform, coeff=self.coeff)