torchaudio 2.9.0__cp314-cp314-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.

Potentially problematic release.


This version of torchaudio might be problematic. Click here for more details.

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.0.dist-info/LICENSE +25 -0
  83. torchaudio-2.9.0.dist-info/METADATA +122 -0
  84. torchaudio-2.9.0.dist-info/RECORD +86 -0
  85. torchaudio-2.9.0.dist-info/WHEEL +5 -0
  86. torchaudio-2.9.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,380 @@
1
+ import json
2
+ import math
3
+ from abc import ABC, abstractmethod
4
+ from dataclasses import dataclass
5
+ from functools import partial
6
+ from typing import Callable, List, Tuple
7
+
8
+ import torch
9
+ import torchaudio
10
+ from torchaudio._internal import module_utils
11
+ from torchaudio.models import emformer_rnnt_base, RNNT, RNNTBeamSearch
12
+
13
+
14
+ __all__ = []
15
+
16
+ _decibel = 2 * 20 * math.log10(torch.iinfo(torch.int16).max)
17
+ _gain = pow(10, 0.05 * _decibel)
18
+
19
+
20
+ def _piecewise_linear_log(x):
21
+ x[x > math.e] = torch.log(x[x > math.e])
22
+ x[x <= math.e] = x[x <= math.e] / math.e
23
+ return x
24
+
25
+
26
+ class _FunctionalModule(torch.nn.Module):
27
+ def __init__(self, functional):
28
+ super().__init__()
29
+ self.functional = functional
30
+
31
+ def forward(self, input):
32
+ return self.functional(input)
33
+
34
+
35
+ class _GlobalStatsNormalization(torch.nn.Module):
36
+ def __init__(self, global_stats_path):
37
+ super().__init__()
38
+
39
+ with open(global_stats_path) as f:
40
+ blob = json.loads(f.read())
41
+
42
+ self.register_buffer("mean", torch.tensor(blob["mean"]))
43
+ self.register_buffer("invstddev", torch.tensor(blob["invstddev"]))
44
+
45
+ def forward(self, input):
46
+ return (input - self.mean) * self.invstddev
47
+
48
+
49
+ class _FeatureExtractor(ABC):
50
+ @abstractmethod
51
+ def __call__(self, input: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
52
+ """Generates features and length output from the given input tensor.
53
+
54
+ Args:
55
+ input (torch.Tensor): input tensor.
56
+
57
+ Returns:
58
+ (torch.Tensor, torch.Tensor):
59
+ torch.Tensor:
60
+ Features, with shape `(length, *)`.
61
+ torch.Tensor:
62
+ Length, with shape `(1,)`.
63
+ """
64
+
65
+
66
+ class _TokenProcessor(ABC):
67
+ @abstractmethod
68
+ def __call__(self, tokens: List[int], **kwargs) -> str:
69
+ """Decodes given list of tokens to text sequence.
70
+
71
+ Args:
72
+ tokens (List[int]): list of tokens to decode.
73
+
74
+ Returns:
75
+ str:
76
+ Decoded text sequence.
77
+ """
78
+
79
+
80
+ class _ModuleFeatureExtractor(torch.nn.Module, _FeatureExtractor):
81
+ """``torch.nn.Module``-based feature extraction pipeline.
82
+
83
+ Args:
84
+ pipeline (torch.nn.Module): module that implements feature extraction logic.
85
+ """
86
+
87
+ def __init__(self, pipeline: torch.nn.Module) -> None:
88
+ super().__init__()
89
+ self.pipeline = pipeline
90
+
91
+ def forward(self, input: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
92
+ """Generates features and length output from the given input tensor.
93
+
94
+ Args:
95
+ input (torch.Tensor): input tensor.
96
+
97
+ Returns:
98
+ (torch.Tensor, torch.Tensor):
99
+ torch.Tensor:
100
+ Features, with shape `(length, *)`.
101
+ torch.Tensor:
102
+ Length, with shape `(1,)`.
103
+ """
104
+ features = self.pipeline(input)
105
+ length = torch.tensor([features.shape[0]])
106
+ return features, length
107
+
108
+
109
+ class _SentencePieceTokenProcessor(_TokenProcessor):
110
+ """SentencePiece-model-based token processor.
111
+
112
+ Args:
113
+ sp_model_path (str): path to SentencePiece model.
114
+ """
115
+
116
+ def __init__(self, sp_model_path: str) -> None:
117
+ if not module_utils.is_module_available("sentencepiece"):
118
+ raise RuntimeError("SentencePiece is not available. Please install it.")
119
+
120
+ import sentencepiece as spm
121
+
122
+ self.sp_model = spm.SentencePieceProcessor(model_file=sp_model_path)
123
+ self.post_process_remove_list = {
124
+ self.sp_model.unk_id(),
125
+ self.sp_model.eos_id(),
126
+ self.sp_model.pad_id(),
127
+ }
128
+
129
+ def __call__(self, tokens: List[int], lstrip: bool = True) -> str:
130
+ """Decodes given list of tokens to text sequence.
131
+
132
+ Args:
133
+ tokens (List[int]): list of tokens to decode.
134
+ lstrip (bool, optional): if ``True``, returns text sequence with leading whitespace
135
+ removed. (Default: ``True``).
136
+
137
+ Returns:
138
+ str:
139
+ Decoded text sequence.
140
+ """
141
+ filtered_hypo_tokens = [
142
+ token_index for token_index in tokens[1:] if token_index not in self.post_process_remove_list
143
+ ]
144
+ output_string = "".join(self.sp_model.id_to_piece(filtered_hypo_tokens)).replace("\u2581", " ")
145
+
146
+ if lstrip:
147
+ return output_string.lstrip()
148
+ else:
149
+ return output_string
150
+
151
+
152
+ @dataclass
153
+ class RNNTBundle:
154
+ """Dataclass that bundles components for performing automatic speech recognition (ASR, speech-to-text)
155
+ inference with an RNN-T model.
156
+
157
+ More specifically, the class provides methods that produce the featurization pipeline,
158
+ decoder wrapping the specified RNN-T model, and output token post-processor that together
159
+ constitute a complete end-to-end ASR inference pipeline that produces a text sequence
160
+ given a raw waveform.
161
+
162
+ It can support non-streaming (full-context) inference as well as streaming inference.
163
+
164
+ Users should not directly instantiate objects of this class; rather, users should use the
165
+ instances (representing pre-trained models) that exist within the module,
166
+ e.g. :data:`torchaudio.pipelines.EMFORMER_RNNT_BASE_LIBRISPEECH`.
167
+
168
+ Example
169
+ >>> import torchaudio
170
+ >>> from torchaudio.pipelines import EMFORMER_RNNT_BASE_LIBRISPEECH
171
+ >>> import torch
172
+ >>>
173
+ >>> # Non-streaming inference.
174
+ >>> # Build feature extractor, decoder with RNN-T model, and token processor.
175
+ >>> feature_extractor = EMFORMER_RNNT_BASE_LIBRISPEECH.get_feature_extractor()
176
+ 100%|███████████████████████████████| 3.81k/3.81k [00:00<00:00, 4.22MB/s]
177
+ >>> decoder = EMFORMER_RNNT_BASE_LIBRISPEECH.get_decoder()
178
+ Downloading: "https://download.pytorch.org/torchaudio/models/emformer_rnnt_base_librispeech.pt"
179
+ 100%|███████████████████████████████| 293M/293M [00:07<00:00, 42.1MB/s]
180
+ >>> token_processor = EMFORMER_RNNT_BASE_LIBRISPEECH.get_token_processor()
181
+ 100%|███████████████████████████████| 295k/295k [00:00<00:00, 25.4MB/s]
182
+ >>>
183
+ >>> # Instantiate LibriSpeech dataset; retrieve waveform for first sample.
184
+ >>> dataset = torchaudio.datasets.LIBRISPEECH("/home/librispeech", url="test-clean")
185
+ >>> waveform = next(iter(dataset))[0].squeeze()
186
+ >>>
187
+ >>> with torch.no_grad():
188
+ >>> # Produce mel-scale spectrogram features.
189
+ >>> features, length = feature_extractor(waveform)
190
+ >>>
191
+ >>> # Generate top-10 hypotheses.
192
+ >>> hypotheses = decoder(features, length, 10)
193
+ >>>
194
+ >>> # For top hypothesis, convert predicted tokens to text.
195
+ >>> text = token_processor(hypotheses[0][0])
196
+ >>> print(text)
197
+ he hoped there would be stew for dinner turnips and carrots and bruised potatoes and fat mutton pieces to [...]
198
+ >>>
199
+ >>>
200
+ >>> # Streaming inference.
201
+ >>> hop_length = EMFORMER_RNNT_BASE_LIBRISPEECH.hop_length
202
+ >>> num_samples_segment = EMFORMER_RNNT_BASE_LIBRISPEECH.segment_length * hop_length
203
+ >>> num_samples_segment_right_context = (
204
+ >>> num_samples_segment + EMFORMER_RNNT_BASE_LIBRISPEECH.right_context_length * hop_length
205
+ >>> )
206
+ >>>
207
+ >>> # Build streaming inference feature extractor.
208
+ >>> streaming_feature_extractor = EMFORMER_RNNT_BASE_LIBRISPEECH.get_streaming_feature_extractor()
209
+ >>>
210
+ >>> # Process same waveform as before, this time sequentially across overlapping segments
211
+ >>> # to simulate streaming inference. Note the usage of ``streaming_feature_extractor`` and ``decoder.infer``.
212
+ >>> state, hypothesis = None, None
213
+ >>> for idx in range(0, len(waveform), num_samples_segment):
214
+ >>> segment = waveform[idx: idx + num_samples_segment_right_context]
215
+ >>> segment = torch.nn.functional.pad(segment, (0, num_samples_segment_right_context - len(segment)))
216
+ >>> with torch.no_grad():
217
+ >>> features, length = streaming_feature_extractor(segment)
218
+ >>> hypotheses, state = decoder.infer(features, length, 10, state=state, hypothesis=hypothesis)
219
+ >>> hypothesis = hypotheses[0]
220
+ >>> transcript = token_processor(hypothesis[0])
221
+ >>> if transcript:
222
+ >>> print(transcript, end=" ", flush=True)
223
+ he hoped there would be stew for dinner turn ips and car rots and bru 'd oes and fat mut ton pieces to [...]
224
+ """
225
+
226
+ class FeatureExtractor(_FeatureExtractor):
227
+ """Interface of the feature extraction part of RNN-T pipeline"""
228
+
229
+ class TokenProcessor(_TokenProcessor):
230
+ """Interface of the token processor part of RNN-T pipeline"""
231
+
232
+ _rnnt_path: str
233
+ _rnnt_factory_func: Callable[[], RNNT]
234
+ _global_stats_path: str
235
+ _sp_model_path: str
236
+ _right_padding: int
237
+ _blank: int
238
+ _sample_rate: int
239
+ _n_fft: int
240
+ _n_mels: int
241
+ _hop_length: int
242
+ _segment_length: int
243
+ _right_context_length: int
244
+
245
+ def _get_model(self) -> RNNT:
246
+ model = self._rnnt_factory_func()
247
+ path = torchaudio.utils._download_asset(self._rnnt_path)
248
+ state_dict = torch.load(path)
249
+ model.load_state_dict(state_dict)
250
+ model.eval()
251
+ return model
252
+
253
+ @property
254
+ def sample_rate(self) -> int:
255
+ """Sample rate (in cycles per second) of input waveforms.
256
+
257
+ :type: int
258
+ """
259
+ return self._sample_rate
260
+
261
+ @property
262
+ def n_fft(self) -> int:
263
+ """Size of FFT window to use.
264
+
265
+ :type: int
266
+ """
267
+ return self._n_fft
268
+
269
+ @property
270
+ def n_mels(self) -> int:
271
+ """Number of mel spectrogram features to extract from input waveforms.
272
+
273
+ :type: int
274
+ """
275
+ return self._n_mels
276
+
277
+ @property
278
+ def hop_length(self) -> int:
279
+ """Number of samples between successive frames in input expected by model.
280
+
281
+ :type: int
282
+ """
283
+ return self._hop_length
284
+
285
+ @property
286
+ def segment_length(self) -> int:
287
+ """Number of frames in segment in input expected by model.
288
+
289
+ :type: int
290
+ """
291
+ return self._segment_length
292
+
293
+ @property
294
+ def right_context_length(self) -> int:
295
+ """Number of frames in right contextual block in input expected by model.
296
+
297
+ :type: int
298
+ """
299
+ return self._right_context_length
300
+
301
+ def get_decoder(self) -> RNNTBeamSearch:
302
+ """Constructs RNN-T decoder.
303
+
304
+ Returns:
305
+ RNNTBeamSearch
306
+ """
307
+ model = self._get_model()
308
+ return RNNTBeamSearch(model, self._blank)
309
+
310
+ def get_feature_extractor(self) -> FeatureExtractor:
311
+ """Constructs feature extractor for non-streaming (full-context) ASR.
312
+
313
+ Returns:
314
+ FeatureExtractor
315
+ """
316
+ local_path = torchaudio.utils._download_asset(self._global_stats_path)
317
+ return _ModuleFeatureExtractor(
318
+ torch.nn.Sequential(
319
+ torchaudio.transforms.MelSpectrogram(
320
+ sample_rate=self.sample_rate, n_fft=self.n_fft, n_mels=self.n_mels, hop_length=self.hop_length
321
+ ),
322
+ _FunctionalModule(lambda x: x.transpose(1, 0)),
323
+ _FunctionalModule(lambda x: _piecewise_linear_log(x * _gain)),
324
+ _GlobalStatsNormalization(local_path),
325
+ _FunctionalModule(lambda x: torch.nn.functional.pad(x, (0, 0, 0, self._right_padding))),
326
+ )
327
+ )
328
+
329
+ def get_streaming_feature_extractor(self) -> FeatureExtractor:
330
+ """Constructs feature extractor for streaming (simultaneous) ASR.
331
+
332
+ Returns:
333
+ FeatureExtractor
334
+ """
335
+ local_path = torchaudio.utils._download_asset(self._global_stats_path)
336
+ return _ModuleFeatureExtractor(
337
+ torch.nn.Sequential(
338
+ torchaudio.transforms.MelSpectrogram(
339
+ sample_rate=self.sample_rate, n_fft=self.n_fft, n_mels=self.n_mels, hop_length=self.hop_length
340
+ ),
341
+ _FunctionalModule(lambda x: x.transpose(1, 0)),
342
+ _FunctionalModule(lambda x: _piecewise_linear_log(x * _gain)),
343
+ _GlobalStatsNormalization(local_path),
344
+ )
345
+ )
346
+
347
+ def get_token_processor(self) -> TokenProcessor:
348
+ """Constructs token processor.
349
+
350
+ Returns:
351
+ TokenProcessor
352
+ """
353
+ local_path = torchaudio.utils._download_asset(self._sp_model_path)
354
+ return _SentencePieceTokenProcessor(local_path)
355
+
356
+
357
+ EMFORMER_RNNT_BASE_LIBRISPEECH = RNNTBundle(
358
+ _rnnt_path="models/emformer_rnnt_base_librispeech.pt",
359
+ _rnnt_factory_func=partial(emformer_rnnt_base, num_symbols=4097),
360
+ _global_stats_path="pipeline-assets/global_stats_rnnt_librispeech.json",
361
+ _sp_model_path="pipeline-assets/spm_bpe_4096_librispeech.model",
362
+ _right_padding=4,
363
+ _blank=4096,
364
+ _sample_rate=16000,
365
+ _n_fft=400,
366
+ _n_mels=80,
367
+ _hop_length=160,
368
+ _segment_length=16,
369
+ _right_context_length=4,
370
+ )
371
+ EMFORMER_RNNT_BASE_LIBRISPEECH.__doc__ = """ASR pipeline based on Emformer-RNNT,
372
+ pretrained on *LibriSpeech* dataset :cite:`7178964`,
373
+ capable of performing both streaming and non-streaming inference.
374
+
375
+ The underlying model is constructed by :py:func:`torchaudio.models.emformer_rnnt_base`
376
+ and utilizes weights trained on LibriSpeech using training script ``train.py``
377
+ `here <https://github.com/pytorch/audio/tree/main/examples/asr/emformer_rnnt>`__ with default arguments.
378
+
379
+ Please refer to :py:class:`RNNTBundle` for usage instructions.
380
+ """
@@ -0,0 +1,78 @@
1
+ from torchaudio._internal.module_utils import dropping_class_support
2
+
3
+ from ._multi_channel import MVDR, PSD, RTFMVDR, SoudenMVDR
4
+ from ._transforms import (
5
+ AddNoise,
6
+ AmplitudeToDB,
7
+ ComputeDeltas,
8
+ Convolve,
9
+ Deemphasis,
10
+ Fade,
11
+ FFTConvolve,
12
+ FrequencyMasking,
13
+ GriffinLim,
14
+ InverseMelScale,
15
+ InverseSpectrogram,
16
+ LFCC,
17
+ Loudness,
18
+ MelScale,
19
+ MelSpectrogram,
20
+ MFCC,
21
+ MuLawDecoding,
22
+ MuLawEncoding,
23
+ PitchShift,
24
+ Preemphasis,
25
+ Resample,
26
+ RNNTLoss as _RNNTLoss,
27
+ SlidingWindowCmn,
28
+ SpecAugment,
29
+ SpectralCentroid,
30
+ Spectrogram,
31
+ Speed,
32
+ SpeedPerturbation,
33
+ TimeMasking,
34
+ TimeStretch,
35
+ Vad,
36
+ Vol,
37
+ )
38
+
39
+ RNNTLoss = dropping_class_support(_RNNTLoss)
40
+
41
+ __all__ = [
42
+ "AddNoise",
43
+ "AmplitudeToDB",
44
+ "ComputeDeltas",
45
+ "Convolve",
46
+ "Deemphasis",
47
+ "Fade",
48
+ "FFTConvolve",
49
+ "FrequencyMasking",
50
+ "GriffinLim",
51
+ "InverseMelScale",
52
+ "InverseSpectrogram",
53
+ "LFCC",
54
+ "Loudness",
55
+ "MFCC",
56
+ "MVDR",
57
+ "MelScale",
58
+ "MelSpectrogram",
59
+ "MuLawDecoding",
60
+ "MuLawEncoding",
61
+ "PSD",
62
+ "PitchShift",
63
+ "Preemphasis",
64
+ "RNNTLoss",
65
+ "RTFMVDR",
66
+ "Resample",
67
+ "SlidingWindowCmn",
68
+ "SoudenMVDR",
69
+ "SpecAugment",
70
+ "SpectralCentroid",
71
+ "Spectrogram",
72
+ "Speed",
73
+ "SpeedPerturbation",
74
+ "TimeMasking",
75
+ "TimeStretch",
76
+ "Vad",
77
+ "Vol",
78
+ ]