torchaudio 2.7.0__cp310-cp310-manylinux_2_28_x86_64.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.
Potentially problematic release.
This version of torchaudio might be problematic. Click here for more details.
- torchaudio/__init__.py +53 -0
- torchaudio/_backend/__init__.py +61 -0
- torchaudio/_backend/backend.py +53 -0
- torchaudio/_backend/common.py +52 -0
- torchaudio/_backend/ffmpeg.py +334 -0
- torchaudio/_backend/soundfile.py +54 -0
- torchaudio/_backend/soundfile_backend.py +457 -0
- torchaudio/_backend/sox.py +91 -0
- torchaudio/_backend/utils.py +317 -0
- torchaudio/_extension/__init__.py +74 -0
- torchaudio/_extension/utils.py +180 -0
- torchaudio/_internal/__init__.py +10 -0
- torchaudio/_internal/module_utils.py +113 -0
- torchaudio/backend/__init__.py +8 -0
- torchaudio/backend/_no_backend.py +25 -0
- torchaudio/backend/_sox_io_backend.py +294 -0
- torchaudio/backend/common.py +13 -0
- torchaudio/backend/no_backend.py +14 -0
- torchaudio/backend/soundfile_backend.py +14 -0
- torchaudio/backend/sox_io_backend.py +14 -0
- torchaudio/compliance/__init__.py +5 -0
- torchaudio/compliance/kaldi.py +813 -0
- torchaudio/datasets/__init__.py +47 -0
- torchaudio/datasets/cmuarctic.py +157 -0
- torchaudio/datasets/cmudict.py +186 -0
- torchaudio/datasets/commonvoice.py +86 -0
- torchaudio/datasets/dr_vctk.py +121 -0
- torchaudio/datasets/fluentcommands.py +108 -0
- torchaudio/datasets/gtzan.py +1118 -0
- torchaudio/datasets/iemocap.py +147 -0
- torchaudio/datasets/librilight_limited.py +111 -0
- torchaudio/datasets/librimix.py +133 -0
- torchaudio/datasets/librispeech.py +174 -0
- torchaudio/datasets/librispeech_biasing.py +189 -0
- torchaudio/datasets/libritts.py +168 -0
- torchaudio/datasets/ljspeech.py +107 -0
- torchaudio/datasets/musdb_hq.py +139 -0
- torchaudio/datasets/quesst14.py +136 -0
- torchaudio/datasets/snips.py +157 -0
- torchaudio/datasets/speechcommands.py +183 -0
- torchaudio/datasets/tedlium.py +218 -0
- torchaudio/datasets/utils.py +54 -0
- torchaudio/datasets/vctk.py +143 -0
- torchaudio/datasets/voxceleb1.py +309 -0
- torchaudio/datasets/yesno.py +89 -0
- torchaudio/functional/__init__.py +127 -0
- torchaudio/functional/_alignment.py +128 -0
- torchaudio/functional/filtering.py +1670 -0
- torchaudio/functional/functional.py +2535 -0
- torchaudio/io/__init__.py +13 -0
- torchaudio/io/_effector.py +347 -0
- torchaudio/io/_playback.py +72 -0
- torchaudio/kaldi_io.py +144 -0
- torchaudio/lib/__init__.py +0 -0
- torchaudio/lib/_torchaudio.so +0 -0
- torchaudio/lib/_torchaudio_sox.so +0 -0
- torchaudio/lib/libctc_prefix_decoder.so +0 -0
- torchaudio/lib/libtorchaudio.so +0 -0
- torchaudio/lib/libtorchaudio_sox.so +0 -0
- torchaudio/lib/pybind11_prefixctc.so +0 -0
- torchaudio/models/__init__.py +85 -0
- torchaudio/models/_hdemucs.py +1008 -0
- torchaudio/models/conformer.py +293 -0
- torchaudio/models/conv_tasnet.py +330 -0
- torchaudio/models/decoder/__init__.py +46 -0
- torchaudio/models/decoder/_ctc_decoder.py +568 -0
- torchaudio/models/decoder/_cuda_ctc_decoder.py +187 -0
- torchaudio/models/deepspeech.py +84 -0
- torchaudio/models/emformer.py +884 -0
- torchaudio/models/rnnt.py +816 -0
- torchaudio/models/rnnt_decoder.py +339 -0
- torchaudio/models/squim/__init__.py +11 -0
- torchaudio/models/squim/objective.py +326 -0
- torchaudio/models/squim/subjective.py +150 -0
- torchaudio/models/tacotron2.py +1046 -0
- torchaudio/models/wav2letter.py +72 -0
- torchaudio/models/wav2vec2/__init__.py +45 -0
- torchaudio/models/wav2vec2/components.py +1167 -0
- torchaudio/models/wav2vec2/model.py +1579 -0
- torchaudio/models/wav2vec2/utils/__init__.py +7 -0
- torchaudio/models/wav2vec2/utils/import_fairseq.py +213 -0
- torchaudio/models/wav2vec2/utils/import_huggingface.py +134 -0
- torchaudio/models/wav2vec2/wavlm_attention.py +214 -0
- torchaudio/models/wavernn.py +409 -0
- torchaudio/pipelines/__init__.py +102 -0
- torchaudio/pipelines/_source_separation_pipeline.py +109 -0
- torchaudio/pipelines/_squim_pipeline.py +156 -0
- torchaudio/pipelines/_tts/__init__.py +16 -0
- torchaudio/pipelines/_tts/impl.py +385 -0
- torchaudio/pipelines/_tts/interface.py +255 -0
- torchaudio/pipelines/_tts/utils.py +228 -0
- torchaudio/pipelines/_wav2vec2/__init__.py +0 -0
- torchaudio/pipelines/_wav2vec2/aligner.py +87 -0
- torchaudio/pipelines/_wav2vec2/impl.py +1699 -0
- torchaudio/pipelines/_wav2vec2/utils.py +346 -0
- torchaudio/pipelines/rnnt_pipeline.py +380 -0
- torchaudio/prototype/__init__.py +0 -0
- torchaudio/prototype/datasets/__init__.py +4 -0
- torchaudio/prototype/datasets/musan.py +67 -0
- torchaudio/prototype/functional/__init__.py +26 -0
- torchaudio/prototype/functional/_dsp.py +433 -0
- torchaudio/prototype/functional/_rir.py +379 -0
- torchaudio/prototype/functional/functional.py +190 -0
- torchaudio/prototype/models/__init__.py +36 -0
- torchaudio/prototype/models/_conformer_wav2vec2.py +794 -0
- torchaudio/prototype/models/_emformer_hubert.py +333 -0
- torchaudio/prototype/models/conv_emformer.py +525 -0
- torchaudio/prototype/models/hifi_gan.py +336 -0
- torchaudio/prototype/models/rnnt.py +711 -0
- torchaudio/prototype/models/rnnt_decoder.py +399 -0
- torchaudio/prototype/pipelines/__init__.py +12 -0
- torchaudio/prototype/pipelines/_vggish/__init__.py +3 -0
- torchaudio/prototype/pipelines/_vggish/_vggish_impl.py +233 -0
- torchaudio/prototype/pipelines/_vggish/_vggish_pipeline.py +82 -0
- torchaudio/prototype/pipelines/hifigan_pipeline.py +228 -0
- torchaudio/prototype/pipelines/rnnt_pipeline.py +58 -0
- torchaudio/prototype/transforms/__init__.py +9 -0
- torchaudio/prototype/transforms/_transforms.py +456 -0
- torchaudio/sox_effects/__init__.py +10 -0
- torchaudio/sox_effects/sox_effects.py +272 -0
- torchaudio/transforms/__init__.py +75 -0
- torchaudio/transforms/_multi_channel.py +467 -0
- torchaudio/transforms/_transforms.py +2137 -0
- torchaudio/utils/__init__.py +11 -0
- torchaudio/utils/download.py +89 -0
- torchaudio/utils/ffmpeg_utils.py +11 -0
- torchaudio/utils/sox_utils.py +99 -0
- torchaudio/version.py +2 -0
- torchaudio-2.7.0.dist-info/LICENSE +25 -0
- torchaudio-2.7.0.dist-info/METADATA +124 -0
- torchaudio-2.7.0.dist-info/RECORD +148 -0
- torchaudio-2.7.0.dist-info/WHEEL +5 -0
- torchaudio-2.7.0.dist-info/top_level.txt +2 -0
- torio/__init__.py +8 -0
- torio/_extension/__init__.py +13 -0
- torio/_extension/utils.py +147 -0
- torio/io/__init__.py +9 -0
- torio/io/_streaming_media_decoder.py +978 -0
- torio/io/_streaming_media_encoder.py +502 -0
- torio/lib/__init__.py +0 -0
- torio/lib/_torio_ffmpeg4.so +0 -0
- torio/lib/_torio_ffmpeg5.so +0 -0
- torio/lib/_torio_ffmpeg6.so +0 -0
- torio/lib/libtorio_ffmpeg4.so +0 -0
- torio/lib/libtorio_ffmpeg5.so +0 -0
- torio/lib/libtorio_ffmpeg6.so +0 -0
- torio/utils/__init__.py +4 -0
- torio/utils/ffmpeg_utils.py +247 -0
|
@@ -0,0 +1,317 @@
|
|
|
1
|
+
import os
|
|
2
|
+
from functools import lru_cache
|
|
3
|
+
from typing import BinaryIO, Dict, Optional, Tuple, Type, Union
|
|
4
|
+
|
|
5
|
+
import torch
|
|
6
|
+
|
|
7
|
+
from torchaudio._extension import lazy_import_sox_ext
|
|
8
|
+
from torchaudio.io import CodecConfig
|
|
9
|
+
from torio._extension import lazy_import_ffmpeg_ext
|
|
10
|
+
|
|
11
|
+
from . import soundfile_backend
|
|
12
|
+
|
|
13
|
+
from .backend import Backend
|
|
14
|
+
from .common import AudioMetaData
|
|
15
|
+
from .ffmpeg import FFmpegBackend
|
|
16
|
+
from .soundfile import SoundfileBackend
|
|
17
|
+
from .sox import SoXBackend
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@lru_cache(None)
|
|
21
|
+
def get_available_backends() -> Dict[str, Type[Backend]]:
|
|
22
|
+
backend_specs: Dict[str, Type[Backend]] = {}
|
|
23
|
+
if lazy_import_ffmpeg_ext().is_available():
|
|
24
|
+
backend_specs["ffmpeg"] = FFmpegBackend
|
|
25
|
+
if lazy_import_sox_ext().is_available():
|
|
26
|
+
backend_specs["sox"] = SoXBackend
|
|
27
|
+
if soundfile_backend._IS_SOUNDFILE_AVAILABLE:
|
|
28
|
+
backend_specs["soundfile"] = SoundfileBackend
|
|
29
|
+
return backend_specs
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def get_backend(backend_name, backends) -> Backend:
|
|
33
|
+
if backend := backends.get(backend_name):
|
|
34
|
+
return backend
|
|
35
|
+
else:
|
|
36
|
+
raise ValueError(
|
|
37
|
+
f"Unsupported backend '{backend_name}' specified; ",
|
|
38
|
+
f"please select one of {list(backends.keys())} instead.",
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def get_info_func():
|
|
43
|
+
backends = get_available_backends()
|
|
44
|
+
|
|
45
|
+
def dispatcher(
|
|
46
|
+
uri: Union[BinaryIO, str, os.PathLike], format: Optional[str], backend_name: Optional[str]
|
|
47
|
+
) -> Backend:
|
|
48
|
+
if backend_name is not None:
|
|
49
|
+
return get_backend(backend_name, backends)
|
|
50
|
+
|
|
51
|
+
for backend in backends.values():
|
|
52
|
+
if backend.can_decode(uri, format):
|
|
53
|
+
return backend
|
|
54
|
+
raise RuntimeError(f"Couldn't find appropriate backend to handle uri {uri} and format {format}.")
|
|
55
|
+
|
|
56
|
+
def info(
|
|
57
|
+
uri: Union[BinaryIO, str, os.PathLike],
|
|
58
|
+
format: Optional[str] = None,
|
|
59
|
+
buffer_size: int = 4096,
|
|
60
|
+
backend: Optional[str] = None,
|
|
61
|
+
) -> AudioMetaData:
|
|
62
|
+
"""Get signal information of an audio file.
|
|
63
|
+
|
|
64
|
+
Note:
|
|
65
|
+
When the input type is file-like object, this function cannot
|
|
66
|
+
get the correct length (``num_samples``) for certain formats,
|
|
67
|
+
such as ``vorbis``.
|
|
68
|
+
In this case, the value of ``num_samples`` is ``0``.
|
|
69
|
+
|
|
70
|
+
Args:
|
|
71
|
+
uri (path-like object or file-like object):
|
|
72
|
+
Source of audio data. The following types are accepted:
|
|
73
|
+
|
|
74
|
+
* ``path-like``: File path or URL.
|
|
75
|
+
* ``file-like``: Object with ``read(size: int) -> bytes`` method,
|
|
76
|
+
which returns byte string of at most ``size`` length.
|
|
77
|
+
|
|
78
|
+
format (str or None, optional):
|
|
79
|
+
If not ``None``, interpreted as hint that may allow backend to override the detected format.
|
|
80
|
+
(Default: ``None``)
|
|
81
|
+
|
|
82
|
+
buffer_size (int, optional):
|
|
83
|
+
Size of buffer to use when processing file-like objects, in bytes. (Default: ``4096``)
|
|
84
|
+
|
|
85
|
+
backend (str or None, optional):
|
|
86
|
+
I/O backend to use.
|
|
87
|
+
If ``None``, function selects backend given input and available backends.
|
|
88
|
+
Otherwise, must be one of [``"ffmpeg"``, ``"sox"``, ``"soundfile"``],
|
|
89
|
+
with the corresponding backend available.
|
|
90
|
+
(Default: ``None``)
|
|
91
|
+
|
|
92
|
+
.. seealso::
|
|
93
|
+
:ref:`backend`
|
|
94
|
+
|
|
95
|
+
Returns:
|
|
96
|
+
AudioMetaData
|
|
97
|
+
"""
|
|
98
|
+
backend = dispatcher(uri, format, backend)
|
|
99
|
+
return backend.info(uri, format, buffer_size)
|
|
100
|
+
|
|
101
|
+
return info
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def get_load_func():
|
|
105
|
+
backends = get_available_backends()
|
|
106
|
+
|
|
107
|
+
def dispatcher(
|
|
108
|
+
uri: Union[BinaryIO, str, os.PathLike], format: Optional[str], backend_name: Optional[str]
|
|
109
|
+
) -> Backend:
|
|
110
|
+
if backend_name is not None:
|
|
111
|
+
return get_backend(backend_name, backends)
|
|
112
|
+
|
|
113
|
+
for backend in backends.values():
|
|
114
|
+
if backend.can_decode(uri, format):
|
|
115
|
+
return backend
|
|
116
|
+
raise RuntimeError(f"Couldn't find appropriate backend to handle uri {uri} and format {format}.")
|
|
117
|
+
|
|
118
|
+
def load(
|
|
119
|
+
uri: Union[BinaryIO, str, os.PathLike],
|
|
120
|
+
frame_offset: int = 0,
|
|
121
|
+
num_frames: int = -1,
|
|
122
|
+
normalize: bool = True,
|
|
123
|
+
channels_first: bool = True,
|
|
124
|
+
format: Optional[str] = None,
|
|
125
|
+
buffer_size: int = 4096,
|
|
126
|
+
backend: Optional[str] = None,
|
|
127
|
+
) -> Tuple[torch.Tensor, int]:
|
|
128
|
+
"""Load audio data from source.
|
|
129
|
+
|
|
130
|
+
By default (``normalize=True``, ``channels_first=True``), this function returns Tensor with
|
|
131
|
+
``float32`` dtype, and the shape of `[channel, time]`.
|
|
132
|
+
|
|
133
|
+
Note:
|
|
134
|
+
The formats this function can handle depend on the availability of backends.
|
|
135
|
+
Please use the following functions to fetch the supported formats.
|
|
136
|
+
|
|
137
|
+
- FFmpeg: :py:func:`torchaudio.utils.ffmpeg_utils.get_audio_decoders`
|
|
138
|
+
- Sox: :py:func:`torchaudio.utils.sox_utils.list_read_formats`
|
|
139
|
+
- SoundFile: Refer to `the official document <https://pysoundfile.readthedocs.io/>`__.
|
|
140
|
+
|
|
141
|
+
.. warning::
|
|
142
|
+
|
|
143
|
+
``normalize`` argument does not perform volume normalization.
|
|
144
|
+
It only converts the sample type to `torch.float32` from the native sample
|
|
145
|
+
type.
|
|
146
|
+
|
|
147
|
+
When the input format is WAV with integer type, such as 32-bit signed integer, 16-bit
|
|
148
|
+
signed integer, 24-bit signed integer, and 8-bit unsigned integer, by providing ``normalize=False``,
|
|
149
|
+
this function can return integer Tensor, where the samples are expressed within the whole range
|
|
150
|
+
of the corresponding dtype, that is, ``int32`` tensor for 32-bit signed PCM,
|
|
151
|
+
``int16`` for 16-bit signed PCM and ``uint8`` for 8-bit unsigned PCM. Since torch does not
|
|
152
|
+
support ``int24`` dtype, 24-bit signed PCM are converted to ``int32`` tensors.
|
|
153
|
+
|
|
154
|
+
``normalize`` argument has no effect on 32-bit floating-point WAV and other formats, such as
|
|
155
|
+
``flac`` and ``mp3``.
|
|
156
|
+
|
|
157
|
+
For these formats, this function always returns ``float32`` Tensor with values.
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
Args:
|
|
161
|
+
uri (path-like object or file-like object):
|
|
162
|
+
Source of audio data.
|
|
163
|
+
frame_offset (int, optional):
|
|
164
|
+
Number of frames to skip before start reading data.
|
|
165
|
+
num_frames (int, optional):
|
|
166
|
+
Maximum number of frames to read. ``-1`` reads all the remaining samples,
|
|
167
|
+
starting from ``frame_offset``.
|
|
168
|
+
This function may return the less number of frames if there is not enough
|
|
169
|
+
frames in the given file.
|
|
170
|
+
normalize (bool, optional):
|
|
171
|
+
When ``True``, this function converts the native sample type to ``float32``.
|
|
172
|
+
Default: ``True``.
|
|
173
|
+
|
|
174
|
+
If input file is integer WAV, giving ``False`` will change the resulting Tensor type to
|
|
175
|
+
integer type.
|
|
176
|
+
This argument has no effect for formats other than integer WAV type.
|
|
177
|
+
|
|
178
|
+
channels_first (bool, optional):
|
|
179
|
+
When True, the returned Tensor has dimension `[channel, time]`.
|
|
180
|
+
Otherwise, the returned Tensor's dimension is `[time, channel]`.
|
|
181
|
+
|
|
182
|
+
format (str or None, optional):
|
|
183
|
+
If not ``None``, interpreted as hint that may allow backend to override the detected format.
|
|
184
|
+
(Default: ``None``)
|
|
185
|
+
|
|
186
|
+
buffer_size (int, optional):
|
|
187
|
+
Size of buffer to use when processing file-like objects, in bytes. (Default: ``4096``)
|
|
188
|
+
|
|
189
|
+
backend (str or None, optional):
|
|
190
|
+
I/O backend to use.
|
|
191
|
+
If ``None``, function selects backend given input and available backends.
|
|
192
|
+
Otherwise, must be one of [``"ffmpeg"``, ``"sox"``, ``"soundfile"``],
|
|
193
|
+
with the corresponding backend being available. (Default: ``None``)
|
|
194
|
+
|
|
195
|
+
.. seealso::
|
|
196
|
+
:ref:`backend`
|
|
197
|
+
|
|
198
|
+
Returns:
|
|
199
|
+
(torch.Tensor, int): Resulting Tensor and sample rate.
|
|
200
|
+
If the input file has integer wav format and normalization is off, then it has
|
|
201
|
+
integer type, else ``float32`` type. If ``channels_first=True``, it has
|
|
202
|
+
`[channel, time]` else `[time, channel]`.
|
|
203
|
+
"""
|
|
204
|
+
backend = dispatcher(uri, format, backend)
|
|
205
|
+
return backend.load(uri, frame_offset, num_frames, normalize, channels_first, format, buffer_size)
|
|
206
|
+
|
|
207
|
+
return load
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def get_save_func():
|
|
211
|
+
backends = get_available_backends()
|
|
212
|
+
|
|
213
|
+
def dispatcher(
|
|
214
|
+
uri: Union[BinaryIO, str, os.PathLike], format: Optional[str], backend_name: Optional[str]
|
|
215
|
+
) -> Backend:
|
|
216
|
+
if backend_name is not None:
|
|
217
|
+
return get_backend(backend_name, backends)
|
|
218
|
+
|
|
219
|
+
for backend in backends.values():
|
|
220
|
+
if backend.can_encode(uri, format):
|
|
221
|
+
return backend
|
|
222
|
+
raise RuntimeError(f"Couldn't find appropriate backend to handle uri {uri} and format {format}.")
|
|
223
|
+
|
|
224
|
+
def save(
|
|
225
|
+
uri: Union[BinaryIO, str, os.PathLike],
|
|
226
|
+
src: torch.Tensor,
|
|
227
|
+
sample_rate: int,
|
|
228
|
+
channels_first: bool = True,
|
|
229
|
+
format: Optional[str] = None,
|
|
230
|
+
encoding: Optional[str] = None,
|
|
231
|
+
bits_per_sample: Optional[int] = None,
|
|
232
|
+
buffer_size: int = 4096,
|
|
233
|
+
backend: Optional[str] = None,
|
|
234
|
+
compression: Optional[Union[CodecConfig, float, int]] = None,
|
|
235
|
+
):
|
|
236
|
+
"""Save audio data to file.
|
|
237
|
+
|
|
238
|
+
Note:
|
|
239
|
+
The formats this function can handle depend on the availability of backends.
|
|
240
|
+
Please use the following functions to fetch the supported formats.
|
|
241
|
+
|
|
242
|
+
- FFmpeg: :py:func:`torchaudio.utils.ffmpeg_utils.get_audio_encoders`
|
|
243
|
+
- Sox: :py:func:`torchaudio.utils.sox_utils.list_write_formats`
|
|
244
|
+
- SoundFile: Refer to `the official document <https://pysoundfile.readthedocs.io/>`__.
|
|
245
|
+
|
|
246
|
+
Args:
|
|
247
|
+
uri (str or pathlib.Path): Path to audio file.
|
|
248
|
+
src (torch.Tensor): Audio data to save. must be 2D tensor.
|
|
249
|
+
sample_rate (int): sampling rate
|
|
250
|
+
channels_first (bool, optional): If ``True``, the given tensor is interpreted as `[channel, time]`,
|
|
251
|
+
otherwise `[time, channel]`.
|
|
252
|
+
format (str or None, optional): Override the audio format.
|
|
253
|
+
When ``uri`` argument is path-like object, audio format is
|
|
254
|
+
inferred from file extension. If the file extension is missing or
|
|
255
|
+
different, you can specify the correct format with this argument.
|
|
256
|
+
|
|
257
|
+
When ``uri`` argument is file-like object,
|
|
258
|
+
this argument is required.
|
|
259
|
+
|
|
260
|
+
Valid values are ``"wav"``, ``"ogg"``, and ``"flac"``.
|
|
261
|
+
encoding (str or None, optional): Changes the encoding for supported formats.
|
|
262
|
+
This argument is effective only for supported formats, i.e.
|
|
263
|
+
``"wav"`` and ``""flac"```. Valid values are
|
|
264
|
+
|
|
265
|
+
- ``"PCM_S"`` (signed integer Linear PCM)
|
|
266
|
+
- ``"PCM_U"`` (unsigned integer Linear PCM)
|
|
267
|
+
- ``"PCM_F"`` (floating point PCM)
|
|
268
|
+
- ``"ULAW"`` (mu-law)
|
|
269
|
+
- ``"ALAW"`` (a-law)
|
|
270
|
+
|
|
271
|
+
bits_per_sample (int or None, optional): Changes the bit depth for the
|
|
272
|
+
supported formats.
|
|
273
|
+
When ``format`` is one of ``"wav"`` and ``"flac"``,
|
|
274
|
+
you can change the bit depth.
|
|
275
|
+
Valid values are ``8``, ``16``, ``24``, ``32`` and ``64``.
|
|
276
|
+
|
|
277
|
+
buffer_size (int, optional):
|
|
278
|
+
Size of buffer to use when processing file-like objects, in bytes. (Default: ``4096``)
|
|
279
|
+
|
|
280
|
+
backend (str or None, optional):
|
|
281
|
+
I/O backend to use.
|
|
282
|
+
If ``None``, function selects backend given input and available backends.
|
|
283
|
+
Otherwise, must be one of [``"ffmpeg"``, ``"sox"``, ``"soundfile"``],
|
|
284
|
+
with the corresponding backend being available.
|
|
285
|
+
(Default: ``None``)
|
|
286
|
+
|
|
287
|
+
.. seealso::
|
|
288
|
+
:ref:`backend`
|
|
289
|
+
|
|
290
|
+
compression (CodecConfig, float, int, or None, optional):
|
|
291
|
+
Compression configuration to apply.
|
|
292
|
+
|
|
293
|
+
If the selected backend is FFmpeg, an instance of :py:class:`CodecConfig` must be provided.
|
|
294
|
+
|
|
295
|
+
Otherwise, if the selected backend is SoX, a float or int value corresponding to option ``-C`` of the
|
|
296
|
+
``sox`` command line interface must be provided. For instance:
|
|
297
|
+
|
|
298
|
+
``"mp3"``
|
|
299
|
+
Either bitrate (in ``kbps``) with quality factor, such as ``128.2``, or
|
|
300
|
+
VBR encoding with quality factor such as ``-4.2``. Default: ``-4.5``.
|
|
301
|
+
|
|
302
|
+
``"flac"``
|
|
303
|
+
Whole number from ``0`` to ``8``. ``8`` is default and highest compression.
|
|
304
|
+
|
|
305
|
+
``"ogg"``, ``"vorbis"``
|
|
306
|
+
Number from ``-1`` to ``10``; ``-1`` is the highest compression
|
|
307
|
+
and lowest quality. Default: ``3``.
|
|
308
|
+
|
|
309
|
+
Refer to http://sox.sourceforge.net/soxformat.html for more details.
|
|
310
|
+
|
|
311
|
+
"""
|
|
312
|
+
backend = dispatcher(uri, format, backend)
|
|
313
|
+
return backend.save(
|
|
314
|
+
uri, src, sample_rate, channels_first, format, encoding, bits_per_sample, buffer_size, compression
|
|
315
|
+
)
|
|
316
|
+
|
|
317
|
+
return save
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
import os
|
|
3
|
+
import sys
|
|
4
|
+
|
|
5
|
+
from torchaudio._internal.module_utils import fail_with_message, is_module_available, no_op
|
|
6
|
+
|
|
7
|
+
from .utils import _check_cuda_version, _init_dll_path, _init_sox, _LazyImporter, _load_lib
|
|
8
|
+
|
|
9
|
+
_LG = logging.getLogger(__name__)
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
# Note:
|
|
13
|
+
# `_check_cuda_version` is not meant to be used by regular users.
|
|
14
|
+
# Builder uses it for debugging purpose, so we export it.
|
|
15
|
+
# https://github.com/pytorch/builder/blob/e2e4542b8eb0bdf491214451a1a4128bd606cce2/test/smoke_test/smoke_test.py#L80
|
|
16
|
+
__all__ = [
|
|
17
|
+
"_check_cuda_version",
|
|
18
|
+
"_IS_TORCHAUDIO_EXT_AVAILABLE",
|
|
19
|
+
"_IS_RIR_AVAILABLE",
|
|
20
|
+
"lazy_import_sox_ext",
|
|
21
|
+
]
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
if os.name == "nt" and (3, 8) <= sys.version_info < (3, 9):
|
|
25
|
+
_init_dll_path()
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
# When the extension module is built, we initialize it.
|
|
29
|
+
# In case of an error, we do not catch the failure as it suggests there is something
|
|
30
|
+
# wrong with the installation.
|
|
31
|
+
_IS_TORCHAUDIO_EXT_AVAILABLE = is_module_available("torchaudio.lib._torchaudio")
|
|
32
|
+
# RIR features are implemented in _torchaudio extension, but they can be individually
|
|
33
|
+
# turned on/off at build time. Available means that _torchaudio is loaded properly, and
|
|
34
|
+
# RIR features are found there.
|
|
35
|
+
_IS_RIR_AVAILABLE = False
|
|
36
|
+
_IS_ALIGN_AVAILABLE = False
|
|
37
|
+
if _IS_TORCHAUDIO_EXT_AVAILABLE:
|
|
38
|
+
_load_lib("libtorchaudio")
|
|
39
|
+
|
|
40
|
+
import torchaudio.lib._torchaudio # noqa
|
|
41
|
+
|
|
42
|
+
_check_cuda_version()
|
|
43
|
+
_IS_RIR_AVAILABLE = torchaudio.lib._torchaudio.is_rir_available()
|
|
44
|
+
_IS_ALIGN_AVAILABLE = torchaudio.lib._torchaudio.is_align_available()
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
_SOX_EXT = None
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def lazy_import_sox_ext():
|
|
51
|
+
"""Load SoX integration based on availability in lazy manner"""
|
|
52
|
+
|
|
53
|
+
global _SOX_EXT
|
|
54
|
+
if _SOX_EXT is None:
|
|
55
|
+
_SOX_EXT = _LazyImporter("_torchaudio_sox", _init_sox)
|
|
56
|
+
return _SOX_EXT
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
fail_if_no_rir = (
|
|
60
|
+
no_op
|
|
61
|
+
if _IS_RIR_AVAILABLE
|
|
62
|
+
else fail_with_message(
|
|
63
|
+
"requires RIR extension, but TorchAudio is not compiled with it. Please build TorchAudio with RIR support."
|
|
64
|
+
)
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
fail_if_no_align = (
|
|
68
|
+
no_op
|
|
69
|
+
if _IS_ALIGN_AVAILABLE
|
|
70
|
+
else fail_with_message(
|
|
71
|
+
"Requires alignment extension, but TorchAudio is not compiled with it. \
|
|
72
|
+
Please build TorchAudio with alignment support."
|
|
73
|
+
)
|
|
74
|
+
)
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
"""Module to implement logics used for initializing extensions.
|
|
2
|
+
|
|
3
|
+
The implementations here should be stateless.
|
|
4
|
+
They should not depend on external state.
|
|
5
|
+
Anything that depends on external state should happen in __init__.py
|
|
6
|
+
"""
|
|
7
|
+
import importlib
|
|
8
|
+
import logging
|
|
9
|
+
import os
|
|
10
|
+
import types
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
import torch
|
|
14
|
+
from torchaudio._internal.module_utils import eval_env
|
|
15
|
+
|
|
16
|
+
_LG = logging.getLogger(__name__)
|
|
17
|
+
_LIB_DIR = Path(__file__).parent.parent / "lib"
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _get_lib_path(lib: str):
|
|
21
|
+
suffix = "pyd" if os.name == "nt" else "so"
|
|
22
|
+
path = _LIB_DIR / f"{lib}.{suffix}"
|
|
23
|
+
return path
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _load_lib(lib: str) -> bool:
|
|
27
|
+
"""Load extension module
|
|
28
|
+
|
|
29
|
+
Note:
|
|
30
|
+
In case `torchaudio` is deployed with `pex` format, the library file
|
|
31
|
+
is not in a standard location.
|
|
32
|
+
In this case, we expect that `libtorchaudio` is available somewhere
|
|
33
|
+
in the search path of dynamic loading mechanism, so that importing
|
|
34
|
+
`_torchaudio` will have library loader find and load `libtorchaudio`.
|
|
35
|
+
This is the reason why the function should not raising an error when the library
|
|
36
|
+
file is not found.
|
|
37
|
+
|
|
38
|
+
Returns:
|
|
39
|
+
bool:
|
|
40
|
+
True if the library file is found AND the library loaded without failure.
|
|
41
|
+
False if the library file is not found (like in the case where torchaudio
|
|
42
|
+
is deployed with pex format, thus the shared library file is
|
|
43
|
+
in a non-standard location.).
|
|
44
|
+
If the library file is found but there is an issue loading the library,
|
|
45
|
+
(such as missing dependency) then this function raises the exception as-is.
|
|
46
|
+
|
|
47
|
+
Raises:
|
|
48
|
+
Exception:
|
|
49
|
+
If the library file is found, but there is an issue loading the library file,
|
|
50
|
+
(when underlying `ctype.DLL` throws an exception), this function will pass
|
|
51
|
+
the exception as-is, instead of catching it and returning bool.
|
|
52
|
+
The expected case is `OSError` thrown by `ctype.DLL` when a dynamic dependency
|
|
53
|
+
is not found.
|
|
54
|
+
This behavior was chosen because the expected failure case is not recoverable.
|
|
55
|
+
If a dependency is missing, then users have to install it.
|
|
56
|
+
"""
|
|
57
|
+
path = _get_lib_path(lib)
|
|
58
|
+
if not path.exists():
|
|
59
|
+
return False
|
|
60
|
+
torch.ops.load_library(path)
|
|
61
|
+
return True
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _import_sox_ext():
|
|
65
|
+
if os.name == "nt":
|
|
66
|
+
raise RuntimeError("sox extension is not supported on Windows")
|
|
67
|
+
if not eval_env("TORCHAUDIO_USE_SOX", True):
|
|
68
|
+
raise RuntimeError("sox extension is disabled. (TORCHAUDIO_USE_SOX=0)")
|
|
69
|
+
|
|
70
|
+
ext = "torchaudio.lib._torchaudio_sox"
|
|
71
|
+
|
|
72
|
+
if not importlib.util.find_spec(ext):
|
|
73
|
+
raise RuntimeError(
|
|
74
|
+
# fmt: off
|
|
75
|
+
"TorchAudio is not built with sox extension. "
|
|
76
|
+
"Please build TorchAudio with libsox support. (BUILD_SOX=1)"
|
|
77
|
+
# fmt: on
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
_load_lib("libtorchaudio_sox")
|
|
81
|
+
return importlib.import_module(ext)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _init_sox():
|
|
85
|
+
ext = _import_sox_ext()
|
|
86
|
+
ext.set_verbosity(0)
|
|
87
|
+
|
|
88
|
+
import atexit
|
|
89
|
+
|
|
90
|
+
torch.ops.torchaudio_sox.initialize_sox_effects()
|
|
91
|
+
atexit.register(torch.ops.torchaudio_sox.shutdown_sox_effects)
|
|
92
|
+
|
|
93
|
+
# Bundle functions registered with TORCH_LIBRARY into extension
|
|
94
|
+
# so that they can also be accessed in the same (lazy) manner
|
|
95
|
+
# from the extension.
|
|
96
|
+
keys = [
|
|
97
|
+
"get_info",
|
|
98
|
+
"load_audio_file",
|
|
99
|
+
"save_audio_file",
|
|
100
|
+
"apply_effects_tensor",
|
|
101
|
+
"apply_effects_file",
|
|
102
|
+
]
|
|
103
|
+
for key in keys:
|
|
104
|
+
setattr(ext, key, getattr(torch.ops.torchaudio_sox, key))
|
|
105
|
+
|
|
106
|
+
return ext
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
class _LazyImporter(types.ModuleType):
|
|
110
|
+
"""Lazily import module/extension."""
|
|
111
|
+
|
|
112
|
+
def __init__(self, name, import_func):
|
|
113
|
+
super().__init__(name)
|
|
114
|
+
self.import_func = import_func
|
|
115
|
+
self.module = None
|
|
116
|
+
|
|
117
|
+
# Note:
|
|
118
|
+
# Python caches what was retrieved with `__getattr__`, so this method will not be
|
|
119
|
+
# called again for the same item.
|
|
120
|
+
def __getattr__(self, item):
|
|
121
|
+
self._import_once()
|
|
122
|
+
return getattr(self.module, item)
|
|
123
|
+
|
|
124
|
+
def __repr__(self):
|
|
125
|
+
if self.module is None:
|
|
126
|
+
return f"<module '{self.__module__}.{self.__class__.__name__}(\"{self.name}\")'>"
|
|
127
|
+
return repr(self.module)
|
|
128
|
+
|
|
129
|
+
def __dir__(self):
|
|
130
|
+
self._import_once()
|
|
131
|
+
return dir(self.module)
|
|
132
|
+
|
|
133
|
+
def _import_once(self):
|
|
134
|
+
if self.module is None:
|
|
135
|
+
self.module = self.import_func()
|
|
136
|
+
# Note:
|
|
137
|
+
# By attaching the module attributes to self,
|
|
138
|
+
# module attributes are directly accessible.
|
|
139
|
+
# This allows to avoid calling __getattr__ for every attribute access.
|
|
140
|
+
self.__dict__.update(self.module.__dict__)
|
|
141
|
+
|
|
142
|
+
def is_available(self):
|
|
143
|
+
try:
|
|
144
|
+
self._import_once()
|
|
145
|
+
except Exception:
|
|
146
|
+
return False
|
|
147
|
+
return True
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _init_dll_path():
|
|
151
|
+
# On Windows Python-3.8+ has `os.add_dll_directory` call,
|
|
152
|
+
# which is called to configure dll search path.
|
|
153
|
+
# To find cuda related dlls we need to make sure the
|
|
154
|
+
# conda environment/bin path is configured Please take a look:
|
|
155
|
+
# https://stackoverflow.com/questions/59330863/cant-import-dll-module-in-python
|
|
156
|
+
# Please note: if some path can't be added using add_dll_directory we simply ignore this path
|
|
157
|
+
for path in os.environ.get("PATH", "").split(";"):
|
|
158
|
+
if os.path.exists(path):
|
|
159
|
+
try:
|
|
160
|
+
os.add_dll_directory(path)
|
|
161
|
+
except Exception:
|
|
162
|
+
pass
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _check_cuda_version():
|
|
166
|
+
import torchaudio.lib._torchaudio
|
|
167
|
+
|
|
168
|
+
version = torchaudio.lib._torchaudio.cuda_version()
|
|
169
|
+
if version is not None and torch.version.cuda is not None:
|
|
170
|
+
version_str = str(version)
|
|
171
|
+
ta_version = f"{version_str[:-3]}.{version_str[-2]}"
|
|
172
|
+
t_version = torch.version.cuda.split(".")
|
|
173
|
+
t_version = f"{t_version[0]}.{t_version[1]}"
|
|
174
|
+
if ta_version != t_version:
|
|
175
|
+
raise RuntimeError(
|
|
176
|
+
"Detected that PyTorch and TorchAudio were compiled with different CUDA versions. "
|
|
177
|
+
f"PyTorch has CUDA version {t_version} whereas TorchAudio has CUDA version {ta_version}. "
|
|
178
|
+
"Please install the TorchAudio version that matches your PyTorch version."
|
|
179
|
+
)
|
|
180
|
+
return version
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import importlib.util
|
|
2
|
+
import os
|
|
3
|
+
import warnings
|
|
4
|
+
from functools import wraps
|
|
5
|
+
from typing import Optional
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def eval_env(var, default):
|
|
9
|
+
"""Check if environment varable has True-y value"""
|
|
10
|
+
if var not in os.environ:
|
|
11
|
+
return default
|
|
12
|
+
|
|
13
|
+
val = os.environ.get(var, "0")
|
|
14
|
+
trues = ["1", "true", "TRUE", "on", "ON", "yes", "YES"]
|
|
15
|
+
falses = ["0", "false", "FALSE", "off", "OFF", "no", "NO"]
|
|
16
|
+
if val in trues:
|
|
17
|
+
return True
|
|
18
|
+
if val not in falses:
|
|
19
|
+
# fmt: off
|
|
20
|
+
raise RuntimeError(
|
|
21
|
+
f"Unexpected environment variable value `{var}={val}`. "
|
|
22
|
+
f"Expected one of {trues + falses}")
|
|
23
|
+
# fmt: on
|
|
24
|
+
return False
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def is_module_available(*modules: str) -> bool:
|
|
28
|
+
r"""Returns if a top-level module with :attr:`name` exists *without**
|
|
29
|
+
importing it. This is generally safer than try-catch block around a
|
|
30
|
+
`import X`. It avoids third party libraries breaking assumptions of some of
|
|
31
|
+
our tests, e.g., setting multiprocessing start method when imported
|
|
32
|
+
(see librosa/#747, torchvision/#544).
|
|
33
|
+
"""
|
|
34
|
+
return all(importlib.util.find_spec(m) is not None for m in modules)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def requires_module(*modules: str):
|
|
38
|
+
"""Decorate function to give error message if invoked without required optional modules.
|
|
39
|
+
|
|
40
|
+
This decorator is to give better error message to users rather
|
|
41
|
+
than raising ``NameError: name 'module' is not defined`` at random places.
|
|
42
|
+
"""
|
|
43
|
+
missing = [m for m in modules if not is_module_available(m)]
|
|
44
|
+
|
|
45
|
+
if not missing:
|
|
46
|
+
# fall through. If all the modules are available, no need to decorate
|
|
47
|
+
def decorator(func):
|
|
48
|
+
return func
|
|
49
|
+
|
|
50
|
+
else:
|
|
51
|
+
req = f"module: {missing[0]}" if len(missing) == 1 else f"modules: {missing}"
|
|
52
|
+
|
|
53
|
+
def decorator(func):
|
|
54
|
+
@wraps(func)
|
|
55
|
+
def wrapped(*args, **kwargs):
|
|
56
|
+
raise RuntimeError(f"{func.__module__}.{func.__name__} requires {req}")
|
|
57
|
+
|
|
58
|
+
return wrapped
|
|
59
|
+
|
|
60
|
+
return decorator
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def deprecated(direction: str, version: Optional[str] = None, remove: bool = False):
|
|
64
|
+
"""Decorator to add deprecation message
|
|
65
|
+
|
|
66
|
+
Args:
|
|
67
|
+
direction (str): Migration steps to be given to users.
|
|
68
|
+
version (str or int): The version when the object will be removed
|
|
69
|
+
remove (bool): If enabled, append future removal message.
|
|
70
|
+
"""
|
|
71
|
+
|
|
72
|
+
def decorator(func):
|
|
73
|
+
@wraps(func)
|
|
74
|
+
def wrapped(*args, **kwargs):
|
|
75
|
+
message = f"{func.__module__}.{func.__name__} has been deprecated. {direction}"
|
|
76
|
+
if remove:
|
|
77
|
+
message += f' It will be removed from {"future" if version is None else version} release. '
|
|
78
|
+
warnings.warn(message, stacklevel=2)
|
|
79
|
+
return func(*args, **kwargs)
|
|
80
|
+
|
|
81
|
+
message = "This function has been deprecated. "
|
|
82
|
+
if remove:
|
|
83
|
+
message += f'It will be removed from {"future" if version is None else version} release. '
|
|
84
|
+
|
|
85
|
+
wrapped.__doc__ = f"""DEPRECATED: {func.__doc__}
|
|
86
|
+
|
|
87
|
+
.. warning::
|
|
88
|
+
|
|
89
|
+
{message}
|
|
90
|
+
{direction}
|
|
91
|
+
"""
|
|
92
|
+
|
|
93
|
+
return wrapped
|
|
94
|
+
|
|
95
|
+
return decorator
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def fail_with_message(message):
|
|
99
|
+
"""Generate decorator to give users message about missing TorchAudio extension."""
|
|
100
|
+
|
|
101
|
+
def decorator(func):
|
|
102
|
+
@wraps(func)
|
|
103
|
+
def wrapped(*args, **kwargs):
|
|
104
|
+
raise RuntimeError(f"{func.__module__}.{func.__name__} {message}")
|
|
105
|
+
|
|
106
|
+
return wrapped
|
|
107
|
+
|
|
108
|
+
return decorator
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def no_op(func):
|
|
112
|
+
"""Op-op decorator. Used in place of fail_with_message when a functionality that requires extension works fine."""
|
|
113
|
+
return func
|