Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/__pycache__/__init__.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/__pycache__/kaldi_io.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/__pycache__/version.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/_backend/__init__.py +61 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/_backend/__pycache__/__init__.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/_backend/__pycache__/backend.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/_backend/__pycache__/common.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/_backend/__pycache__/ffmpeg.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/_backend/__pycache__/soundfile.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/_backend/__pycache__/soundfile_backend.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/_backend/__pycache__/sox.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/_backend/__pycache__/utils.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/_backend/backend.py +53 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/_backend/common.py +52 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/_backend/ffmpeg.py +334 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/_backend/soundfile.py +54 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/_backend/soundfile_backend.py +457 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/_backend/sox.py +91 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/_backend/utils.py +317 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/_extension/__init__.py +74 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/_extension/__pycache__/__init__.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/_extension/__pycache__/utils.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/_extension/utils.py +180 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/_internal/__init__.py +10 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/_internal/__pycache__/__init__.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/_internal/__pycache__/module_utils.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/_internal/module_utils.py +113 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/backend/__init__.py +8 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/backend/_no_backend.py +25 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/backend/_sox_io_backend.py +294 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/backend/common.py +13 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/backend/no_backend.py +14 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/backend/soundfile_backend.py +14 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/backend/sox_io_backend.py +14 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/compliance/__init__.py +5 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/compliance/kaldi.py +813 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/datasets/__init__.py +47 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/datasets/cmuarctic.py +157 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/datasets/cmudict.py +186 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/datasets/commonvoice.py +86 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/datasets/dr_vctk.py +121 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/datasets/fluentcommands.py +108 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/datasets/gtzan.py +1118 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/datasets/iemocap.py +147 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/datasets/librilight_limited.py +111 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/datasets/librimix.py +133 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/datasets/librispeech.py +174 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/datasets/librispeech_biasing.py +189 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/datasets/libritts.py +168 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/datasets/ljspeech.py +107 -0
micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (1.19 kB). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/__pycache__/kaldi_io.cpython-311.pyc
ADDED
|
Binary file (5.86 kB). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/__pycache__/version.cpython-311.pyc
ADDED
|
Binary file (293 Bytes). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/_backend/__init__.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import List, Optional
|
| 2 |
+
|
| 3 |
+
from torchaudio._internal.module_utils import deprecated
|
| 4 |
+
|
| 5 |
+
from . import utils
|
| 6 |
+
from .common import AudioMetaData
|
| 7 |
+
|
| 8 |
+
__all__ = [
|
| 9 |
+
"AudioMetaData",
|
| 10 |
+
"load",
|
| 11 |
+
"info",
|
| 12 |
+
"save",
|
| 13 |
+
"list_audio_backends",
|
| 14 |
+
"get_audio_backend",
|
| 15 |
+
"set_audio_backend",
|
| 16 |
+
]
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
info = utils.get_info_func()
|
| 20 |
+
load = utils.get_load_func()
|
| 21 |
+
save = utils.get_save_func()
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def list_audio_backends() -> List[str]:
|
| 25 |
+
"""List available backends
|
| 26 |
+
|
| 27 |
+
Returns:
|
| 28 |
+
list of str: The list of available backends.
|
| 29 |
+
|
| 30 |
+
The possible values are; ``"ffmpeg"``, ``"sox"`` and ``"soundfile"``.
|
| 31 |
+
"""
|
| 32 |
+
|
| 33 |
+
return list(utils.get_available_backends().keys())
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
# Temporary until global backend is removed
|
| 37 |
+
@deprecated("With dispatcher enabled, this function is no-op. You can remove the function call.")
|
| 38 |
+
def get_audio_backend() -> Optional[str]:
|
| 39 |
+
"""Get the name of the current global backend
|
| 40 |
+
|
| 41 |
+
Returns:
|
| 42 |
+
str or None:
|
| 43 |
+
If dispatcher mode is enabled, returns ``None`` otherwise,
|
| 44 |
+
the name of current backend or ``None`` (no backend is set).
|
| 45 |
+
"""
|
| 46 |
+
return None
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
# Temporary until global backend is removed
|
| 50 |
+
@deprecated("With dispatcher enabled, this function is no-op. You can remove the function call.")
|
| 51 |
+
def set_audio_backend(backend: Optional[str]): # noqa
|
| 52 |
+
"""Set the global backend.
|
| 53 |
+
|
| 54 |
+
This is a no-op when dispatcher mode is enabled.
|
| 55 |
+
|
| 56 |
+
Args:
|
| 57 |
+
backend (str or None): Name of the backend.
|
| 58 |
+
One of ``"sox_io"`` or ``"soundfile"`` based on availability
|
| 59 |
+
of the system. If ``None`` is provided the current backend is unassigned.
|
| 60 |
+
"""
|
| 61 |
+
pass
|
micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/_backend/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (2.35 kB). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/_backend/__pycache__/backend.cpython-311.pyc
ADDED
|
Binary file (3.1 kB). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/_backend/__pycache__/common.cpython-311.pyc
ADDED
|
Binary file (2.37 kB). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/_backend/__pycache__/ffmpeg.cpython-311.pyc
ADDED
|
Binary file (14 kB). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/_backend/__pycache__/soundfile.cpython-311.pyc
ADDED
|
Binary file (3.24 kB). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/_backend/__pycache__/soundfile_backend.cpython-311.pyc
ADDED
|
Binary file (17.7 kB). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/_backend/__pycache__/sox.cpython-311.pyc
ADDED
|
Binary file (5 kB). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/_backend/__pycache__/utils.cpython-311.pyc
ADDED
|
Binary file (16.5 kB). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/_backend/backend.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from abc import ABC, abstractmethod
|
| 3 |
+
from typing import BinaryIO, Optional, Tuple, Union
|
| 4 |
+
|
| 5 |
+
from torch import Tensor
|
| 6 |
+
from torchaudio.io import CodecConfig
|
| 7 |
+
|
| 8 |
+
from .common import AudioMetaData
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class Backend(ABC):
|
| 12 |
+
@staticmethod
|
| 13 |
+
@abstractmethod
|
| 14 |
+
def info(uri: Union[BinaryIO, str, os.PathLike], format: Optional[str], buffer_size: int = 4096) -> AudioMetaData:
|
| 15 |
+
raise NotImplementedError
|
| 16 |
+
|
| 17 |
+
@staticmethod
|
| 18 |
+
@abstractmethod
|
| 19 |
+
def load(
|
| 20 |
+
uri: Union[BinaryIO, str, os.PathLike],
|
| 21 |
+
frame_offset: int = 0,
|
| 22 |
+
num_frames: int = -1,
|
| 23 |
+
normalize: bool = True,
|
| 24 |
+
channels_first: bool = True,
|
| 25 |
+
format: Optional[str] = None,
|
| 26 |
+
buffer_size: int = 4096,
|
| 27 |
+
) -> Tuple[Tensor, int]:
|
| 28 |
+
raise NotImplementedError
|
| 29 |
+
|
| 30 |
+
@staticmethod
|
| 31 |
+
@abstractmethod
|
| 32 |
+
def save(
|
| 33 |
+
uri: Union[BinaryIO, str, os.PathLike],
|
| 34 |
+
src: Tensor,
|
| 35 |
+
sample_rate: int,
|
| 36 |
+
channels_first: bool = True,
|
| 37 |
+
format: Optional[str] = None,
|
| 38 |
+
encoding: Optional[str] = None,
|
| 39 |
+
bits_per_sample: Optional[int] = None,
|
| 40 |
+
buffer_size: int = 4096,
|
| 41 |
+
compression: Optional[Union[CodecConfig, float, int]] = None,
|
| 42 |
+
) -> None:
|
| 43 |
+
raise NotImplementedError
|
| 44 |
+
|
| 45 |
+
@staticmethod
|
| 46 |
+
@abstractmethod
|
| 47 |
+
def can_decode(uri: Union[BinaryIO, str, os.PathLike], format: Optional[str]) -> bool:
|
| 48 |
+
raise NotImplementedError
|
| 49 |
+
|
| 50 |
+
@staticmethod
|
| 51 |
+
@abstractmethod
|
| 52 |
+
def can_encode(uri: Union[BinaryIO, str, os.PathLike], format: Optional[str]) -> bool:
|
| 53 |
+
raise NotImplementedError
|
micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/_backend/common.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
class AudioMetaData:
|
| 2 |
+
"""AudioMetaData()
|
| 3 |
+
|
| 4 |
+
Return type of ``torchaudio.info`` function.
|
| 5 |
+
|
| 6 |
+
:ivar int sample_rate: Sample rate
|
| 7 |
+
:ivar int num_frames: The number of frames
|
| 8 |
+
:ivar int num_channels: The number of channels
|
| 9 |
+
:ivar int bits_per_sample: The number of bits per sample. This is 0 for lossy formats,
|
| 10 |
+
or when it cannot be accurately inferred.
|
| 11 |
+
:ivar str encoding: Audio encoding
|
| 12 |
+
The values encoding can take are one of the following:
|
| 13 |
+
|
| 14 |
+
* ``PCM_S``: Signed integer linear PCM
|
| 15 |
+
* ``PCM_U``: Unsigned integer linear PCM
|
| 16 |
+
* ``PCM_F``: Floating point linear PCM
|
| 17 |
+
* ``FLAC``: Flac, Free Lossless Audio Codec
|
| 18 |
+
* ``ULAW``: Mu-law
|
| 19 |
+
* ``ALAW``: A-law
|
| 20 |
+
* ``MP3`` : MP3, MPEG-1 Audio Layer III
|
| 21 |
+
* ``VORBIS``: OGG Vorbis
|
| 22 |
+
* ``AMR_WB``: Adaptive Multi-Rate Wideband
|
| 23 |
+
* ``AMR_NB``: Adaptive Multi-Rate Narrowband
|
| 24 |
+
* ``OPUS``: Opus
|
| 25 |
+
* ``HTK``: Single channel 16-bit PCM
|
| 26 |
+
* ``UNKNOWN`` : None of above
|
| 27 |
+
"""
|
| 28 |
+
|
| 29 |
+
def __init__(
|
| 30 |
+
self,
|
| 31 |
+
sample_rate: int,
|
| 32 |
+
num_frames: int,
|
| 33 |
+
num_channels: int,
|
| 34 |
+
bits_per_sample: int,
|
| 35 |
+
encoding: str,
|
| 36 |
+
):
|
| 37 |
+
self.sample_rate = sample_rate
|
| 38 |
+
self.num_frames = num_frames
|
| 39 |
+
self.num_channels = num_channels
|
| 40 |
+
self.bits_per_sample = bits_per_sample
|
| 41 |
+
self.encoding = encoding
|
| 42 |
+
|
| 43 |
+
def __str__(self):
|
| 44 |
+
return (
|
| 45 |
+
f"AudioMetaData("
|
| 46 |
+
f"sample_rate={self.sample_rate}, "
|
| 47 |
+
f"num_frames={self.num_frames}, "
|
| 48 |
+
f"num_channels={self.num_channels}, "
|
| 49 |
+
f"bits_per_sample={self.bits_per_sample}, "
|
| 50 |
+
f"encoding={self.encoding}"
|
| 51 |
+
f")"
|
| 52 |
+
)
|
micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/_backend/ffmpeg.py
ADDED
|
@@ -0,0 +1,334 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import re
|
| 3 |
+
import sys
|
| 4 |
+
from typing import BinaryIO, Optional, Tuple, Union
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
import torchaudio
|
| 8 |
+
|
| 9 |
+
from .backend import Backend
|
| 10 |
+
from .common import AudioMetaData
|
| 11 |
+
|
| 12 |
+
InputType = Union[BinaryIO, str, os.PathLike]
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def info_audio(
|
| 16 |
+
src: InputType,
|
| 17 |
+
format: Optional[str],
|
| 18 |
+
buffer_size: int = 4096,
|
| 19 |
+
) -> AudioMetaData:
|
| 20 |
+
s = torchaudio.io.StreamReader(src, format, None, buffer_size)
|
| 21 |
+
sinfo = s.get_src_stream_info(s.default_audio_stream)
|
| 22 |
+
if sinfo.num_frames == 0:
|
| 23 |
+
waveform = _load_audio(s)
|
| 24 |
+
num_frames = waveform.size(1)
|
| 25 |
+
else:
|
| 26 |
+
num_frames = sinfo.num_frames
|
| 27 |
+
return AudioMetaData(
|
| 28 |
+
int(sinfo.sample_rate),
|
| 29 |
+
num_frames,
|
| 30 |
+
sinfo.num_channels,
|
| 31 |
+
sinfo.bits_per_sample,
|
| 32 |
+
sinfo.codec.upper(),
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def _get_load_filter(
|
| 37 |
+
frame_offset: int = 0,
|
| 38 |
+
num_frames: int = -1,
|
| 39 |
+
convert: bool = True,
|
| 40 |
+
) -> Optional[str]:
|
| 41 |
+
if frame_offset < 0:
|
| 42 |
+
raise RuntimeError("Invalid argument: frame_offset must be non-negative. Found: {}".format(frame_offset))
|
| 43 |
+
if num_frames == 0 or num_frames < -1:
|
| 44 |
+
raise RuntimeError("Invalid argument: num_frames must be -1 or greater than 0. Found: {}".format(num_frames))
|
| 45 |
+
|
| 46 |
+
# All default values -> no filter
|
| 47 |
+
if frame_offset == 0 and num_frames == -1 and not convert:
|
| 48 |
+
return None
|
| 49 |
+
# Only convert
|
| 50 |
+
aformat = "aformat=sample_fmts=fltp"
|
| 51 |
+
if frame_offset == 0 and num_frames == -1 and convert:
|
| 52 |
+
return aformat
|
| 53 |
+
# At least one of frame_offset or num_frames has non-default value
|
| 54 |
+
if num_frames > 0:
|
| 55 |
+
atrim = "atrim=start_sample={}:end_sample={}".format(frame_offset, frame_offset + num_frames)
|
| 56 |
+
else:
|
| 57 |
+
atrim = "atrim=start_sample={}".format(frame_offset)
|
| 58 |
+
if not convert:
|
| 59 |
+
return atrim
|
| 60 |
+
return "{},{}".format(atrim, aformat)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def _load_audio(
|
| 64 |
+
s: "torchaudio.io.StreamReader",
|
| 65 |
+
filter: Optional[str] = None,
|
| 66 |
+
channels_first: bool = True,
|
| 67 |
+
) -> torch.Tensor:
|
| 68 |
+
s.add_audio_stream(-1, -1, filter_desc=filter)
|
| 69 |
+
s.process_all_packets()
|
| 70 |
+
chunk = s.pop_chunks()[0]
|
| 71 |
+
if chunk is None:
|
| 72 |
+
raise RuntimeError("Failed to decode audio.")
|
| 73 |
+
waveform = chunk._elem
|
| 74 |
+
return waveform.T if channels_first else waveform
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def load_audio(
|
| 78 |
+
src: InputType,
|
| 79 |
+
frame_offset: int = 0,
|
| 80 |
+
num_frames: int = -1,
|
| 81 |
+
convert: bool = True,
|
| 82 |
+
channels_first: bool = True,
|
| 83 |
+
format: Optional[str] = None,
|
| 84 |
+
buffer_size: int = 4096,
|
| 85 |
+
) -> Tuple[torch.Tensor, int]:
|
| 86 |
+
if hasattr(src, "read") and format == "vorbis":
|
| 87 |
+
format = "ogg"
|
| 88 |
+
s = torchaudio.io.StreamReader(src, format, None, buffer_size)
|
| 89 |
+
sample_rate = int(s.get_src_stream_info(s.default_audio_stream).sample_rate)
|
| 90 |
+
filter = _get_load_filter(frame_offset, num_frames, convert)
|
| 91 |
+
waveform = _load_audio(s, filter, channels_first)
|
| 92 |
+
return waveform, sample_rate
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def _get_sample_format(dtype: torch.dtype) -> str:
|
| 96 |
+
dtype_to_format = {
|
| 97 |
+
torch.uint8: "u8",
|
| 98 |
+
torch.int16: "s16",
|
| 99 |
+
torch.int32: "s32",
|
| 100 |
+
torch.int64: "s64",
|
| 101 |
+
torch.float32: "flt",
|
| 102 |
+
torch.float64: "dbl",
|
| 103 |
+
}
|
| 104 |
+
format = dtype_to_format.get(dtype)
|
| 105 |
+
if format is None:
|
| 106 |
+
raise ValueError(f"No format found for dtype {dtype}; dtype must be one of {list(dtype_to_format.keys())}.")
|
| 107 |
+
return format
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def _native_endianness() -> str:
|
| 111 |
+
if sys.byteorder == "little":
|
| 112 |
+
return "le"
|
| 113 |
+
else:
|
| 114 |
+
return "be"
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def _get_encoder_for_wav(encoding: str, bits_per_sample: int) -> str:
|
| 118 |
+
if bits_per_sample not in {None, 8, 16, 24, 32, 64}:
|
| 119 |
+
raise ValueError(f"Invalid bits_per_sample {bits_per_sample} for WAV encoding.")
|
| 120 |
+
endianness = _native_endianness()
|
| 121 |
+
if not encoding:
|
| 122 |
+
if not bits_per_sample:
|
| 123 |
+
# default to PCM S16
|
| 124 |
+
return f"pcm_s16{endianness}"
|
| 125 |
+
if bits_per_sample == 8:
|
| 126 |
+
return "pcm_u8"
|
| 127 |
+
return f"pcm_s{bits_per_sample}{endianness}"
|
| 128 |
+
if encoding == "PCM_S":
|
| 129 |
+
if not bits_per_sample:
|
| 130 |
+
bits_per_sample = 16
|
| 131 |
+
if bits_per_sample == 8:
|
| 132 |
+
raise ValueError("For WAV signed PCM, 8-bit encoding is not supported.")
|
| 133 |
+
return f"pcm_s{bits_per_sample}{endianness}"
|
| 134 |
+
if encoding == "PCM_U":
|
| 135 |
+
if bits_per_sample in (None, 8):
|
| 136 |
+
return "pcm_u8"
|
| 137 |
+
raise ValueError("For WAV unsigned PCM, only 8-bit encoding is supported.")
|
| 138 |
+
if encoding == "PCM_F":
|
| 139 |
+
if not bits_per_sample:
|
| 140 |
+
bits_per_sample = 32
|
| 141 |
+
if bits_per_sample in (32, 64):
|
| 142 |
+
return f"pcm_f{bits_per_sample}{endianness}"
|
| 143 |
+
raise ValueError("For WAV float PCM, only 32- and 64-bit encodings are supported.")
|
| 144 |
+
if encoding == "ULAW":
|
| 145 |
+
if bits_per_sample in (None, 8):
|
| 146 |
+
return "pcm_mulaw"
|
| 147 |
+
raise ValueError("For WAV PCM mu-law, only 8-bit encoding is supported.")
|
| 148 |
+
if encoding == "ALAW":
|
| 149 |
+
if bits_per_sample in (None, 8):
|
| 150 |
+
return "pcm_alaw"
|
| 151 |
+
raise ValueError("For WAV PCM A-law, only 8-bit encoding is supported.")
|
| 152 |
+
raise ValueError(f"WAV encoding {encoding} is not supported.")
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def _get_flac_sample_fmt(bps):
|
| 156 |
+
if bps is None or bps == 16:
|
| 157 |
+
return "s16"
|
| 158 |
+
if bps == 24:
|
| 159 |
+
return "s32"
|
| 160 |
+
raise ValueError(f"FLAC only supports bits_per_sample values of 16 and 24 ({bps} specified).")
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def _parse_save_args(
|
| 164 |
+
ext: Optional[str],
|
| 165 |
+
format: Optional[str],
|
| 166 |
+
encoding: Optional[str],
|
| 167 |
+
bps: Optional[int],
|
| 168 |
+
):
|
| 169 |
+
# torchaudio's save function accepts the followings, which do not 1to1 map
|
| 170 |
+
# to FFmpeg.
|
| 171 |
+
#
|
| 172 |
+
# - format: audio format
|
| 173 |
+
# - bits_per_sample: encoder sample format
|
| 174 |
+
# - encoding: such as PCM_U8.
|
| 175 |
+
#
|
| 176 |
+
# In FFmpeg, format is specified with the following three (and more)
|
| 177 |
+
#
|
| 178 |
+
# - muxer: could be audio format or container format.
|
| 179 |
+
# the one we passed to the constructor of StreamWriter
|
| 180 |
+
# - encoder: the audio encoder used to encode audio
|
| 181 |
+
# - encoder sample format: the format used by encoder to encode audio.
|
| 182 |
+
#
|
| 183 |
+
# If encoder sample format is different from source sample format, StreamWriter
|
| 184 |
+
# will insert a filter automatically.
|
| 185 |
+
#
|
| 186 |
+
def _type(spec):
|
| 187 |
+
# either format is exactly the specified one
|
| 188 |
+
# or extension matches to the spec AND there is no format override.
|
| 189 |
+
return format == spec or (format is None and ext == spec)
|
| 190 |
+
|
| 191 |
+
if _type("wav") or _type("amb"):
|
| 192 |
+
# wav is special because it supports different encoding through encoders
|
| 193 |
+
# each encoder only supports one encoder format
|
| 194 |
+
#
|
| 195 |
+
# amb format is a special case originated from libsox.
|
| 196 |
+
# It is basically a WAV format, with slight modification.
|
| 197 |
+
# https://github.com/chirlu/sox/commit/4a4ea33edbca5972a1ed8933cc3512c7302fa67a#diff-39171191a858add9df87f5f210a34a776ac2c026842ae6db6ce97f5e68836795
|
| 198 |
+
# It is a format so that decoders will recognize it as ambisonic.
|
| 199 |
+
# https://www.ambisonia.com/Members/mleese/file-format-for-b-format/
|
| 200 |
+
# FFmpeg does not recognize amb because it is basically a WAV format.
|
| 201 |
+
muxer = "wav"
|
| 202 |
+
encoder = _get_encoder_for_wav(encoding, bps)
|
| 203 |
+
sample_fmt = None
|
| 204 |
+
elif _type("vorbis"):
|
| 205 |
+
# FFpmeg does not recognize vorbis extension, while libsox used to do.
|
| 206 |
+
# For the sake of bakward compatibility, (and the simplicity),
|
| 207 |
+
# we support the case where users want to do save("foo.vorbis")
|
| 208 |
+
muxer = "ogg"
|
| 209 |
+
encoder = "vorbis"
|
| 210 |
+
sample_fmt = None
|
| 211 |
+
else:
|
| 212 |
+
muxer = format
|
| 213 |
+
encoder = None
|
| 214 |
+
sample_fmt = None
|
| 215 |
+
if _type("flac"):
|
| 216 |
+
sample_fmt = _get_flac_sample_fmt(bps)
|
| 217 |
+
if _type("ogg"):
|
| 218 |
+
sample_fmt = _get_flac_sample_fmt(bps)
|
| 219 |
+
return muxer, encoder, sample_fmt
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
def save_audio(
|
| 223 |
+
uri: InputType,
|
| 224 |
+
src: torch.Tensor,
|
| 225 |
+
sample_rate: int,
|
| 226 |
+
channels_first: bool = True,
|
| 227 |
+
format: Optional[str] = None,
|
| 228 |
+
encoding: Optional[str] = None,
|
| 229 |
+
bits_per_sample: Optional[int] = None,
|
| 230 |
+
buffer_size: int = 4096,
|
| 231 |
+
compression: Optional[torchaudio.io.CodecConfig] = None,
|
| 232 |
+
) -> None:
|
| 233 |
+
ext = None
|
| 234 |
+
if hasattr(uri, "write"):
|
| 235 |
+
if format is None:
|
| 236 |
+
raise RuntimeError("'format' is required when saving to file object.")
|
| 237 |
+
else:
|
| 238 |
+
uri = os.path.normpath(uri)
|
| 239 |
+
if tokens := str(uri).split(".")[1:]:
|
| 240 |
+
ext = tokens[-1].lower()
|
| 241 |
+
|
| 242 |
+
muxer, encoder, enc_fmt = _parse_save_args(ext, format, encoding, bits_per_sample)
|
| 243 |
+
|
| 244 |
+
if channels_first:
|
| 245 |
+
src = src.T
|
| 246 |
+
|
| 247 |
+
s = torchaudio.io.StreamWriter(uri, format=muxer, buffer_size=buffer_size)
|
| 248 |
+
s.add_audio_stream(
|
| 249 |
+
sample_rate,
|
| 250 |
+
num_channels=src.size(-1),
|
| 251 |
+
format=_get_sample_format(src.dtype),
|
| 252 |
+
encoder=encoder,
|
| 253 |
+
encoder_format=enc_fmt,
|
| 254 |
+
codec_config=compression,
|
| 255 |
+
)
|
| 256 |
+
with s.open():
|
| 257 |
+
s.write_audio_chunk(0, src)
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
def _map_encoding(encoding: str) -> str:
|
| 261 |
+
for dst in ["PCM_S", "PCM_U", "PCM_F"]:
|
| 262 |
+
if dst in encoding:
|
| 263 |
+
return dst
|
| 264 |
+
if encoding == "PCM_MULAW":
|
| 265 |
+
return "ULAW"
|
| 266 |
+
elif encoding == "PCM_ALAW":
|
| 267 |
+
return "ALAW"
|
| 268 |
+
return encoding
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
def _get_bits_per_sample(encoding: str, bits_per_sample: int) -> str:
|
| 272 |
+
if m := re.search(r"PCM_\w(\d+)\w*", encoding):
|
| 273 |
+
return int(m.group(1))
|
| 274 |
+
elif encoding in ["PCM_ALAW", "PCM_MULAW"]:
|
| 275 |
+
return 8
|
| 276 |
+
return bits_per_sample
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
class FFmpegBackend(Backend):
|
| 280 |
+
@staticmethod
|
| 281 |
+
def info(uri: InputType, format: Optional[str], buffer_size: int = 4096) -> AudioMetaData:
|
| 282 |
+
metadata = info_audio(uri, format, buffer_size)
|
| 283 |
+
metadata.bits_per_sample = _get_bits_per_sample(metadata.encoding, metadata.bits_per_sample)
|
| 284 |
+
metadata.encoding = _map_encoding(metadata.encoding)
|
| 285 |
+
return metadata
|
| 286 |
+
|
| 287 |
+
@staticmethod
|
| 288 |
+
def load(
|
| 289 |
+
uri: InputType,
|
| 290 |
+
frame_offset: int = 0,
|
| 291 |
+
num_frames: int = -1,
|
| 292 |
+
normalize: bool = True,
|
| 293 |
+
channels_first: bool = True,
|
| 294 |
+
format: Optional[str] = None,
|
| 295 |
+
buffer_size: int = 4096,
|
| 296 |
+
) -> Tuple[torch.Tensor, int]:
|
| 297 |
+
return load_audio(uri, frame_offset, num_frames, normalize, channels_first, format)
|
| 298 |
+
|
| 299 |
+
@staticmethod
|
| 300 |
+
def save(
|
| 301 |
+
uri: InputType,
|
| 302 |
+
src: torch.Tensor,
|
| 303 |
+
sample_rate: int,
|
| 304 |
+
channels_first: bool = True,
|
| 305 |
+
format: Optional[str] = None,
|
| 306 |
+
encoding: Optional[str] = None,
|
| 307 |
+
bits_per_sample: Optional[int] = None,
|
| 308 |
+
buffer_size: int = 4096,
|
| 309 |
+
compression: Optional[Union[torchaudio.io.CodecConfig, float, int]] = None,
|
| 310 |
+
) -> None:
|
| 311 |
+
if not isinstance(compression, (torchaudio.io.CodecConfig, type(None))):
|
| 312 |
+
raise ValueError(
|
| 313 |
+
"FFmpeg backend expects non-`None` value for argument `compression` to be of ",
|
| 314 |
+
f"type `torchaudio.io.CodecConfig`, but received value of type {type(compression)}",
|
| 315 |
+
)
|
| 316 |
+
save_audio(
|
| 317 |
+
uri,
|
| 318 |
+
src,
|
| 319 |
+
sample_rate,
|
| 320 |
+
channels_first,
|
| 321 |
+
format,
|
| 322 |
+
encoding,
|
| 323 |
+
bits_per_sample,
|
| 324 |
+
buffer_size,
|
| 325 |
+
compression,
|
| 326 |
+
)
|
| 327 |
+
|
| 328 |
+
@staticmethod
|
| 329 |
+
def can_decode(uri: InputType, format: Optional[str]) -> bool:
|
| 330 |
+
return True
|
| 331 |
+
|
| 332 |
+
@staticmethod
|
| 333 |
+
def can_encode(uri: InputType, format: Optional[str]) -> bool:
|
| 334 |
+
return True
|
micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/_backend/soundfile.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from typing import BinaryIO, Optional, Tuple, Union
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
from torchaudio.io import CodecConfig
|
| 6 |
+
|
| 7 |
+
from . import soundfile_backend
|
| 8 |
+
from .backend import Backend
|
| 9 |
+
from .common import AudioMetaData
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class SoundfileBackend(Backend):
|
| 13 |
+
@staticmethod
|
| 14 |
+
def info(uri: Union[BinaryIO, str, os.PathLike], format: Optional[str], buffer_size: int = 4096) -> AudioMetaData:
|
| 15 |
+
return soundfile_backend.info(uri, format)
|
| 16 |
+
|
| 17 |
+
@staticmethod
|
| 18 |
+
def load(
|
| 19 |
+
uri: Union[BinaryIO, str, os.PathLike],
|
| 20 |
+
frame_offset: int = 0,
|
| 21 |
+
num_frames: int = -1,
|
| 22 |
+
normalize: bool = True,
|
| 23 |
+
channels_first: bool = True,
|
| 24 |
+
format: Optional[str] = None,
|
| 25 |
+
buffer_size: int = 4096,
|
| 26 |
+
) -> Tuple[torch.Tensor, int]:
|
| 27 |
+
return soundfile_backend.load(uri, frame_offset, num_frames, normalize, channels_first, format)
|
| 28 |
+
|
| 29 |
+
@staticmethod
|
| 30 |
+
def save(
|
| 31 |
+
uri: Union[BinaryIO, str, os.PathLike],
|
| 32 |
+
src: torch.Tensor,
|
| 33 |
+
sample_rate: int,
|
| 34 |
+
channels_first: bool = True,
|
| 35 |
+
format: Optional[str] = None,
|
| 36 |
+
encoding: Optional[str] = None,
|
| 37 |
+
bits_per_sample: Optional[int] = None,
|
| 38 |
+
buffer_size: int = 4096,
|
| 39 |
+
compression: Optional[Union[CodecConfig, float, int]] = None,
|
| 40 |
+
) -> None:
|
| 41 |
+
if compression:
|
| 42 |
+
raise ValueError("soundfile backend does not support argument `compression`.")
|
| 43 |
+
|
| 44 |
+
soundfile_backend.save(
|
| 45 |
+
uri, src, sample_rate, channels_first, format=format, encoding=encoding, bits_per_sample=bits_per_sample
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
@staticmethod
|
| 49 |
+
def can_decode(uri, format) -> bool:
|
| 50 |
+
return True
|
| 51 |
+
|
| 52 |
+
@staticmethod
|
| 53 |
+
def can_encode(uri, format) -> bool:
|
| 54 |
+
return True
|
micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/_backend/soundfile_backend.py
ADDED
|
@@ -0,0 +1,457 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
import torch
|
| 6 |
+
from torchaudio._internal import module_utils as _mod_utils
|
| 7 |
+
|
| 8 |
+
from .common import AudioMetaData
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
_IS_SOUNDFILE_AVAILABLE = False
|
| 12 |
+
|
| 13 |
+
# TODO: import soundfile only when it is used.
|
| 14 |
+
if _mod_utils.is_module_available("soundfile"):
|
| 15 |
+
try:
|
| 16 |
+
import soundfile
|
| 17 |
+
|
| 18 |
+
_requires_soundfile = _mod_utils.no_op
|
| 19 |
+
_IS_SOUNDFILE_AVAILABLE = True
|
| 20 |
+
except Exception:
|
| 21 |
+
_requires_soundfile = _mod_utils.fail_with_message(
|
| 22 |
+
"requires soundfile, but we failed to import it. Please check the installation of soundfile."
|
| 23 |
+
)
|
| 24 |
+
else:
|
| 25 |
+
_requires_soundfile = _mod_utils.fail_with_message(
|
| 26 |
+
"requires soundfile, but it is not installed. Please install soundfile."
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
# Mapping from soundfile subtype to number of bits per sample.
|
| 31 |
+
# This is mostly heuristical and the value is set to 0 when it is irrelevant
|
| 32 |
+
# (lossy formats) or when it can't be inferred.
|
| 33 |
+
# For ADPCM (and G72X) subtypes, it's hard to infer the bit depth because it's not part of the standard:
|
| 34 |
+
# According to https://en.wikipedia.org/wiki/Adaptive_differential_pulse-code_modulation#In_telephony,
|
| 35 |
+
# the default seems to be 8 bits but it can be compressed further to 4 bits.
|
| 36 |
+
# The dict is inspired from
|
| 37 |
+
# https://github.com/bastibe/python-soundfile/blob/744efb4b01abc72498a96b09115b42a4cabd85e4/soundfile.py#L66-L94
|
| 38 |
+
_SUBTYPE_TO_BITS_PER_SAMPLE = {
|
| 39 |
+
"PCM_S8": 8, # Signed 8 bit data
|
| 40 |
+
"PCM_16": 16, # Signed 16 bit data
|
| 41 |
+
"PCM_24": 24, # Signed 24 bit data
|
| 42 |
+
"PCM_32": 32, # Signed 32 bit data
|
| 43 |
+
"PCM_U8": 8, # Unsigned 8 bit data (WAV and RAW only)
|
| 44 |
+
"FLOAT": 32, # 32 bit float data
|
| 45 |
+
"DOUBLE": 64, # 64 bit float data
|
| 46 |
+
"ULAW": 8, # U-Law encoded. See https://en.wikipedia.org/wiki/G.711#Types
|
| 47 |
+
"ALAW": 8, # A-Law encoded. See https://en.wikipedia.org/wiki/G.711#Types
|
| 48 |
+
"IMA_ADPCM": 0, # IMA ADPCM.
|
| 49 |
+
"MS_ADPCM": 0, # Microsoft ADPCM.
|
| 50 |
+
"GSM610": 0, # GSM 6.10 encoding. (Wikipedia says 1.625 bit depth?? https://en.wikipedia.org/wiki/Full_Rate)
|
| 51 |
+
"VOX_ADPCM": 0, # OKI / Dialogix ADPCM
|
| 52 |
+
"G721_32": 0, # 32kbs G721 ADPCM encoding.
|
| 53 |
+
"G723_24": 0, # 24kbs G723 ADPCM encoding.
|
| 54 |
+
"G723_40": 0, # 40kbs G723 ADPCM encoding.
|
| 55 |
+
"DWVW_12": 12, # 12 bit Delta Width Variable Word encoding.
|
| 56 |
+
"DWVW_16": 16, # 16 bit Delta Width Variable Word encoding.
|
| 57 |
+
"DWVW_24": 24, # 24 bit Delta Width Variable Word encoding.
|
| 58 |
+
"DWVW_N": 0, # N bit Delta Width Variable Word encoding.
|
| 59 |
+
"DPCM_8": 8, # 8 bit differential PCM (XI only)
|
| 60 |
+
"DPCM_16": 16, # 16 bit differential PCM (XI only)
|
| 61 |
+
"VORBIS": 0, # Xiph Vorbis encoding. (lossy)
|
| 62 |
+
"ALAC_16": 16, # Apple Lossless Audio Codec (16 bit).
|
| 63 |
+
"ALAC_20": 20, # Apple Lossless Audio Codec (20 bit).
|
| 64 |
+
"ALAC_24": 24, # Apple Lossless Audio Codec (24 bit).
|
| 65 |
+
"ALAC_32": 32, # Apple Lossless Audio Codec (32 bit).
|
| 66 |
+
}
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def _get_bit_depth(subtype):
|
| 70 |
+
if subtype not in _SUBTYPE_TO_BITS_PER_SAMPLE:
|
| 71 |
+
warnings.warn(
|
| 72 |
+
f"The {subtype} subtype is unknown to TorchAudio. As a result, the bits_per_sample "
|
| 73 |
+
"attribute will be set to 0. If you are seeing this warning, please "
|
| 74 |
+
"report by opening an issue on github (after checking for existing/closed ones). "
|
| 75 |
+
"You may otherwise ignore this warning."
|
| 76 |
+
)
|
| 77 |
+
return _SUBTYPE_TO_BITS_PER_SAMPLE.get(subtype, 0)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
_SUBTYPE_TO_ENCODING = {
|
| 81 |
+
"PCM_S8": "PCM_S",
|
| 82 |
+
"PCM_16": "PCM_S",
|
| 83 |
+
"PCM_24": "PCM_S",
|
| 84 |
+
"PCM_32": "PCM_S",
|
| 85 |
+
"PCM_U8": "PCM_U",
|
| 86 |
+
"FLOAT": "PCM_F",
|
| 87 |
+
"DOUBLE": "PCM_F",
|
| 88 |
+
"ULAW": "ULAW",
|
| 89 |
+
"ALAW": "ALAW",
|
| 90 |
+
"VORBIS": "VORBIS",
|
| 91 |
+
}
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def _get_encoding(format: str, subtype: str):
|
| 95 |
+
if format == "FLAC":
|
| 96 |
+
return "FLAC"
|
| 97 |
+
return _SUBTYPE_TO_ENCODING.get(subtype, "UNKNOWN")
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
@_requires_soundfile
|
| 101 |
+
def info(filepath: str, format: Optional[str] = None) -> AudioMetaData:
|
| 102 |
+
"""Get signal information of an audio file.
|
| 103 |
+
|
| 104 |
+
Note:
|
| 105 |
+
``filepath`` argument is intentionally annotated as ``str`` only, even though it accepts
|
| 106 |
+
``pathlib.Path`` object as well. This is for the consistency with ``"sox_io"`` backend,
|
| 107 |
+
which has a restriction on type annotation due to TorchScript compiler compatiblity.
|
| 108 |
+
|
| 109 |
+
Args:
|
| 110 |
+
filepath (path-like object or file-like object):
|
| 111 |
+
Source of audio data.
|
| 112 |
+
format (str or None, optional):
|
| 113 |
+
Not used. PySoundFile does not accept format hint.
|
| 114 |
+
|
| 115 |
+
Returns:
|
| 116 |
+
AudioMetaData: meta data of the given audio.
|
| 117 |
+
|
| 118 |
+
"""
|
| 119 |
+
sinfo = soundfile.info(filepath)
|
| 120 |
+
return AudioMetaData(
|
| 121 |
+
sinfo.samplerate,
|
| 122 |
+
sinfo.frames,
|
| 123 |
+
sinfo.channels,
|
| 124 |
+
bits_per_sample=_get_bit_depth(sinfo.subtype),
|
| 125 |
+
encoding=_get_encoding(sinfo.format, sinfo.subtype),
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
_SUBTYPE2DTYPE = {
|
| 130 |
+
"PCM_S8": "int8",
|
| 131 |
+
"PCM_U8": "uint8",
|
| 132 |
+
"PCM_16": "int16",
|
| 133 |
+
"PCM_32": "int32",
|
| 134 |
+
"FLOAT": "float32",
|
| 135 |
+
"DOUBLE": "float64",
|
| 136 |
+
}
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
@_requires_soundfile
|
| 140 |
+
def load(
|
| 141 |
+
filepath: str,
|
| 142 |
+
frame_offset: int = 0,
|
| 143 |
+
num_frames: int = -1,
|
| 144 |
+
normalize: bool = True,
|
| 145 |
+
channels_first: bool = True,
|
| 146 |
+
format: Optional[str] = None,
|
| 147 |
+
) -> Tuple[torch.Tensor, int]:
|
| 148 |
+
"""Load audio data from file.
|
| 149 |
+
|
| 150 |
+
Note:
|
| 151 |
+
The formats this function can handle depend on the soundfile installation.
|
| 152 |
+
This function is tested on the following formats;
|
| 153 |
+
|
| 154 |
+
* WAV
|
| 155 |
+
|
| 156 |
+
* 32-bit floating-point
|
| 157 |
+
* 32-bit signed integer
|
| 158 |
+
* 16-bit signed integer
|
| 159 |
+
* 8-bit unsigned integer
|
| 160 |
+
|
| 161 |
+
* FLAC
|
| 162 |
+
* OGG/VORBIS
|
| 163 |
+
* SPHERE
|
| 164 |
+
|
| 165 |
+
By default (``normalize=True``, ``channels_first=True``), this function returns Tensor with
|
| 166 |
+
``float32`` dtype, and the shape of `[channel, time]`.
|
| 167 |
+
|
| 168 |
+
.. warning::
|
| 169 |
+
|
| 170 |
+
``normalize`` argument does not perform volume normalization.
|
| 171 |
+
It only converts the sample type to `torch.float32` from the native sample
|
| 172 |
+
type.
|
| 173 |
+
|
| 174 |
+
When the input format is WAV with integer type, such as 32-bit signed integer, 16-bit
|
| 175 |
+
signed integer, 24-bit signed integer, and 8-bit unsigned integer, by providing ``normalize=False``,
|
| 176 |
+
this function can return integer Tensor, where the samples are expressed within the whole range
|
| 177 |
+
of the corresponding dtype, that is, ``int32`` tensor for 32-bit signed PCM,
|
| 178 |
+
``int16`` for 16-bit signed PCM and ``uint8`` for 8-bit unsigned PCM. Since torch does not
|
| 179 |
+
support ``int24`` dtype, 24-bit signed PCM are converted to ``int32`` tensors.
|
| 180 |
+
|
| 181 |
+
``normalize`` argument has no effect on 32-bit floating-point WAV and other formats, such as
|
| 182 |
+
``flac`` and ``mp3``.
|
| 183 |
+
|
| 184 |
+
For these formats, this function always returns ``float32`` Tensor with values.
|
| 185 |
+
|
| 186 |
+
Note:
|
| 187 |
+
``filepath`` argument is intentionally annotated as ``str`` only, even though it accepts
|
| 188 |
+
``pathlib.Path`` object as well. This is for the consistency with ``"sox_io"`` backend,
|
| 189 |
+
which has a restriction on type annotation due to TorchScript compiler compatiblity.
|
| 190 |
+
|
| 191 |
+
Args:
|
| 192 |
+
filepath (path-like object or file-like object):
|
| 193 |
+
Source of audio data.
|
| 194 |
+
frame_offset (int, optional):
|
| 195 |
+
Number of frames to skip before start reading data.
|
| 196 |
+
num_frames (int, optional):
|
| 197 |
+
Maximum number of frames to read. ``-1`` reads all the remaining samples,
|
| 198 |
+
starting from ``frame_offset``.
|
| 199 |
+
This function may return the less number of frames if there is not enough
|
| 200 |
+
frames in the given file.
|
| 201 |
+
normalize (bool, optional):
|
| 202 |
+
When ``True``, this function converts the native sample type to ``float32``.
|
| 203 |
+
Default: ``True``.
|
| 204 |
+
|
| 205 |
+
If input file is integer WAV, giving ``False`` will change the resulting Tensor type to
|
| 206 |
+
integer type.
|
| 207 |
+
This argument has no effect for formats other than integer WAV type.
|
| 208 |
+
|
| 209 |
+
channels_first (bool, optional):
|
| 210 |
+
When True, the returned Tensor has dimension `[channel, time]`.
|
| 211 |
+
Otherwise, the returned Tensor's dimension is `[time, channel]`.
|
| 212 |
+
format (str or None, optional):
|
| 213 |
+
Not used. PySoundFile does not accept format hint.
|
| 214 |
+
|
| 215 |
+
Returns:
|
| 216 |
+
(torch.Tensor, int): Resulting Tensor and sample rate.
|
| 217 |
+
If the input file has integer wav format and normalization is off, then it has
|
| 218 |
+
integer type, else ``float32`` type. If ``channels_first=True``, it has
|
| 219 |
+
`[channel, time]` else `[time, channel]`.
|
| 220 |
+
"""
|
| 221 |
+
with soundfile.SoundFile(filepath, "r") as file_:
|
| 222 |
+
if file_.format != "WAV" or normalize:
|
| 223 |
+
dtype = "float32"
|
| 224 |
+
elif file_.subtype not in _SUBTYPE2DTYPE:
|
| 225 |
+
raise ValueError(f"Unsupported subtype: {file_.subtype}")
|
| 226 |
+
else:
|
| 227 |
+
dtype = _SUBTYPE2DTYPE[file_.subtype]
|
| 228 |
+
|
| 229 |
+
frames = file_._prepare_read(frame_offset, None, num_frames)
|
| 230 |
+
waveform = file_.read(frames, dtype, always_2d=True)
|
| 231 |
+
sample_rate = file_.samplerate
|
| 232 |
+
|
| 233 |
+
waveform = torch.from_numpy(waveform)
|
| 234 |
+
if channels_first:
|
| 235 |
+
waveform = waveform.t()
|
| 236 |
+
return waveform, sample_rate
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
def _get_subtype_for_wav(dtype: torch.dtype, encoding: str, bits_per_sample: int):
|
| 240 |
+
if not encoding:
|
| 241 |
+
if not bits_per_sample:
|
| 242 |
+
subtype = {
|
| 243 |
+
torch.uint8: "PCM_U8",
|
| 244 |
+
torch.int16: "PCM_16",
|
| 245 |
+
torch.int32: "PCM_32",
|
| 246 |
+
torch.float32: "FLOAT",
|
| 247 |
+
torch.float64: "DOUBLE",
|
| 248 |
+
}.get(dtype)
|
| 249 |
+
if not subtype:
|
| 250 |
+
raise ValueError(f"Unsupported dtype for wav: {dtype}")
|
| 251 |
+
return subtype
|
| 252 |
+
if bits_per_sample == 8:
|
| 253 |
+
return "PCM_U8"
|
| 254 |
+
return f"PCM_{bits_per_sample}"
|
| 255 |
+
if encoding == "PCM_S":
|
| 256 |
+
if not bits_per_sample:
|
| 257 |
+
return "PCM_32"
|
| 258 |
+
if bits_per_sample == 8:
|
| 259 |
+
raise ValueError("wav does not support 8-bit signed PCM encoding.")
|
| 260 |
+
return f"PCM_{bits_per_sample}"
|
| 261 |
+
if encoding == "PCM_U":
|
| 262 |
+
if bits_per_sample in (None, 8):
|
| 263 |
+
return "PCM_U8"
|
| 264 |
+
raise ValueError("wav only supports 8-bit unsigned PCM encoding.")
|
| 265 |
+
if encoding == "PCM_F":
|
| 266 |
+
if bits_per_sample in (None, 32):
|
| 267 |
+
return "FLOAT"
|
| 268 |
+
if bits_per_sample == 64:
|
| 269 |
+
return "DOUBLE"
|
| 270 |
+
raise ValueError("wav only supports 32/64-bit float PCM encoding.")
|
| 271 |
+
if encoding == "ULAW":
|
| 272 |
+
if bits_per_sample in (None, 8):
|
| 273 |
+
return "ULAW"
|
| 274 |
+
raise ValueError("wav only supports 8-bit mu-law encoding.")
|
| 275 |
+
if encoding == "ALAW":
|
| 276 |
+
if bits_per_sample in (None, 8):
|
| 277 |
+
return "ALAW"
|
| 278 |
+
raise ValueError("wav only supports 8-bit a-law encoding.")
|
| 279 |
+
raise ValueError(f"wav does not support {encoding}.")
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
def _get_subtype_for_sphere(encoding: str, bits_per_sample: int):
|
| 283 |
+
if encoding in (None, "PCM_S"):
|
| 284 |
+
return f"PCM_{bits_per_sample}" if bits_per_sample else "PCM_32"
|
| 285 |
+
if encoding in ("PCM_U", "PCM_F"):
|
| 286 |
+
raise ValueError(f"sph does not support {encoding} encoding.")
|
| 287 |
+
if encoding == "ULAW":
|
| 288 |
+
if bits_per_sample in (None, 8):
|
| 289 |
+
return "ULAW"
|
| 290 |
+
raise ValueError("sph only supports 8-bit for mu-law encoding.")
|
| 291 |
+
if encoding == "ALAW":
|
| 292 |
+
return "ALAW"
|
| 293 |
+
raise ValueError(f"sph does not support {encoding}.")
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
def _get_subtype(dtype: torch.dtype, format: str, encoding: str, bits_per_sample: int):
|
| 297 |
+
if format == "wav":
|
| 298 |
+
return _get_subtype_for_wav(dtype, encoding, bits_per_sample)
|
| 299 |
+
if format == "flac":
|
| 300 |
+
if encoding:
|
| 301 |
+
raise ValueError("flac does not support encoding.")
|
| 302 |
+
if not bits_per_sample:
|
| 303 |
+
return "PCM_16"
|
| 304 |
+
if bits_per_sample > 24:
|
| 305 |
+
raise ValueError("flac does not support bits_per_sample > 24.")
|
| 306 |
+
return "PCM_S8" if bits_per_sample == 8 else f"PCM_{bits_per_sample}"
|
| 307 |
+
if format in ("ogg", "vorbis"):
|
| 308 |
+
if bits_per_sample:
|
| 309 |
+
raise ValueError("ogg/vorbis does not support bits_per_sample.")
|
| 310 |
+
if encoding is None or encoding == "vorbis":
|
| 311 |
+
return "VORBIS"
|
| 312 |
+
if encoding == "opus":
|
| 313 |
+
return "OPUS"
|
| 314 |
+
raise ValueError(f"Unexpected encoding: {encoding}")
|
| 315 |
+
if format == "mp3":
|
| 316 |
+
return "MPEG_LAYER_III"
|
| 317 |
+
if format == "sph":
|
| 318 |
+
return _get_subtype_for_sphere(encoding, bits_per_sample)
|
| 319 |
+
if format in ("nis", "nist"):
|
| 320 |
+
return "PCM_16"
|
| 321 |
+
raise ValueError(f"Unsupported format: {format}")
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
@_requires_soundfile
|
| 325 |
+
def save(
|
| 326 |
+
filepath: str,
|
| 327 |
+
src: torch.Tensor,
|
| 328 |
+
sample_rate: int,
|
| 329 |
+
channels_first: bool = True,
|
| 330 |
+
compression: Optional[float] = None,
|
| 331 |
+
format: Optional[str] = None,
|
| 332 |
+
encoding: Optional[str] = None,
|
| 333 |
+
bits_per_sample: Optional[int] = None,
|
| 334 |
+
):
|
| 335 |
+
"""Save audio data to file.
|
| 336 |
+
|
| 337 |
+
Note:
|
| 338 |
+
The formats this function can handle depend on the soundfile installation.
|
| 339 |
+
This function is tested on the following formats;
|
| 340 |
+
|
| 341 |
+
* WAV
|
| 342 |
+
|
| 343 |
+
* 32-bit floating-point
|
| 344 |
+
* 32-bit signed integer
|
| 345 |
+
* 16-bit signed integer
|
| 346 |
+
* 8-bit unsigned integer
|
| 347 |
+
|
| 348 |
+
* FLAC
|
| 349 |
+
* OGG/VORBIS
|
| 350 |
+
* SPHERE
|
| 351 |
+
|
| 352 |
+
Note:
|
| 353 |
+
``filepath`` argument is intentionally annotated as ``str`` only, even though it accepts
|
| 354 |
+
``pathlib.Path`` object as well. This is for the consistency with ``"sox_io"`` backend,
|
| 355 |
+
which has a restriction on type annotation due to TorchScript compiler compatiblity.
|
| 356 |
+
|
| 357 |
+
Args:
|
| 358 |
+
filepath (str or pathlib.Path): Path to audio file.
|
| 359 |
+
src (torch.Tensor): Audio data to save. must be 2D tensor.
|
| 360 |
+
sample_rate (int): sampling rate
|
| 361 |
+
channels_first (bool, optional): If ``True``, the given tensor is interpreted as `[channel, time]`,
|
| 362 |
+
otherwise `[time, channel]`.
|
| 363 |
+
compression (float of None, optional): Not used.
|
| 364 |
+
It is here only for interface compatibility reson with "sox_io" backend.
|
| 365 |
+
format (str or None, optional): Override the audio format.
|
| 366 |
+
When ``filepath`` argument is path-like object, audio format is
|
| 367 |
+
inferred from file extension. If the file extension is missing or
|
| 368 |
+
different, you can specify the correct format with this argument.
|
| 369 |
+
|
| 370 |
+
When ``filepath`` argument is file-like object,
|
| 371 |
+
this argument is required.
|
| 372 |
+
|
| 373 |
+
Valid values are ``"wav"``, ``"ogg"``, ``"vorbis"``,
|
| 374 |
+
``"flac"`` and ``"sph"``.
|
| 375 |
+
encoding (str or None, optional): Changes the encoding for supported formats.
|
| 376 |
+
This argument is effective only for supported formats, sush as
|
| 377 |
+
``"wav"``, ``""flac"`` and ``"sph"``. Valid values are;
|
| 378 |
+
|
| 379 |
+
- ``"PCM_S"`` (signed integer Linear PCM)
|
| 380 |
+
- ``"PCM_U"`` (unsigned integer Linear PCM)
|
| 381 |
+
- ``"PCM_F"`` (floating point PCM)
|
| 382 |
+
- ``"ULAW"`` (mu-law)
|
| 383 |
+
- ``"ALAW"`` (a-law)
|
| 384 |
+
|
| 385 |
+
bits_per_sample (int or None, optional): Changes the bit depth for the
|
| 386 |
+
supported formats.
|
| 387 |
+
When ``format`` is one of ``"wav"``, ``"flac"`` or ``"sph"``,
|
| 388 |
+
you can change the bit depth.
|
| 389 |
+
Valid values are ``8``, ``16``, ``24``, ``32`` and ``64``.
|
| 390 |
+
|
| 391 |
+
Supported formats/encodings/bit depth/compression are:
|
| 392 |
+
|
| 393 |
+
``"wav"``
|
| 394 |
+
- 32-bit floating-point PCM
|
| 395 |
+
- 32-bit signed integer PCM
|
| 396 |
+
- 24-bit signed integer PCM
|
| 397 |
+
- 16-bit signed integer PCM
|
| 398 |
+
- 8-bit unsigned integer PCM
|
| 399 |
+
- 8-bit mu-law
|
| 400 |
+
- 8-bit a-law
|
| 401 |
+
|
| 402 |
+
Note:
|
| 403 |
+
Default encoding/bit depth is determined by the dtype of
|
| 404 |
+
the input Tensor.
|
| 405 |
+
|
| 406 |
+
``"flac"``
|
| 407 |
+
- 8-bit
|
| 408 |
+
- 16-bit (default)
|
| 409 |
+
- 24-bit
|
| 410 |
+
|
| 411 |
+
``"ogg"``, ``"vorbis"``
|
| 412 |
+
- Doesn't accept changing configuration.
|
| 413 |
+
|
| 414 |
+
``"sph"``
|
| 415 |
+
- 8-bit signed integer PCM
|
| 416 |
+
- 16-bit signed integer PCM
|
| 417 |
+
- 24-bit signed integer PCM
|
| 418 |
+
- 32-bit signed integer PCM (default)
|
| 419 |
+
- 8-bit mu-law
|
| 420 |
+
- 8-bit a-law
|
| 421 |
+
- 16-bit a-law
|
| 422 |
+
- 24-bit a-law
|
| 423 |
+
- 32-bit a-law
|
| 424 |
+
|
| 425 |
+
"""
|
| 426 |
+
if src.ndim != 2:
|
| 427 |
+
raise ValueError(f"Expected 2D Tensor, got {src.ndim}D.")
|
| 428 |
+
if compression is not None:
|
| 429 |
+
warnings.warn(
|
| 430 |
+
'`save` function of "soundfile" backend does not support "compression" parameter. '
|
| 431 |
+
"The argument is silently ignored."
|
| 432 |
+
)
|
| 433 |
+
if hasattr(filepath, "write"):
|
| 434 |
+
if format is None:
|
| 435 |
+
raise RuntimeError("`format` is required when saving to file object.")
|
| 436 |
+
ext = format.lower()
|
| 437 |
+
else:
|
| 438 |
+
ext = str(filepath).split(".")[-1].lower()
|
| 439 |
+
|
| 440 |
+
if bits_per_sample not in (None, 8, 16, 24, 32, 64):
|
| 441 |
+
raise ValueError("Invalid bits_per_sample.")
|
| 442 |
+
if bits_per_sample == 24:
|
| 443 |
+
warnings.warn(
|
| 444 |
+
"Saving audio with 24 bits per sample might warp samples near -1. "
|
| 445 |
+
"Using 16 bits per sample might be able to avoid this."
|
| 446 |
+
)
|
| 447 |
+
subtype = _get_subtype(src.dtype, ext, encoding, bits_per_sample)
|
| 448 |
+
|
| 449 |
+
# sph is a extension used in TED-LIUM but soundfile does not recognize it as NIST format,
|
| 450 |
+
# so we extend the extensions manually here
|
| 451 |
+
if ext in ["nis", "nist", "sph"] and format is None:
|
| 452 |
+
format = "NIST"
|
| 453 |
+
|
| 454 |
+
if channels_first:
|
| 455 |
+
src = src.t()
|
| 456 |
+
|
| 457 |
+
soundfile.write(file=filepath, data=src, samplerate=sample_rate, subtype=subtype, format=format)
|
micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/_backend/sox.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from typing import BinaryIO, Optional, Tuple, Union
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
import torchaudio
|
| 6 |
+
|
| 7 |
+
from .backend import Backend
|
| 8 |
+
from .common import AudioMetaData
|
| 9 |
+
|
| 10 |
+
sox_ext = torchaudio._extension.lazy_import_sox_ext()
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class SoXBackend(Backend):
|
| 14 |
+
@staticmethod
|
| 15 |
+
def info(uri: Union[BinaryIO, str, os.PathLike], format: Optional[str], buffer_size: int = 4096) -> AudioMetaData:
|
| 16 |
+
if hasattr(uri, "read"):
|
| 17 |
+
raise ValueError(
|
| 18 |
+
"SoX backend does not support reading from file-like objects. ",
|
| 19 |
+
"Please use an alternative backend that does support reading from file-like objects, e.g. FFmpeg.",
|
| 20 |
+
)
|
| 21 |
+
else:
|
| 22 |
+
sinfo = sox_ext.get_info(uri, format)
|
| 23 |
+
if sinfo:
|
| 24 |
+
return AudioMetaData(*sinfo)
|
| 25 |
+
else:
|
| 26 |
+
raise RuntimeError(f"Failed to fetch metadata for {uri}.")
|
| 27 |
+
|
| 28 |
+
@staticmethod
|
| 29 |
+
def load(
|
| 30 |
+
uri: Union[BinaryIO, str, os.PathLike],
|
| 31 |
+
frame_offset: int = 0,
|
| 32 |
+
num_frames: int = -1,
|
| 33 |
+
normalize: bool = True,
|
| 34 |
+
channels_first: bool = True,
|
| 35 |
+
format: Optional[str] = None,
|
| 36 |
+
buffer_size: int = 4096,
|
| 37 |
+
) -> Tuple[torch.Tensor, int]:
|
| 38 |
+
if hasattr(uri, "read"):
|
| 39 |
+
raise ValueError(
|
| 40 |
+
"SoX backend does not support loading from file-like objects. ",
|
| 41 |
+
"Please use an alternative backend that does support loading from file-like objects, e.g. FFmpeg.",
|
| 42 |
+
)
|
| 43 |
+
else:
|
| 44 |
+
ret = sox_ext.load_audio_file(uri, frame_offset, num_frames, normalize, channels_first, format)
|
| 45 |
+
if not ret:
|
| 46 |
+
raise RuntimeError(f"Failed to load audio from {uri}.")
|
| 47 |
+
return ret
|
| 48 |
+
|
| 49 |
+
@staticmethod
|
| 50 |
+
def save(
|
| 51 |
+
uri: Union[BinaryIO, str, os.PathLike],
|
| 52 |
+
src: torch.Tensor,
|
| 53 |
+
sample_rate: int,
|
| 54 |
+
channels_first: bool = True,
|
| 55 |
+
format: Optional[str] = None,
|
| 56 |
+
encoding: Optional[str] = None,
|
| 57 |
+
bits_per_sample: Optional[int] = None,
|
| 58 |
+
buffer_size: int = 4096,
|
| 59 |
+
compression: Optional[Union[torchaudio.io.CodecConfig, float, int]] = None,
|
| 60 |
+
) -> None:
|
| 61 |
+
if not isinstance(compression, (float, int, type(None))):
|
| 62 |
+
raise ValueError(
|
| 63 |
+
"SoX backend expects non-`None` value for argument `compression` to be of ",
|
| 64 |
+
f"type `float` or `int`, but received value of type {type(compression)}",
|
| 65 |
+
)
|
| 66 |
+
if hasattr(uri, "write"):
|
| 67 |
+
raise ValueError(
|
| 68 |
+
"SoX backend does not support writing to file-like objects. ",
|
| 69 |
+
"Please use an alternative backend that does support writing to file-like objects, e.g. FFmpeg.",
|
| 70 |
+
)
|
| 71 |
+
else:
|
| 72 |
+
sox_ext.save_audio_file(
|
| 73 |
+
uri,
|
| 74 |
+
src,
|
| 75 |
+
sample_rate,
|
| 76 |
+
channels_first,
|
| 77 |
+
compression,
|
| 78 |
+
format,
|
| 79 |
+
encoding,
|
| 80 |
+
bits_per_sample,
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
@staticmethod
|
| 84 |
+
def can_decode(uri: Union[BinaryIO, str, os.PathLike], format: Optional[str]) -> bool:
|
| 85 |
+
# i.e. not a file-like object.
|
| 86 |
+
return not hasattr(uri, "read")
|
| 87 |
+
|
| 88 |
+
@staticmethod
|
| 89 |
+
def can_encode(uri: Union[BinaryIO, str, os.PathLike], format: Optional[str]) -> bool:
|
| 90 |
+
# i.e. not a file-like object.
|
| 91 |
+
return not hasattr(uri, "write")
|
micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/_backend/utils.py
ADDED
|
@@ -0,0 +1,317 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
|
micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/_extension/__init__.py
ADDED
|
@@ -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 |
+
)
|
micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/_extension/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (2.22 kB). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/torch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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
|
micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/_internal/__init__.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
try:
|
| 2 |
+
from .fb import download_url_to_file, load_state_dict_from_url
|
| 3 |
+
except ImportError:
|
| 4 |
+
from torch.hub import download_url_to_file, load_state_dict_from_url
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
__all__ = [
|
| 8 |
+
"load_state_dict_from_url",
|
| 9 |
+
"download_url_to_file",
|
| 10 |
+
]
|
micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/_internal/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (509 Bytes). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/_internal/__pycache__/module_utils.cpython-311.pyc
ADDED
|
Binary file (6.26 kB). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/_internal/module_utils.py
ADDED
|
@@ -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
|
micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/backend/__init__.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# NOTE:
|
| 2 |
+
# The entire `torchaudio.backend` module is deprecated.
|
| 3 |
+
# New things should be added to `torchaudio._backend`.
|
| 4 |
+
# Only things related to backward compatibility should be placed here.
|
| 5 |
+
|
| 6 |
+
from . import common, no_backend, soundfile_backend, sox_io_backend # noqa
|
| 7 |
+
|
| 8 |
+
__all__ = []
|
micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/backend/_no_backend.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
from typing import Callable, Optional, Tuple, Union
|
| 3 |
+
|
| 4 |
+
from torch import Tensor
|
| 5 |
+
from torchaudio import AudioMetaData
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def load(
|
| 9 |
+
filepath: Union[str, Path],
|
| 10 |
+
out: Optional[Tensor] = None,
|
| 11 |
+
normalization: Union[bool, float, Callable] = True,
|
| 12 |
+
channels_first: bool = True,
|
| 13 |
+
num_frames: int = 0,
|
| 14 |
+
offset: int = 0,
|
| 15 |
+
filetype: Optional[str] = None,
|
| 16 |
+
) -> Tuple[Tensor, int]:
|
| 17 |
+
raise RuntimeError("No audio I/O backend is available.")
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def save(filepath: str, src: Tensor, sample_rate: int, precision: int = 16, channels_first: bool = True) -> None:
|
| 21 |
+
raise RuntimeError("No audio I/O backend is available.")
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def info(filepath: str) -> AudioMetaData:
|
| 25 |
+
raise RuntimeError("No audio I/O backend is available.")
|
micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/backend/_sox_io_backend.py
ADDED
|
@@ -0,0 +1,294 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from typing import Optional, Tuple
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
import torchaudio
|
| 6 |
+
from torchaudio import AudioMetaData
|
| 7 |
+
|
| 8 |
+
sox_ext = torchaudio._extension.lazy_import_sox_ext()
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def info(
|
| 12 |
+
filepath: str,
|
| 13 |
+
format: Optional[str] = None,
|
| 14 |
+
) -> AudioMetaData:
|
| 15 |
+
"""Get signal information of an audio file.
|
| 16 |
+
|
| 17 |
+
Args:
|
| 18 |
+
filepath (str):
|
| 19 |
+
Source of audio data.
|
| 20 |
+
|
| 21 |
+
format (str or None, optional):
|
| 22 |
+
Override the format detection with the given format.
|
| 23 |
+
Providing the argument might help when libsox can not infer the format
|
| 24 |
+
from header or extension.
|
| 25 |
+
|
| 26 |
+
Returns:
|
| 27 |
+
AudioMetaData: Metadata of the given audio.
|
| 28 |
+
"""
|
| 29 |
+
if not torch.jit.is_scripting():
|
| 30 |
+
if hasattr(filepath, "read"):
|
| 31 |
+
raise RuntimeError("sox_io backend does not support file-like object.")
|
| 32 |
+
filepath = os.fspath(filepath)
|
| 33 |
+
sinfo = sox_ext.get_info(filepath, format)
|
| 34 |
+
return AudioMetaData(*sinfo)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def load(
|
| 38 |
+
filepath: str,
|
| 39 |
+
frame_offset: int = 0,
|
| 40 |
+
num_frames: int = -1,
|
| 41 |
+
normalize: bool = True,
|
| 42 |
+
channels_first: bool = True,
|
| 43 |
+
format: Optional[str] = None,
|
| 44 |
+
) -> Tuple[torch.Tensor, int]:
|
| 45 |
+
"""Load audio data from file.
|
| 46 |
+
|
| 47 |
+
Note:
|
| 48 |
+
This function can handle all the codecs that underlying libsox can handle,
|
| 49 |
+
however it is tested on the following formats;
|
| 50 |
+
|
| 51 |
+
* WAV, AMB
|
| 52 |
+
|
| 53 |
+
* 32-bit floating-point
|
| 54 |
+
* 32-bit signed integer
|
| 55 |
+
* 24-bit signed integer
|
| 56 |
+
* 16-bit signed integer
|
| 57 |
+
* 8-bit unsigned integer (WAV only)
|
| 58 |
+
|
| 59 |
+
* MP3
|
| 60 |
+
* FLAC
|
| 61 |
+
* OGG/VORBIS
|
| 62 |
+
* OPUS
|
| 63 |
+
* SPHERE
|
| 64 |
+
* AMR-NB
|
| 65 |
+
|
| 66 |
+
To load ``MP3``, ``FLAC``, ``OGG/VORBIS``, ``OPUS`` and other codecs ``libsox`` does not
|
| 67 |
+
handle natively, your installation of ``torchaudio`` has to be linked to ``libsox``
|
| 68 |
+
and corresponding codec libraries such as ``libmad`` or ``libmp3lame`` etc.
|
| 69 |
+
|
| 70 |
+
By default (``normalize=True``, ``channels_first=True``), this function returns Tensor with
|
| 71 |
+
``float32`` dtype, and the shape of `[channel, time]`.
|
| 72 |
+
|
| 73 |
+
.. warning::
|
| 74 |
+
|
| 75 |
+
``normalize`` argument does not perform volume normalization.
|
| 76 |
+
It only converts the sample type to `torch.float32` from the native sample
|
| 77 |
+
type.
|
| 78 |
+
|
| 79 |
+
When the input format is WAV with integer type, such as 32-bit signed integer, 16-bit
|
| 80 |
+
signed integer, 24-bit signed integer, and 8-bit unsigned integer, by providing ``normalize=False``,
|
| 81 |
+
this function can return integer Tensor, where the samples are expressed within the whole range
|
| 82 |
+
of the corresponding dtype, that is, ``int32`` tensor for 32-bit signed PCM,
|
| 83 |
+
``int16`` for 16-bit signed PCM and ``uint8`` for 8-bit unsigned PCM. Since torch does not
|
| 84 |
+
support ``int24`` dtype, 24-bit signed PCM are converted to ``int32`` tensors.
|
| 85 |
+
|
| 86 |
+
``normalize`` argument has no effect on 32-bit floating-point WAV and other formats, such as
|
| 87 |
+
``flac`` and ``mp3``.
|
| 88 |
+
|
| 89 |
+
For these formats, this function always returns ``float32`` Tensor with values.
|
| 90 |
+
|
| 91 |
+
Args:
|
| 92 |
+
filepath (path-like object): Source of audio data.
|
| 93 |
+
frame_offset (int):
|
| 94 |
+
Number of frames to skip before start reading data.
|
| 95 |
+
num_frames (int, optional):
|
| 96 |
+
Maximum number of frames to read. ``-1`` reads all the remaining samples,
|
| 97 |
+
starting from ``frame_offset``.
|
| 98 |
+
This function may return the less number of frames if there is not enough
|
| 99 |
+
frames in the given file.
|
| 100 |
+
normalize (bool, optional):
|
| 101 |
+
When ``True``, this function converts the native sample type to ``float32``.
|
| 102 |
+
Default: ``True``.
|
| 103 |
+
|
| 104 |
+
If input file is integer WAV, giving ``False`` will change the resulting Tensor type to
|
| 105 |
+
integer type.
|
| 106 |
+
This argument has no effect for formats other than integer WAV type.
|
| 107 |
+
|
| 108 |
+
channels_first (bool, optional):
|
| 109 |
+
When True, the returned Tensor has dimension `[channel, time]`.
|
| 110 |
+
Otherwise, the returned Tensor's dimension is `[time, channel]`.
|
| 111 |
+
format (str or None, optional):
|
| 112 |
+
Override the format detection with the given format.
|
| 113 |
+
Providing the argument might help when libsox can not infer the format
|
| 114 |
+
from header or extension.
|
| 115 |
+
|
| 116 |
+
Returns:
|
| 117 |
+
(torch.Tensor, int): Resulting Tensor and sample rate.
|
| 118 |
+
If the input file has integer wav format and ``normalize=False``, then it has
|
| 119 |
+
integer type, else ``float32`` type. If ``channels_first=True``, it has
|
| 120 |
+
`[channel, time]` else `[time, channel]`.
|
| 121 |
+
"""
|
| 122 |
+
if not torch.jit.is_scripting():
|
| 123 |
+
if hasattr(filepath, "read"):
|
| 124 |
+
raise RuntimeError("sox_io backend does not support file-like object.")
|
| 125 |
+
filepath = os.fspath(filepath)
|
| 126 |
+
return sox_ext.load_audio_file(filepath, frame_offset, num_frames, normalize, channels_first, format)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def save(
|
| 130 |
+
filepath: str,
|
| 131 |
+
src: torch.Tensor,
|
| 132 |
+
sample_rate: int,
|
| 133 |
+
channels_first: bool = True,
|
| 134 |
+
compression: Optional[float] = None,
|
| 135 |
+
format: Optional[str] = None,
|
| 136 |
+
encoding: Optional[str] = None,
|
| 137 |
+
bits_per_sample: Optional[int] = None,
|
| 138 |
+
):
|
| 139 |
+
"""Save audio data to file.
|
| 140 |
+
|
| 141 |
+
Args:
|
| 142 |
+
filepath (path-like object): Path to save file.
|
| 143 |
+
src (torch.Tensor): Audio data to save. must be 2D tensor.
|
| 144 |
+
sample_rate (int): sampling rate
|
| 145 |
+
channels_first (bool, optional): If ``True``, the given tensor is interpreted as `[channel, time]`,
|
| 146 |
+
otherwise `[time, channel]`.
|
| 147 |
+
compression (float or None, optional): Used for formats other than WAV.
|
| 148 |
+
This corresponds to ``-C`` option of ``sox`` command.
|
| 149 |
+
|
| 150 |
+
``"mp3"``
|
| 151 |
+
Either bitrate (in ``kbps``) with quality factor, such as ``128.2``, or
|
| 152 |
+
VBR encoding with quality factor such as ``-4.2``. Default: ``-4.5``.
|
| 153 |
+
|
| 154 |
+
``"flac"``
|
| 155 |
+
Whole number from ``0`` to ``8``. ``8`` is default and highest compression.
|
| 156 |
+
|
| 157 |
+
``"ogg"``, ``"vorbis"``
|
| 158 |
+
Number from ``-1`` to ``10``; ``-1`` is the highest compression
|
| 159 |
+
and lowest quality. Default: ``3``.
|
| 160 |
+
|
| 161 |
+
See the detail at http://sox.sourceforge.net/soxformat.html.
|
| 162 |
+
format (str or None, optional): Override the audio format.
|
| 163 |
+
When ``filepath`` argument is path-like object, audio format is infered from
|
| 164 |
+
file extension. If file extension is missing or different, you can specify the
|
| 165 |
+
correct format with this argument.
|
| 166 |
+
|
| 167 |
+
When ``filepath`` argument is file-like object, this argument is required.
|
| 168 |
+
|
| 169 |
+
Valid values are ``"wav"``, ``"mp3"``, ``"ogg"``, ``"vorbis"``, ``"amr-nb"``,
|
| 170 |
+
``"amb"``, ``"flac"``, ``"sph"``, ``"gsm"``, and ``"htk"``.
|
| 171 |
+
|
| 172 |
+
encoding (str or None, optional): Changes the encoding for the supported formats.
|
| 173 |
+
This argument is effective only for supported formats, such as ``"wav"``, ``""amb"``
|
| 174 |
+
and ``"sph"``. Valid values are;
|
| 175 |
+
|
| 176 |
+
- ``"PCM_S"`` (signed integer Linear PCM)
|
| 177 |
+
- ``"PCM_U"`` (unsigned integer Linear PCM)
|
| 178 |
+
- ``"PCM_F"`` (floating point PCM)
|
| 179 |
+
- ``"ULAW"`` (mu-law)
|
| 180 |
+
- ``"ALAW"`` (a-law)
|
| 181 |
+
|
| 182 |
+
Default values
|
| 183 |
+
If not provided, the default value is picked based on ``format`` and ``bits_per_sample``.
|
| 184 |
+
|
| 185 |
+
``"wav"``, ``"amb"``
|
| 186 |
+
- | If both ``encoding`` and ``bits_per_sample`` are not provided, the ``dtype`` of the
|
| 187 |
+
| Tensor is used to determine the default value.
|
| 188 |
+
|
| 189 |
+
- ``"PCM_U"`` if dtype is ``uint8``
|
| 190 |
+
- ``"PCM_S"`` if dtype is ``int16`` or ``int32``
|
| 191 |
+
- ``"PCM_F"`` if dtype is ``float32``
|
| 192 |
+
|
| 193 |
+
- ``"PCM_U"`` if ``bits_per_sample=8``
|
| 194 |
+
- ``"PCM_S"`` otherwise
|
| 195 |
+
|
| 196 |
+
``"sph"`` format;
|
| 197 |
+
- the default value is ``"PCM_S"``
|
| 198 |
+
|
| 199 |
+
bits_per_sample (int or None, optional): Changes the bit depth for the supported formats.
|
| 200 |
+
When ``format`` is one of ``"wav"``, ``"flac"``, ``"sph"``, or ``"amb"``, you can change the
|
| 201 |
+
bit depth. Valid values are ``8``, ``16``, ``32`` and ``64``.
|
| 202 |
+
|
| 203 |
+
Default Value;
|
| 204 |
+
If not provided, the default values are picked based on ``format`` and ``"encoding"``;
|
| 205 |
+
|
| 206 |
+
``"wav"``, ``"amb"``;
|
| 207 |
+
- | If both ``encoding`` and ``bits_per_sample`` are not provided, the ``dtype`` of the
|
| 208 |
+
| Tensor is used.
|
| 209 |
+
|
| 210 |
+
- ``8`` if dtype is ``uint8``
|
| 211 |
+
- ``16`` if dtype is ``int16``
|
| 212 |
+
- ``32`` if dtype is ``int32`` or ``float32``
|
| 213 |
+
|
| 214 |
+
- ``8`` if ``encoding`` is ``"PCM_U"``, ``"ULAW"`` or ``"ALAW"``
|
| 215 |
+
- ``16`` if ``encoding`` is ``"PCM_S"``
|
| 216 |
+
- ``32`` if ``encoding`` is ``"PCM_F"``
|
| 217 |
+
|
| 218 |
+
``"flac"`` format;
|
| 219 |
+
- the default value is ``24``
|
| 220 |
+
|
| 221 |
+
``"sph"`` format;
|
| 222 |
+
- ``16`` if ``encoding`` is ``"PCM_U"``, ``"PCM_S"``, ``"PCM_F"`` or not provided.
|
| 223 |
+
- ``8`` if ``encoding`` is ``"ULAW"`` or ``"ALAW"``
|
| 224 |
+
|
| 225 |
+
``"amb"`` format;
|
| 226 |
+
- ``8`` if ``encoding`` is ``"PCM_U"``, ``"ULAW"`` or ``"ALAW"``
|
| 227 |
+
- ``16`` if ``encoding`` is ``"PCM_S"`` or not provided.
|
| 228 |
+
- ``32`` if ``encoding`` is ``"PCM_F"``
|
| 229 |
+
|
| 230 |
+
Supported formats/encodings/bit depth/compression are;
|
| 231 |
+
|
| 232 |
+
``"wav"``, ``"amb"``
|
| 233 |
+
- 32-bit floating-point PCM
|
| 234 |
+
- 32-bit signed integer PCM
|
| 235 |
+
- 24-bit signed integer PCM
|
| 236 |
+
- 16-bit signed integer PCM
|
| 237 |
+
- 8-bit unsigned integer PCM
|
| 238 |
+
- 8-bit mu-law
|
| 239 |
+
- 8-bit a-law
|
| 240 |
+
|
| 241 |
+
Note: Default encoding/bit depth is determined by the dtype of the input Tensor.
|
| 242 |
+
|
| 243 |
+
``"mp3"``
|
| 244 |
+
Fixed bit rate (such as 128kHz) and variable bit rate compression.
|
| 245 |
+
Default: VBR with high quality.
|
| 246 |
+
|
| 247 |
+
``"flac"``
|
| 248 |
+
- 8-bit
|
| 249 |
+
- 16-bit
|
| 250 |
+
- 24-bit (default)
|
| 251 |
+
|
| 252 |
+
``"ogg"``, ``"vorbis"``
|
| 253 |
+
- Different quality level. Default: approx. 112kbps
|
| 254 |
+
|
| 255 |
+
``"sph"``
|
| 256 |
+
- 8-bit signed integer PCM
|
| 257 |
+
- 16-bit signed integer PCM
|
| 258 |
+
- 24-bit signed integer PCM
|
| 259 |
+
- 32-bit signed integer PCM (default)
|
| 260 |
+
- 8-bit mu-law
|
| 261 |
+
- 8-bit a-law
|
| 262 |
+
- 16-bit a-law
|
| 263 |
+
- 24-bit a-law
|
| 264 |
+
- 32-bit a-law
|
| 265 |
+
|
| 266 |
+
``"amr-nb"``
|
| 267 |
+
Bitrate ranging from 4.75 kbit/s to 12.2 kbit/s. Default: 4.75 kbit/s
|
| 268 |
+
|
| 269 |
+
``"gsm"``
|
| 270 |
+
Lossy Speech Compression, CPU intensive.
|
| 271 |
+
|
| 272 |
+
``"htk"``
|
| 273 |
+
Uses a default single-channel 16-bit PCM format.
|
| 274 |
+
|
| 275 |
+
Note:
|
| 276 |
+
To save into formats that ``libsox`` does not handle natively, (such as ``"mp3"``,
|
| 277 |
+
``"flac"``, ``"ogg"`` and ``"vorbis"``), your installation of ``torchaudio`` has
|
| 278 |
+
to be linked to ``libsox`` and corresponding codec libraries such as ``libmad``
|
| 279 |
+
or ``libmp3lame`` etc.
|
| 280 |
+
"""
|
| 281 |
+
if not torch.jit.is_scripting():
|
| 282 |
+
if hasattr(filepath, "write"):
|
| 283 |
+
raise RuntimeError("sox_io backend does not handle file-like object.")
|
| 284 |
+
filepath = os.fspath(filepath)
|
| 285 |
+
sox_ext.save_audio_file(
|
| 286 |
+
filepath,
|
| 287 |
+
src,
|
| 288 |
+
sample_rate,
|
| 289 |
+
channels_first,
|
| 290 |
+
compression,
|
| 291 |
+
format,
|
| 292 |
+
encoding,
|
| 293 |
+
bits_per_sample,
|
| 294 |
+
)
|
micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/backend/common.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
def __getattr__(name: str):
|
| 2 |
+
if name == "AudioMetaData":
|
| 3 |
+
import warnings
|
| 4 |
+
|
| 5 |
+
warnings.warn(
|
| 6 |
+
"`torchaudio.backend.common.AudioMetaData` has been moved to "
|
| 7 |
+
"`torchaudio.AudioMetaData`. Please update the import path.",
|
| 8 |
+
stacklevel=2,
|
| 9 |
+
)
|
| 10 |
+
from torchaudio import AudioMetaData
|
| 11 |
+
|
| 12 |
+
return AudioMetaData
|
| 13 |
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/backend/no_backend.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
def __getattr__(name: str):
|
| 2 |
+
import warnings
|
| 3 |
+
|
| 4 |
+
warnings.warn(
|
| 5 |
+
"Torchaudio's I/O functions now support par-call bakcend dispatch. "
|
| 6 |
+
"Importing backend implementation directly is no longer guaranteed to work. "
|
| 7 |
+
"Please use `backend` keyword with load/save/info function, instead of "
|
| 8 |
+
"calling the udnerlying implementation directly.",
|
| 9 |
+
stacklevel=2,
|
| 10 |
+
)
|
| 11 |
+
|
| 12 |
+
from . import _no_backend
|
| 13 |
+
|
| 14 |
+
return getattr(_no_backend, name)
|
micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/backend/soundfile_backend.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
def __getattr__(name: str):
|
| 2 |
+
import warnings
|
| 3 |
+
|
| 4 |
+
warnings.warn(
|
| 5 |
+
"Torchaudio's I/O functions now support par-call bakcend dispatch. "
|
| 6 |
+
"Importing backend implementation directly is no longer guaranteed to work. "
|
| 7 |
+
"Please use `backend` keyword with load/save/info function, instead of "
|
| 8 |
+
"calling the udnerlying implementation directly.",
|
| 9 |
+
stacklevel=2,
|
| 10 |
+
)
|
| 11 |
+
|
| 12 |
+
from torchaudio._backend import soundfile_backend
|
| 13 |
+
|
| 14 |
+
return getattr(soundfile_backend, name)
|
micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/backend/sox_io_backend.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
def __getattr__(name: str):
|
| 2 |
+
import warnings
|
| 3 |
+
|
| 4 |
+
warnings.warn(
|
| 5 |
+
"Torchaudio's I/O functions now support par-call bakcend dispatch. "
|
| 6 |
+
"Importing backend implementation directly is no longer guaranteed to work. "
|
| 7 |
+
"Please use `backend` keyword with load/save/info function, instead of "
|
| 8 |
+
"calling the udnerlying implementation directly.",
|
| 9 |
+
stacklevel=2,
|
| 10 |
+
)
|
| 11 |
+
|
| 12 |
+
from . import _sox_io_backend
|
| 13 |
+
|
| 14 |
+
return getattr(_sox_io_backend, name)
|
micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/compliance/__init__.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from . import kaldi
|
| 2 |
+
|
| 3 |
+
__all__ = [
|
| 4 |
+
"kaldi",
|
| 5 |
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 11 |
+
"inverse_mel_scale_scalar",
|
| 12 |
+
"mel_scale",
|
| 13 |
+
"mel_scale_scalar",
|
| 14 |
+
"spectrogram",
|
| 15 |
+
"fbank",
|
| 16 |
+
"mfcc",
|
| 17 |
+
"vtln_warp_freq",
|
| 18 |
+
"vtln_warp_mel_freq",
|
| 19 |
+
]
|
| 20 |
+
|
| 21 |
+
# numeric_limits<float>::epsilon() 1.1920928955078125e-07
|
| 22 |
+
EPSILON = torch.tensor(torch.finfo(torch.float).eps)
|
| 23 |
+
# 1 milliseconds = 0.001 seconds
|
| 24 |
+
MILLISECONDS_TO_SECONDS = 0.001
|
| 25 |
+
|
| 26 |
+
# window types
|
| 27 |
+
HAMMING = "hamming"
|
| 28 |
+
HANNING = "hanning"
|
| 29 |
+
POVEY = "povey"
|
| 30 |
+
RECTANGULAR = "rectangular"
|
| 31 |
+
BLACKMAN = "blackman"
|
| 32 |
+
WINDOWS = [HAMMING, HANNING, POVEY, RECTANGULAR, BLACKMAN]
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def _get_epsilon(device, dtype):
|
| 36 |
+
return EPSILON.to(device=device, dtype=dtype)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def _next_power_of_2(x: int) -> int:
|
| 40 |
+
r"""Returns the smallest power of 2 that is greater than x"""
|
| 41 |
+
return 1 if x == 0 else 2 ** (x - 1).bit_length()
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def _get_strided(waveform: Tensor, window_size: int, window_shift: int, snip_edges: bool) -> Tensor:
|
| 45 |
+
r"""Given a waveform (1D tensor of size ``num_samples``), it returns a 2D tensor (m, ``window_size``)
|
| 46 |
+
representing how the window is shifted along the waveform. Each row is a frame.
|
| 47 |
+
|
| 48 |
+
Args:
|
| 49 |
+
waveform (Tensor): Tensor of size ``num_samples``
|
| 50 |
+
window_size (int): Frame length
|
| 51 |
+
window_shift (int): Frame shift
|
| 52 |
+
snip_edges (bool): If True, end effects will be handled by outputting only frames that completely fit
|
| 53 |
+
in the file, and the number of frames depends on the frame_length. If False, the number of frames
|
| 54 |
+
depends only on the frame_shift, and we reflect the data at the ends.
|
| 55 |
+
|
| 56 |
+
Returns:
|
| 57 |
+
Tensor: 2D tensor of size (m, ``window_size``) where each row is a frame
|
| 58 |
+
"""
|
| 59 |
+
assert waveform.dim() == 1
|
| 60 |
+
num_samples = waveform.size(0)
|
| 61 |
+
strides = (window_shift * waveform.stride(0), waveform.stride(0))
|
| 62 |
+
|
| 63 |
+
if snip_edges:
|
| 64 |
+
if num_samples < window_size:
|
| 65 |
+
return torch.empty((0, 0), dtype=waveform.dtype, device=waveform.device)
|
| 66 |
+
else:
|
| 67 |
+
m = 1 + (num_samples - window_size) // window_shift
|
| 68 |
+
else:
|
| 69 |
+
reversed_waveform = torch.flip(waveform, [0])
|
| 70 |
+
m = (num_samples + (window_shift // 2)) // window_shift
|
| 71 |
+
pad = window_size // 2 - window_shift // 2
|
| 72 |
+
pad_right = reversed_waveform
|
| 73 |
+
if pad > 0:
|
| 74 |
+
# torch.nn.functional.pad returns [2,1,0,1,2] for 'reflect'
|
| 75 |
+
# but we want [2, 1, 0, 0, 1, 2]
|
| 76 |
+
pad_left = reversed_waveform[-pad:]
|
| 77 |
+
waveform = torch.cat((pad_left, waveform, pad_right), dim=0)
|
| 78 |
+
else:
|
| 79 |
+
# pad is negative so we want to trim the waveform at the front
|
| 80 |
+
waveform = torch.cat((waveform[-pad:], pad_right), dim=0)
|
| 81 |
+
|
| 82 |
+
sizes = (m, window_size)
|
| 83 |
+
return waveform.as_strided(sizes, strides)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def _feature_window_function(
|
| 87 |
+
window_type: str,
|
| 88 |
+
window_size: int,
|
| 89 |
+
blackman_coeff: float,
|
| 90 |
+
device: torch.device,
|
| 91 |
+
dtype: int,
|
| 92 |
+
) -> Tensor:
|
| 93 |
+
r"""Returns a window function with the given type and size"""
|
| 94 |
+
if window_type == HANNING:
|
| 95 |
+
return torch.hann_window(window_size, periodic=False, device=device, dtype=dtype)
|
| 96 |
+
elif window_type == HAMMING:
|
| 97 |
+
return torch.hamming_window(window_size, periodic=False, alpha=0.54, beta=0.46, device=device, dtype=dtype)
|
| 98 |
+
elif window_type == POVEY:
|
| 99 |
+
# like hanning but goes to zero at edges
|
| 100 |
+
return torch.hann_window(window_size, periodic=False, device=device, dtype=dtype).pow(0.85)
|
| 101 |
+
elif window_type == RECTANGULAR:
|
| 102 |
+
return torch.ones(window_size, device=device, dtype=dtype)
|
| 103 |
+
elif window_type == BLACKMAN:
|
| 104 |
+
a = 2 * math.pi / (window_size - 1)
|
| 105 |
+
window_function = torch.arange(window_size, device=device, dtype=dtype)
|
| 106 |
+
# can't use torch.blackman_window as they use different coefficients
|
| 107 |
+
return (
|
| 108 |
+
blackman_coeff
|
| 109 |
+
- 0.5 * torch.cos(a * window_function)
|
| 110 |
+
+ (0.5 - blackman_coeff) * torch.cos(2 * a * window_function)
|
| 111 |
+
).to(device=device, dtype=dtype)
|
| 112 |
+
else:
|
| 113 |
+
raise Exception("Invalid window type " + window_type)
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def _get_log_energy(strided_input: Tensor, epsilon: Tensor, energy_floor: float) -> Tensor:
|
| 117 |
+
r"""Returns the log energy of size (m) for a strided_input (m,*)"""
|
| 118 |
+
device, dtype = strided_input.device, strided_input.dtype
|
| 119 |
+
log_energy = torch.max(strided_input.pow(2).sum(1), epsilon).log() # size (m)
|
| 120 |
+
if energy_floor == 0.0:
|
| 121 |
+
return log_energy
|
| 122 |
+
return torch.max(log_energy, torch.tensor(math.log(energy_floor), device=device, dtype=dtype))
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def _get_waveform_and_window_properties(
|
| 126 |
+
waveform: Tensor,
|
| 127 |
+
channel: int,
|
| 128 |
+
sample_frequency: float,
|
| 129 |
+
frame_shift: float,
|
| 130 |
+
frame_length: float,
|
| 131 |
+
round_to_power_of_two: bool,
|
| 132 |
+
preemphasis_coefficient: float,
|
| 133 |
+
) -> Tuple[Tensor, int, int, int]:
|
| 134 |
+
r"""Gets the waveform and window properties"""
|
| 135 |
+
channel = max(channel, 0)
|
| 136 |
+
assert channel < waveform.size(0), "Invalid channel {} for size {}".format(channel, waveform.size(0))
|
| 137 |
+
waveform = waveform[channel, :] # size (n)
|
| 138 |
+
window_shift = int(sample_frequency * frame_shift * MILLISECONDS_TO_SECONDS)
|
| 139 |
+
window_size = int(sample_frequency * frame_length * MILLISECONDS_TO_SECONDS)
|
| 140 |
+
padded_window_size = _next_power_of_2(window_size) if round_to_power_of_two else window_size
|
| 141 |
+
|
| 142 |
+
assert 2 <= window_size <= len(waveform), "choose a window size {} that is [2, {}]".format(
|
| 143 |
+
window_size, len(waveform)
|
| 144 |
+
)
|
| 145 |
+
assert 0 < window_shift, "`window_shift` must be greater than 0"
|
| 146 |
+
assert padded_window_size % 2 == 0, (
|
| 147 |
+
"the padded `window_size` must be divisible by two." " use `round_to_power_of_two` or change `frame_length`"
|
| 148 |
+
)
|
| 149 |
+
assert 0.0 <= preemphasis_coefficient <= 1.0, "`preemphasis_coefficient` must be between [0,1]"
|
| 150 |
+
assert sample_frequency > 0, "`sample_frequency` must be greater than zero"
|
| 151 |
+
return waveform, window_shift, window_size, padded_window_size
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def _get_window(
|
| 155 |
+
waveform: Tensor,
|
| 156 |
+
padded_window_size: int,
|
| 157 |
+
window_size: int,
|
| 158 |
+
window_shift: int,
|
| 159 |
+
window_type: str,
|
| 160 |
+
blackman_coeff: float,
|
| 161 |
+
snip_edges: bool,
|
| 162 |
+
raw_energy: bool,
|
| 163 |
+
energy_floor: float,
|
| 164 |
+
dither: float,
|
| 165 |
+
remove_dc_offset: bool,
|
| 166 |
+
preemphasis_coefficient: float,
|
| 167 |
+
) -> Tuple[Tensor, Tensor]:
|
| 168 |
+
r"""Gets a window and its log energy
|
| 169 |
+
|
| 170 |
+
Returns:
|
| 171 |
+
(Tensor, Tensor): strided_input of size (m, ``padded_window_size``) and signal_log_energy of size (m)
|
| 172 |
+
"""
|
| 173 |
+
device, dtype = waveform.device, waveform.dtype
|
| 174 |
+
epsilon = _get_epsilon(device, dtype)
|
| 175 |
+
|
| 176 |
+
# size (m, window_size)
|
| 177 |
+
strided_input = _get_strided(waveform, window_size, window_shift, snip_edges)
|
| 178 |
+
|
| 179 |
+
if dither != 0.0:
|
| 180 |
+
rand_gauss = torch.randn(strided_input.shape, device=device, dtype=dtype)
|
| 181 |
+
strided_input = strided_input + rand_gauss * dither
|
| 182 |
+
|
| 183 |
+
if remove_dc_offset:
|
| 184 |
+
# Subtract each row/frame by its mean
|
| 185 |
+
row_means = torch.mean(strided_input, dim=1).unsqueeze(1) # size (m, 1)
|
| 186 |
+
strided_input = strided_input - row_means
|
| 187 |
+
|
| 188 |
+
if raw_energy:
|
| 189 |
+
# Compute the log energy of each row/frame before applying preemphasis and
|
| 190 |
+
# window function
|
| 191 |
+
signal_log_energy = _get_log_energy(strided_input, epsilon, energy_floor) # size (m)
|
| 192 |
+
|
| 193 |
+
if preemphasis_coefficient != 0.0:
|
| 194 |
+
# strided_input[i,j] -= preemphasis_coefficient * strided_input[i, max(0, j-1)] for all i,j
|
| 195 |
+
offset_strided_input = torch.nn.functional.pad(strided_input.unsqueeze(0), (1, 0), mode="replicate").squeeze(
|
| 196 |
+
0
|
| 197 |
+
) # size (m, window_size + 1)
|
| 198 |
+
strided_input = strided_input - preemphasis_coefficient * offset_strided_input[:, :-1]
|
| 199 |
+
|
| 200 |
+
# Apply window_function to each row/frame
|
| 201 |
+
window_function = _feature_window_function(window_type, window_size, blackman_coeff, device, dtype).unsqueeze(
|
| 202 |
+
0
|
| 203 |
+
) # size (1, window_size)
|
| 204 |
+
strided_input = strided_input * window_function # size (m, window_size)
|
| 205 |
+
|
| 206 |
+
# Pad columns with zero until we reach size (m, padded_window_size)
|
| 207 |
+
if padded_window_size != window_size:
|
| 208 |
+
padding_right = padded_window_size - window_size
|
| 209 |
+
strided_input = torch.nn.functional.pad(
|
| 210 |
+
strided_input.unsqueeze(0), (0, padding_right), mode="constant", value=0
|
| 211 |
+
).squeeze(0)
|
| 212 |
+
|
| 213 |
+
# Compute energy after window function (not the raw one)
|
| 214 |
+
if not raw_energy:
|
| 215 |
+
signal_log_energy = _get_log_energy(strided_input, epsilon, energy_floor) # size (m)
|
| 216 |
+
|
| 217 |
+
return strided_input, signal_log_energy
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
def _subtract_column_mean(tensor: Tensor, subtract_mean: bool) -> Tensor:
|
| 221 |
+
# subtracts the column mean of the tensor size (m, n) if subtract_mean=True
|
| 222 |
+
# it returns size (m, n)
|
| 223 |
+
if subtract_mean:
|
| 224 |
+
col_means = torch.mean(tensor, dim=0).unsqueeze(0)
|
| 225 |
+
tensor = tensor - col_means
|
| 226 |
+
return tensor
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
def spectrogram(
|
| 230 |
+
waveform: Tensor,
|
| 231 |
+
blackman_coeff: float = 0.42,
|
| 232 |
+
channel: int = -1,
|
| 233 |
+
dither: float = 0.0,
|
| 234 |
+
energy_floor: float = 1.0,
|
| 235 |
+
frame_length: float = 25.0,
|
| 236 |
+
frame_shift: float = 10.0,
|
| 237 |
+
min_duration: float = 0.0,
|
| 238 |
+
preemphasis_coefficient: float = 0.97,
|
| 239 |
+
raw_energy: bool = True,
|
| 240 |
+
remove_dc_offset: bool = True,
|
| 241 |
+
round_to_power_of_two: bool = True,
|
| 242 |
+
sample_frequency: float = 16000.0,
|
| 243 |
+
snip_edges: bool = True,
|
| 244 |
+
subtract_mean: bool = False,
|
| 245 |
+
window_type: str = POVEY,
|
| 246 |
+
) -> Tensor:
|
| 247 |
+
r"""Create a spectrogram from a raw audio signal. This matches the input/output of Kaldi's
|
| 248 |
+
compute-spectrogram-feats.
|
| 249 |
+
|
| 250 |
+
Args:
|
| 251 |
+
waveform (Tensor): Tensor of audio of size (c, n) where c is in the range [0,2)
|
| 252 |
+
blackman_coeff (float, optional): Constant coefficient for generalized Blackman window. (Default: ``0.42``)
|
| 253 |
+
channel (int, optional): Channel to extract (-1 -> expect mono, 0 -> left, 1 -> right) (Default: ``-1``)
|
| 254 |
+
dither (float, optional): Dithering constant (0.0 means no dither). If you turn this off, you should set
|
| 255 |
+
the energy_floor option, e.g. to 1.0 or 0.1 (Default: ``0.0``)
|
| 256 |
+
energy_floor (float, optional): Floor on energy (absolute, not relative) in Spectrogram computation. Caution:
|
| 257 |
+
this floor is applied to the zeroth component, representing the total signal energy. The floor on the
|
| 258 |
+
individual spectrogram elements is fixed at std::numeric_limits<float>::epsilon(). (Default: ``1.0``)
|
| 259 |
+
frame_length (float, optional): Frame length in milliseconds (Default: ``25.0``)
|
| 260 |
+
frame_shift (float, optional): Frame shift in milliseconds (Default: ``10.0``)
|
| 261 |
+
min_duration (float, optional): Minimum duration of segments to process (in seconds). (Default: ``0.0``)
|
| 262 |
+
preemphasis_coefficient (float, optional): Coefficient for use in signal preemphasis (Default: ``0.97``)
|
| 263 |
+
raw_energy (bool, optional): If True, compute energy before preemphasis and windowing (Default: ``True``)
|
| 264 |
+
remove_dc_offset (bool, optional): Subtract mean from waveform on each frame (Default: ``True``)
|
| 265 |
+
round_to_power_of_two (bool, optional): If True, round window size to power of two by zero-padding input
|
| 266 |
+
to FFT. (Default: ``True``)
|
| 267 |
+
sample_frequency (float, optional): Waveform data sample frequency (must match the waveform file, if
|
| 268 |
+
specified there) (Default: ``16000.0``)
|
| 269 |
+
snip_edges (bool, optional): If True, end effects will be handled by outputting only frames that completely fit
|
| 270 |
+
in the file, and the number of frames depends on the frame_length. If False, the number of frames
|
| 271 |
+
depends only on the frame_shift, and we reflect the data at the ends. (Default: ``True``)
|
| 272 |
+
subtract_mean (bool, optional): Subtract mean of each feature file [CMS]; not recommended to do
|
| 273 |
+
it this way. (Default: ``False``)
|
| 274 |
+
window_type (str, optional): Type of window ('hamming'|'hanning'|'povey'|'rectangular'|'blackman')
|
| 275 |
+
(Default: ``'povey'``)
|
| 276 |
+
|
| 277 |
+
Returns:
|
| 278 |
+
Tensor: A spectrogram identical to what Kaldi would output. The shape is
|
| 279 |
+
(m, ``padded_window_size // 2 + 1``) where m is calculated in _get_strided
|
| 280 |
+
"""
|
| 281 |
+
device, dtype = waveform.device, waveform.dtype
|
| 282 |
+
epsilon = _get_epsilon(device, dtype)
|
| 283 |
+
|
| 284 |
+
waveform, window_shift, window_size, padded_window_size = _get_waveform_and_window_properties(
|
| 285 |
+
waveform, channel, sample_frequency, frame_shift, frame_length, round_to_power_of_two, preemphasis_coefficient
|
| 286 |
+
)
|
| 287 |
+
|
| 288 |
+
if len(waveform) < min_duration * sample_frequency:
|
| 289 |
+
# signal is too short
|
| 290 |
+
return torch.empty(0)
|
| 291 |
+
|
| 292 |
+
strided_input, signal_log_energy = _get_window(
|
| 293 |
+
waveform,
|
| 294 |
+
padded_window_size,
|
| 295 |
+
window_size,
|
| 296 |
+
window_shift,
|
| 297 |
+
window_type,
|
| 298 |
+
blackman_coeff,
|
| 299 |
+
snip_edges,
|
| 300 |
+
raw_energy,
|
| 301 |
+
energy_floor,
|
| 302 |
+
dither,
|
| 303 |
+
remove_dc_offset,
|
| 304 |
+
preemphasis_coefficient,
|
| 305 |
+
)
|
| 306 |
+
|
| 307 |
+
# size (m, padded_window_size // 2 + 1, 2)
|
| 308 |
+
fft = torch.fft.rfft(strided_input)
|
| 309 |
+
|
| 310 |
+
# Convert the FFT into a power spectrum
|
| 311 |
+
power_spectrum = torch.max(fft.abs().pow(2.0), epsilon).log() # size (m, padded_window_size // 2 + 1)
|
| 312 |
+
power_spectrum[:, 0] = signal_log_energy
|
| 313 |
+
|
| 314 |
+
power_spectrum = _subtract_column_mean(power_spectrum, subtract_mean)
|
| 315 |
+
return power_spectrum
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
def inverse_mel_scale_scalar(mel_freq: float) -> float:
|
| 319 |
+
return 700.0 * (math.exp(mel_freq / 1127.0) - 1.0)
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
def inverse_mel_scale(mel_freq: Tensor) -> Tensor:
|
| 323 |
+
return 700.0 * ((mel_freq / 1127.0).exp() - 1.0)
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
def mel_scale_scalar(freq: float) -> float:
|
| 327 |
+
return 1127.0 * math.log(1.0 + freq / 700.0)
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
def mel_scale(freq: Tensor) -> Tensor:
|
| 331 |
+
return 1127.0 * (1.0 + freq / 700.0).log()
|
| 332 |
+
|
| 333 |
+
|
| 334 |
+
def vtln_warp_freq(
|
| 335 |
+
vtln_low_cutoff: float,
|
| 336 |
+
vtln_high_cutoff: float,
|
| 337 |
+
low_freq: float,
|
| 338 |
+
high_freq: float,
|
| 339 |
+
vtln_warp_factor: float,
|
| 340 |
+
freq: Tensor,
|
| 341 |
+
) -> Tensor:
|
| 342 |
+
r"""This computes a VTLN warping function that is not the same as HTK's one,
|
| 343 |
+
but has similar inputs (this function has the advantage of never producing
|
| 344 |
+
empty bins).
|
| 345 |
+
|
| 346 |
+
This function computes a warp function F(freq), defined between low_freq
|
| 347 |
+
and high_freq inclusive, with the following properties:
|
| 348 |
+
F(low_freq) == low_freq
|
| 349 |
+
F(high_freq) == high_freq
|
| 350 |
+
The function is continuous and piecewise linear with two inflection
|
| 351 |
+
points.
|
| 352 |
+
The lower inflection point (measured in terms of the unwarped
|
| 353 |
+
frequency) is at frequency l, determined as described below.
|
| 354 |
+
The higher inflection point is at a frequency h, determined as
|
| 355 |
+
described below.
|
| 356 |
+
If l <= f <= h, then F(f) = f/vtln_warp_factor.
|
| 357 |
+
If the higher inflection point (measured in terms of the unwarped
|
| 358 |
+
frequency) is at h, then max(h, F(h)) == vtln_high_cutoff.
|
| 359 |
+
Since (by the last point) F(h) == h/vtln_warp_factor, then
|
| 360 |
+
max(h, h/vtln_warp_factor) == vtln_high_cutoff, so
|
| 361 |
+
h = vtln_high_cutoff / max(1, 1/vtln_warp_factor).
|
| 362 |
+
= vtln_high_cutoff * min(1, vtln_warp_factor).
|
| 363 |
+
If the lower inflection point (measured in terms of the unwarped
|
| 364 |
+
frequency) is at l, then min(l, F(l)) == vtln_low_cutoff
|
| 365 |
+
This implies that l = vtln_low_cutoff / min(1, 1/vtln_warp_factor)
|
| 366 |
+
= vtln_low_cutoff * max(1, vtln_warp_factor)
|
| 367 |
+
Args:
|
| 368 |
+
vtln_low_cutoff (float): Lower frequency cutoffs for VTLN
|
| 369 |
+
vtln_high_cutoff (float): Upper frequency cutoffs for VTLN
|
| 370 |
+
low_freq (float): Lower frequency cutoffs in mel computation
|
| 371 |
+
high_freq (float): Upper frequency cutoffs in mel computation
|
| 372 |
+
vtln_warp_factor (float): Vtln warp factor
|
| 373 |
+
freq (Tensor): given frequency in Hz
|
| 374 |
+
|
| 375 |
+
Returns:
|
| 376 |
+
Tensor: Freq after vtln warp
|
| 377 |
+
"""
|
| 378 |
+
assert vtln_low_cutoff > low_freq, "be sure to set the vtln_low option higher than low_freq"
|
| 379 |
+
assert vtln_high_cutoff < high_freq, "be sure to set the vtln_high option lower than high_freq [or negative]"
|
| 380 |
+
l = vtln_low_cutoff * max(1.0, vtln_warp_factor)
|
| 381 |
+
h = vtln_high_cutoff * min(1.0, vtln_warp_factor)
|
| 382 |
+
scale = 1.0 / vtln_warp_factor
|
| 383 |
+
Fl = scale * l # F(l)
|
| 384 |
+
Fh = scale * h # F(h)
|
| 385 |
+
assert l > low_freq and h < high_freq
|
| 386 |
+
# slope of left part of the 3-piece linear function
|
| 387 |
+
scale_left = (Fl - low_freq) / (l - low_freq)
|
| 388 |
+
# [slope of center part is just "scale"]
|
| 389 |
+
|
| 390 |
+
# slope of right part of the 3-piece linear function
|
| 391 |
+
scale_right = (high_freq - Fh) / (high_freq - h)
|
| 392 |
+
|
| 393 |
+
res = torch.empty_like(freq)
|
| 394 |
+
|
| 395 |
+
outside_low_high_freq = torch.lt(freq, low_freq) | torch.gt(freq, high_freq) # freq < low_freq || freq > high_freq
|
| 396 |
+
before_l = torch.lt(freq, l) # freq < l
|
| 397 |
+
before_h = torch.lt(freq, h) # freq < h
|
| 398 |
+
after_h = torch.ge(freq, h) # freq >= h
|
| 399 |
+
|
| 400 |
+
# order of operations matter here (since there is overlapping frequency regions)
|
| 401 |
+
res[after_h] = high_freq + scale_right * (freq[after_h] - high_freq)
|
| 402 |
+
res[before_h] = scale * freq[before_h]
|
| 403 |
+
res[before_l] = low_freq + scale_left * (freq[before_l] - low_freq)
|
| 404 |
+
res[outside_low_high_freq] = freq[outside_low_high_freq]
|
| 405 |
+
|
| 406 |
+
return res
|
| 407 |
+
|
| 408 |
+
|
| 409 |
+
def vtln_warp_mel_freq(
|
| 410 |
+
vtln_low_cutoff: float,
|
| 411 |
+
vtln_high_cutoff: float,
|
| 412 |
+
low_freq,
|
| 413 |
+
high_freq: float,
|
| 414 |
+
vtln_warp_factor: float,
|
| 415 |
+
mel_freq: Tensor,
|
| 416 |
+
) -> Tensor:
|
| 417 |
+
r"""
|
| 418 |
+
Args:
|
| 419 |
+
vtln_low_cutoff (float): Lower frequency cutoffs for VTLN
|
| 420 |
+
vtln_high_cutoff (float): Upper frequency cutoffs for VTLN
|
| 421 |
+
low_freq (float): Lower frequency cutoffs in mel computation
|
| 422 |
+
high_freq (float): Upper frequency cutoffs in mel computation
|
| 423 |
+
vtln_warp_factor (float): Vtln warp factor
|
| 424 |
+
mel_freq (Tensor): Given frequency in Mel
|
| 425 |
+
|
| 426 |
+
Returns:
|
| 427 |
+
Tensor: ``mel_freq`` after vtln warp
|
| 428 |
+
"""
|
| 429 |
+
return mel_scale(
|
| 430 |
+
vtln_warp_freq(
|
| 431 |
+
vtln_low_cutoff, vtln_high_cutoff, low_freq, high_freq, vtln_warp_factor, inverse_mel_scale(mel_freq)
|
| 432 |
+
)
|
| 433 |
+
)
|
| 434 |
+
|
| 435 |
+
|
| 436 |
+
def get_mel_banks(
|
| 437 |
+
num_bins: int,
|
| 438 |
+
window_length_padded: int,
|
| 439 |
+
sample_freq: float,
|
| 440 |
+
low_freq: float,
|
| 441 |
+
high_freq: float,
|
| 442 |
+
vtln_low: float,
|
| 443 |
+
vtln_high: float,
|
| 444 |
+
vtln_warp_factor: float,
|
| 445 |
+
) -> Tuple[Tensor, Tensor]:
|
| 446 |
+
"""
|
| 447 |
+
Returns:
|
| 448 |
+
(Tensor, Tensor): The tuple consists of ``bins`` (which is
|
| 449 |
+
melbank of size (``num_bins``, ``num_fft_bins``)) and ``center_freqs`` (which is
|
| 450 |
+
center frequencies of bins of size (``num_bins``)).
|
| 451 |
+
"""
|
| 452 |
+
assert num_bins > 3, "Must have at least 3 mel bins"
|
| 453 |
+
assert window_length_padded % 2 == 0
|
| 454 |
+
num_fft_bins = window_length_padded / 2
|
| 455 |
+
nyquist = 0.5 * sample_freq
|
| 456 |
+
|
| 457 |
+
if high_freq <= 0.0:
|
| 458 |
+
high_freq += nyquist
|
| 459 |
+
|
| 460 |
+
assert (
|
| 461 |
+
(0.0 <= low_freq < nyquist) and (0.0 < high_freq <= nyquist) and (low_freq < high_freq)
|
| 462 |
+
), "Bad values in options: low-freq {} and high-freq {} vs. nyquist {}".format(low_freq, high_freq, nyquist)
|
| 463 |
+
|
| 464 |
+
# fft-bin width [think of it as Nyquist-freq / half-window-length]
|
| 465 |
+
fft_bin_width = sample_freq / window_length_padded
|
| 466 |
+
mel_low_freq = mel_scale_scalar(low_freq)
|
| 467 |
+
mel_high_freq = mel_scale_scalar(high_freq)
|
| 468 |
+
|
| 469 |
+
# divide by num_bins+1 in next line because of end-effects where the bins
|
| 470 |
+
# spread out to the sides.
|
| 471 |
+
mel_freq_delta = (mel_high_freq - mel_low_freq) / (num_bins + 1)
|
| 472 |
+
|
| 473 |
+
if vtln_high < 0.0:
|
| 474 |
+
vtln_high += nyquist
|
| 475 |
+
|
| 476 |
+
assert vtln_warp_factor == 1.0 or (
|
| 477 |
+
(low_freq < vtln_low < high_freq) and (0.0 < vtln_high < high_freq) and (vtln_low < vtln_high)
|
| 478 |
+
), "Bad values in options: vtln-low {} and vtln-high {}, versus " "low-freq {} and high-freq {}".format(
|
| 479 |
+
vtln_low, vtln_high, low_freq, high_freq
|
| 480 |
+
)
|
| 481 |
+
|
| 482 |
+
bin = torch.arange(num_bins).unsqueeze(1)
|
| 483 |
+
left_mel = mel_low_freq + bin * mel_freq_delta # size(num_bins, 1)
|
| 484 |
+
center_mel = mel_low_freq + (bin + 1.0) * mel_freq_delta # size(num_bins, 1)
|
| 485 |
+
right_mel = mel_low_freq + (bin + 2.0) * mel_freq_delta # size(num_bins, 1)
|
| 486 |
+
|
| 487 |
+
if vtln_warp_factor != 1.0:
|
| 488 |
+
left_mel = vtln_warp_mel_freq(vtln_low, vtln_high, low_freq, high_freq, vtln_warp_factor, left_mel)
|
| 489 |
+
center_mel = vtln_warp_mel_freq(vtln_low, vtln_high, low_freq, high_freq, vtln_warp_factor, center_mel)
|
| 490 |
+
right_mel = vtln_warp_mel_freq(vtln_low, vtln_high, low_freq, high_freq, vtln_warp_factor, right_mel)
|
| 491 |
+
|
| 492 |
+
center_freqs = inverse_mel_scale(center_mel) # size (num_bins)
|
| 493 |
+
# size(1, num_fft_bins)
|
| 494 |
+
mel = mel_scale(fft_bin_width * torch.arange(num_fft_bins)).unsqueeze(0)
|
| 495 |
+
|
| 496 |
+
# size (num_bins, num_fft_bins)
|
| 497 |
+
up_slope = (mel - left_mel) / (center_mel - left_mel)
|
| 498 |
+
down_slope = (right_mel - mel) / (right_mel - center_mel)
|
| 499 |
+
|
| 500 |
+
if vtln_warp_factor == 1.0:
|
| 501 |
+
# left_mel < center_mel < right_mel so we can min the two slopes and clamp negative values
|
| 502 |
+
bins = torch.max(torch.zeros(1), torch.min(up_slope, down_slope))
|
| 503 |
+
else:
|
| 504 |
+
# warping can move the order of left_mel, center_mel, right_mel anywhere
|
| 505 |
+
bins = torch.zeros_like(up_slope)
|
| 506 |
+
up_idx = torch.gt(mel, left_mel) & torch.le(mel, center_mel) # left_mel < mel <= center_mel
|
| 507 |
+
down_idx = torch.gt(mel, center_mel) & torch.lt(mel, right_mel) # center_mel < mel < right_mel
|
| 508 |
+
bins[up_idx] = up_slope[up_idx]
|
| 509 |
+
bins[down_idx] = down_slope[down_idx]
|
| 510 |
+
|
| 511 |
+
return bins, center_freqs
|
| 512 |
+
|
| 513 |
+
|
| 514 |
+
def fbank(
|
| 515 |
+
waveform: Tensor,
|
| 516 |
+
blackman_coeff: float = 0.42,
|
| 517 |
+
channel: int = -1,
|
| 518 |
+
dither: float = 0.0,
|
| 519 |
+
energy_floor: float = 1.0,
|
| 520 |
+
frame_length: float = 25.0,
|
| 521 |
+
frame_shift: float = 10.0,
|
| 522 |
+
high_freq: float = 0.0,
|
| 523 |
+
htk_compat: bool = False,
|
| 524 |
+
low_freq: float = 20.0,
|
| 525 |
+
min_duration: float = 0.0,
|
| 526 |
+
num_mel_bins: int = 23,
|
| 527 |
+
preemphasis_coefficient: float = 0.97,
|
| 528 |
+
raw_energy: bool = True,
|
| 529 |
+
remove_dc_offset: bool = True,
|
| 530 |
+
round_to_power_of_two: bool = True,
|
| 531 |
+
sample_frequency: float = 16000.0,
|
| 532 |
+
snip_edges: bool = True,
|
| 533 |
+
subtract_mean: bool = False,
|
| 534 |
+
use_energy: bool = False,
|
| 535 |
+
use_log_fbank: bool = True,
|
| 536 |
+
use_power: bool = True,
|
| 537 |
+
vtln_high: float = -500.0,
|
| 538 |
+
vtln_low: float = 100.0,
|
| 539 |
+
vtln_warp: float = 1.0,
|
| 540 |
+
window_type: str = POVEY,
|
| 541 |
+
) -> Tensor:
|
| 542 |
+
r"""Create a fbank from a raw audio signal. This matches the input/output of Kaldi's
|
| 543 |
+
compute-fbank-feats.
|
| 544 |
+
|
| 545 |
+
Args:
|
| 546 |
+
waveform (Tensor): Tensor of audio of size (c, n) where c is in the range [0,2)
|
| 547 |
+
blackman_coeff (float, optional): Constant coefficient for generalized Blackman window. (Default: ``0.42``)
|
| 548 |
+
channel (int, optional): Channel to extract (-1 -> expect mono, 0 -> left, 1 -> right) (Default: ``-1``)
|
| 549 |
+
dither (float, optional): Dithering constant (0.0 means no dither). If you turn this off, you should set
|
| 550 |
+
the energy_floor option, e.g. to 1.0 or 0.1 (Default: ``0.0``)
|
| 551 |
+
energy_floor (float, optional): Floor on energy (absolute, not relative) in Spectrogram computation. Caution:
|
| 552 |
+
this floor is applied to the zeroth component, representing the total signal energy. The floor on the
|
| 553 |
+
individual spectrogram elements is fixed at std::numeric_limits<float>::epsilon(). (Default: ``1.0``)
|
| 554 |
+
frame_length (float, optional): Frame length in milliseconds (Default: ``25.0``)
|
| 555 |
+
frame_shift (float, optional): Frame shift in milliseconds (Default: ``10.0``)
|
| 556 |
+
high_freq (float, optional): High cutoff frequency for mel bins (if <= 0, offset from Nyquist)
|
| 557 |
+
(Default: ``0.0``)
|
| 558 |
+
htk_compat (bool, optional): If true, put energy last. Warning: not sufficient to get HTK compatible features
|
| 559 |
+
(need to change other parameters). (Default: ``False``)
|
| 560 |
+
low_freq (float, optional): Low cutoff frequency for mel bins (Default: ``20.0``)
|
| 561 |
+
min_duration (float, optional): Minimum duration of segments to process (in seconds). (Default: ``0.0``)
|
| 562 |
+
num_mel_bins (int, optional): Number of triangular mel-frequency bins (Default: ``23``)
|
| 563 |
+
preemphasis_coefficient (float, optional): Coefficient for use in signal preemphasis (Default: ``0.97``)
|
| 564 |
+
raw_energy (bool, optional): If True, compute energy before preemphasis and windowing (Default: ``True``)
|
| 565 |
+
remove_dc_offset (bool, optional): Subtract mean from waveform on each frame (Default: ``True``)
|
| 566 |
+
round_to_power_of_two (bool, optional): If True, round window size to power of two by zero-padding input
|
| 567 |
+
to FFT. (Default: ``True``)
|
| 568 |
+
sample_frequency (float, optional): Waveform data sample frequency (must match the waveform file, if
|
| 569 |
+
specified there) (Default: ``16000.0``)
|
| 570 |
+
snip_edges (bool, optional): If True, end effects will be handled by outputting only frames that completely fit
|
| 571 |
+
in the file, and the number of frames depends on the frame_length. If False, the number of frames
|
| 572 |
+
depends only on the frame_shift, and we reflect the data at the ends. (Default: ``True``)
|
| 573 |
+
subtract_mean (bool, optional): Subtract mean of each feature file [CMS]; not recommended to do
|
| 574 |
+
it this way. (Default: ``False``)
|
| 575 |
+
use_energy (bool, optional): Add an extra dimension with energy to the FBANK output. (Default: ``False``)
|
| 576 |
+
use_log_fbank (bool, optional):If true, produce log-filterbank, else produce linear. (Default: ``True``)
|
| 577 |
+
use_power (bool, optional): If true, use power, else use magnitude. (Default: ``True``)
|
| 578 |
+
vtln_high (float, optional): High inflection point in piecewise linear VTLN warping function (if
|
| 579 |
+
negative, offset from high-mel-freq (Default: ``-500.0``)
|
| 580 |
+
vtln_low (float, optional): Low inflection point in piecewise linear VTLN warping function (Default: ``100.0``)
|
| 581 |
+
vtln_warp (float, optional): Vtln warp factor (only applicable if vtln_map not specified) (Default: ``1.0``)
|
| 582 |
+
window_type (str, optional): Type of window ('hamming'|'hanning'|'povey'|'rectangular'|'blackman')
|
| 583 |
+
(Default: ``'povey'``)
|
| 584 |
+
|
| 585 |
+
Returns:
|
| 586 |
+
Tensor: A fbank identical to what Kaldi would output. The shape is (m, ``num_mel_bins + use_energy``)
|
| 587 |
+
where m is calculated in _get_strided
|
| 588 |
+
"""
|
| 589 |
+
device, dtype = waveform.device, waveform.dtype
|
| 590 |
+
|
| 591 |
+
waveform, window_shift, window_size, padded_window_size = _get_waveform_and_window_properties(
|
| 592 |
+
waveform, channel, sample_frequency, frame_shift, frame_length, round_to_power_of_two, preemphasis_coefficient
|
| 593 |
+
)
|
| 594 |
+
|
| 595 |
+
if len(waveform) < min_duration * sample_frequency:
|
| 596 |
+
# signal is too short
|
| 597 |
+
return torch.empty(0, device=device, dtype=dtype)
|
| 598 |
+
|
| 599 |
+
# strided_input, size (m, padded_window_size) and signal_log_energy, size (m)
|
| 600 |
+
strided_input, signal_log_energy = _get_window(
|
| 601 |
+
waveform,
|
| 602 |
+
padded_window_size,
|
| 603 |
+
window_size,
|
| 604 |
+
window_shift,
|
| 605 |
+
window_type,
|
| 606 |
+
blackman_coeff,
|
| 607 |
+
snip_edges,
|
| 608 |
+
raw_energy,
|
| 609 |
+
energy_floor,
|
| 610 |
+
dither,
|
| 611 |
+
remove_dc_offset,
|
| 612 |
+
preemphasis_coefficient,
|
| 613 |
+
)
|
| 614 |
+
|
| 615 |
+
# size (m, padded_window_size // 2 + 1)
|
| 616 |
+
spectrum = torch.fft.rfft(strided_input).abs()
|
| 617 |
+
if use_power:
|
| 618 |
+
spectrum = spectrum.pow(2.0)
|
| 619 |
+
|
| 620 |
+
# size (num_mel_bins, padded_window_size // 2)
|
| 621 |
+
mel_energies, _ = get_mel_banks(
|
| 622 |
+
num_mel_bins, padded_window_size, sample_frequency, low_freq, high_freq, vtln_low, vtln_high, vtln_warp
|
| 623 |
+
)
|
| 624 |
+
mel_energies = mel_energies.to(device=device, dtype=dtype)
|
| 625 |
+
|
| 626 |
+
# pad right column with zeros and add dimension, size (num_mel_bins, padded_window_size // 2 + 1)
|
| 627 |
+
mel_energies = torch.nn.functional.pad(mel_energies, (0, 1), mode="constant", value=0)
|
| 628 |
+
|
| 629 |
+
# sum with mel fiterbanks over the power spectrum, size (m, num_mel_bins)
|
| 630 |
+
mel_energies = torch.mm(spectrum, mel_energies.T)
|
| 631 |
+
if use_log_fbank:
|
| 632 |
+
# avoid log of zero (which should be prevented anyway by dithering)
|
| 633 |
+
mel_energies = torch.max(mel_energies, _get_epsilon(device, dtype)).log()
|
| 634 |
+
|
| 635 |
+
# if use_energy then add it as the last column for htk_compat == true else first column
|
| 636 |
+
if use_energy:
|
| 637 |
+
signal_log_energy = signal_log_energy.unsqueeze(1) # size (m, 1)
|
| 638 |
+
# returns size (m, num_mel_bins + 1)
|
| 639 |
+
if htk_compat:
|
| 640 |
+
mel_energies = torch.cat((mel_energies, signal_log_energy), dim=1)
|
| 641 |
+
else:
|
| 642 |
+
mel_energies = torch.cat((signal_log_energy, mel_energies), dim=1)
|
| 643 |
+
|
| 644 |
+
mel_energies = _subtract_column_mean(mel_energies, subtract_mean)
|
| 645 |
+
return mel_energies
|
| 646 |
+
|
| 647 |
+
|
| 648 |
+
def _get_dct_matrix(num_ceps: int, num_mel_bins: int) -> Tensor:
|
| 649 |
+
# returns a dct matrix of size (num_mel_bins, num_ceps)
|
| 650 |
+
# size (num_mel_bins, num_mel_bins)
|
| 651 |
+
dct_matrix = torchaudio.functional.create_dct(num_mel_bins, num_mel_bins, "ortho")
|
| 652 |
+
# kaldi expects the first cepstral to be weighted sum of factor sqrt(1/num_mel_bins)
|
| 653 |
+
# this would be the first column in the dct_matrix for torchaudio as it expects a
|
| 654 |
+
# right multiply (which would be the first column of the kaldi's dct_matrix as kaldi
|
| 655 |
+
# expects a left multiply e.g. dct_matrix * vector).
|
| 656 |
+
dct_matrix[:, 0] = math.sqrt(1 / float(num_mel_bins))
|
| 657 |
+
dct_matrix = dct_matrix[:, :num_ceps]
|
| 658 |
+
return dct_matrix
|
| 659 |
+
|
| 660 |
+
|
| 661 |
+
def _get_lifter_coeffs(num_ceps: int, cepstral_lifter: float) -> Tensor:
|
| 662 |
+
# returns size (num_ceps)
|
| 663 |
+
# Compute liftering coefficients (scaling on cepstral coeffs)
|
| 664 |
+
# coeffs are numbered slightly differently from HTK: the zeroth index is C0, which is not affected.
|
| 665 |
+
i = torch.arange(num_ceps)
|
| 666 |
+
return 1.0 + 0.5 * cepstral_lifter * torch.sin(math.pi * i / cepstral_lifter)
|
| 667 |
+
|
| 668 |
+
|
| 669 |
+
def mfcc(
|
| 670 |
+
waveform: Tensor,
|
| 671 |
+
blackman_coeff: float = 0.42,
|
| 672 |
+
cepstral_lifter: float = 22.0,
|
| 673 |
+
channel: int = -1,
|
| 674 |
+
dither: float = 0.0,
|
| 675 |
+
energy_floor: float = 1.0,
|
| 676 |
+
frame_length: float = 25.0,
|
| 677 |
+
frame_shift: float = 10.0,
|
| 678 |
+
high_freq: float = 0.0,
|
| 679 |
+
htk_compat: bool = False,
|
| 680 |
+
low_freq: float = 20.0,
|
| 681 |
+
num_ceps: int = 13,
|
| 682 |
+
min_duration: float = 0.0,
|
| 683 |
+
num_mel_bins: int = 23,
|
| 684 |
+
preemphasis_coefficient: float = 0.97,
|
| 685 |
+
raw_energy: bool = True,
|
| 686 |
+
remove_dc_offset: bool = True,
|
| 687 |
+
round_to_power_of_two: bool = True,
|
| 688 |
+
sample_frequency: float = 16000.0,
|
| 689 |
+
snip_edges: bool = True,
|
| 690 |
+
subtract_mean: bool = False,
|
| 691 |
+
use_energy: bool = False,
|
| 692 |
+
vtln_high: float = -500.0,
|
| 693 |
+
vtln_low: float = 100.0,
|
| 694 |
+
vtln_warp: float = 1.0,
|
| 695 |
+
window_type: str = POVEY,
|
| 696 |
+
) -> Tensor:
|
| 697 |
+
r"""Create a mfcc from a raw audio signal. This matches the input/output of Kaldi's
|
| 698 |
+
compute-mfcc-feats.
|
| 699 |
+
|
| 700 |
+
Args:
|
| 701 |
+
waveform (Tensor): Tensor of audio of size (c, n) where c is in the range [0,2)
|
| 702 |
+
blackman_coeff (float, optional): Constant coefficient for generalized Blackman window. (Default: ``0.42``)
|
| 703 |
+
cepstral_lifter (float, optional): Constant that controls scaling of MFCCs (Default: ``22.0``)
|
| 704 |
+
channel (int, optional): Channel to extract (-1 -> expect mono, 0 -> left, 1 -> right) (Default: ``-1``)
|
| 705 |
+
dither (float, optional): Dithering constant (0.0 means no dither). If you turn this off, you should set
|
| 706 |
+
the energy_floor option, e.g. to 1.0 or 0.1 (Default: ``0.0``)
|
| 707 |
+
energy_floor (float, optional): Floor on energy (absolute, not relative) in Spectrogram computation. Caution:
|
| 708 |
+
this floor is applied to the zeroth component, representing the total signal energy. The floor on the
|
| 709 |
+
individual spectrogram elements is fixed at std::numeric_limits<float>::epsilon(). (Default: ``1.0``)
|
| 710 |
+
frame_length (float, optional): Frame length in milliseconds (Default: ``25.0``)
|
| 711 |
+
frame_shift (float, optional): Frame shift in milliseconds (Default: ``10.0``)
|
| 712 |
+
high_freq (float, optional): High cutoff frequency for mel bins (if <= 0, offset from Nyquist)
|
| 713 |
+
(Default: ``0.0``)
|
| 714 |
+
htk_compat (bool, optional): If true, put energy last. Warning: not sufficient to get HTK compatible
|
| 715 |
+
features (need to change other parameters). (Default: ``False``)
|
| 716 |
+
low_freq (float, optional): Low cutoff frequency for mel bins (Default: ``20.0``)
|
| 717 |
+
num_ceps (int, optional): Number of cepstra in MFCC computation (including C0) (Default: ``13``)
|
| 718 |
+
min_duration (float, optional): Minimum duration of segments to process (in seconds). (Default: ``0.0``)
|
| 719 |
+
num_mel_bins (int, optional): Number of triangular mel-frequency bins (Default: ``23``)
|
| 720 |
+
preemphasis_coefficient (float, optional): Coefficient for use in signal preemphasis (Default: ``0.97``)
|
| 721 |
+
raw_energy (bool, optional): If True, compute energy before preemphasis and windowing (Default: ``True``)
|
| 722 |
+
remove_dc_offset (bool, optional): Subtract mean from waveform on each frame (Default: ``True``)
|
| 723 |
+
round_to_power_of_two (bool, optional): If True, round window size to power of two by zero-padding input
|
| 724 |
+
to FFT. (Default: ``True``)
|
| 725 |
+
sample_frequency (float, optional): Waveform data sample frequency (must match the waveform file, if
|
| 726 |
+
specified there) (Default: ``16000.0``)
|
| 727 |
+
snip_edges (bool, optional): If True, end effects will be handled by outputting only frames that completely fit
|
| 728 |
+
in the file, and the number of frames depends on the frame_length. If False, the number of frames
|
| 729 |
+
depends only on the frame_shift, and we reflect the data at the ends. (Default: ``True``)
|
| 730 |
+
subtract_mean (bool, optional): Subtract mean of each feature file [CMS]; not recommended to do
|
| 731 |
+
it this way. (Default: ``False``)
|
| 732 |
+
use_energy (bool, optional): Add an extra dimension with energy to the FBANK output. (Default: ``False``)
|
| 733 |
+
vtln_high (float, optional): High inflection point in piecewise linear VTLN warping function (if
|
| 734 |
+
negative, offset from high-mel-freq (Default: ``-500.0``)
|
| 735 |
+
vtln_low (float, optional): Low inflection point in piecewise linear VTLN warping function (Default: ``100.0``)
|
| 736 |
+
vtln_warp (float, optional): Vtln warp factor (only applicable if vtln_map not specified) (Default: ``1.0``)
|
| 737 |
+
window_type (str, optional): Type of window ('hamming'|'hanning'|'povey'|'rectangular'|'blackman')
|
| 738 |
+
(Default: ``"povey"``)
|
| 739 |
+
|
| 740 |
+
Returns:
|
| 741 |
+
Tensor: A mfcc identical to what Kaldi would output. The shape is (m, ``num_ceps``)
|
| 742 |
+
where m is calculated in _get_strided
|
| 743 |
+
"""
|
| 744 |
+
assert num_ceps <= num_mel_bins, "num_ceps cannot be larger than num_mel_bins: %d vs %d" % (num_ceps, num_mel_bins)
|
| 745 |
+
|
| 746 |
+
device, dtype = waveform.device, waveform.dtype
|
| 747 |
+
|
| 748 |
+
# The mel_energies should not be squared (use_power=True), not have mean subtracted
|
| 749 |
+
# (subtract_mean=False), and use log (use_log_fbank=True).
|
| 750 |
+
# size (m, num_mel_bins + use_energy)
|
| 751 |
+
feature = fbank(
|
| 752 |
+
waveform=waveform,
|
| 753 |
+
blackman_coeff=blackman_coeff,
|
| 754 |
+
channel=channel,
|
| 755 |
+
dither=dither,
|
| 756 |
+
energy_floor=energy_floor,
|
| 757 |
+
frame_length=frame_length,
|
| 758 |
+
frame_shift=frame_shift,
|
| 759 |
+
high_freq=high_freq,
|
| 760 |
+
htk_compat=htk_compat,
|
| 761 |
+
low_freq=low_freq,
|
| 762 |
+
min_duration=min_duration,
|
| 763 |
+
num_mel_bins=num_mel_bins,
|
| 764 |
+
preemphasis_coefficient=preemphasis_coefficient,
|
| 765 |
+
raw_energy=raw_energy,
|
| 766 |
+
remove_dc_offset=remove_dc_offset,
|
| 767 |
+
round_to_power_of_two=round_to_power_of_two,
|
| 768 |
+
sample_frequency=sample_frequency,
|
| 769 |
+
snip_edges=snip_edges,
|
| 770 |
+
subtract_mean=False,
|
| 771 |
+
use_energy=use_energy,
|
| 772 |
+
use_log_fbank=True,
|
| 773 |
+
use_power=True,
|
| 774 |
+
vtln_high=vtln_high,
|
| 775 |
+
vtln_low=vtln_low,
|
| 776 |
+
vtln_warp=vtln_warp,
|
| 777 |
+
window_type=window_type,
|
| 778 |
+
)
|
| 779 |
+
|
| 780 |
+
if use_energy:
|
| 781 |
+
# size (m)
|
| 782 |
+
signal_log_energy = feature[:, num_mel_bins if htk_compat else 0]
|
| 783 |
+
# offset is 0 if htk_compat==True else 1
|
| 784 |
+
mel_offset = int(not htk_compat)
|
| 785 |
+
feature = feature[:, mel_offset : (num_mel_bins + mel_offset)]
|
| 786 |
+
|
| 787 |
+
# size (num_mel_bins, num_ceps)
|
| 788 |
+
dct_matrix = _get_dct_matrix(num_ceps, num_mel_bins).to(dtype=dtype, device=device)
|
| 789 |
+
|
| 790 |
+
# size (m, num_ceps)
|
| 791 |
+
feature = feature.matmul(dct_matrix)
|
| 792 |
+
|
| 793 |
+
if cepstral_lifter != 0.0:
|
| 794 |
+
# size (1, num_ceps)
|
| 795 |
+
lifter_coeffs = _get_lifter_coeffs(num_ceps, cepstral_lifter).unsqueeze(0)
|
| 796 |
+
feature *= lifter_coeffs.to(device=device, dtype=dtype)
|
| 797 |
+
|
| 798 |
+
# if use_energy then replace the last column for htk_compat == true else first column
|
| 799 |
+
if use_energy:
|
| 800 |
+
feature[:, 0] = signal_log_energy
|
| 801 |
+
|
| 802 |
+
if htk_compat:
|
| 803 |
+
energy = feature[:, 0].unsqueeze(1) # size (m, 1)
|
| 804 |
+
feature = feature[:, 1:] # size (m, num_ceps - 1)
|
| 805 |
+
if not use_energy:
|
| 806 |
+
# scale on C0 (actually removing a scale we previously added that's
|
| 807 |
+
# part of one common definition of the cosine transform.)
|
| 808 |
+
energy *= math.sqrt(2)
|
| 809 |
+
|
| 810 |
+
feature = torch.cat((feature, energy), dim=1)
|
| 811 |
+
|
| 812 |
+
feature = _subtract_column_mean(feature, subtract_mean)
|
| 813 |
+
return feature
|
micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/datasets/__init__.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .cmuarctic import CMUARCTIC
|
| 2 |
+
from .cmudict import CMUDict
|
| 3 |
+
from .commonvoice import COMMONVOICE
|
| 4 |
+
from .dr_vctk import DR_VCTK
|
| 5 |
+
from .fluentcommands import FluentSpeechCommands
|
| 6 |
+
from .gtzan import GTZAN
|
| 7 |
+
from .iemocap import IEMOCAP
|
| 8 |
+
from .librilight_limited import LibriLightLimited
|
| 9 |
+
from .librimix import LibriMix
|
| 10 |
+
from .librispeech import LIBRISPEECH
|
| 11 |
+
from .librispeech_biasing import LibriSpeechBiasing
|
| 12 |
+
from .libritts import LIBRITTS
|
| 13 |
+
from .ljspeech import LJSPEECH
|
| 14 |
+
from .musdb_hq import MUSDB_HQ
|
| 15 |
+
from .quesst14 import QUESST14
|
| 16 |
+
from .snips import Snips
|
| 17 |
+
from .speechcommands import SPEECHCOMMANDS
|
| 18 |
+
from .tedlium import TEDLIUM
|
| 19 |
+
from .vctk import VCTK_092
|
| 20 |
+
from .voxceleb1 import VoxCeleb1Identification, VoxCeleb1Verification
|
| 21 |
+
from .yesno import YESNO
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
__all__ = [
|
| 25 |
+
"COMMONVOICE",
|
| 26 |
+
"LIBRISPEECH",
|
| 27 |
+
"LibriSpeechBiasing",
|
| 28 |
+
"LibriLightLimited",
|
| 29 |
+
"SPEECHCOMMANDS",
|
| 30 |
+
"VCTK_092",
|
| 31 |
+
"DR_VCTK",
|
| 32 |
+
"YESNO",
|
| 33 |
+
"LJSPEECH",
|
| 34 |
+
"GTZAN",
|
| 35 |
+
"CMUARCTIC",
|
| 36 |
+
"CMUDict",
|
| 37 |
+
"LibriMix",
|
| 38 |
+
"LIBRITTS",
|
| 39 |
+
"TEDLIUM",
|
| 40 |
+
"QUESST14",
|
| 41 |
+
"MUSDB_HQ",
|
| 42 |
+
"FluentSpeechCommands",
|
| 43 |
+
"VoxCeleb1Identification",
|
| 44 |
+
"VoxCeleb1Verification",
|
| 45 |
+
"IEMOCAP",
|
| 46 |
+
"Snips",
|
| 47 |
+
]
|
micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/datasets/cmuarctic.py
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import csv
|
| 2 |
+
import os
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
from typing import Tuple, Union
|
| 5 |
+
|
| 6 |
+
import torchaudio
|
| 7 |
+
from torch import Tensor
|
| 8 |
+
from torch.utils.data import Dataset
|
| 9 |
+
from torchaudio._internal import download_url_to_file
|
| 10 |
+
from torchaudio.datasets.utils import _extract_tar
|
| 11 |
+
|
| 12 |
+
URL = "aew"
|
| 13 |
+
FOLDER_IN_ARCHIVE = "ARCTIC"
|
| 14 |
+
_CHECKSUMS = {
|
| 15 |
+
"http://festvox.org/cmu_arctic/packed/cmu_us_aew_arctic.tar.bz2": "645cb33c0f0b2ce41384fdd8d3db2c3f5fc15c1e688baeb74d2e08cab18ab406", # noqa: E501
|
| 16 |
+
"http://festvox.org/cmu_arctic/packed/cmu_us_ahw_arctic.tar.bz2": "024664adeb892809d646a3efd043625b46b5bfa3e6189b3500b2d0d59dfab06c", # noqa: E501
|
| 17 |
+
"http://festvox.org/cmu_arctic/packed/cmu_us_aup_arctic.tar.bz2": "2c55bc3050caa996758869126ad10cf42e1441212111db034b3a45189c18b6fc", # noqa: E501
|
| 18 |
+
"http://festvox.org/cmu_arctic/packed/cmu_us_awb_arctic.tar.bz2": "d74a950c9739a65f7bfc4dfa6187f2730fa03de5b8eb3f2da97a51b74df64d3c", # noqa: E501
|
| 19 |
+
"http://festvox.org/cmu_arctic/packed/cmu_us_axb_arctic.tar.bz2": "dd65c3d2907d1ee52f86e44f578319159e60f4bf722a9142be01161d84e330ff", # noqa: E501
|
| 20 |
+
"http://festvox.org/cmu_arctic/packed/cmu_us_bdl_arctic.tar.bz2": "26b91aaf48b2799b2956792b4632c2f926cd0542f402b5452d5adecb60942904", # noqa: E501
|
| 21 |
+
"http://festvox.org/cmu_arctic/packed/cmu_us_clb_arctic.tar.bz2": "3f16dc3f3b97955ea22623efb33b444341013fc660677b2e170efdcc959fa7c6", # noqa: E501
|
| 22 |
+
"http://festvox.org/cmu_arctic/packed/cmu_us_eey_arctic.tar.bz2": "8a0ee4e5acbd4b2f61a4fb947c1730ab3adcc9dc50b195981d99391d29928e8a", # noqa: E501
|
| 23 |
+
"http://festvox.org/cmu_arctic/packed/cmu_us_fem_arctic.tar.bz2": "3fcff629412b57233589cdb058f730594a62c4f3a75c20de14afe06621ef45e2", # noqa: E501
|
| 24 |
+
"http://festvox.org/cmu_arctic/packed/cmu_us_gka_arctic.tar.bz2": "dc82e7967cbd5eddbed33074b0699128dbd4482b41711916d58103707e38c67f", # noqa: E501
|
| 25 |
+
"http://festvox.org/cmu_arctic/packed/cmu_us_jmk_arctic.tar.bz2": "3a37c0e1dfc91e734fdbc88b562d9e2ebca621772402cdc693bbc9b09b211d73", # noqa: E501
|
| 26 |
+
"http://festvox.org/cmu_arctic/packed/cmu_us_ksp_arctic.tar.bz2": "8029cafce8296f9bed3022c44ef1e7953332b6bf6943c14b929f468122532717", # noqa: E501
|
| 27 |
+
"http://festvox.org/cmu_arctic/packed/cmu_us_ljm_arctic.tar.bz2": "b23993765cbf2b9e7bbc3c85b6c56eaf292ac81ee4bb887b638a24d104f921a0", # noqa: E501
|
| 28 |
+
"http://festvox.org/cmu_arctic/packed/cmu_us_lnh_arctic.tar.bz2": "4faf34d71aa7112813252fb20c5433e2fdd9a9de55a00701ffcbf05f24a5991a", # noqa: E501
|
| 29 |
+
"http://festvox.org/cmu_arctic/packed/cmu_us_rms_arctic.tar.bz2": "c6dc11235629c58441c071a7ba8a2d067903dfefbaabc4056d87da35b72ecda4", # noqa: E501
|
| 30 |
+
"http://festvox.org/cmu_arctic/packed/cmu_us_rxr_arctic.tar.bz2": "1fa4271c393e5998d200e56c102ff46fcfea169aaa2148ad9e9469616fbfdd9b", # noqa: E501
|
| 31 |
+
"http://festvox.org/cmu_arctic/packed/cmu_us_slp_arctic.tar.bz2": "54345ed55e45c23d419e9a823eef427f1cc93c83a710735ec667d068c916abf1", # noqa: E501
|
| 32 |
+
"http://festvox.org/cmu_arctic/packed/cmu_us_slt_arctic.tar.bz2": "7c173297916acf3cc7fcab2713be4c60b27312316765a90934651d367226b4ea", # noqa: E501
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def load_cmuarctic_item(line: str, path: str, folder_audio: str, ext_audio: str) -> Tuple[Tensor, int, str, str]:
|
| 37 |
+
|
| 38 |
+
utterance_id, transcript = line[0].strip().split(" ", 2)[1:]
|
| 39 |
+
|
| 40 |
+
# Remove space, double quote, and single parenthesis from transcript
|
| 41 |
+
transcript = transcript[1:-3]
|
| 42 |
+
|
| 43 |
+
file_audio = os.path.join(path, folder_audio, utterance_id + ext_audio)
|
| 44 |
+
|
| 45 |
+
# Load audio
|
| 46 |
+
waveform, sample_rate = torchaudio.load(file_audio)
|
| 47 |
+
|
| 48 |
+
return (waveform, sample_rate, transcript, utterance_id.split("_")[1])
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class CMUARCTIC(Dataset):
|
| 52 |
+
"""*CMU ARCTIC* :cite:`Kominek03cmuarctic` dataset.
|
| 53 |
+
|
| 54 |
+
Args:
|
| 55 |
+
root (str or Path): Path to the directory where the dataset is found or downloaded.
|
| 56 |
+
url (str, optional):
|
| 57 |
+
The URL to download the dataset from or the type of the dataset to download.
|
| 58 |
+
(default: ``"aew"``)
|
| 59 |
+
Allowed type values are ``"aew"``, ``"ahw"``, ``"aup"``, ``"awb"``, ``"axb"``, ``"bdl"``,
|
| 60 |
+
``"clb"``, ``"eey"``, ``"fem"``, ``"gka"``, ``"jmk"``, ``"ksp"``, ``"ljm"``, ``"lnh"``,
|
| 61 |
+
``"rms"``, ``"rxr"``, ``"slp"`` or ``"slt"``.
|
| 62 |
+
folder_in_archive (str, optional):
|
| 63 |
+
The top-level directory of the dataset. (default: ``"ARCTIC"``)
|
| 64 |
+
download (bool, optional):
|
| 65 |
+
Whether to download the dataset if it is not found at root path. (default: ``False``).
|
| 66 |
+
"""
|
| 67 |
+
|
| 68 |
+
_file_text = "txt.done.data"
|
| 69 |
+
_folder_text = "etc"
|
| 70 |
+
_ext_audio = ".wav"
|
| 71 |
+
_folder_audio = "wav"
|
| 72 |
+
|
| 73 |
+
def __init__(
|
| 74 |
+
self, root: Union[str, Path], url: str = URL, folder_in_archive: str = FOLDER_IN_ARCHIVE, download: bool = False
|
| 75 |
+
) -> None:
|
| 76 |
+
|
| 77 |
+
if url in [
|
| 78 |
+
"aew",
|
| 79 |
+
"ahw",
|
| 80 |
+
"aup",
|
| 81 |
+
"awb",
|
| 82 |
+
"axb",
|
| 83 |
+
"bdl",
|
| 84 |
+
"clb",
|
| 85 |
+
"eey",
|
| 86 |
+
"fem",
|
| 87 |
+
"gka",
|
| 88 |
+
"jmk",
|
| 89 |
+
"ksp",
|
| 90 |
+
"ljm",
|
| 91 |
+
"lnh",
|
| 92 |
+
"rms",
|
| 93 |
+
"rxr",
|
| 94 |
+
"slp",
|
| 95 |
+
"slt",
|
| 96 |
+
]:
|
| 97 |
+
|
| 98 |
+
url = "cmu_us_" + url + "_arctic"
|
| 99 |
+
ext_archive = ".tar.bz2"
|
| 100 |
+
base_url = "http://www.festvox.org/cmu_arctic/packed/"
|
| 101 |
+
|
| 102 |
+
url = os.path.join(base_url, url + ext_archive)
|
| 103 |
+
|
| 104 |
+
# Get string representation of 'root' in case Path object is passed
|
| 105 |
+
root = os.fspath(root)
|
| 106 |
+
|
| 107 |
+
basename = os.path.basename(url)
|
| 108 |
+
root = os.path.join(root, folder_in_archive)
|
| 109 |
+
if not os.path.isdir(root):
|
| 110 |
+
os.mkdir(root)
|
| 111 |
+
archive = os.path.join(root, basename)
|
| 112 |
+
|
| 113 |
+
basename = basename.split(".")[0]
|
| 114 |
+
|
| 115 |
+
self._path = os.path.join(root, basename)
|
| 116 |
+
|
| 117 |
+
if download:
|
| 118 |
+
if not os.path.isdir(self._path):
|
| 119 |
+
if not os.path.isfile(archive):
|
| 120 |
+
checksum = _CHECKSUMS.get(url, None)
|
| 121 |
+
download_url_to_file(url, archive, hash_prefix=checksum)
|
| 122 |
+
_extract_tar(archive)
|
| 123 |
+
else:
|
| 124 |
+
if not os.path.exists(self._path):
|
| 125 |
+
raise RuntimeError(
|
| 126 |
+
f"The path {self._path} doesn't exist. "
|
| 127 |
+
"Please check the ``root`` path or set `download=True` to download it"
|
| 128 |
+
)
|
| 129 |
+
self._text = os.path.join(self._path, self._folder_text, self._file_text)
|
| 130 |
+
|
| 131 |
+
with open(self._text, "r") as text:
|
| 132 |
+
walker = csv.reader(text, delimiter="\n")
|
| 133 |
+
self._walker = list(walker)
|
| 134 |
+
|
| 135 |
+
def __getitem__(self, n: int) -> Tuple[Tensor, int, str, str]:
|
| 136 |
+
"""Load the n-th sample from the dataset.
|
| 137 |
+
|
| 138 |
+
Args:
|
| 139 |
+
n (int): The index of the sample to be loaded
|
| 140 |
+
|
| 141 |
+
Returns:
|
| 142 |
+
Tuple of the following items;
|
| 143 |
+
|
| 144 |
+
Tensor:
|
| 145 |
+
Waveform
|
| 146 |
+
int:
|
| 147 |
+
Sample rate
|
| 148 |
+
str:
|
| 149 |
+
Transcript
|
| 150 |
+
str:
|
| 151 |
+
Utterance ID
|
| 152 |
+
"""
|
| 153 |
+
line = self._walker[n]
|
| 154 |
+
return load_cmuarctic_item(line, self._path, self._folder_audio, self._ext_audio)
|
| 155 |
+
|
| 156 |
+
def __len__(self) -> int:
|
| 157 |
+
return len(self._walker)
|
micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/datasets/cmudict.py
ADDED
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import re
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
from typing import Iterable, List, Tuple, Union
|
| 5 |
+
|
| 6 |
+
from torch.utils.data import Dataset
|
| 7 |
+
from torchaudio._internal import download_url_to_file
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
_CHECKSUMS = {
|
| 11 |
+
"http://svn.code.sf.net/p/cmusphinx/code/trunk/cmudict/cmudict-0.7b": "209a8b4cd265013e96f4658632a9878103b0c5abf62b50d4ef3ae1be226b29e4", # noqa: E501
|
| 12 |
+
"http://svn.code.sf.net/p/cmusphinx/code/trunk/cmudict/cmudict-0.7b.symbols": "408ccaae803641c6d7b626b6299949320c2dbca96b2220fd3fb17887b023b027", # noqa: E501
|
| 13 |
+
}
|
| 14 |
+
_PUNCTUATIONS = {
|
| 15 |
+
"!EXCLAMATION-POINT",
|
| 16 |
+
'"CLOSE-QUOTE',
|
| 17 |
+
'"DOUBLE-QUOTE',
|
| 18 |
+
'"END-OF-QUOTE',
|
| 19 |
+
'"END-QUOTE',
|
| 20 |
+
'"IN-QUOTES',
|
| 21 |
+
'"QUOTE',
|
| 22 |
+
'"UNQUOTE',
|
| 23 |
+
"#HASH-MARK",
|
| 24 |
+
"#POUND-SIGN",
|
| 25 |
+
"#SHARP-SIGN",
|
| 26 |
+
"%PERCENT",
|
| 27 |
+
"&ERSAND",
|
| 28 |
+
"'END-INNER-QUOTE",
|
| 29 |
+
"'END-QUOTE",
|
| 30 |
+
"'INNER-QUOTE",
|
| 31 |
+
"'QUOTE",
|
| 32 |
+
"'SINGLE-QUOTE",
|
| 33 |
+
"(BEGIN-PARENS",
|
| 34 |
+
"(IN-PARENTHESES",
|
| 35 |
+
"(LEFT-PAREN",
|
| 36 |
+
"(OPEN-PARENTHESES",
|
| 37 |
+
"(PAREN",
|
| 38 |
+
"(PARENS",
|
| 39 |
+
"(PARENTHESES",
|
| 40 |
+
")CLOSE-PAREN",
|
| 41 |
+
")CLOSE-PARENTHESES",
|
| 42 |
+
")END-PAREN",
|
| 43 |
+
")END-PARENS",
|
| 44 |
+
")END-PARENTHESES",
|
| 45 |
+
")END-THE-PAREN",
|
| 46 |
+
")PAREN",
|
| 47 |
+
")PARENS",
|
| 48 |
+
")RIGHT-PAREN",
|
| 49 |
+
")UN-PARENTHESES",
|
| 50 |
+
"+PLUS",
|
| 51 |
+
",COMMA",
|
| 52 |
+
"--DASH",
|
| 53 |
+
"-DASH",
|
| 54 |
+
"-HYPHEN",
|
| 55 |
+
"...ELLIPSIS",
|
| 56 |
+
".DECIMAL",
|
| 57 |
+
".DOT",
|
| 58 |
+
".FULL-STOP",
|
| 59 |
+
".PERIOD",
|
| 60 |
+
".POINT",
|
| 61 |
+
"/SLASH",
|
| 62 |
+
":COLON",
|
| 63 |
+
";SEMI-COLON",
|
| 64 |
+
";SEMI-COLON(1)",
|
| 65 |
+
"?QUESTION-MARK",
|
| 66 |
+
"{BRACE",
|
| 67 |
+
"{LEFT-BRACE",
|
| 68 |
+
"{OPEN-BRACE",
|
| 69 |
+
"}CLOSE-BRACE",
|
| 70 |
+
"}RIGHT-BRACE",
|
| 71 |
+
}
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def _parse_dictionary(lines: Iterable[str], exclude_punctuations: bool) -> List[str]:
|
| 75 |
+
_alt_re = re.compile(r"\([0-9]+\)")
|
| 76 |
+
cmudict: List[Tuple[str, List[str]]] = []
|
| 77 |
+
for line in lines:
|
| 78 |
+
if not line or line.startswith(";;;"): # ignore comments
|
| 79 |
+
continue
|
| 80 |
+
|
| 81 |
+
word, phones = line.strip().split(" ")
|
| 82 |
+
if word in _PUNCTUATIONS:
|
| 83 |
+
if exclude_punctuations:
|
| 84 |
+
continue
|
| 85 |
+
# !EXCLAMATION-POINT -> !
|
| 86 |
+
# --DASH -> --
|
| 87 |
+
# ...ELLIPSIS -> ...
|
| 88 |
+
if word.startswith("..."):
|
| 89 |
+
word = "..."
|
| 90 |
+
elif word.startswith("--"):
|
| 91 |
+
word = "--"
|
| 92 |
+
else:
|
| 93 |
+
word = word[0]
|
| 94 |
+
|
| 95 |
+
# if a word have multiple pronunciations, there will be (number) appended to it
|
| 96 |
+
# for example, DATAPOINTS and DATAPOINTS(1),
|
| 97 |
+
# the regular expression `_alt_re` removes the '(1)' and change the word DATAPOINTS(1) to DATAPOINTS
|
| 98 |
+
word = re.sub(_alt_re, "", word)
|
| 99 |
+
phones = phones.split(" ")
|
| 100 |
+
cmudict.append((word, phones))
|
| 101 |
+
|
| 102 |
+
return cmudict
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
class CMUDict(Dataset):
|
| 106 |
+
"""*CMU Pronouncing Dictionary* :cite:`cmudict` (CMUDict) dataset.
|
| 107 |
+
|
| 108 |
+
Args:
|
| 109 |
+
root (str or Path): Path to the directory where the dataset is found or downloaded.
|
| 110 |
+
exclude_punctuations (bool, optional):
|
| 111 |
+
When enabled, exclude the pronounciation of punctuations, such as
|
| 112 |
+
`!EXCLAMATION-POINT` and `#HASH-MARK`.
|
| 113 |
+
download (bool, optional):
|
| 114 |
+
Whether to download the dataset if it is not found at root path. (default: ``False``).
|
| 115 |
+
url (str, optional):
|
| 116 |
+
The URL to download the dictionary from.
|
| 117 |
+
(default: ``"http://svn.code.sf.net/p/cmusphinx/code/trunk/cmudict/cmudict-0.7b"``)
|
| 118 |
+
url_symbols (str, optional):
|
| 119 |
+
The URL to download the list of symbols from.
|
| 120 |
+
(default: ``"http://svn.code.sf.net/p/cmusphinx/code/trunk/cmudict/cmudict-0.7b.symbols"``)
|
| 121 |
+
"""
|
| 122 |
+
|
| 123 |
+
def __init__(
|
| 124 |
+
self,
|
| 125 |
+
root: Union[str, Path],
|
| 126 |
+
exclude_punctuations: bool = True,
|
| 127 |
+
*,
|
| 128 |
+
download: bool = False,
|
| 129 |
+
url: str = "http://svn.code.sf.net/p/cmusphinx/code/trunk/cmudict/cmudict-0.7b",
|
| 130 |
+
url_symbols: str = "http://svn.code.sf.net/p/cmusphinx/code/trunk/cmudict/cmudict-0.7b.symbols",
|
| 131 |
+
) -> None:
|
| 132 |
+
|
| 133 |
+
self.exclude_punctuations = exclude_punctuations
|
| 134 |
+
|
| 135 |
+
self._root_path = Path(root)
|
| 136 |
+
if not os.path.isdir(self._root_path):
|
| 137 |
+
raise RuntimeError(f"The root directory does not exist; {root}")
|
| 138 |
+
|
| 139 |
+
dict_file = self._root_path / os.path.basename(url)
|
| 140 |
+
symbol_file = self._root_path / os.path.basename(url_symbols)
|
| 141 |
+
if not os.path.exists(dict_file):
|
| 142 |
+
if not download:
|
| 143 |
+
raise RuntimeError(
|
| 144 |
+
"The dictionary file is not found in the following location. "
|
| 145 |
+
f"Set `download=True` to download it. {dict_file}"
|
| 146 |
+
)
|
| 147 |
+
checksum = _CHECKSUMS.get(url, None)
|
| 148 |
+
download_url_to_file(url, dict_file, checksum)
|
| 149 |
+
if not os.path.exists(symbol_file):
|
| 150 |
+
if not download:
|
| 151 |
+
raise RuntimeError(
|
| 152 |
+
"The symbol file is not found in the following location. "
|
| 153 |
+
f"Set `download=True` to download it. {symbol_file}"
|
| 154 |
+
)
|
| 155 |
+
checksum = _CHECKSUMS.get(url_symbols, None)
|
| 156 |
+
download_url_to_file(url_symbols, symbol_file, checksum)
|
| 157 |
+
|
| 158 |
+
with open(symbol_file, "r") as text:
|
| 159 |
+
self._symbols = [line.strip() for line in text.readlines()]
|
| 160 |
+
|
| 161 |
+
with open(dict_file, "r", encoding="latin-1") as text:
|
| 162 |
+
self._dictionary = _parse_dictionary(text.readlines(), exclude_punctuations=self.exclude_punctuations)
|
| 163 |
+
|
| 164 |
+
def __getitem__(self, n: int) -> Tuple[str, List[str]]:
|
| 165 |
+
"""Load the n-th sample from the dataset.
|
| 166 |
+
|
| 167 |
+
Args:
|
| 168 |
+
n (int): The index of the sample to be loaded.
|
| 169 |
+
|
| 170 |
+
Returns:
|
| 171 |
+
Tuple of a word and its phonemes
|
| 172 |
+
|
| 173 |
+
str:
|
| 174 |
+
Word
|
| 175 |
+
List[str]:
|
| 176 |
+
Phonemes
|
| 177 |
+
"""
|
| 178 |
+
return self._dictionary[n]
|
| 179 |
+
|
| 180 |
+
def __len__(self) -> int:
|
| 181 |
+
return len(self._dictionary)
|
| 182 |
+
|
| 183 |
+
@property
|
| 184 |
+
def symbols(self) -> List[str]:
|
| 185 |
+
"""list[str]: A list of phonemes symbols, such as ``"AA"``, ``"AE"``, ``"AH"``."""
|
| 186 |
+
return self._symbols.copy()
|
micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/datasets/commonvoice.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import csv
|
| 2 |
+
import os
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
from typing import Dict, List, Tuple, Union
|
| 5 |
+
|
| 6 |
+
import torchaudio
|
| 7 |
+
from torch import Tensor
|
| 8 |
+
from torch.utils.data import Dataset
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def load_commonvoice_item(
|
| 12 |
+
line: List[str], header: List[str], path: str, folder_audio: str, ext_audio: str
|
| 13 |
+
) -> Tuple[Tensor, int, Dict[str, str]]:
|
| 14 |
+
# Each line as the following data:
|
| 15 |
+
# client_id, path, sentence, up_votes, down_votes, age, gender, accent
|
| 16 |
+
|
| 17 |
+
if header[1] != "path":
|
| 18 |
+
raise ValueError(f"expect `header[1]` to be 'path', but got {header[1]}")
|
| 19 |
+
fileid = line[1]
|
| 20 |
+
filename = os.path.join(path, folder_audio, fileid)
|
| 21 |
+
if not filename.endswith(ext_audio):
|
| 22 |
+
filename += ext_audio
|
| 23 |
+
waveform, sample_rate = torchaudio.load(filename)
|
| 24 |
+
|
| 25 |
+
dic = dict(zip(header, line))
|
| 26 |
+
|
| 27 |
+
return waveform, sample_rate, dic
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class COMMONVOICE(Dataset):
|
| 31 |
+
"""*CommonVoice* :cite:`ardila2020common` dataset.
|
| 32 |
+
|
| 33 |
+
Args:
|
| 34 |
+
root (str or Path): Path to the directory where the dataset is located.
|
| 35 |
+
(Where the ``tsv`` file is present.)
|
| 36 |
+
tsv (str, optional):
|
| 37 |
+
The name of the tsv file used to construct the metadata, such as
|
| 38 |
+
``"train.tsv"``, ``"test.tsv"``, ``"dev.tsv"``, ``"invalidated.tsv"``,
|
| 39 |
+
``"validated.tsv"`` and ``"other.tsv"``. (default: ``"train.tsv"``)
|
| 40 |
+
"""
|
| 41 |
+
|
| 42 |
+
_ext_txt = ".txt"
|
| 43 |
+
_ext_audio = ".mp3"
|
| 44 |
+
_folder_audio = "clips"
|
| 45 |
+
|
| 46 |
+
def __init__(self, root: Union[str, Path], tsv: str = "train.tsv") -> None:
|
| 47 |
+
|
| 48 |
+
# Get string representation of 'root' in case Path object is passed
|
| 49 |
+
self._path = os.fspath(root)
|
| 50 |
+
self._tsv = os.path.join(self._path, tsv)
|
| 51 |
+
|
| 52 |
+
with open(self._tsv, "r") as tsv_:
|
| 53 |
+
walker = csv.reader(tsv_, delimiter="\t")
|
| 54 |
+
self._header = next(walker)
|
| 55 |
+
self._walker = list(walker)
|
| 56 |
+
|
| 57 |
+
def __getitem__(self, n: int) -> Tuple[Tensor, int, Dict[str, str]]:
|
| 58 |
+
"""Load the n-th sample from the dataset.
|
| 59 |
+
|
| 60 |
+
Args:
|
| 61 |
+
n (int): The index of the sample to be loaded
|
| 62 |
+
|
| 63 |
+
Returns:
|
| 64 |
+
Tuple of the following items;
|
| 65 |
+
|
| 66 |
+
Tensor:
|
| 67 |
+
Waveform
|
| 68 |
+
int:
|
| 69 |
+
Sample rate
|
| 70 |
+
Dict[str, str]:
|
| 71 |
+
Dictionary containing the following items from the corresponding TSV file;
|
| 72 |
+
|
| 73 |
+
* ``"client_id"``
|
| 74 |
+
* ``"path"``
|
| 75 |
+
* ``"sentence"``
|
| 76 |
+
* ``"up_votes"``
|
| 77 |
+
* ``"down_votes"``
|
| 78 |
+
* ``"age"``
|
| 79 |
+
* ``"gender"``
|
| 80 |
+
* ``"accent"``
|
| 81 |
+
"""
|
| 82 |
+
line = self._walker[n]
|
| 83 |
+
return load_commonvoice_item(line, self._header, self._path, self._folder_audio, self._ext_audio)
|
| 84 |
+
|
| 85 |
+
def __len__(self) -> int:
|
| 86 |
+
return len(self._walker)
|
micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/datasets/dr_vctk.py
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
from typing import Dict, Tuple, Union
|
| 3 |
+
|
| 4 |
+
import torchaudio
|
| 5 |
+
from torch import Tensor
|
| 6 |
+
from torch.utils.data import Dataset
|
| 7 |
+
from torchaudio._internal import download_url_to_file
|
| 8 |
+
from torchaudio.datasets.utils import _extract_zip
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
_URL = "https://datashare.ed.ac.uk/bitstream/handle/10283/3038/DR-VCTK.zip"
|
| 12 |
+
_CHECKSUM = "781f12f4406ed36ed27ae3bce55da47ba176e2d8bae67319e389e07b2c9bd769"
|
| 13 |
+
_SUPPORTED_SUBSETS = {"train", "test"}
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class DR_VCTK(Dataset):
|
| 17 |
+
"""*Device Recorded VCTK (Small subset version)* :cite:`Sarfjoo2018DeviceRV` dataset.
|
| 18 |
+
|
| 19 |
+
Args:
|
| 20 |
+
root (str or Path): Root directory where the dataset's top level directory is found.
|
| 21 |
+
subset (str): The subset to use. Can be one of ``"train"`` and ``"test"``. (default: ``"train"``).
|
| 22 |
+
download (bool):
|
| 23 |
+
Whether to download the dataset if it is not found at root path. (default: ``False``).
|
| 24 |
+
url (str): The URL to download the dataset from.
|
| 25 |
+
(default: ``"https://datashare.ed.ac.uk/bitstream/handle/10283/3038/DR-VCTK.zip"``)
|
| 26 |
+
"""
|
| 27 |
+
|
| 28 |
+
def __init__(
|
| 29 |
+
self,
|
| 30 |
+
root: Union[str, Path],
|
| 31 |
+
subset: str = "train",
|
| 32 |
+
*,
|
| 33 |
+
download: bool = False,
|
| 34 |
+
url: str = _URL,
|
| 35 |
+
) -> None:
|
| 36 |
+
if subset not in _SUPPORTED_SUBSETS:
|
| 37 |
+
raise RuntimeError(
|
| 38 |
+
f"The subset '{subset}' does not match any of the supported subsets: {_SUPPORTED_SUBSETS}"
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
root = Path(root).expanduser()
|
| 42 |
+
archive = root / "DR-VCTK.zip"
|
| 43 |
+
|
| 44 |
+
self._subset = subset
|
| 45 |
+
self._path = root / "DR-VCTK" / "DR-VCTK"
|
| 46 |
+
self._clean_audio_dir = self._path / f"clean_{self._subset}set_wav_16k"
|
| 47 |
+
self._noisy_audio_dir = self._path / f"device-recorded_{self._subset}set_wav_16k"
|
| 48 |
+
self._config_filepath = self._path / "configurations" / f"{self._subset}_ch_log.txt"
|
| 49 |
+
|
| 50 |
+
if not self._path.is_dir():
|
| 51 |
+
if not archive.is_file():
|
| 52 |
+
if not download:
|
| 53 |
+
raise RuntimeError("Dataset not found. Please use `download=True` to download it.")
|
| 54 |
+
download_url_to_file(url, archive, hash_prefix=_CHECKSUM)
|
| 55 |
+
_extract_zip(archive, root)
|
| 56 |
+
|
| 57 |
+
self._config = self._load_config(self._config_filepath)
|
| 58 |
+
self._filename_list = sorted(self._config)
|
| 59 |
+
|
| 60 |
+
def _load_config(self, filepath: str) -> Dict[str, Tuple[str, int]]:
|
| 61 |
+
# Skip header
|
| 62 |
+
skip_rows = 2 if self._subset == "train" else 1
|
| 63 |
+
|
| 64 |
+
config = {}
|
| 65 |
+
with open(filepath) as f:
|
| 66 |
+
for i, line in enumerate(f):
|
| 67 |
+
if i < skip_rows or not line:
|
| 68 |
+
continue
|
| 69 |
+
filename, source, channel_id = line.strip().split("\t")
|
| 70 |
+
config[filename] = (source, int(channel_id))
|
| 71 |
+
return config
|
| 72 |
+
|
| 73 |
+
def _load_dr_vctk_item(self, filename: str) -> Tuple[Tensor, int, Tensor, int, str, str, str, int]:
|
| 74 |
+
speaker_id, utterance_id = filename.split(".")[0].split("_")
|
| 75 |
+
source, channel_id = self._config[filename]
|
| 76 |
+
file_clean_audio = self._clean_audio_dir / filename
|
| 77 |
+
file_noisy_audio = self._noisy_audio_dir / filename
|
| 78 |
+
waveform_clean, sample_rate_clean = torchaudio.load(file_clean_audio)
|
| 79 |
+
waveform_noisy, sample_rate_noisy = torchaudio.load(file_noisy_audio)
|
| 80 |
+
return (
|
| 81 |
+
waveform_clean,
|
| 82 |
+
sample_rate_clean,
|
| 83 |
+
waveform_noisy,
|
| 84 |
+
sample_rate_noisy,
|
| 85 |
+
speaker_id,
|
| 86 |
+
utterance_id,
|
| 87 |
+
source,
|
| 88 |
+
channel_id,
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
def __getitem__(self, n: int) -> Tuple[Tensor, int, Tensor, int, str, str, str, int]:
|
| 92 |
+
"""Load the n-th sample from the dataset.
|
| 93 |
+
|
| 94 |
+
Args:
|
| 95 |
+
n (int): The index of the sample to be loaded
|
| 96 |
+
|
| 97 |
+
Returns:
|
| 98 |
+
Tuple of the following items;
|
| 99 |
+
|
| 100 |
+
Tensor:
|
| 101 |
+
Clean waveform
|
| 102 |
+
int:
|
| 103 |
+
Sample rate of the clean waveform
|
| 104 |
+
Tensor:
|
| 105 |
+
Noisy waveform
|
| 106 |
+
int:
|
| 107 |
+
Sample rate of the noisy waveform
|
| 108 |
+
str:
|
| 109 |
+
Speaker ID
|
| 110 |
+
str:
|
| 111 |
+
Utterance ID
|
| 112 |
+
str:
|
| 113 |
+
Source
|
| 114 |
+
int:
|
| 115 |
+
Channel ID
|
| 116 |
+
"""
|
| 117 |
+
filename = self._filename_list[n]
|
| 118 |
+
return self._load_dr_vctk_item(filename)
|
| 119 |
+
|
| 120 |
+
def __len__(self) -> int:
|
| 121 |
+
return len(self._filename_list)
|
micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/datasets/fluentcommands.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import csv
|
| 2 |
+
import os
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
from typing import Tuple, Union
|
| 5 |
+
|
| 6 |
+
from torch import Tensor
|
| 7 |
+
from torch.utils.data import Dataset
|
| 8 |
+
from torchaudio.datasets.utils import _load_waveform
|
| 9 |
+
|
| 10 |
+
SAMPLE_RATE = 16000
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class FluentSpeechCommands(Dataset):
|
| 14 |
+
"""*Fluent Speech Commands* :cite:`fluent` dataset
|
| 15 |
+
|
| 16 |
+
Args:
|
| 17 |
+
root (str of Path): Path to the directory where the dataset is found.
|
| 18 |
+
subset (str, optional): subset of the dataset to use.
|
| 19 |
+
Options: [``"train"``, ``"valid"``, ``"test"``].
|
| 20 |
+
(Default: ``"train"``)
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
def __init__(self, root: Union[str, Path], subset: str = "train"):
|
| 24 |
+
if subset not in ["train", "valid", "test"]:
|
| 25 |
+
raise ValueError("`subset` must be one of ['train', 'valid', 'test']")
|
| 26 |
+
|
| 27 |
+
root = os.fspath(root)
|
| 28 |
+
self._path = os.path.join(root, "fluent_speech_commands_dataset")
|
| 29 |
+
|
| 30 |
+
if not os.path.isdir(self._path):
|
| 31 |
+
raise RuntimeError("Dataset not found.")
|
| 32 |
+
|
| 33 |
+
subset_path = os.path.join(self._path, "data", f"{subset}_data.csv")
|
| 34 |
+
with open(subset_path) as subset_csv:
|
| 35 |
+
subset_reader = csv.reader(subset_csv)
|
| 36 |
+
data = list(subset_reader)
|
| 37 |
+
|
| 38 |
+
self.header = data[0]
|
| 39 |
+
self.data = data[1:]
|
| 40 |
+
|
| 41 |
+
def get_metadata(self, n: int) -> Tuple[str, int, str, int, str, str, str, str]:
|
| 42 |
+
"""Get metadata for the n-th sample from the dataset. Returns filepath instead of waveform,
|
| 43 |
+
but otherwise returns the same fields as :py:func:`__getitem__`.
|
| 44 |
+
|
| 45 |
+
Args:
|
| 46 |
+
n (int): The index of the sample to be loaded
|
| 47 |
+
|
| 48 |
+
Returns:
|
| 49 |
+
Tuple of the following items;
|
| 50 |
+
|
| 51 |
+
str:
|
| 52 |
+
Path to audio
|
| 53 |
+
int:
|
| 54 |
+
Sample rate
|
| 55 |
+
str:
|
| 56 |
+
File name
|
| 57 |
+
int:
|
| 58 |
+
Speaker ID
|
| 59 |
+
str:
|
| 60 |
+
Transcription
|
| 61 |
+
str:
|
| 62 |
+
Action
|
| 63 |
+
str:
|
| 64 |
+
Object
|
| 65 |
+
str:
|
| 66 |
+
Location
|
| 67 |
+
"""
|
| 68 |
+
sample = self.data[n]
|
| 69 |
+
|
| 70 |
+
file_name = sample[self.header.index("path")].split("/")[-1]
|
| 71 |
+
file_name = file_name.split(".")[0]
|
| 72 |
+
speaker_id, transcription, action, obj, location = sample[2:]
|
| 73 |
+
file_path = os.path.join("wavs", "speakers", speaker_id, f"{file_name}.wav")
|
| 74 |
+
|
| 75 |
+
return file_path, SAMPLE_RATE, file_name, speaker_id, transcription, action, obj, location
|
| 76 |
+
|
| 77 |
+
def __len__(self) -> int:
|
| 78 |
+
return len(self.data)
|
| 79 |
+
|
| 80 |
+
def __getitem__(self, n: int) -> Tuple[Tensor, int, str, int, str, str, str, str]:
|
| 81 |
+
"""Load the n-th sample from the dataset.
|
| 82 |
+
|
| 83 |
+
Args:
|
| 84 |
+
n (int): The index of the sample to be loaded
|
| 85 |
+
|
| 86 |
+
Returns:
|
| 87 |
+
Tuple of the following items;
|
| 88 |
+
|
| 89 |
+
Tensor:
|
| 90 |
+
Waveform
|
| 91 |
+
int:
|
| 92 |
+
Sample rate
|
| 93 |
+
str:
|
| 94 |
+
File name
|
| 95 |
+
int:
|
| 96 |
+
Speaker ID
|
| 97 |
+
str:
|
| 98 |
+
Transcription
|
| 99 |
+
str:
|
| 100 |
+
Action
|
| 101 |
+
str:
|
| 102 |
+
Object
|
| 103 |
+
str:
|
| 104 |
+
Location
|
| 105 |
+
"""
|
| 106 |
+
metadata = self.get_metadata(n)
|
| 107 |
+
waveform = _load_waveform(self._path, metadata[0], metadata[1])
|
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
from typing import Optional, Tuple, Union
|
| 4 |
+
|
| 5 |
+
import torchaudio
|
| 6 |
+
from torch import Tensor
|
| 7 |
+
from torch.utils.data import Dataset
|
| 8 |
+
from torchaudio._internal import download_url_to_file
|
| 9 |
+
from torchaudio.datasets.utils import _extract_tar
|
| 10 |
+
|
| 11 |
+
# The following lists prefixed with `filtered_` provide a filtered split
|
| 12 |
+
# that:
|
| 13 |
+
#
|
| 14 |
+
# a. Mitigate a known issue with GTZAN (duplication)
|
| 15 |
+
#
|
| 16 |
+
# b. Provide a standard split for testing it against other
|
| 17 |
+
# methods (e.g. the one in jordipons/sklearn-audio-transfer-learning).
|
| 18 |
+
#
|
| 19 |
+
# Those are used when GTZAN is initialised with the `filtered` keyword.
|
| 20 |
+
# The split was taken from (github) jordipons/sklearn-audio-transfer-learning.
|
| 21 |
+
|
| 22 |
+
gtzan_genres = [
|
| 23 |
+
"blues",
|
| 24 |
+
"classical",
|
| 25 |
+
"country",
|
| 26 |
+
"disco",
|
| 27 |
+
"hiphop",
|
| 28 |
+
"jazz",
|
| 29 |
+
"metal",
|
| 30 |
+
"pop",
|
| 31 |
+
"reggae",
|
| 32 |
+
"rock",
|
| 33 |
+
]
|
| 34 |
+
|
| 35 |
+
filtered_test = [
|
| 36 |
+
"blues.00012",
|
| 37 |
+
"blues.00013",
|
| 38 |
+
"blues.00014",
|
| 39 |
+
"blues.00015",
|
| 40 |
+
"blues.00016",
|
| 41 |
+
"blues.00017",
|
| 42 |
+
"blues.00018",
|
| 43 |
+
"blues.00019",
|
| 44 |
+
"blues.00020",
|
| 45 |
+
"blues.00021",
|
| 46 |
+
"blues.00022",
|
| 47 |
+
"blues.00023",
|
| 48 |
+
"blues.00024",
|
| 49 |
+
"blues.00025",
|
| 50 |
+
"blues.00026",
|
| 51 |
+
"blues.00027",
|
| 52 |
+
"blues.00028",
|
| 53 |
+
"blues.00061",
|
| 54 |
+
"blues.00062",
|
| 55 |
+
"blues.00063",
|
| 56 |
+
"blues.00064",
|
| 57 |
+
"blues.00065",
|
| 58 |
+
"blues.00066",
|
| 59 |
+
"blues.00067",
|
| 60 |
+
"blues.00068",
|
| 61 |
+
"blues.00069",
|
| 62 |
+
"blues.00070",
|
| 63 |
+
"blues.00071",
|
| 64 |
+
"blues.00072",
|
| 65 |
+
"blues.00098",
|
| 66 |
+
"blues.00099",
|
| 67 |
+
"classical.00011",
|
| 68 |
+
"classical.00012",
|
| 69 |
+
"classical.00013",
|
| 70 |
+
"classical.00014",
|
| 71 |
+
"classical.00015",
|
| 72 |
+
"classical.00016",
|
| 73 |
+
"classical.00017",
|
| 74 |
+
"classical.00018",
|
| 75 |
+
"classical.00019",
|
| 76 |
+
"classical.00020",
|
| 77 |
+
"classical.00021",
|
| 78 |
+
"classical.00022",
|
| 79 |
+
"classical.00023",
|
| 80 |
+
"classical.00024",
|
| 81 |
+
"classical.00025",
|
| 82 |
+
"classical.00026",
|
| 83 |
+
"classical.00027",
|
| 84 |
+
"classical.00028",
|
| 85 |
+
"classical.00029",
|
| 86 |
+
"classical.00034",
|
| 87 |
+
"classical.00035",
|
| 88 |
+
"classical.00036",
|
| 89 |
+
"classical.00037",
|
| 90 |
+
"classical.00038",
|
| 91 |
+
"classical.00039",
|
| 92 |
+
"classical.00040",
|
| 93 |
+
"classical.00041",
|
| 94 |
+
"classical.00049",
|
| 95 |
+
"classical.00077",
|
| 96 |
+
"classical.00078",
|
| 97 |
+
"classical.00079",
|
| 98 |
+
"country.00030",
|
| 99 |
+
"country.00031",
|
| 100 |
+
"country.00032",
|
| 101 |
+
"country.00033",
|
| 102 |
+
"country.00034",
|
| 103 |
+
"country.00035",
|
| 104 |
+
"country.00036",
|
| 105 |
+
"country.00037",
|
| 106 |
+
"country.00038",
|
| 107 |
+
"country.00039",
|
| 108 |
+
"country.00040",
|
| 109 |
+
"country.00043",
|
| 110 |
+
"country.00044",
|
| 111 |
+
"country.00046",
|
| 112 |
+
"country.00047",
|
| 113 |
+
"country.00048",
|
| 114 |
+
"country.00050",
|
| 115 |
+
"country.00051",
|
| 116 |
+
"country.00053",
|
| 117 |
+
"country.00054",
|
| 118 |
+
"country.00055",
|
| 119 |
+
"country.00056",
|
| 120 |
+
"country.00057",
|
| 121 |
+
"country.00058",
|
| 122 |
+
"country.00059",
|
| 123 |
+
"country.00060",
|
| 124 |
+
"country.00061",
|
| 125 |
+
"country.00062",
|
| 126 |
+
"country.00063",
|
| 127 |
+
"country.00064",
|
| 128 |
+
"disco.00001",
|
| 129 |
+
"disco.00021",
|
| 130 |
+
"disco.00058",
|
| 131 |
+
"disco.00062",
|
| 132 |
+
"disco.00063",
|
| 133 |
+
"disco.00064",
|
| 134 |
+
"disco.00065",
|
| 135 |
+
"disco.00066",
|
| 136 |
+
"disco.00069",
|
| 137 |
+
"disco.00076",
|
| 138 |
+
"disco.00077",
|
| 139 |
+
"disco.00078",
|
| 140 |
+
"disco.00079",
|
| 141 |
+
"disco.00080",
|
| 142 |
+
"disco.00081",
|
| 143 |
+
"disco.00082",
|
| 144 |
+
"disco.00083",
|
| 145 |
+
"disco.00084",
|
| 146 |
+
"disco.00085",
|
| 147 |
+
"disco.00086",
|
| 148 |
+
"disco.00087",
|
| 149 |
+
"disco.00088",
|
| 150 |
+
"disco.00091",
|
| 151 |
+
"disco.00092",
|
| 152 |
+
"disco.00093",
|
| 153 |
+
"disco.00094",
|
| 154 |
+
"disco.00096",
|
| 155 |
+
"disco.00097",
|
| 156 |
+
"disco.00099",
|
| 157 |
+
"hiphop.00000",
|
| 158 |
+
"hiphop.00026",
|
| 159 |
+
"hiphop.00027",
|
| 160 |
+
"hiphop.00030",
|
| 161 |
+
"hiphop.00040",
|
| 162 |
+
"hiphop.00043",
|
| 163 |
+
"hiphop.00044",
|
| 164 |
+
"hiphop.00045",
|
| 165 |
+
"hiphop.00051",
|
| 166 |
+
"hiphop.00052",
|
| 167 |
+
"hiphop.00053",
|
| 168 |
+
"hiphop.00054",
|
| 169 |
+
"hiphop.00062",
|
| 170 |
+
"hiphop.00063",
|
| 171 |
+
"hiphop.00064",
|
| 172 |
+
"hiphop.00065",
|
| 173 |
+
"hiphop.00066",
|
| 174 |
+
"hiphop.00067",
|
| 175 |
+
"hiphop.00068",
|
| 176 |
+
"hiphop.00069",
|
| 177 |
+
"hiphop.00070",
|
| 178 |
+
"hiphop.00071",
|
| 179 |
+
"hiphop.00072",
|
| 180 |
+
"hiphop.00073",
|
| 181 |
+
"hiphop.00074",
|
| 182 |
+
"hiphop.00075",
|
| 183 |
+
"hiphop.00099",
|
| 184 |
+
"jazz.00073",
|
| 185 |
+
"jazz.00074",
|
| 186 |
+
"jazz.00075",
|
| 187 |
+
"jazz.00076",
|
| 188 |
+
"jazz.00077",
|
| 189 |
+
"jazz.00078",
|
| 190 |
+
"jazz.00079",
|
| 191 |
+
"jazz.00080",
|
| 192 |
+
"jazz.00081",
|
| 193 |
+
"jazz.00082",
|
| 194 |
+
"jazz.00083",
|
| 195 |
+
"jazz.00084",
|
| 196 |
+
"jazz.00085",
|
| 197 |
+
"jazz.00086",
|
| 198 |
+
"jazz.00087",
|
| 199 |
+
"jazz.00088",
|
| 200 |
+
"jazz.00089",
|
| 201 |
+
"jazz.00090",
|
| 202 |
+
"jazz.00091",
|
| 203 |
+
"jazz.00092",
|
| 204 |
+
"jazz.00093",
|
| 205 |
+
"jazz.00094",
|
| 206 |
+
"jazz.00095",
|
| 207 |
+
"jazz.00096",
|
| 208 |
+
"jazz.00097",
|
| 209 |
+
"jazz.00098",
|
| 210 |
+
"jazz.00099",
|
| 211 |
+
"metal.00012",
|
| 212 |
+
"metal.00013",
|
| 213 |
+
"metal.00014",
|
| 214 |
+
"metal.00015",
|
| 215 |
+
"metal.00022",
|
| 216 |
+
"metal.00023",
|
| 217 |
+
"metal.00025",
|
| 218 |
+
"metal.00026",
|
| 219 |
+
"metal.00027",
|
| 220 |
+
"metal.00028",
|
| 221 |
+
"metal.00029",
|
| 222 |
+
"metal.00030",
|
| 223 |
+
"metal.00031",
|
| 224 |
+
"metal.00032",
|
| 225 |
+
"metal.00033",
|
| 226 |
+
"metal.00038",
|
| 227 |
+
"metal.00039",
|
| 228 |
+
"metal.00067",
|
| 229 |
+
"metal.00070",
|
| 230 |
+
"metal.00073",
|
| 231 |
+
"metal.00074",
|
| 232 |
+
"metal.00075",
|
| 233 |
+
"metal.00078",
|
| 234 |
+
"metal.00083",
|
| 235 |
+
"metal.00085",
|
| 236 |
+
"metal.00087",
|
| 237 |
+
"metal.00088",
|
| 238 |
+
"pop.00000",
|
| 239 |
+
"pop.00001",
|
| 240 |
+
"pop.00013",
|
| 241 |
+
"pop.00014",
|
| 242 |
+
"pop.00043",
|
| 243 |
+
"pop.00063",
|
| 244 |
+
"pop.00064",
|
| 245 |
+
"pop.00065",
|
| 246 |
+
"pop.00066",
|
| 247 |
+
"pop.00069",
|
| 248 |
+
"pop.00070",
|
| 249 |
+
"pop.00071",
|
| 250 |
+
"pop.00072",
|
| 251 |
+
"pop.00073",
|
| 252 |
+
"pop.00074",
|
| 253 |
+
"pop.00075",
|
| 254 |
+
"pop.00076",
|
| 255 |
+
"pop.00077",
|
| 256 |
+
"pop.00078",
|
| 257 |
+
"pop.00079",
|
| 258 |
+
"pop.00082",
|
| 259 |
+
"pop.00088",
|
| 260 |
+
"pop.00089",
|
| 261 |
+
"pop.00090",
|
| 262 |
+
"pop.00091",
|
| 263 |
+
"pop.00092",
|
| 264 |
+
"pop.00093",
|
| 265 |
+
"pop.00094",
|
| 266 |
+
"pop.00095",
|
| 267 |
+
"pop.00096",
|
| 268 |
+
"reggae.00034",
|
| 269 |
+
"reggae.00035",
|
| 270 |
+
"reggae.00036",
|
| 271 |
+
"reggae.00037",
|
| 272 |
+
"reggae.00038",
|
| 273 |
+
"reggae.00039",
|
| 274 |
+
"reggae.00040",
|
| 275 |
+
"reggae.00046",
|
| 276 |
+
"reggae.00047",
|
| 277 |
+
"reggae.00048",
|
| 278 |
+
"reggae.00052",
|
| 279 |
+
"reggae.00053",
|
| 280 |
+
"reggae.00064",
|
| 281 |
+
"reggae.00065",
|
| 282 |
+
"reggae.00066",
|
| 283 |
+
"reggae.00067",
|
| 284 |
+
"reggae.00068",
|
| 285 |
+
"reggae.00071",
|
| 286 |
+
"reggae.00079",
|
| 287 |
+
"reggae.00082",
|
| 288 |
+
"reggae.00083",
|
| 289 |
+
"reggae.00084",
|
| 290 |
+
"reggae.00087",
|
| 291 |
+
"reggae.00088",
|
| 292 |
+
"reggae.00089",
|
| 293 |
+
"reggae.00090",
|
| 294 |
+
"rock.00010",
|
| 295 |
+
"rock.00011",
|
| 296 |
+
"rock.00012",
|
| 297 |
+
"rock.00013",
|
| 298 |
+
"rock.00014",
|
| 299 |
+
"rock.00015",
|
| 300 |
+
"rock.00027",
|
| 301 |
+
"rock.00028",
|
| 302 |
+
"rock.00029",
|
| 303 |
+
"rock.00030",
|
| 304 |
+
"rock.00031",
|
| 305 |
+
"rock.00032",
|
| 306 |
+
"rock.00033",
|
| 307 |
+
"rock.00034",
|
| 308 |
+
"rock.00035",
|
| 309 |
+
"rock.00036",
|
| 310 |
+
"rock.00037",
|
| 311 |
+
"rock.00039",
|
| 312 |
+
"rock.00040",
|
| 313 |
+
"rock.00041",
|
| 314 |
+
"rock.00042",
|
| 315 |
+
"rock.00043",
|
| 316 |
+
"rock.00044",
|
| 317 |
+
"rock.00045",
|
| 318 |
+
"rock.00046",
|
| 319 |
+
"rock.00047",
|
| 320 |
+
"rock.00048",
|
| 321 |
+
"rock.00086",
|
| 322 |
+
"rock.00087",
|
| 323 |
+
"rock.00088",
|
| 324 |
+
"rock.00089",
|
| 325 |
+
"rock.00090",
|
| 326 |
+
]
|
| 327 |
+
|
| 328 |
+
filtered_train = [
|
| 329 |
+
"blues.00029",
|
| 330 |
+
"blues.00030",
|
| 331 |
+
"blues.00031",
|
| 332 |
+
"blues.00032",
|
| 333 |
+
"blues.00033",
|
| 334 |
+
"blues.00034",
|
| 335 |
+
"blues.00035",
|
| 336 |
+
"blues.00036",
|
| 337 |
+
"blues.00037",
|
| 338 |
+
"blues.00038",
|
| 339 |
+
"blues.00039",
|
| 340 |
+
"blues.00040",
|
| 341 |
+
"blues.00041",
|
| 342 |
+
"blues.00042",
|
| 343 |
+
"blues.00043",
|
| 344 |
+
"blues.00044",
|
| 345 |
+
"blues.00045",
|
| 346 |
+
"blues.00046",
|
| 347 |
+
"blues.00047",
|
| 348 |
+
"blues.00048",
|
| 349 |
+
"blues.00049",
|
| 350 |
+
"blues.00073",
|
| 351 |
+
"blues.00074",
|
| 352 |
+
"blues.00075",
|
| 353 |
+
"blues.00076",
|
| 354 |
+
"blues.00077",
|
| 355 |
+
"blues.00078",
|
| 356 |
+
"blues.00079",
|
| 357 |
+
"blues.00080",
|
| 358 |
+
"blues.00081",
|
| 359 |
+
"blues.00082",
|
| 360 |
+
"blues.00083",
|
| 361 |
+
"blues.00084",
|
| 362 |
+
"blues.00085",
|
| 363 |
+
"blues.00086",
|
| 364 |
+
"blues.00087",
|
| 365 |
+
"blues.00088",
|
| 366 |
+
"blues.00089",
|
| 367 |
+
"blues.00090",
|
| 368 |
+
"blues.00091",
|
| 369 |
+
"blues.00092",
|
| 370 |
+
"blues.00093",
|
| 371 |
+
"blues.00094",
|
| 372 |
+
"blues.00095",
|
| 373 |
+
"blues.00096",
|
| 374 |
+
"blues.00097",
|
| 375 |
+
"classical.00030",
|
| 376 |
+
"classical.00031",
|
| 377 |
+
"classical.00032",
|
| 378 |
+
"classical.00033",
|
| 379 |
+
"classical.00043",
|
| 380 |
+
"classical.00044",
|
| 381 |
+
"classical.00045",
|
| 382 |
+
"classical.00046",
|
| 383 |
+
"classical.00047",
|
| 384 |
+
"classical.00048",
|
| 385 |
+
"classical.00050",
|
| 386 |
+
"classical.00051",
|
| 387 |
+
"classical.00052",
|
| 388 |
+
"classical.00053",
|
| 389 |
+
"classical.00054",
|
| 390 |
+
"classical.00055",
|
| 391 |
+
"classical.00056",
|
| 392 |
+
"classical.00057",
|
| 393 |
+
"classical.00058",
|
| 394 |
+
"classical.00059",
|
| 395 |
+
"classical.00060",
|
| 396 |
+
"classical.00061",
|
| 397 |
+
"classical.00062",
|
| 398 |
+
"classical.00063",
|
| 399 |
+
"classical.00064",
|
| 400 |
+
"classical.00065",
|
| 401 |
+
"classical.00066",
|
| 402 |
+
"classical.00067",
|
| 403 |
+
"classical.00080",
|
| 404 |
+
"classical.00081",
|
| 405 |
+
"classical.00082",
|
| 406 |
+
"classical.00083",
|
| 407 |
+
"classical.00084",
|
| 408 |
+
"classical.00085",
|
| 409 |
+
"classical.00086",
|
| 410 |
+
"classical.00087",
|
| 411 |
+
"classical.00088",
|
| 412 |
+
"classical.00089",
|
| 413 |
+
"classical.00090",
|
| 414 |
+
"classical.00091",
|
| 415 |
+
"classical.00092",
|
| 416 |
+
"classical.00093",
|
| 417 |
+
"classical.00094",
|
| 418 |
+
"classical.00095",
|
| 419 |
+
"classical.00096",
|
| 420 |
+
"classical.00097",
|
| 421 |
+
"classical.00098",
|
| 422 |
+
"classical.00099",
|
| 423 |
+
"country.00019",
|
| 424 |
+
"country.00020",
|
| 425 |
+
"country.00021",
|
| 426 |
+
"country.00022",
|
| 427 |
+
"country.00023",
|
| 428 |
+
"country.00024",
|
| 429 |
+
"country.00025",
|
| 430 |
+
"country.00026",
|
| 431 |
+
"country.00028",
|
| 432 |
+
"country.00029",
|
| 433 |
+
"country.00065",
|
| 434 |
+
"country.00066",
|
| 435 |
+
"country.00067",
|
| 436 |
+
"country.00068",
|
| 437 |
+
"country.00069",
|
| 438 |
+
"country.00070",
|
| 439 |
+
"country.00071",
|
| 440 |
+
"country.00072",
|
| 441 |
+
"country.00073",
|
| 442 |
+
"country.00074",
|
| 443 |
+
"country.00075",
|
| 444 |
+
"country.00076",
|
| 445 |
+
"country.00077",
|
| 446 |
+
"country.00078",
|
| 447 |
+
"country.00079",
|
| 448 |
+
"country.00080",
|
| 449 |
+
"country.00081",
|
| 450 |
+
"country.00082",
|
| 451 |
+
"country.00083",
|
| 452 |
+
"country.00084",
|
| 453 |
+
"country.00085",
|
| 454 |
+
"country.00086",
|
| 455 |
+
"country.00087",
|
| 456 |
+
"country.00088",
|
| 457 |
+
"country.00089",
|
| 458 |
+
"country.00090",
|
| 459 |
+
"country.00091",
|
| 460 |
+
"country.00092",
|
| 461 |
+
"country.00093",
|
| 462 |
+
"country.00094",
|
| 463 |
+
"country.00095",
|
| 464 |
+
"country.00096",
|
| 465 |
+
"country.00097",
|
| 466 |
+
"country.00098",
|
| 467 |
+
"country.00099",
|
| 468 |
+
"disco.00005",
|
| 469 |
+
"disco.00015",
|
| 470 |
+
"disco.00016",
|
| 471 |
+
"disco.00017",
|
| 472 |
+
"disco.00018",
|
| 473 |
+
"disco.00019",
|
| 474 |
+
"disco.00020",
|
| 475 |
+
"disco.00022",
|
| 476 |
+
"disco.00023",
|
| 477 |
+
"disco.00024",
|
| 478 |
+
"disco.00025",
|
| 479 |
+
"disco.00026",
|
| 480 |
+
"disco.00027",
|
| 481 |
+
"disco.00028",
|
| 482 |
+
"disco.00029",
|
| 483 |
+
"disco.00030",
|
| 484 |
+
"disco.00031",
|
| 485 |
+
"disco.00032",
|
| 486 |
+
"disco.00033",
|
| 487 |
+
"disco.00034",
|
| 488 |
+
"disco.00035",
|
| 489 |
+
"disco.00036",
|
| 490 |
+
"disco.00037",
|
| 491 |
+
"disco.00039",
|
| 492 |
+
"disco.00040",
|
| 493 |
+
"disco.00041",
|
| 494 |
+
"disco.00042",
|
| 495 |
+
"disco.00043",
|
| 496 |
+
"disco.00044",
|
| 497 |
+
"disco.00045",
|
| 498 |
+
"disco.00047",
|
| 499 |
+
"disco.00049",
|
| 500 |
+
"disco.00053",
|
| 501 |
+
"disco.00054",
|
| 502 |
+
"disco.00056",
|
| 503 |
+
"disco.00057",
|
| 504 |
+
"disco.00059",
|
| 505 |
+
"disco.00061",
|
| 506 |
+
"disco.00070",
|
| 507 |
+
"disco.00073",
|
| 508 |
+
"disco.00074",
|
| 509 |
+
"disco.00089",
|
| 510 |
+
"hiphop.00002",
|
| 511 |
+
"hiphop.00003",
|
| 512 |
+
"hiphop.00004",
|
| 513 |
+
"hiphop.00005",
|
| 514 |
+
"hiphop.00006",
|
| 515 |
+
"hiphop.00007",
|
| 516 |
+
"hiphop.00008",
|
| 517 |
+
"hiphop.00009",
|
| 518 |
+
"hiphop.00010",
|
| 519 |
+
"hiphop.00011",
|
| 520 |
+
"hiphop.00012",
|
| 521 |
+
"hiphop.00013",
|
| 522 |
+
"hiphop.00014",
|
| 523 |
+
"hiphop.00015",
|
| 524 |
+
"hiphop.00016",
|
| 525 |
+
"hiphop.00017",
|
| 526 |
+
"hiphop.00018",
|
| 527 |
+
"hiphop.00019",
|
| 528 |
+
"hiphop.00020",
|
| 529 |
+
"hiphop.00021",
|
| 530 |
+
"hiphop.00022",
|
| 531 |
+
"hiphop.00023",
|
| 532 |
+
"hiphop.00024",
|
| 533 |
+
"hiphop.00025",
|
| 534 |
+
"hiphop.00028",
|
| 535 |
+
"hiphop.00029",
|
| 536 |
+
"hiphop.00031",
|
| 537 |
+
"hiphop.00032",
|
| 538 |
+
"hiphop.00033",
|
| 539 |
+
"hiphop.00034",
|
| 540 |
+
"hiphop.00035",
|
| 541 |
+
"hiphop.00036",
|
| 542 |
+
"hiphop.00037",
|
| 543 |
+
"hiphop.00038",
|
| 544 |
+
"hiphop.00041",
|
| 545 |
+
"hiphop.00042",
|
| 546 |
+
"hiphop.00055",
|
| 547 |
+
"hiphop.00056",
|
| 548 |
+
"hiphop.00057",
|
| 549 |
+
"hiphop.00058",
|
| 550 |
+
"hiphop.00059",
|
| 551 |
+
"hiphop.00060",
|
| 552 |
+
"hiphop.00061",
|
| 553 |
+
"hiphop.00077",
|
| 554 |
+
"hiphop.00078",
|
| 555 |
+
"hiphop.00079",
|
| 556 |
+
"hiphop.00080",
|
| 557 |
+
"jazz.00000",
|
| 558 |
+
"jazz.00001",
|
| 559 |
+
"jazz.00011",
|
| 560 |
+
"jazz.00012",
|
| 561 |
+
"jazz.00013",
|
| 562 |
+
"jazz.00014",
|
| 563 |
+
"jazz.00015",
|
| 564 |
+
"jazz.00016",
|
| 565 |
+
"jazz.00017",
|
| 566 |
+
"jazz.00018",
|
| 567 |
+
"jazz.00019",
|
| 568 |
+
"jazz.00020",
|
| 569 |
+
"jazz.00021",
|
| 570 |
+
"jazz.00022",
|
| 571 |
+
"jazz.00023",
|
| 572 |
+
"jazz.00024",
|
| 573 |
+
"jazz.00041",
|
| 574 |
+
"jazz.00047",
|
| 575 |
+
"jazz.00048",
|
| 576 |
+
"jazz.00049",
|
| 577 |
+
"jazz.00050",
|
| 578 |
+
"jazz.00051",
|
| 579 |
+
"jazz.00052",
|
| 580 |
+
"jazz.00053",
|
| 581 |
+
"jazz.00054",
|
| 582 |
+
"jazz.00055",
|
| 583 |
+
"jazz.00056",
|
| 584 |
+
"jazz.00057",
|
| 585 |
+
"jazz.00058",
|
| 586 |
+
"jazz.00059",
|
| 587 |
+
"jazz.00060",
|
| 588 |
+
"jazz.00061",
|
| 589 |
+
"jazz.00062",
|
| 590 |
+
"jazz.00063",
|
| 591 |
+
"jazz.00064",
|
| 592 |
+
"jazz.00065",
|
| 593 |
+
"jazz.00066",
|
| 594 |
+
"jazz.00067",
|
| 595 |
+
"jazz.00068",
|
| 596 |
+
"jazz.00069",
|
| 597 |
+
"jazz.00070",
|
| 598 |
+
"jazz.00071",
|
| 599 |
+
"jazz.00072",
|
| 600 |
+
"metal.00002",
|
| 601 |
+
"metal.00003",
|
| 602 |
+
"metal.00005",
|
| 603 |
+
"metal.00021",
|
| 604 |
+
"metal.00024",
|
| 605 |
+
"metal.00035",
|
| 606 |
+
"metal.00046",
|
| 607 |
+
"metal.00047",
|
| 608 |
+
"metal.00048",
|
| 609 |
+
"metal.00049",
|
| 610 |
+
"metal.00050",
|
| 611 |
+
"metal.00051",
|
| 612 |
+
"metal.00052",
|
| 613 |
+
"metal.00053",
|
| 614 |
+
"metal.00054",
|
| 615 |
+
"metal.00055",
|
| 616 |
+
"metal.00056",
|
| 617 |
+
"metal.00057",
|
| 618 |
+
"metal.00059",
|
| 619 |
+
"metal.00060",
|
| 620 |
+
"metal.00061",
|
| 621 |
+
"metal.00062",
|
| 622 |
+
"metal.00063",
|
| 623 |
+
"metal.00064",
|
| 624 |
+
"metal.00065",
|
| 625 |
+
"metal.00066",
|
| 626 |
+
"metal.00069",
|
| 627 |
+
"metal.00071",
|
| 628 |
+
"metal.00072",
|
| 629 |
+
"metal.00079",
|
| 630 |
+
"metal.00080",
|
| 631 |
+
"metal.00084",
|
| 632 |
+
"metal.00086",
|
| 633 |
+
"metal.00089",
|
| 634 |
+
"metal.00090",
|
| 635 |
+
"metal.00091",
|
| 636 |
+
"metal.00092",
|
| 637 |
+
"metal.00093",
|
| 638 |
+
"metal.00094",
|
| 639 |
+
"metal.00095",
|
| 640 |
+
"metal.00096",
|
| 641 |
+
"metal.00097",
|
| 642 |
+
"metal.00098",
|
| 643 |
+
"metal.00099",
|
| 644 |
+
"pop.00002",
|
| 645 |
+
"pop.00003",
|
| 646 |
+
"pop.00004",
|
| 647 |
+
"pop.00005",
|
| 648 |
+
"pop.00006",
|
| 649 |
+
"pop.00007",
|
| 650 |
+
"pop.00008",
|
| 651 |
+
"pop.00009",
|
| 652 |
+
"pop.00011",
|
| 653 |
+
"pop.00012",
|
| 654 |
+
"pop.00016",
|
| 655 |
+
"pop.00017",
|
| 656 |
+
"pop.00018",
|
| 657 |
+
"pop.00019",
|
| 658 |
+
"pop.00020",
|
| 659 |
+
"pop.00023",
|
| 660 |
+
"pop.00024",
|
| 661 |
+
"pop.00025",
|
| 662 |
+
"pop.00026",
|
| 663 |
+
"pop.00027",
|
| 664 |
+
"pop.00028",
|
| 665 |
+
"pop.00029",
|
| 666 |
+
"pop.00031",
|
| 667 |
+
"pop.00032",
|
| 668 |
+
"pop.00033",
|
| 669 |
+
"pop.00034",
|
| 670 |
+
"pop.00035",
|
| 671 |
+
"pop.00036",
|
| 672 |
+
"pop.00038",
|
| 673 |
+
"pop.00039",
|
| 674 |
+
"pop.00040",
|
| 675 |
+
"pop.00041",
|
| 676 |
+
"pop.00042",
|
| 677 |
+
"pop.00044",
|
| 678 |
+
"pop.00046",
|
| 679 |
+
"pop.00049",
|
| 680 |
+
"pop.00050",
|
| 681 |
+
"pop.00080",
|
| 682 |
+
"pop.00097",
|
| 683 |
+
"pop.00098",
|
| 684 |
+
"pop.00099",
|
| 685 |
+
"reggae.00000",
|
| 686 |
+
"reggae.00001",
|
| 687 |
+
"reggae.00002",
|
| 688 |
+
"reggae.00004",
|
| 689 |
+
"reggae.00006",
|
| 690 |
+
"reggae.00009",
|
| 691 |
+
"reggae.00011",
|
| 692 |
+
"reggae.00012",
|
| 693 |
+
"reggae.00014",
|
| 694 |
+
"reggae.00015",
|
| 695 |
+
"reggae.00016",
|
| 696 |
+
"reggae.00017",
|
| 697 |
+
"reggae.00018",
|
| 698 |
+
"reggae.00019",
|
| 699 |
+
"reggae.00020",
|
| 700 |
+
"reggae.00021",
|
| 701 |
+
"reggae.00022",
|
| 702 |
+
"reggae.00023",
|
| 703 |
+
"reggae.00024",
|
| 704 |
+
"reggae.00025",
|
| 705 |
+
"reggae.00026",
|
| 706 |
+
"reggae.00027",
|
| 707 |
+
"reggae.00028",
|
| 708 |
+
"reggae.00029",
|
| 709 |
+
"reggae.00030",
|
| 710 |
+
"reggae.00031",
|
| 711 |
+
"reggae.00032",
|
| 712 |
+
"reggae.00042",
|
| 713 |
+
"reggae.00043",
|
| 714 |
+
"reggae.00044",
|
| 715 |
+
"reggae.00045",
|
| 716 |
+
"reggae.00049",
|
| 717 |
+
"reggae.00050",
|
| 718 |
+
"reggae.00051",
|
| 719 |
+
"reggae.00054",
|
| 720 |
+
"reggae.00055",
|
| 721 |
+
"reggae.00056",
|
| 722 |
+
"reggae.00057",
|
| 723 |
+
"reggae.00058",
|
| 724 |
+
"reggae.00059",
|
| 725 |
+
"reggae.00060",
|
| 726 |
+
"reggae.00063",
|
| 727 |
+
"reggae.00069",
|
| 728 |
+
"rock.00000",
|
| 729 |
+
"rock.00001",
|
| 730 |
+
"rock.00002",
|
| 731 |
+
"rock.00003",
|
| 732 |
+
"rock.00004",
|
| 733 |
+
"rock.00005",
|
| 734 |
+
"rock.00006",
|
| 735 |
+
"rock.00007",
|
| 736 |
+
"rock.00008",
|
| 737 |
+
"rock.00009",
|
| 738 |
+
"rock.00016",
|
| 739 |
+
"rock.00017",
|
| 740 |
+
"rock.00018",
|
| 741 |
+
"rock.00019",
|
| 742 |
+
"rock.00020",
|
| 743 |
+
"rock.00021",
|
| 744 |
+
"rock.00022",
|
| 745 |
+
"rock.00023",
|
| 746 |
+
"rock.00024",
|
| 747 |
+
"rock.00025",
|
| 748 |
+
"rock.00026",
|
| 749 |
+
"rock.00057",
|
| 750 |
+
"rock.00058",
|
| 751 |
+
"rock.00059",
|
| 752 |
+
"rock.00060",
|
| 753 |
+
"rock.00061",
|
| 754 |
+
"rock.00062",
|
| 755 |
+
"rock.00063",
|
| 756 |
+
"rock.00064",
|
| 757 |
+
"rock.00065",
|
| 758 |
+
"rock.00066",
|
| 759 |
+
"rock.00067",
|
| 760 |
+
"rock.00068",
|
| 761 |
+
"rock.00069",
|
| 762 |
+
"rock.00070",
|
| 763 |
+
"rock.00091",
|
| 764 |
+
"rock.00092",
|
| 765 |
+
"rock.00093",
|
| 766 |
+
"rock.00094",
|
| 767 |
+
"rock.00095",
|
| 768 |
+
"rock.00096",
|
| 769 |
+
"rock.00097",
|
| 770 |
+
"rock.00098",
|
| 771 |
+
"rock.00099",
|
| 772 |
+
]
|
| 773 |
+
|
| 774 |
+
filtered_valid = [
|
| 775 |
+
"blues.00000",
|
| 776 |
+
"blues.00001",
|
| 777 |
+
"blues.00002",
|
| 778 |
+
"blues.00003",
|
| 779 |
+
"blues.00004",
|
| 780 |
+
"blues.00005",
|
| 781 |
+
"blues.00006",
|
| 782 |
+
"blues.00007",
|
| 783 |
+
"blues.00008",
|
| 784 |
+
"blues.00009",
|
| 785 |
+
"blues.00010",
|
| 786 |
+
"blues.00011",
|
| 787 |
+
"blues.00050",
|
| 788 |
+
"blues.00051",
|
| 789 |
+
"blues.00052",
|
| 790 |
+
"blues.00053",
|
| 791 |
+
"blues.00054",
|
| 792 |
+
"blues.00055",
|
| 793 |
+
"blues.00056",
|
| 794 |
+
"blues.00057",
|
| 795 |
+
"blues.00058",
|
| 796 |
+
"blues.00059",
|
| 797 |
+
"blues.00060",
|
| 798 |
+
"classical.00000",
|
| 799 |
+
"classical.00001",
|
| 800 |
+
"classical.00002",
|
| 801 |
+
"classical.00003",
|
| 802 |
+
"classical.00004",
|
| 803 |
+
"classical.00005",
|
| 804 |
+
"classical.00006",
|
| 805 |
+
"classical.00007",
|
| 806 |
+
"classical.00008",
|
| 807 |
+
"classical.00009",
|
| 808 |
+
"classical.00010",
|
| 809 |
+
"classical.00068",
|
| 810 |
+
"classical.00069",
|
| 811 |
+
"classical.00070",
|
| 812 |
+
"classical.00071",
|
| 813 |
+
"classical.00072",
|
| 814 |
+
"classical.00073",
|
| 815 |
+
"classical.00074",
|
| 816 |
+
"classical.00075",
|
| 817 |
+
"classical.00076",
|
| 818 |
+
"country.00000",
|
| 819 |
+
"country.00001",
|
| 820 |
+
"country.00002",
|
| 821 |
+
"country.00003",
|
| 822 |
+
"country.00004",
|
| 823 |
+
"country.00005",
|
| 824 |
+
"country.00006",
|
| 825 |
+
"country.00007",
|
| 826 |
+
"country.00009",
|
| 827 |
+
"country.00010",
|
| 828 |
+
"country.00011",
|
| 829 |
+
"country.00012",
|
| 830 |
+
"country.00013",
|
| 831 |
+
"country.00014",
|
| 832 |
+
"country.00015",
|
| 833 |
+
"country.00016",
|
| 834 |
+
"country.00017",
|
| 835 |
+
"country.00018",
|
| 836 |
+
"country.00027",
|
| 837 |
+
"country.00041",
|
| 838 |
+
"country.00042",
|
| 839 |
+
"country.00045",
|
| 840 |
+
"country.00049",
|
| 841 |
+
"disco.00000",
|
| 842 |
+
"disco.00002",
|
| 843 |
+
"disco.00003",
|
| 844 |
+
"disco.00004",
|
| 845 |
+
"disco.00006",
|
| 846 |
+
"disco.00007",
|
| 847 |
+
"disco.00008",
|
| 848 |
+
"disco.00009",
|
| 849 |
+
"disco.00010",
|
| 850 |
+
"disco.00011",
|
| 851 |
+
"disco.00012",
|
| 852 |
+
"disco.00013",
|
| 853 |
+
"disco.00014",
|
| 854 |
+
"disco.00046",
|
| 855 |
+
"disco.00048",
|
| 856 |
+
"disco.00052",
|
| 857 |
+
"disco.00067",
|
| 858 |
+
"disco.00068",
|
| 859 |
+
"disco.00072",
|
| 860 |
+
"disco.00075",
|
| 861 |
+
"disco.00090",
|
| 862 |
+
"disco.00095",
|
| 863 |
+
"hiphop.00081",
|
| 864 |
+
"hiphop.00082",
|
| 865 |
+
"hiphop.00083",
|
| 866 |
+
"hiphop.00084",
|
| 867 |
+
"hiphop.00085",
|
| 868 |
+
"hiphop.00086",
|
| 869 |
+
"hiphop.00087",
|
| 870 |
+
"hiphop.00088",
|
| 871 |
+
"hiphop.00089",
|
| 872 |
+
"hiphop.00090",
|
| 873 |
+
"hiphop.00091",
|
| 874 |
+
"hiphop.00092",
|
| 875 |
+
"hiphop.00093",
|
| 876 |
+
"hiphop.00094",
|
| 877 |
+
"hiphop.00095",
|
| 878 |
+
"hiphop.00096",
|
| 879 |
+
"hiphop.00097",
|
| 880 |
+
"hiphop.00098",
|
| 881 |
+
"jazz.00002",
|
| 882 |
+
"jazz.00003",
|
| 883 |
+
"jazz.00004",
|
| 884 |
+
"jazz.00005",
|
| 885 |
+
"jazz.00006",
|
| 886 |
+
"jazz.00007",
|
| 887 |
+
"jazz.00008",
|
| 888 |
+
"jazz.00009",
|
| 889 |
+
"jazz.00010",
|
| 890 |
+
"jazz.00025",
|
| 891 |
+
"jazz.00026",
|
| 892 |
+
"jazz.00027",
|
| 893 |
+
"jazz.00028",
|
| 894 |
+
"jazz.00029",
|
| 895 |
+
"jazz.00030",
|
| 896 |
+
"jazz.00031",
|
| 897 |
+
"jazz.00032",
|
| 898 |
+
"metal.00000",
|
| 899 |
+
"metal.00001",
|
| 900 |
+
"metal.00006",
|
| 901 |
+
"metal.00007",
|
| 902 |
+
"metal.00008",
|
| 903 |
+
"metal.00009",
|
| 904 |
+
"metal.00010",
|
| 905 |
+
"metal.00011",
|
| 906 |
+
"metal.00016",
|
| 907 |
+
"metal.00017",
|
| 908 |
+
"metal.00018",
|
| 909 |
+
"metal.00019",
|
| 910 |
+
"metal.00020",
|
| 911 |
+
"metal.00036",
|
| 912 |
+
"metal.00037",
|
| 913 |
+
"metal.00068",
|
| 914 |
+
"metal.00076",
|
| 915 |
+
"metal.00077",
|
| 916 |
+
"metal.00081",
|
| 917 |
+
"metal.00082",
|
| 918 |
+
"pop.00010",
|
| 919 |
+
"pop.00053",
|
| 920 |
+
"pop.00055",
|
| 921 |
+
"pop.00058",
|
| 922 |
+
"pop.00059",
|
| 923 |
+
"pop.00060",
|
| 924 |
+
"pop.00061",
|
| 925 |
+
"pop.00062",
|
| 926 |
+
"pop.00081",
|
| 927 |
+
"pop.00083",
|
| 928 |
+
"pop.00084",
|
| 929 |
+
"pop.00085",
|
| 930 |
+
"pop.00086",
|
| 931 |
+
"reggae.00061",
|
| 932 |
+
"reggae.00062",
|
| 933 |
+
"reggae.00070",
|
| 934 |
+
"reggae.00072",
|
| 935 |
+
"reggae.00074",
|
| 936 |
+
"reggae.00076",
|
| 937 |
+
"reggae.00077",
|
| 938 |
+
"reggae.00078",
|
| 939 |
+
"reggae.00085",
|
| 940 |
+
"reggae.00092",
|
| 941 |
+
"reggae.00093",
|
| 942 |
+
"reggae.00094",
|
| 943 |
+
"reggae.00095",
|
| 944 |
+
"reggae.00096",
|
| 945 |
+
"reggae.00097",
|
| 946 |
+
"reggae.00098",
|
| 947 |
+
"reggae.00099",
|
| 948 |
+
"rock.00038",
|
| 949 |
+
"rock.00049",
|
| 950 |
+
"rock.00050",
|
| 951 |
+
"rock.00051",
|
| 952 |
+
"rock.00052",
|
| 953 |
+
"rock.00053",
|
| 954 |
+
"rock.00054",
|
| 955 |
+
"rock.00055",
|
| 956 |
+
"rock.00056",
|
| 957 |
+
"rock.00071",
|
| 958 |
+
"rock.00072",
|
| 959 |
+
"rock.00073",
|
| 960 |
+
"rock.00074",
|
| 961 |
+
"rock.00075",
|
| 962 |
+
"rock.00076",
|
| 963 |
+
"rock.00077",
|
| 964 |
+
"rock.00078",
|
| 965 |
+
"rock.00079",
|
| 966 |
+
"rock.00080",
|
| 967 |
+
"rock.00081",
|
| 968 |
+
"rock.00082",
|
| 969 |
+
"rock.00083",
|
| 970 |
+
"rock.00084",
|
| 971 |
+
"rock.00085",
|
| 972 |
+
]
|
| 973 |
+
|
| 974 |
+
|
| 975 |
+
URL = "http://opihi.cs.uvic.ca/sound/genres.tar.gz"
|
| 976 |
+
FOLDER_IN_ARCHIVE = "genres"
|
| 977 |
+
_CHECKSUMS = {
|
| 978 |
+
"http://opihi.cs.uvic.ca/sound/genres.tar.gz": "24347e0223d2ba798e0a558c4c172d9d4a19c00bb7963fe055d183dadb4ef2c6"
|
| 979 |
+
}
|
| 980 |
+
|
| 981 |
+
|
| 982 |
+
def load_gtzan_item(fileid: str, path: str, ext_audio: str) -> Tuple[Tensor, str]:
|
| 983 |
+
"""
|
| 984 |
+
Loads a file from the dataset and returns the raw waveform
|
| 985 |
+
as a Torch Tensor, its sample rate as an integer, and its
|
| 986 |
+
genre as a string.
|
| 987 |
+
"""
|
| 988 |
+
# Filenames are of the form label.id, e.g. blues.00078
|
| 989 |
+
label, _ = fileid.split(".")
|
| 990 |
+
|
| 991 |
+
# Read wav
|
| 992 |
+
file_audio = os.path.join(path, label, fileid + ext_audio)
|
| 993 |
+
waveform, sample_rate = torchaudio.load(file_audio)
|
| 994 |
+
|
| 995 |
+
return waveform, sample_rate, label
|
| 996 |
+
|
| 997 |
+
|
| 998 |
+
class GTZAN(Dataset):
|
| 999 |
+
"""*GTZAN* :cite:`tzanetakis_essl_cook_2001` dataset.
|
| 1000 |
+
|
| 1001 |
+
Note:
|
| 1002 |
+
Please see http://marsyas.info/downloads/datasets.html if you are planning to use
|
| 1003 |
+
this dataset to publish results.
|
| 1004 |
+
|
| 1005 |
+
Note:
|
| 1006 |
+
As of October 2022, the download link is not currently working. Setting ``download=True``
|
| 1007 |
+
in GTZAN dataset will result in a URL connection error.
|
| 1008 |
+
|
| 1009 |
+
Args:
|
| 1010 |
+
root (str or Path): Path to the directory where the dataset is found or downloaded.
|
| 1011 |
+
url (str, optional): The URL to download the dataset from.
|
| 1012 |
+
(default: ``"http://opihi.cs.uvic.ca/sound/genres.tar.gz"``)
|
| 1013 |
+
folder_in_archive (str, optional): The top-level directory of the dataset.
|
| 1014 |
+
download (bool, optional):
|
| 1015 |
+
Whether to download the dataset if it is not found at root path. (default: ``False``).
|
| 1016 |
+
subset (str or None, optional): Which subset of the dataset to use.
|
| 1017 |
+
One of ``"training"``, ``"validation"``, ``"testing"`` or ``None``.
|
| 1018 |
+
If ``None``, the entire dataset is used. (default: ``None``).
|
| 1019 |
+
"""
|
| 1020 |
+
|
| 1021 |
+
_ext_audio = ".wav"
|
| 1022 |
+
|
| 1023 |
+
def __init__(
|
| 1024 |
+
self,
|
| 1025 |
+
root: Union[str, Path],
|
| 1026 |
+
url: str = URL,
|
| 1027 |
+
folder_in_archive: str = FOLDER_IN_ARCHIVE,
|
| 1028 |
+
download: bool = False,
|
| 1029 |
+
subset: Optional[str] = None,
|
| 1030 |
+
) -> None:
|
| 1031 |
+
|
| 1032 |
+
# super(GTZAN, self).__init__()
|
| 1033 |
+
|
| 1034 |
+
# Get string representation of 'root' in case Path object is passed
|
| 1035 |
+
root = os.fspath(root)
|
| 1036 |
+
|
| 1037 |
+
self.root = root
|
| 1038 |
+
self.url = url
|
| 1039 |
+
self.folder_in_archive = folder_in_archive
|
| 1040 |
+
self.download = download
|
| 1041 |
+
self.subset = subset
|
| 1042 |
+
|
| 1043 |
+
if subset is not None and subset not in ["training", "validation", "testing"]:
|
| 1044 |
+
raise ValueError("When `subset` is not None, it must be one of ['training', 'validation', 'testing'].")
|
| 1045 |
+
|
| 1046 |
+
archive = os.path.basename(url)
|
| 1047 |
+
archive = os.path.join(root, archive)
|
| 1048 |
+
self._path = os.path.join(root, folder_in_archive)
|
| 1049 |
+
|
| 1050 |
+
if download:
|
| 1051 |
+
if not os.path.isdir(self._path):
|
| 1052 |
+
if not os.path.isfile(archive):
|
| 1053 |
+
checksum = _CHECKSUMS.get(url, None)
|
| 1054 |
+
download_url_to_file(url, archive, hash_prefix=checksum)
|
| 1055 |
+
_extract_tar(archive)
|
| 1056 |
+
|
| 1057 |
+
if not os.path.isdir(self._path):
|
| 1058 |
+
raise RuntimeError("Dataset not found. Please use `download=True` to download it.")
|
| 1059 |
+
|
| 1060 |
+
if self.subset is None:
|
| 1061 |
+
# Check every subdirectory under dataset root
|
| 1062 |
+
# which has the same name as the genres in
|
| 1063 |
+
# GTZAN (e.g. `root_dir'/blues/, `root_dir'/rock, etc.)
|
| 1064 |
+
# This lets users remove or move around song files,
|
| 1065 |
+
# useful when e.g. they want to use only some of the files
|
| 1066 |
+
# in a genre or want to label other files with a different
|
| 1067 |
+
# genre.
|
| 1068 |
+
self._walker = []
|
| 1069 |
+
|
| 1070 |
+
root = os.path.expanduser(self._path)
|
| 1071 |
+
|
| 1072 |
+
for directory in gtzan_genres:
|
| 1073 |
+
fulldir = os.path.join(root, directory)
|
| 1074 |
+
|
| 1075 |
+
if not os.path.exists(fulldir):
|
| 1076 |
+
continue
|
| 1077 |
+
|
| 1078 |
+
songs_in_genre = os.listdir(fulldir)
|
| 1079 |
+
songs_in_genre.sort()
|
| 1080 |
+
for fname in songs_in_genre:
|
| 1081 |
+
name, ext = os.path.splitext(fname)
|
| 1082 |
+
if ext.lower() == ".wav" and "." in name:
|
| 1083 |
+
# Check whether the file is of the form
|
| 1084 |
+
# `gtzan_genre`.`5 digit number`.wav
|
| 1085 |
+
genre, num = name.split(".")
|
| 1086 |
+
if genre in gtzan_genres and len(num) == 5 and num.isdigit():
|
| 1087 |
+
self._walker.append(name)
|
| 1088 |
+
else:
|
| 1089 |
+
if self.subset == "training":
|
| 1090 |
+
self._walker = filtered_train
|
| 1091 |
+
elif self.subset == "validation":
|
| 1092 |
+
self._walker = filtered_valid
|
| 1093 |
+
elif self.subset == "testing":
|
| 1094 |
+
self._walker = filtered_test
|
| 1095 |
+
|
| 1096 |
+
def __getitem__(self, n: int) -> Tuple[Tensor, int, str]:
|
| 1097 |
+
"""Load the n-th sample from the dataset.
|
| 1098 |
+
|
| 1099 |
+
Args:
|
| 1100 |
+
n (int): The index of the sample to be loaded
|
| 1101 |
+
|
| 1102 |
+
Returns:
|
| 1103 |
+
Tuple of the following items;
|
| 1104 |
+
|
| 1105 |
+
Tensor:
|
| 1106 |
+
Waveform
|
| 1107 |
+
int:
|
| 1108 |
+
Sample rate
|
| 1109 |
+
str:
|
| 1110 |
+
Label
|
| 1111 |
+
"""
|
| 1112 |
+
fileid = self._walker[n]
|
| 1113 |
+
item = load_gtzan_item(fileid, self._path, self._ext_audio)
|
| 1114 |
+
waveform, sample_rate, label = item
|
| 1115 |
+
return waveform, sample_rate, label
|
| 1116 |
+
|
| 1117 |
+
def __len__(self) -> int:
|
| 1118 |
+
return len(self._walker)
|
micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/datasets/iemocap.py
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import re
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
from typing import Optional, Tuple, Union
|
| 5 |
+
|
| 6 |
+
from torch import Tensor
|
| 7 |
+
from torch.utils.data import Dataset
|
| 8 |
+
from torchaudio.datasets.utils import _load_waveform
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
_SAMPLE_RATE = 16000
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def _get_wavs_paths(data_dir):
|
| 15 |
+
wav_dir = data_dir / "sentences" / "wav"
|
| 16 |
+
wav_paths = sorted(str(p) for p in wav_dir.glob("*/*.wav"))
|
| 17 |
+
relative_paths = []
|
| 18 |
+
for wav_path in wav_paths:
|
| 19 |
+
start = wav_path.find("Session")
|
| 20 |
+
wav_path = wav_path[start:]
|
| 21 |
+
relative_paths.append(wav_path)
|
| 22 |
+
return relative_paths
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class IEMOCAP(Dataset):
|
| 26 |
+
"""*IEMOCAP* :cite:`iemocap` dataset.
|
| 27 |
+
|
| 28 |
+
Args:
|
| 29 |
+
root (str or Path): Root directory where the dataset's top level directory is found
|
| 30 |
+
sessions (Tuple[int]): Tuple of sessions (1-5) to use. (Default: ``(1, 2, 3, 4, 5)``)
|
| 31 |
+
utterance_type (str or None, optional): Which type(s) of utterances to include in the dataset.
|
| 32 |
+
Options: ("scripted", "improvised", ``None``). If ``None``, both scripted and improvised
|
| 33 |
+
data are used.
|
| 34 |
+
"""
|
| 35 |
+
|
| 36 |
+
def __init__(
|
| 37 |
+
self,
|
| 38 |
+
root: Union[str, Path],
|
| 39 |
+
sessions: Tuple[str] = (1, 2, 3, 4, 5),
|
| 40 |
+
utterance_type: Optional[str] = None,
|
| 41 |
+
):
|
| 42 |
+
root = Path(root)
|
| 43 |
+
self._path = root / "IEMOCAP"
|
| 44 |
+
|
| 45 |
+
if not os.path.isdir(self._path):
|
| 46 |
+
raise RuntimeError("Dataset not found.")
|
| 47 |
+
|
| 48 |
+
if utterance_type not in ["scripted", "improvised", None]:
|
| 49 |
+
raise ValueError("utterance_type must be one of ['scripted', 'improvised', or None]")
|
| 50 |
+
|
| 51 |
+
all_data = []
|
| 52 |
+
self.data = []
|
| 53 |
+
self.mapping = {}
|
| 54 |
+
|
| 55 |
+
for session in sessions:
|
| 56 |
+
session_name = f"Session{session}"
|
| 57 |
+
session_dir = self._path / session_name
|
| 58 |
+
|
| 59 |
+
# get wav paths
|
| 60 |
+
wav_paths = _get_wavs_paths(session_dir)
|
| 61 |
+
for wav_path in wav_paths:
|
| 62 |
+
wav_stem = str(Path(wav_path).stem)
|
| 63 |
+
all_data.append(wav_stem)
|
| 64 |
+
|
| 65 |
+
# add labels
|
| 66 |
+
label_dir = session_dir / "dialog" / "EmoEvaluation"
|
| 67 |
+
query = "*.txt"
|
| 68 |
+
if utterance_type == "scripted":
|
| 69 |
+
query = "*script*.txt"
|
| 70 |
+
elif utterance_type == "improvised":
|
| 71 |
+
query = "*impro*.txt"
|
| 72 |
+
label_paths = label_dir.glob(query)
|
| 73 |
+
|
| 74 |
+
for label_path in label_paths:
|
| 75 |
+
with open(label_path, "r") as f:
|
| 76 |
+
for line in f:
|
| 77 |
+
if not line.startswith("["):
|
| 78 |
+
continue
|
| 79 |
+
line = re.split("[\t\n]", line)
|
| 80 |
+
wav_stem = line[1]
|
| 81 |
+
label = line[2]
|
| 82 |
+
if wav_stem not in all_data:
|
| 83 |
+
continue
|
| 84 |
+
if label not in ["neu", "hap", "ang", "sad", "exc", "fru"]:
|
| 85 |
+
continue
|
| 86 |
+
self.mapping[wav_stem] = {}
|
| 87 |
+
self.mapping[wav_stem]["label"] = label
|
| 88 |
+
|
| 89 |
+
for wav_path in wav_paths:
|
| 90 |
+
wav_stem = str(Path(wav_path).stem)
|
| 91 |
+
if wav_stem in self.mapping:
|
| 92 |
+
self.data.append(wav_stem)
|
| 93 |
+
self.mapping[wav_stem]["path"] = wav_path
|
| 94 |
+
|
| 95 |
+
def get_metadata(self, n: int) -> Tuple[str, int, str, str, str]:
|
| 96 |
+
"""Get metadata for the n-th sample from the dataset. Returns filepath instead of waveform,
|
| 97 |
+
but otherwise returns the same fields as :py:meth:`__getitem__`.
|
| 98 |
+
|
| 99 |
+
Args:
|
| 100 |
+
n (int): The index of the sample to be loaded
|
| 101 |
+
|
| 102 |
+
Returns:
|
| 103 |
+
Tuple of the following items;
|
| 104 |
+
|
| 105 |
+
str:
|
| 106 |
+
Path to audio
|
| 107 |
+
int:
|
| 108 |
+
Sample rate
|
| 109 |
+
str:
|
| 110 |
+
File name
|
| 111 |
+
str:
|
| 112 |
+
Label (one of ``"neu"``, ``"hap"``, ``"ang"``, ``"sad"``, ``"exc"``, ``"fru"``)
|
| 113 |
+
str:
|
| 114 |
+
Speaker
|
| 115 |
+
"""
|
| 116 |
+
wav_stem = self.data[n]
|
| 117 |
+
wav_path = self.mapping[wav_stem]["path"]
|
| 118 |
+
label = self.mapping[wav_stem]["label"]
|
| 119 |
+
speaker = wav_stem.split("_")[0]
|
| 120 |
+
return (wav_path, _SAMPLE_RATE, wav_stem, label, speaker)
|
| 121 |
+
|
| 122 |
+
def __getitem__(self, n: int) -> Tuple[Tensor, int, str, str, str]:
|
| 123 |
+
"""Load the n-th sample from the dataset.
|
| 124 |
+
|
| 125 |
+
Args:
|
| 126 |
+
n (int): The index of the sample to be loaded
|
| 127 |
+
|
| 128 |
+
Returns:
|
| 129 |
+
Tuple of the following items;
|
| 130 |
+
|
| 131 |
+
Tensor:
|
| 132 |
+
Waveform
|
| 133 |
+
int:
|
| 134 |
+
Sample rate
|
| 135 |
+
str:
|
| 136 |
+
File name
|
| 137 |
+
str:
|
| 138 |
+
Label (one of ``"neu"``, ``"hap"``, ``"ang"``, ``"sad"``, ``"exc"``, ``"fru"``)
|
| 139 |
+
str:
|
| 140 |
+
Speaker
|
| 141 |
+
"""
|
| 142 |
+
metadata = self.get_metadata(n)
|
| 143 |
+
waveform = _load_waveform(self._path, metadata[0], metadata[1])
|
| 144 |
+
return (waveform,) + metadata[1:]
|
| 145 |
+
|
| 146 |
+
def __len__(self):
|
| 147 |
+
return len(self.data)
|
micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/datasets/librilight_limited.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
from typing import List, Tuple, Union
|
| 4 |
+
|
| 5 |
+
import torchaudio
|
| 6 |
+
from torch import Tensor
|
| 7 |
+
from torch.utils.data import Dataset
|
| 8 |
+
from torchaudio._internal import download_url_to_file
|
| 9 |
+
from torchaudio.datasets.librispeech import _get_librispeech_metadata
|
| 10 |
+
from torchaudio.datasets.utils import _extract_tar
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
_ARCHIVE_NAME = "librispeech_finetuning"
|
| 14 |
+
_URL = "https://dl.fbaipublicfiles.com/librilight/data/librispeech_finetuning.tgz"
|
| 15 |
+
_CHECKSUM = "5d1efdc777b548194d7e09ba89126e2188026df9fd57aa57eb14408d2b2342af"
|
| 16 |
+
_SUBSET_MAP = {"10min": ["1h/0"], "1h": ["1h/*"], "10h": ["1h/*", "9h"]}
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def _get_fileids_paths(path: Path, folders: List[str], _ext_audio: str) -> List[Tuple[str, str]]:
|
| 20 |
+
"""Get the file names and the corresponding file paths without `speaker_id`
|
| 21 |
+
and `chapter_id` directories.
|
| 22 |
+
The format of path is like:
|
| 23 |
+
{root}/{_ARCHIVE_NAME}/1h/[0-5]/[clean, other] or
|
| 24 |
+
{root}/{_ARCHIVE_NAME}/9h/[clean, other]
|
| 25 |
+
|
| 26 |
+
Args:
|
| 27 |
+
path (Path): Root path to the dataset.
|
| 28 |
+
folders (List[str]): Folders that contain the desired audio files.
|
| 29 |
+
_ext_audio (str): Extension of audio files.
|
| 30 |
+
|
| 31 |
+
Returns:
|
| 32 |
+
List[Tuple[str, str]]:
|
| 33 |
+
List of tuples where the first element is the relative path to the audio file.
|
| 34 |
+
The format of relative path is like:
|
| 35 |
+
1h/[0-5]/[clean, other] or 9h/[clean, other]
|
| 36 |
+
The second element is the file name without audio extension.
|
| 37 |
+
"""
|
| 38 |
+
|
| 39 |
+
path = Path(path)
|
| 40 |
+
files_paths = []
|
| 41 |
+
for folder in folders:
|
| 42 |
+
paths = [p.relative_to(path) for p in path.glob(f"{folder}/*/*/*/*{_ext_audio}")]
|
| 43 |
+
files_paths += [(str(p.parent.parent.parent), str(p.stem)) for p in paths] # get subset folder and file name
|
| 44 |
+
files_paths.sort(key=lambda x: x[0] + x[1])
|
| 45 |
+
return files_paths
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class LibriLightLimited(Dataset):
|
| 49 |
+
"""Subset of Libri-light :cite:`librilight` dataset,
|
| 50 |
+
which was used in HuBERT :cite:`hsu2021hubert` for supervised fine-tuning.
|
| 51 |
+
|
| 52 |
+
Args:
|
| 53 |
+
root (str or Path): Path to the directory where the dataset is found or downloaded.
|
| 54 |
+
subset (str, optional): The subset to use. Options: [``"10min"``, ``"1h"``, ``"10h"``]
|
| 55 |
+
(Default: ``"10min"``).
|
| 56 |
+
download (bool, optional):
|
| 57 |
+
Whether to download the dataset if it is not found at root path. (default: ``False``).
|
| 58 |
+
"""
|
| 59 |
+
|
| 60 |
+
_ext_txt = ".trans.txt"
|
| 61 |
+
_ext_audio = ".flac"
|
| 62 |
+
|
| 63 |
+
def __init__(
|
| 64 |
+
self,
|
| 65 |
+
root: Union[str, Path],
|
| 66 |
+
subset: str = "10min",
|
| 67 |
+
download: bool = False,
|
| 68 |
+
) -> None:
|
| 69 |
+
if subset not in _SUBSET_MAP:
|
| 70 |
+
raise ValueError(f"`subset` must be one of {_SUBSET_MAP.keys()}. Found: {subset}")
|
| 71 |
+
folders = _SUBSET_MAP[subset]
|
| 72 |
+
|
| 73 |
+
root = os.fspath(root)
|
| 74 |
+
self._path = os.path.join(root, _ARCHIVE_NAME)
|
| 75 |
+
archive = os.path.join(root, f"{_ARCHIVE_NAME}.tgz")
|
| 76 |
+
if not os.path.isdir(self._path):
|
| 77 |
+
if not download:
|
| 78 |
+
raise RuntimeError("Dataset not found. Please use `download=True` to download")
|
| 79 |
+
if not os.path.isfile(archive):
|
| 80 |
+
download_url_to_file(_URL, archive, hash_prefix=_CHECKSUM)
|
| 81 |
+
_extract_tar(archive)
|
| 82 |
+
self._fileids_paths = _get_fileids_paths(self._path, folders, self._ext_audio)
|
| 83 |
+
|
| 84 |
+
def __getitem__(self, n: int) -> Tuple[Tensor, int, str, int, int, int]:
|
| 85 |
+
"""Load the n-th sample from the dataset.
|
| 86 |
+
|
| 87 |
+
Args:
|
| 88 |
+
n (int): The index of the sample to be loaded
|
| 89 |
+
Returns:
|
| 90 |
+
Tuple of the following items;
|
| 91 |
+
|
| 92 |
+
Tensor:
|
| 93 |
+
Waveform
|
| 94 |
+
int:
|
| 95 |
+
Sample rate
|
| 96 |
+
str:
|
| 97 |
+
Transcript
|
| 98 |
+
int:
|
| 99 |
+
Speaker ID
|
| 100 |
+
int:
|
| 101 |
+
Chapter ID
|
| 102 |
+
int:
|
| 103 |
+
Utterance ID
|
| 104 |
+
"""
|
| 105 |
+
file_path, fileid = self._fileids_paths[n]
|
| 106 |
+
metadata = _get_librispeech_metadata(fileid, self._path, file_path, self._ext_audio, self._ext_txt)
|
| 107 |
+
waveform, _ = torchaudio.load(os.path.join(self._path, metadata[0]))
|
| 108 |
+
return (waveform,) + metadata[1:]
|
| 109 |
+
|
| 110 |
+
def __len__(self) -> int:
|
| 111 |
+
return len(self._fileids_paths)
|
micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/datasets/librimix.py
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
from typing import List, Tuple, Union
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
from torch.utils.data import Dataset
|
| 7 |
+
from torchaudio.datasets.utils import _load_waveform
|
| 8 |
+
|
| 9 |
+
_TASKS_TO_MIXTURE = {
|
| 10 |
+
"sep_clean": "mix_clean",
|
| 11 |
+
"enh_single": "mix_single",
|
| 12 |
+
"enh_both": "mix_both",
|
| 13 |
+
"sep_noisy": "mix_both",
|
| 14 |
+
}
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class LibriMix(Dataset):
|
| 18 |
+
r"""*LibriMix* :cite:`cosentino2020librimix` dataset.
|
| 19 |
+
|
| 20 |
+
Args:
|
| 21 |
+
root (str or Path): The path where the directory ``Libri2Mix`` or
|
| 22 |
+
``Libri3Mix`` is stored. Not the path of those directories.
|
| 23 |
+
subset (str, optional): The subset to use. Options: [``"train-360"``, ``"train-100"``,
|
| 24 |
+
``"dev"``, and ``"test"``] (Default: ``"train-360"``).
|
| 25 |
+
num_speakers (int, optional): The number of speakers, which determines the directories
|
| 26 |
+
to traverse. The Dataset will traverse ``s1`` to ``sN`` directories to collect
|
| 27 |
+
N source audios. (Default: 2)
|
| 28 |
+
sample_rate (int, optional): Sample rate of audio files. The ``sample_rate`` determines
|
| 29 |
+
which subdirectory the audio are fetched. If any of the audio has a different sample
|
| 30 |
+
rate, raises ``ValueError``. Options: [8000, 16000] (Default: 8000)
|
| 31 |
+
task (str, optional): The task of LibriMix.
|
| 32 |
+
Options: [``"enh_single"``, ``"enh_both"``, ``"sep_clean"``, ``"sep_noisy"``]
|
| 33 |
+
(Default: ``"sep_clean"``)
|
| 34 |
+
mode (str, optional): The mode when creating the mixture. If set to ``"min"``, the lengths of mixture
|
| 35 |
+
and sources are the minimum length of all sources. If set to ``"max"``, the lengths of mixture and
|
| 36 |
+
sources are zero padded to the maximum length of all sources.
|
| 37 |
+
Options: [``"min"``, ``"max"``]
|
| 38 |
+
(Default: ``"min"``)
|
| 39 |
+
|
| 40 |
+
Note:
|
| 41 |
+
The LibriMix dataset needs to be manually generated. Please check https://github.com/JorisCos/LibriMix
|
| 42 |
+
"""
|
| 43 |
+
|
| 44 |
+
def __init__(
|
| 45 |
+
self,
|
| 46 |
+
root: Union[str, Path],
|
| 47 |
+
subset: str = "train-360",
|
| 48 |
+
num_speakers: int = 2,
|
| 49 |
+
sample_rate: int = 8000,
|
| 50 |
+
task: str = "sep_clean",
|
| 51 |
+
mode: str = "min",
|
| 52 |
+
):
|
| 53 |
+
self.root = Path(root) / f"Libri{num_speakers}Mix"
|
| 54 |
+
if not os.path.exists(self.root):
|
| 55 |
+
raise RuntimeError(
|
| 56 |
+
f"The path {self.root} doesn't exist. "
|
| 57 |
+
"Please check the ``root`` path and ``num_speakers`` or download the dataset manually."
|
| 58 |
+
)
|
| 59 |
+
if mode not in ["max", "min"]:
|
| 60 |
+
raise ValueError(f'Expect ``mode`` to be one in ["min", "max"]. Found {mode}.')
|
| 61 |
+
if sample_rate == 8000:
|
| 62 |
+
mix_dir = self.root / "wav8k" / mode / subset
|
| 63 |
+
elif sample_rate == 16000:
|
| 64 |
+
mix_dir = self.root / "wav16k" / mode / subset
|
| 65 |
+
else:
|
| 66 |
+
raise ValueError(f"Unsupported sample rate. Found {sample_rate}.")
|
| 67 |
+
self.sample_rate = sample_rate
|
| 68 |
+
self.task = task
|
| 69 |
+
|
| 70 |
+
self.mix_dir = mix_dir / _TASKS_TO_MIXTURE[task]
|
| 71 |
+
if task == "enh_both":
|
| 72 |
+
self.src_dirs = [(mix_dir / "mix_clean")]
|
| 73 |
+
else:
|
| 74 |
+
self.src_dirs = [(mix_dir / f"s{i+1}") for i in range(num_speakers)]
|
| 75 |
+
|
| 76 |
+
self.files = [p.name for p in self.mix_dir.glob("*.wav")]
|
| 77 |
+
self.files.sort()
|
| 78 |
+
|
| 79 |
+
def _load_sample(self, key) -> Tuple[int, torch.Tensor, List[torch.Tensor]]:
|
| 80 |
+
metadata = self.get_metadata(key)
|
| 81 |
+
mixed = _load_waveform(self.root, metadata[1], metadata[0])
|
| 82 |
+
srcs = []
|
| 83 |
+
for i, path_ in enumerate(metadata[2]):
|
| 84 |
+
src = _load_waveform(self.root, path_, metadata[0])
|
| 85 |
+
if mixed.shape != src.shape:
|
| 86 |
+
raise ValueError(f"Different waveform shapes. mixed: {mixed.shape}, src[{i}]: {src.shape}")
|
| 87 |
+
srcs.append(src)
|
| 88 |
+
return self.sample_rate, mixed, srcs
|
| 89 |
+
|
| 90 |
+
def get_metadata(self, key: int) -> Tuple[int, str, List[str]]:
|
| 91 |
+
"""Get metadata for the n-th sample from the dataset.
|
| 92 |
+
|
| 93 |
+
Args:
|
| 94 |
+
key (int): The index of the sample to be loaded
|
| 95 |
+
|
| 96 |
+
Returns:
|
| 97 |
+
Tuple of the following items;
|
| 98 |
+
|
| 99 |
+
int:
|
| 100 |
+
Sample rate
|
| 101 |
+
str:
|
| 102 |
+
Path to mixed audio
|
| 103 |
+
List of str:
|
| 104 |
+
List of paths to source audios
|
| 105 |
+
"""
|
| 106 |
+
filename = self.files[key]
|
| 107 |
+
mixed_path = os.path.relpath(self.mix_dir / filename, self.root)
|
| 108 |
+
srcs_paths = []
|
| 109 |
+
for dir_ in self.src_dirs:
|
| 110 |
+
src = os.path.relpath(dir_ / filename, self.root)
|
| 111 |
+
srcs_paths.append(src)
|
| 112 |
+
return self.sample_rate, mixed_path, srcs_paths
|
| 113 |
+
|
| 114 |
+
def __len__(self) -> int:
|
| 115 |
+
return len(self.files)
|
| 116 |
+
|
| 117 |
+
def __getitem__(self, key: int) -> Tuple[int, torch.Tensor, List[torch.Tensor]]:
|
| 118 |
+
"""Load the n-th sample from the dataset.
|
| 119 |
+
|
| 120 |
+
Args:
|
| 121 |
+
key (int): The index of the sample to be loaded
|
| 122 |
+
|
| 123 |
+
Returns:
|
| 124 |
+
Tuple of the following items;
|
| 125 |
+
|
| 126 |
+
int:
|
| 127 |
+
Sample rate
|
| 128 |
+
Tensor:
|
| 129 |
+
Mixture waveform
|
| 130 |
+
List of Tensors:
|
| 131 |
+
List of source waveforms
|
| 132 |
+
"""
|
| 133 |
+
return self._load_sample(key)
|
micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/datasets/librispeech.py
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
from typing import Tuple, Union
|
| 4 |
+
|
| 5 |
+
from torch import Tensor
|
| 6 |
+
from torch.utils.data import Dataset
|
| 7 |
+
from torchaudio._internal import download_url_to_file
|
| 8 |
+
from torchaudio.datasets.utils import _extract_tar, _load_waveform
|
| 9 |
+
|
| 10 |
+
URL = "train-clean-100"
|
| 11 |
+
FOLDER_IN_ARCHIVE = "LibriSpeech"
|
| 12 |
+
SAMPLE_RATE = 16000
|
| 13 |
+
_DATA_SUBSETS = [
|
| 14 |
+
"dev-clean",
|
| 15 |
+
"dev-other",
|
| 16 |
+
"test-clean",
|
| 17 |
+
"test-other",
|
| 18 |
+
"train-clean-100",
|
| 19 |
+
"train-clean-360",
|
| 20 |
+
"train-other-500",
|
| 21 |
+
]
|
| 22 |
+
_CHECKSUMS = {
|
| 23 |
+
"http://www.openslr.org/resources/12/dev-clean.tar.gz": "76f87d090650617fca0cac8f88b9416e0ebf80350acb97b343a85fa903728ab3", # noqa: E501
|
| 24 |
+
"http://www.openslr.org/resources/12/dev-other.tar.gz": "12661c48e8c3fe1de2c1caa4c3e135193bfb1811584f11f569dd12645aa84365", # noqa: E501
|
| 25 |
+
"http://www.openslr.org/resources/12/test-clean.tar.gz": "39fde525e59672dc6d1551919b1478f724438a95aa55f874b576be21967e6c23", # noqa: E501
|
| 26 |
+
"http://www.openslr.org/resources/12/test-other.tar.gz": "d09c181bba5cf717b3dee7d4d592af11a3ee3a09e08ae025c5506f6ebe961c29", # noqa: E501
|
| 27 |
+
"http://www.openslr.org/resources/12/train-clean-100.tar.gz": "d4ddd1d5a6ab303066f14971d768ee43278a5f2a0aa43dc716b0e64ecbbbf6e2", # noqa: E501
|
| 28 |
+
"http://www.openslr.org/resources/12/train-clean-360.tar.gz": "146a56496217e96c14334a160df97fffedd6e0a04e66b9c5af0d40be3c792ecf", # noqa: E501
|
| 29 |
+
"http://www.openslr.org/resources/12/train-other-500.tar.gz": "ddb22f27f96ec163645d53215559df6aa36515f26e01dd70798188350adcb6d2", # noqa: E501
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def _download_librispeech(root, url):
|
| 34 |
+
base_url = "http://www.openslr.org/resources/12/"
|
| 35 |
+
ext_archive = ".tar.gz"
|
| 36 |
+
|
| 37 |
+
filename = url + ext_archive
|
| 38 |
+
archive = os.path.join(root, filename)
|
| 39 |
+
download_url = os.path.join(base_url, filename)
|
| 40 |
+
if not os.path.isfile(archive):
|
| 41 |
+
checksum = _CHECKSUMS.get(download_url, None)
|
| 42 |
+
download_url_to_file(download_url, archive, hash_prefix=checksum)
|
| 43 |
+
_extract_tar(archive)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def _get_librispeech_metadata(
|
| 47 |
+
fileid: str, root: str, folder: str, ext_audio: str, ext_txt: str
|
| 48 |
+
) -> Tuple[str, int, str, int, int, int]:
|
| 49 |
+
speaker_id, chapter_id, utterance_id = fileid.split("-")
|
| 50 |
+
|
| 51 |
+
# Get audio path and sample rate
|
| 52 |
+
fileid_audio = f"{speaker_id}-{chapter_id}-{utterance_id}"
|
| 53 |
+
filepath = os.path.join(folder, speaker_id, chapter_id, f"{fileid_audio}{ext_audio}")
|
| 54 |
+
|
| 55 |
+
# Load text
|
| 56 |
+
file_text = f"{speaker_id}-{chapter_id}{ext_txt}"
|
| 57 |
+
file_text = os.path.join(root, folder, speaker_id, chapter_id, file_text)
|
| 58 |
+
with open(file_text) as ft:
|
| 59 |
+
for line in ft:
|
| 60 |
+
fileid_text, transcript = line.strip().split(" ", 1)
|
| 61 |
+
if fileid_audio == fileid_text:
|
| 62 |
+
break
|
| 63 |
+
else:
|
| 64 |
+
# Translation not found
|
| 65 |
+
raise FileNotFoundError(f"Translation not found for {fileid_audio}")
|
| 66 |
+
|
| 67 |
+
return (
|
| 68 |
+
filepath,
|
| 69 |
+
SAMPLE_RATE,
|
| 70 |
+
transcript,
|
| 71 |
+
int(speaker_id),
|
| 72 |
+
int(chapter_id),
|
| 73 |
+
int(utterance_id),
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
class LIBRISPEECH(Dataset):
|
| 78 |
+
"""*LibriSpeech* :cite:`7178964` dataset.
|
| 79 |
+
|
| 80 |
+
Args:
|
| 81 |
+
root (str or Path): Path to the directory where the dataset is found or downloaded.
|
| 82 |
+
url (str, optional): The URL to download the dataset from,
|
| 83 |
+
or the type of the dataset to dowload.
|
| 84 |
+
Allowed type values are ``"dev-clean"``, ``"dev-other"``, ``"test-clean"``,
|
| 85 |
+
``"test-other"``, ``"train-clean-100"``, ``"train-clean-360"`` and
|
| 86 |
+
``"train-other-500"``. (default: ``"train-clean-100"``)
|
| 87 |
+
folder_in_archive (str, optional):
|
| 88 |
+
The top-level directory of the dataset. (default: ``"LibriSpeech"``)
|
| 89 |
+
download (bool, optional):
|
| 90 |
+
Whether to download the dataset if it is not found at root path. (default: ``False``).
|
| 91 |
+
"""
|
| 92 |
+
|
| 93 |
+
_ext_txt = ".trans.txt"
|
| 94 |
+
_ext_audio = ".flac"
|
| 95 |
+
|
| 96 |
+
def __init__(
|
| 97 |
+
self,
|
| 98 |
+
root: Union[str, Path],
|
| 99 |
+
url: str = URL,
|
| 100 |
+
folder_in_archive: str = FOLDER_IN_ARCHIVE,
|
| 101 |
+
download: bool = False,
|
| 102 |
+
) -> None:
|
| 103 |
+
self._url = url
|
| 104 |
+
if url not in _DATA_SUBSETS:
|
| 105 |
+
raise ValueError(f"Invalid url '{url}' given; please provide one of {_DATA_SUBSETS}.")
|
| 106 |
+
|
| 107 |
+
root = os.fspath(root)
|
| 108 |
+
self._archive = os.path.join(root, folder_in_archive)
|
| 109 |
+
self._path = os.path.join(root, folder_in_archive, url)
|
| 110 |
+
|
| 111 |
+
if not os.path.isdir(self._path):
|
| 112 |
+
if download:
|
| 113 |
+
_download_librispeech(root, url)
|
| 114 |
+
else:
|
| 115 |
+
raise RuntimeError(
|
| 116 |
+
f"Dataset not found at {self._path}. Please set `download=True` to download the dataset."
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
self._walker = sorted(str(p.stem) for p in Path(self._path).glob("*/*/*" + self._ext_audio))
|
| 120 |
+
|
| 121 |
+
def get_metadata(self, n: int) -> Tuple[str, int, str, int, int, int]:
|
| 122 |
+
"""Get metadata for the n-th sample from the dataset. Returns filepath instead of waveform,
|
| 123 |
+
but otherwise returns the same fields as :py:func:`__getitem__`.
|
| 124 |
+
|
| 125 |
+
Args:
|
| 126 |
+
n (int): The index of the sample to be loaded
|
| 127 |
+
|
| 128 |
+
Returns:
|
| 129 |
+
Tuple of the following items;
|
| 130 |
+
|
| 131 |
+
str:
|
| 132 |
+
Path to audio
|
| 133 |
+
int:
|
| 134 |
+
Sample rate
|
| 135 |
+
str:
|
| 136 |
+
Transcript
|
| 137 |
+
int:
|
| 138 |
+
Speaker ID
|
| 139 |
+
int:
|
| 140 |
+
Chapter ID
|
| 141 |
+
int:
|
| 142 |
+
Utterance ID
|
| 143 |
+
"""
|
| 144 |
+
fileid = self._walker[n]
|
| 145 |
+
return _get_librispeech_metadata(fileid, self._archive, self._url, self._ext_audio, self._ext_txt)
|
| 146 |
+
|
| 147 |
+
def __getitem__(self, n: int) -> Tuple[Tensor, int, str, int, int, int]:
|
| 148 |
+
"""Load the n-th sample from the dataset.
|
| 149 |
+
|
| 150 |
+
Args:
|
| 151 |
+
n (int): The index of the sample to be loaded
|
| 152 |
+
|
| 153 |
+
Returns:
|
| 154 |
+
Tuple of the following items;
|
| 155 |
+
|
| 156 |
+
Tensor:
|
| 157 |
+
Waveform
|
| 158 |
+
int:
|
| 159 |
+
Sample rate
|
| 160 |
+
str:
|
| 161 |
+
Transcript
|
| 162 |
+
int:
|
| 163 |
+
Speaker ID
|
| 164 |
+
int:
|
| 165 |
+
Chapter ID
|
| 166 |
+
int:
|
| 167 |
+
Utterance ID
|
| 168 |
+
"""
|
| 169 |
+
metadata = self.get_metadata(n)
|
| 170 |
+
waveform = _load_waveform(self._archive, metadata[0], metadata[1])
|
| 171 |
+
return (waveform,) + metadata[1:]
|
| 172 |
+
|
| 173 |
+
def __len__(self) -> int:
|
| 174 |
+
return len(self._walker)
|
micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/datasets/librispeech_biasing.py
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
from typing import List, Tuple, Union
|
| 4 |
+
|
| 5 |
+
from torch import Tensor
|
| 6 |
+
from torch.utils.data import Dataset
|
| 7 |
+
from torchaudio._internal import download_url_to_file
|
| 8 |
+
from torchaudio.datasets.utils import _extract_tar, _load_waveform
|
| 9 |
+
|
| 10 |
+
URL = "train-clean-100"
|
| 11 |
+
FOLDER_IN_ARCHIVE = "LibriSpeech"
|
| 12 |
+
SAMPLE_RATE = 16000
|
| 13 |
+
_DATA_SUBSETS = [
|
| 14 |
+
"dev-clean",
|
| 15 |
+
"dev-other",
|
| 16 |
+
"test-clean",
|
| 17 |
+
"test-other",
|
| 18 |
+
"train-clean-100",
|
| 19 |
+
"train-clean-360",
|
| 20 |
+
"train-other-500",
|
| 21 |
+
]
|
| 22 |
+
_CHECKSUMS = {
|
| 23 |
+
"http://www.openslr.org/resources/12/dev-clean.tar.gz": "76f87d090650617fca0cac8f88b9416e0ebf80350acb97b343a85fa903728ab3", # noqa: E501
|
| 24 |
+
"http://www.openslr.org/resources/12/dev-other.tar.gz": "12661c48e8c3fe1de2c1caa4c3e135193bfb1811584f11f569dd12645aa84365", # noqa: E501
|
| 25 |
+
"http://www.openslr.org/resources/12/test-clean.tar.gz": "39fde525e59672dc6d1551919b1478f724438a95aa55f874b576be21967e6c23", # noqa: E501
|
| 26 |
+
"http://www.openslr.org/resources/12/test-other.tar.gz": "d09c181bba5cf717b3dee7d4d592af11a3ee3a09e08ae025c5506f6ebe961c29", # noqa: E501
|
| 27 |
+
"http://www.openslr.org/resources/12/train-clean-100.tar.gz": "d4ddd1d5a6ab303066f14971d768ee43278a5f2a0aa43dc716b0e64ecbbbf6e2", # noqa: E501
|
| 28 |
+
"http://www.openslr.org/resources/12/train-clean-360.tar.gz": "146a56496217e96c14334a160df97fffedd6e0a04e66b9c5af0d40be3c792ecf", # noqa: E501
|
| 29 |
+
"http://www.openslr.org/resources/12/train-other-500.tar.gz": "ddb22f27f96ec163645d53215559df6aa36515f26e01dd70798188350adcb6d2", # noqa: E501
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def _download_librispeech(root, url):
|
| 34 |
+
base_url = "http://www.openslr.org/resources/12/"
|
| 35 |
+
ext_archive = ".tar.gz"
|
| 36 |
+
|
| 37 |
+
filename = url + ext_archive
|
| 38 |
+
archive = os.path.join(root, filename)
|
| 39 |
+
download_url = os.path.join(base_url, filename)
|
| 40 |
+
if not os.path.isfile(archive):
|
| 41 |
+
checksum = _CHECKSUMS.get(download_url, None)
|
| 42 |
+
download_url_to_file(download_url, archive, hash_prefix=checksum)
|
| 43 |
+
_extract_tar(archive)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def _get_librispeech_metadata(
|
| 47 |
+
fileid: str, root: str, folder: str, ext_audio: str, ext_txt: str, blist: List[str]
|
| 48 |
+
) -> Tuple[str, int, str, int, int, int]:
|
| 49 |
+
blist = blist or []
|
| 50 |
+
speaker_id, chapter_id, utterance_id = fileid.split("-")
|
| 51 |
+
|
| 52 |
+
# Get audio path and sample rate
|
| 53 |
+
fileid_audio = f"{speaker_id}-{chapter_id}-{utterance_id}"
|
| 54 |
+
filepath = os.path.join(folder, speaker_id, chapter_id, f"{fileid_audio}{ext_audio}")
|
| 55 |
+
|
| 56 |
+
# Load text
|
| 57 |
+
file_text = f"{speaker_id}-{chapter_id}{ext_txt}"
|
| 58 |
+
file_text = os.path.join(root, folder, speaker_id, chapter_id, file_text)
|
| 59 |
+
uttblist = []
|
| 60 |
+
with open(file_text) as ft:
|
| 61 |
+
for line in ft:
|
| 62 |
+
fileid_text, transcript = line.strip().split(" ", 1)
|
| 63 |
+
if fileid_audio == fileid_text:
|
| 64 |
+
# get utterance biasing list
|
| 65 |
+
for word in transcript.split():
|
| 66 |
+
if word in blist and word not in uttblist:
|
| 67 |
+
uttblist.append(word)
|
| 68 |
+
break
|
| 69 |
+
else:
|
| 70 |
+
# Translation not found
|
| 71 |
+
raise FileNotFoundError(f"Translation not found for {fileid_audio}")
|
| 72 |
+
|
| 73 |
+
return (
|
| 74 |
+
filepath,
|
| 75 |
+
SAMPLE_RATE,
|
| 76 |
+
transcript,
|
| 77 |
+
int(speaker_id),
|
| 78 |
+
int(chapter_id),
|
| 79 |
+
int(utterance_id),
|
| 80 |
+
uttblist,
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
class LibriSpeechBiasing(Dataset):
|
| 85 |
+
"""*LibriSpeech* :cite:`7178964` dataset with prefix-tree construction and biasing support.
|
| 86 |
+
|
| 87 |
+
Args:
|
| 88 |
+
root (str or Path): Path to the directory where the dataset is found or downloaded.
|
| 89 |
+
url (str, optional): The URL to download the dataset from,
|
| 90 |
+
or the type of the dataset to dowload.
|
| 91 |
+
Allowed type values are ``"dev-clean"``, ``"dev-other"``, ``"test-clean"``,
|
| 92 |
+
``"test-other"``, ``"train-clean-100"``, ``"train-clean-360"`` and
|
| 93 |
+
``"train-other-500"``. (default: ``"train-clean-100"``)
|
| 94 |
+
folder_in_archive (str, optional):
|
| 95 |
+
The top-level directory of the dataset. (default: ``"LibriSpeech"``)
|
| 96 |
+
download (bool, optional):
|
| 97 |
+
Whether to download the dataset if it is not found at root path. (default: ``False``).
|
| 98 |
+
blist (list, optional):
|
| 99 |
+
The list of biasing words (default: ``[]``).
|
| 100 |
+
"""
|
| 101 |
+
|
| 102 |
+
_ext_txt = ".trans.txt"
|
| 103 |
+
_ext_audio = ".flac"
|
| 104 |
+
|
| 105 |
+
def __init__(
|
| 106 |
+
self,
|
| 107 |
+
root: Union[str, Path],
|
| 108 |
+
url: str = URL,
|
| 109 |
+
folder_in_archive: str = FOLDER_IN_ARCHIVE,
|
| 110 |
+
download: bool = False,
|
| 111 |
+
blist: List[str] = None,
|
| 112 |
+
) -> None:
|
| 113 |
+
self._url = url
|
| 114 |
+
if url not in _DATA_SUBSETS:
|
| 115 |
+
raise ValueError(f"Invalid url '{url}' given; please provide one of {_DATA_SUBSETS}.")
|
| 116 |
+
|
| 117 |
+
root = os.fspath(root)
|
| 118 |
+
self._archive = os.path.join(root, folder_in_archive)
|
| 119 |
+
self._path = os.path.join(root, folder_in_archive, url)
|
| 120 |
+
|
| 121 |
+
if not os.path.isdir(self._path):
|
| 122 |
+
if download:
|
| 123 |
+
_download_librispeech(root, url)
|
| 124 |
+
else:
|
| 125 |
+
raise RuntimeError(
|
| 126 |
+
f"Dataset not found at {self._path}. Please set `download=True` to download the dataset."
|
| 127 |
+
)
|
| 128 |
+
|
| 129 |
+
self._walker = sorted(str(p.stem) for p in Path(self._path).glob("*/*/*" + self._ext_audio))
|
| 130 |
+
self.blist = blist
|
| 131 |
+
|
| 132 |
+
def get_metadata(self, n: int) -> Tuple[str, int, str, int, int, int]:
|
| 133 |
+
"""Get metadata for the n-th sample from the dataset. Returns filepath instead of waveform,
|
| 134 |
+
but otherwise returns the same fields as :py:func:`__getitem__`.
|
| 135 |
+
|
| 136 |
+
Args:
|
| 137 |
+
n (int): The index of the sample to be loaded
|
| 138 |
+
|
| 139 |
+
Returns:
|
| 140 |
+
Tuple of the following items;
|
| 141 |
+
|
| 142 |
+
str:
|
| 143 |
+
Path to audio
|
| 144 |
+
int:
|
| 145 |
+
Sample rate
|
| 146 |
+
str:
|
| 147 |
+
Transcript
|
| 148 |
+
int:
|
| 149 |
+
Speaker ID
|
| 150 |
+
int:
|
| 151 |
+
Chapter ID
|
| 152 |
+
int:
|
| 153 |
+
Utterance ID
|
| 154 |
+
list:
|
| 155 |
+
List of biasing words in the utterance
|
| 156 |
+
"""
|
| 157 |
+
fileid = self._walker[n]
|
| 158 |
+
return _get_librispeech_metadata(fileid, self._archive, self._url, self._ext_audio, self._ext_txt, self.blist)
|
| 159 |
+
|
| 160 |
+
def __getitem__(self, n: int) -> Tuple[Tensor, int, str, int, int, int]:
|
| 161 |
+
"""Load the n-th sample from the dataset.
|
| 162 |
+
|
| 163 |
+
Args:
|
| 164 |
+
n (int): The index of the sample to be loaded
|
| 165 |
+
|
| 166 |
+
Returns:
|
| 167 |
+
Tuple of the following items;
|
| 168 |
+
|
| 169 |
+
Tensor:
|
| 170 |
+
Waveform
|
| 171 |
+
int:
|
| 172 |
+
Sample rate
|
| 173 |
+
str:
|
| 174 |
+
Transcript
|
| 175 |
+
int:
|
| 176 |
+
Speaker ID
|
| 177 |
+
int:
|
| 178 |
+
Chapter ID
|
| 179 |
+
int:
|
| 180 |
+
Utterance ID
|
| 181 |
+
list:
|
| 182 |
+
List of biasing words in the utterance
|
| 183 |
+
"""
|
| 184 |
+
metadata = self.get_metadata(n)
|
| 185 |
+
waveform = _load_waveform(self._archive, metadata[0], metadata[1])
|
| 186 |
+
return (waveform,) + metadata[1:]
|
| 187 |
+
|
| 188 |
+
def __len__(self) -> int:
|
| 189 |
+
return len(self._walker)
|
micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/datasets/libritts.py
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
from typing import Tuple, Union
|
| 4 |
+
|
| 5 |
+
import torchaudio
|
| 6 |
+
from torch import Tensor
|
| 7 |
+
from torch.utils.data import Dataset
|
| 8 |
+
from torchaudio._internal import download_url_to_file
|
| 9 |
+
from torchaudio.datasets.utils import _extract_tar
|
| 10 |
+
|
| 11 |
+
URL = "train-clean-100"
|
| 12 |
+
FOLDER_IN_ARCHIVE = "LibriTTS"
|
| 13 |
+
_CHECKSUMS = {
|
| 14 |
+
"http://www.openslr.org/resources/60/dev-clean.tar.gz": "da0864e1bd26debed35da8a869dd5c04dfc27682921936de7cff9c8a254dbe1a", # noqa: E501
|
| 15 |
+
"http://www.openslr.org/resources/60/dev-other.tar.gz": "d413eda26f3a152ac7c9cf3658ef85504dfb1b625296e5fa83727f5186cca79c", # noqa: E501
|
| 16 |
+
"http://www.openslr.org/resources/60/test-clean.tar.gz": "234ea5b25859102a87024a4b9b86641f5b5aaaf1197335c95090cde04fe9a4f5", # noqa: E501
|
| 17 |
+
"http://www.openslr.org/resources/60/test-other.tar.gz": "33a5342094f3bba7ccc2e0500b9e72d558f72eb99328ac8debe1d9080402f10d", # noqa: E501
|
| 18 |
+
"http://www.openslr.org/resources/60/train-clean-100.tar.gz": "c5608bf1ef74bb621935382b8399c5cdd51cd3ee47cec51f00f885a64c6c7f6b", # noqa: E501
|
| 19 |
+
"http://www.openslr.org/resources/60/train-clean-360.tar.gz": "ce7cff44dcac46009d18379f37ef36551123a1dc4e5c8e4eb73ae57260de4886", # noqa: E501
|
| 20 |
+
"http://www.openslr.org/resources/60/train-other-500.tar.gz": "e35f7e34deeb2e2bdfe4403d88c8fdd5fbf64865cae41f027a185a6965f0a5df", # noqa: E501
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def load_libritts_item(
|
| 25 |
+
fileid: str,
|
| 26 |
+
path: str,
|
| 27 |
+
ext_audio: str,
|
| 28 |
+
ext_original_txt: str,
|
| 29 |
+
ext_normalized_txt: str,
|
| 30 |
+
) -> Tuple[Tensor, int, str, str, int, int, str]:
|
| 31 |
+
speaker_id, chapter_id, segment_id, utterance_id = fileid.split("_")
|
| 32 |
+
utterance_id = fileid
|
| 33 |
+
|
| 34 |
+
normalized_text = utterance_id + ext_normalized_txt
|
| 35 |
+
normalized_text = os.path.join(path, speaker_id, chapter_id, normalized_text)
|
| 36 |
+
|
| 37 |
+
original_text = utterance_id + ext_original_txt
|
| 38 |
+
original_text = os.path.join(path, speaker_id, chapter_id, original_text)
|
| 39 |
+
|
| 40 |
+
file_audio = utterance_id + ext_audio
|
| 41 |
+
file_audio = os.path.join(path, speaker_id, chapter_id, file_audio)
|
| 42 |
+
|
| 43 |
+
# Load audio
|
| 44 |
+
waveform, sample_rate = torchaudio.load(file_audio)
|
| 45 |
+
|
| 46 |
+
# Load original text
|
| 47 |
+
with open(original_text) as ft:
|
| 48 |
+
original_text = ft.readline()
|
| 49 |
+
|
| 50 |
+
# Load normalized text
|
| 51 |
+
with open(normalized_text, "r") as ft:
|
| 52 |
+
normalized_text = ft.readline()
|
| 53 |
+
|
| 54 |
+
return (
|
| 55 |
+
waveform,
|
| 56 |
+
sample_rate,
|
| 57 |
+
original_text,
|
| 58 |
+
normalized_text,
|
| 59 |
+
int(speaker_id),
|
| 60 |
+
int(chapter_id),
|
| 61 |
+
utterance_id,
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
class LIBRITTS(Dataset):
|
| 66 |
+
"""*LibriTTS* :cite:`Zen2019LibriTTSAC` dataset.
|
| 67 |
+
|
| 68 |
+
Args:
|
| 69 |
+
root (str or Path): Path to the directory where the dataset is found or downloaded.
|
| 70 |
+
url (str, optional): The URL to download the dataset from,
|
| 71 |
+
or the type of the dataset to dowload.
|
| 72 |
+
Allowed type values are ``"dev-clean"``, ``"dev-other"``, ``"test-clean"``,
|
| 73 |
+
``"test-other"``, ``"train-clean-100"``, ``"train-clean-360"`` and
|
| 74 |
+
``"train-other-500"``. (default: ``"train-clean-100"``)
|
| 75 |
+
folder_in_archive (str, optional):
|
| 76 |
+
The top-level directory of the dataset. (default: ``"LibriTTS"``)
|
| 77 |
+
download (bool, optional):
|
| 78 |
+
Whether to download the dataset if it is not found at root path. (default: ``False``).
|
| 79 |
+
"""
|
| 80 |
+
|
| 81 |
+
_ext_original_txt = ".original.txt"
|
| 82 |
+
_ext_normalized_txt = ".normalized.txt"
|
| 83 |
+
_ext_audio = ".wav"
|
| 84 |
+
|
| 85 |
+
def __init__(
|
| 86 |
+
self,
|
| 87 |
+
root: Union[str, Path],
|
| 88 |
+
url: str = URL,
|
| 89 |
+
folder_in_archive: str = FOLDER_IN_ARCHIVE,
|
| 90 |
+
download: bool = False,
|
| 91 |
+
) -> None:
|
| 92 |
+
|
| 93 |
+
if url in [
|
| 94 |
+
"dev-clean",
|
| 95 |
+
"dev-other",
|
| 96 |
+
"test-clean",
|
| 97 |
+
"test-other",
|
| 98 |
+
"train-clean-100",
|
| 99 |
+
"train-clean-360",
|
| 100 |
+
"train-other-500",
|
| 101 |
+
]:
|
| 102 |
+
|
| 103 |
+
ext_archive = ".tar.gz"
|
| 104 |
+
base_url = "http://www.openslr.org/resources/60/"
|
| 105 |
+
|
| 106 |
+
url = os.path.join(base_url, url + ext_archive)
|
| 107 |
+
|
| 108 |
+
# Get string representation of 'root' in case Path object is passed
|
| 109 |
+
root = os.fspath(root)
|
| 110 |
+
|
| 111 |
+
basename = os.path.basename(url)
|
| 112 |
+
archive = os.path.join(root, basename)
|
| 113 |
+
|
| 114 |
+
basename = basename.split(".")[0]
|
| 115 |
+
folder_in_archive = os.path.join(folder_in_archive, basename)
|
| 116 |
+
|
| 117 |
+
self._path = os.path.join(root, folder_in_archive)
|
| 118 |
+
|
| 119 |
+
if download:
|
| 120 |
+
if not os.path.isdir(self._path):
|
| 121 |
+
if not os.path.isfile(archive):
|
| 122 |
+
checksum = _CHECKSUMS.get(url, None)
|
| 123 |
+
download_url_to_file(url, archive, hash_prefix=checksum)
|
| 124 |
+
_extract_tar(archive)
|
| 125 |
+
else:
|
| 126 |
+
if not os.path.exists(self._path):
|
| 127 |
+
raise RuntimeError(
|
| 128 |
+
f"The path {self._path} doesn't exist. "
|
| 129 |
+
"Please check the ``root`` path or set `download=True` to download it"
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
self._walker = sorted(str(p.stem) for p in Path(self._path).glob("*/*/*" + self._ext_audio))
|
| 133 |
+
|
| 134 |
+
def __getitem__(self, n: int) -> Tuple[Tensor, int, str, str, int, int, str]:
|
| 135 |
+
"""Load the n-th sample from the dataset.
|
| 136 |
+
|
| 137 |
+
Args:
|
| 138 |
+
n (int): The index of the sample to be loaded
|
| 139 |
+
|
| 140 |
+
Returns:
|
| 141 |
+
Tuple of the following items;
|
| 142 |
+
|
| 143 |
+
Tensor:
|
| 144 |
+
Waveform
|
| 145 |
+
int:
|
| 146 |
+
Sample rate
|
| 147 |
+
str:
|
| 148 |
+
Original text
|
| 149 |
+
str:
|
| 150 |
+
Normalized text
|
| 151 |
+
int:
|
| 152 |
+
Speaker ID
|
| 153 |
+
int:
|
| 154 |
+
Chapter ID
|
| 155 |
+
str:
|
| 156 |
+
Utterance ID
|
| 157 |
+
"""
|
| 158 |
+
fileid = self._walker[n]
|
| 159 |
+
return load_libritts_item(
|
| 160 |
+
fileid,
|
| 161 |
+
self._path,
|
| 162 |
+
self._ext_audio,
|
| 163 |
+
self._ext_original_txt,
|
| 164 |
+
self._ext_normalized_txt,
|
| 165 |
+
)
|
| 166 |
+
|
| 167 |
+
def __len__(self) -> int:
|
| 168 |
+
return len(self._walker)
|
micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/datasets/ljspeech.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import csv
|
| 2 |
+
import os
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
from typing import Tuple, Union
|
| 5 |
+
|
| 6 |
+
import torchaudio
|
| 7 |
+
from torch import Tensor
|
| 8 |
+
from torch.utils.data import Dataset
|
| 9 |
+
from torchaudio._internal import download_url_to_file
|
| 10 |
+
from torchaudio.datasets.utils import _extract_tar
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
_RELEASE_CONFIGS = {
|
| 14 |
+
"release1": {
|
| 15 |
+
"folder_in_archive": "wavs",
|
| 16 |
+
"url": "https://data.keithito.com/data/speech/LJSpeech-1.1.tar.bz2",
|
| 17 |
+
"checksum": "be1a30453f28eb8dd26af4101ae40cbf2c50413b1bb21936cbcdc6fae3de8aa5",
|
| 18 |
+
}
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class LJSPEECH(Dataset):
|
| 23 |
+
"""*LJSpeech-1.1* :cite:`ljspeech17` dataset.
|
| 24 |
+
|
| 25 |
+
Args:
|
| 26 |
+
root (str or Path): Path to the directory where the dataset is found or downloaded.
|
| 27 |
+
url (str, optional): The URL to download the dataset from.
|
| 28 |
+
(default: ``"https://data.keithito.com/data/speech/LJSpeech-1.1.tar.bz2"``)
|
| 29 |
+
folder_in_archive (str, optional):
|
| 30 |
+
The top-level directory of the dataset. (default: ``"wavs"``)
|
| 31 |
+
download (bool, optional):
|
| 32 |
+
Whether to download the dataset if it is not found at root path. (default: ``False``).
|
| 33 |
+
"""
|
| 34 |
+
|
| 35 |
+
def __init__(
|
| 36 |
+
self,
|
| 37 |
+
root: Union[str, Path],
|
| 38 |
+
url: str = _RELEASE_CONFIGS["release1"]["url"],
|
| 39 |
+
folder_in_archive: str = _RELEASE_CONFIGS["release1"]["folder_in_archive"],
|
| 40 |
+
download: bool = False,
|
| 41 |
+
) -> None:
|
| 42 |
+
|
| 43 |
+
self._parse_filesystem(root, url, folder_in_archive, download)
|
| 44 |
+
|
| 45 |
+
def _parse_filesystem(self, root: str, url: str, folder_in_archive: str, download: bool) -> None:
|
| 46 |
+
root = Path(root)
|
| 47 |
+
|
| 48 |
+
basename = os.path.basename(url)
|
| 49 |
+
archive = root / basename
|
| 50 |
+
|
| 51 |
+
basename = Path(basename.split(".tar.bz2")[0])
|
| 52 |
+
folder_in_archive = basename / folder_in_archive
|
| 53 |
+
|
| 54 |
+
self._path = root / folder_in_archive
|
| 55 |
+
self._metadata_path = root / basename / "metadata.csv"
|
| 56 |
+
|
| 57 |
+
if download:
|
| 58 |
+
if not os.path.isdir(self._path):
|
| 59 |
+
if not os.path.isfile(archive):
|
| 60 |
+
checksum = _RELEASE_CONFIGS["release1"]["checksum"]
|
| 61 |
+
download_url_to_file(url, archive, hash_prefix=checksum)
|
| 62 |
+
_extract_tar(archive)
|
| 63 |
+
else:
|
| 64 |
+
if not os.path.exists(self._path):
|
| 65 |
+
raise RuntimeError(
|
| 66 |
+
f"The path {self._path} doesn't exist. "
|
| 67 |
+
"Please check the ``root`` path or set `download=True` to download it"
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
with open(self._metadata_path, "r", newline="") as metadata:
|
| 71 |
+
flist = csv.reader(metadata, delimiter="|", quoting=csv.QUOTE_NONE)
|
| 72 |
+
self._flist = list(flist)
|
| 73 |
+
|
| 74 |
+
def __getitem__(self, n: int) -> Tuple[Tensor, int, str, str]:
|
| 75 |
+
"""Load the n-th sample from the dataset.
|
| 76 |
+
|
| 77 |
+
Args:
|
| 78 |
+
n (int): The index of the sample to be loaded
|
| 79 |
+
|
| 80 |
+
Returns:
|
| 81 |
+
Tuple of the following items;
|
| 82 |
+
|
| 83 |
+
Tensor:
|
| 84 |
+
Waveform
|
| 85 |
+
int:
|
| 86 |
+
Sample rate
|
| 87 |
+
str:
|
| 88 |
+
Transcript
|
| 89 |
+
str:
|
| 90 |
+
Normalized Transcript
|
| 91 |
+
"""
|
| 92 |
+
line = self._flist[n]
|
| 93 |
+
fileid, transcript, normalized_transcript = line
|
| 94 |
+
fileid_audio = self._path / (fileid + ".wav")
|
| 95 |
+
|
| 96 |
+
# Load audio
|
| 97 |
+
waveform, sample_rate = torchaudio.load(fileid_audio)
|
| 98 |
+
|
| 99 |
+
return (
|
| 100 |
+
waveform,
|
| 101 |
+
sample_rate,
|
| 102 |
+
transcript,
|
| 103 |
+
normalized_transcript,
|
| 104 |
+
)
|
| 105 |
+
|
| 106 |
+
def __len__(self) -> int:
|
| 107 |
+
return len(self._flist)
|