-
Notifications
You must be signed in to change notification settings - Fork 657
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add LibriLightLimited dataset #2302
Closed
Closed
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
936416e
add LibriSpeechFineTune dataset
nateanl 06586f5
address comments, add unit test
nateanl ff7cf0b
rename LibriSpeechFineTune to LibriLightLimited
nateanl 22cb381
fix
nateanl 73978b4
address comment
nateanl a7ecbe0
fix
nateanl f5b7491
fix
nateanl e096ee1
assert dataset is downloaded to root path
nateanl dc3d9ce
address comments
nateanl e3faf59
fix
nateanl 557064b
fix lint
nateanl File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
112 changes: 112 additions & 0 deletions
112
test/torchaudio_unittest/datasets/librilightlimited_test.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,112 @@ | ||
import os | ||
|
||
from torchaudio.datasets import librilight_limited | ||
from torchaudio_unittest.common_utils import ( | ||
get_whitenoise, | ||
save_wav, | ||
TempDirMixin, | ||
TorchaudioTestCase, | ||
) | ||
|
||
|
||
# Used to generate a unique transcript for each dummy audio file | ||
_NUMBERS = ["ZERO", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE"] | ||
|
||
|
||
def _save_sample(file_path, speaker_id, chapter_id, utterance_id, sample_rate, seed): | ||
filename = f"{speaker_id}-{chapter_id}-{utterance_id:04d}.flac" | ||
path = os.path.join(file_path, filename) | ||
data = get_whitenoise(sample_rate=sample_rate, duration=0.01, n_channels=1, dtype="float32", seed=seed) | ||
transcript = " ".join([_NUMBERS[x] for x in [speaker_id, chapter_id, utterance_id]]) | ||
save_wav(path, data, sample_rate) | ||
sample = (data, sample_rate, transcript, speaker_id, chapter_id, utterance_id) | ||
return sample | ||
|
||
|
||
def get_mock_dataset(dataset_dir: str): | ||
"""Create mocked dataset for a sub directory. | ||
|
||
Args: | ||
dataset_dir (str): the path of the sub directory. | ||
The structure is: audio_type/speaker_id/chapter_id/filename.flac | ||
""" | ||
mocked_data = [] | ||
sample_rate = 16000 # 16kHz | ||
seed = 0 | ||
for audio_type in ["clean", "other"]: | ||
for speaker_id in range(5): | ||
for chapter_id in range(3): | ||
file_path = os.path.join(dataset_dir, audio_type, str(speaker_id), str(chapter_id)) | ||
os.makedirs(file_path, exist_ok=True) | ||
trans_content = [] | ||
for utterance_id in range(3): | ||
sample = _save_sample(file_path, speaker_id, chapter_id, utterance_id, sample_rate, seed) | ||
trans_content.append(f"{sample[3]}-{sample[4]}-{sample[5]:04d} {sample[2]}") | ||
mocked_data.append(sample) | ||
seed += 1 | ||
trans_filename = f"{speaker_id}-{chapter_id}.trans.txt" | ||
trans_path = os.path.join(file_path, trans_filename) | ||
with open(trans_path, "w") as f: | ||
f.write("\n".join(trans_content)) | ||
return mocked_data | ||
|
||
|
||
def get_mock_datasets(root_dir): | ||
""" | ||
root_dir: directory to the mocked dataset | ||
""" | ||
mocked_data_10min, mocked_data_1h, mocked_data_10h = [], [], [] | ||
dataset_dir = os.path.join(root_dir, "librispeech_finetuning", "1h", "0") | ||
os.makedirs(dataset_dir, exist_ok=True) | ||
mocked_data_10min = get_mock_dataset(dataset_dir) | ||
mocked_data_1h += mocked_data_10min | ||
for i in range(1, 6): | ||
dataset_dir = os.path.join(root_dir, "librispeech_finetuning", "1h", str(i)) | ||
os.makedirs(dataset_dir, exist_ok=True) | ||
mocked_data_1h += get_mock_dataset(dataset_dir) | ||
mocked_data_10h += mocked_data_1h | ||
|
||
dataset_dir = os.path.join(root_dir, "librispeech_finetuning", "9h") | ||
os.makedirs(dataset_dir, exist_ok=True) | ||
mocked_data_10h += get_mock_dataset(dataset_dir) | ||
|
||
return mocked_data_10min, mocked_data_1h, mocked_data_10h | ||
|
||
|
||
class TestLibriLightLimited(TempDirMixin, TorchaudioTestCase): | ||
backend = "default" | ||
|
||
root_dir = None | ||
samples_10min = [] | ||
samples_1h = [] | ||
samples_10h = [] | ||
|
||
@classmethod | ||
def setUpClass(cls): | ||
cls.root_dir = cls.get_base_temp_dir() | ||
(cls.samples_10min, cls.samples_1h, cls.samples_10h) = get_mock_datasets(cls.root_dir) | ||
|
||
def _test_librilightlimited(self, dataset, samples): | ||
num_samples = 0 | ||
for i, (data, sample_rate, transcript, speaker_id, chapter_id, utterance_id) in enumerate(dataset): | ||
self.assertEqual(data, samples[i][0], atol=5e-5, rtol=1e-8) | ||
assert sample_rate == samples[i][1] | ||
assert transcript == samples[i][2] | ||
assert speaker_id == samples[i][3] | ||
assert chapter_id == samples[i][4] | ||
assert utterance_id == samples[i][5] | ||
num_samples += 1 | ||
|
||
assert num_samples == len(samples) | ||
|
||
def test_librilightlimited_10min(self): | ||
dataset = librilight_limited.LibriLightLimited(self.root_dir, subset="10min") | ||
self._test_librilightlimited(dataset, self.samples_10min) | ||
|
||
def test_librilightlimited_1h(self): | ||
dataset = librilight_limited.LibriLightLimited(self.root_dir, subset="1h") | ||
self._test_librilightlimited(dataset, self.samples_1h) | ||
|
||
def test_librilightlimited_10h(self): | ||
dataset = librilight_limited.LibriLightLimited(self.root_dir, subset="10h") | ||
self._test_librilightlimited(dataset, self.samples_10h) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,91 @@ | ||
import os | ||
from pathlib import Path | ||
from typing import List, Tuple, Union | ||
|
||
from torch import Tensor | ||
from torch.hub import download_url_to_file | ||
from torch.utils.data import Dataset | ||
from torchaudio.datasets.librispeech import load_librispeech_item | ||
from torchaudio.datasets.utils import extract_archive | ||
|
||
|
||
_ARCHIVE_NAME = "librispeech_finetuning" | ||
_URL = "https://dl.fbaipublicfiles.com/librilight/data/librispeech_finetuning.tgz" | ||
_CHECKSUM = "5d1efdc777b548194d7e09ba89126e2188026df9fd57aa57eb14408d2b2342af" | ||
|
||
|
||
def _get_fileids_paths(path, subset, _ext_audio) -> List[Tuple[str, str]]: | ||
"""Get the file names and the corresponding file paths without `speaker_id` | ||
and `chapter_id` directories. | ||
The format of path is like: | ||
{root}/{_ARCHIVE_NAME}/1h/[0-5]/[clean, other] or | ||
{root}/{_ARCHIVE_NAME}/9h/[clean, other] | ||
""" | ||
if subset == "10min": | ||
files_paths = [ | ||
(os.path.join(os.path.dirname(p), "..", ".."), str(p.stem)) | ||
for p in Path(path).glob("1h/0/*/*/*/*" + _ext_audio) | ||
] | ||
elif subset in ["1h", "10h"]: | ||
files_paths = [ | ||
(os.path.join(os.path.dirname(p), "..", ".."), str(p.stem)) | ||
for p in Path(path).glob("1h/*/*/*/*/*" + _ext_audio) | ||
] | ||
if subset == "10h": | ||
files_paths += [ | ||
(os.path.join(os.path.dirname(p), "..", ".."), str(p.stem)) | ||
for p in Path(path).glob("9h/*/*/*/*" + _ext_audio) | ||
] | ||
else: | ||
raise ValueError(f"Unsupported subset value. Found {subset}.") | ||
files_paths = sorted(files_paths, key=lambda x: x[0] + x[1]) | ||
return files_paths | ||
|
||
|
||
class LibriLightLimited(Dataset): | ||
"""Create a Dataset for LibriLightLimited, which is the supervised subset of | ||
LibriLight dataset. | ||
|
||
Args: | ||
root (str or Path): Path to the directory where the dataset is found or downloaded. | ||
subset (str, optional): The subset to use. Options: [``10min`, ``1h``, ``10h``] | ||
(Default: ``10min``). | ||
download (bool, optional): | ||
Whether to download the dataset if it is not found at root path. (default: ``False``). | ||
""" | ||
|
||
_ext_txt = ".trans.txt" | ||
_ext_audio = ".flac" | ||
|
||
nateanl marked this conversation as resolved.
Show resolved
Hide resolved
|
||
def __init__( | ||
self, | ||
root: Union[str, Path], | ||
subset: str = "10min", | ||
download: bool = False, | ||
) -> None: | ||
assert subset in ["10min", "1h", "10h"], "`subset` must be one of ['10min', '1h', '10h']" | ||
|
||
root = os.fspath(root) | ||
self._path = os.path.join(root, _ARCHIVE_NAME) | ||
archive = os.path.join(root, f"{_ARCHIVE_NAME}.tgz") | ||
if not os.path.isdir(self._path): | ||
if not download: | ||
raise RuntimeError("Dataset not found. Please use `download=True` to download") | ||
if not os.path.isfile(archive): | ||
download_url_to_file(_URL, archive, hash_prefix=_CHECKSUM) | ||
extract_archive(archive) | ||
self._fileids_paths = _get_fileids_paths(self._path, subset, self._ext_audio) | ||
|
||
def __getitem__(self, n: int) -> Tuple[Tensor, int, str, int, int, int]: | ||
"""Load the n-th sample from the dataset. | ||
Args: | ||
n (int): The index of the sample to be loaded | ||
Returns: | ||
(Tensor, int, str, int, int, int): | ||
``(waveform, sample_rate, transcript, speaker_id, chapter_id, utterance_id)`` | ||
""" | ||
file_path, fileid = self._fileids_paths[n] | ||
return load_librispeech_item(fileid, file_path, self._ext_audio, self._ext_txt) | ||
|
||
def __len__(self) -> int: | ||
return len(self._fileids_paths) |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
what's the reasoning behind making these values class variables while making
_URL
and_CHECKSUM
module-level variables?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The flac part particularly is so that in unittest we can mock the dataset with WAV files. In test, we do not want to use torchaudio's I/O module because it will make the test depend on not only the dataset implementation but also on I/O module.
Now, without our own I/O module, there aren't many tools that provide nice FLAC support. (PySoundFile can, but it also depends on installation)
So in test, we generate mock data with WAV format and overwrite the audio extension for the duration of test.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I do not see why
.trans.txt
should be class variable.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
For
.trans.txt
we can make a separate PR to address for all datasets, such as LibriSpeech and CommonVoice.