librispeech.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. import os
  2. from pathlib import Path
  3. from typing import Tuple, Union
  4. import torchaudio
  5. from torch import Tensor
  6. from torch.hub import download_url_to_file
  7. from torch.utils.data import Dataset
  8. from torchaudio.datasets.utils import extract_archive
  9. URL = "train-clean-100"
  10. FOLDER_IN_ARCHIVE = "LibriSpeech"
  11. _DATA_SUBSETS = [
  12. "dev-clean",
  13. "dev-other",
  14. "test-clean",
  15. "test-other",
  16. "train-clean-100",
  17. "train-clean-360",
  18. "train-other-500",
  19. ]
  20. _CHECKSUMS = {
  21. "http://www.openslr.org/resources/12/dev-clean.tar.gz": "76f87d090650617fca0cac8f88b9416e0ebf80350acb97b343a85fa903728ab3", # noqa: E501
  22. "http://www.openslr.org/resources/12/dev-other.tar.gz": "12661c48e8c3fe1de2c1caa4c3e135193bfb1811584f11f569dd12645aa84365", # noqa: E501
  23. "http://www.openslr.org/resources/12/test-clean.tar.gz": "39fde525e59672dc6d1551919b1478f724438a95aa55f874b576be21967e6c23", # noqa: E501
  24. "http://www.openslr.org/resources/12/test-other.tar.gz": "d09c181bba5cf717b3dee7d4d592af11a3ee3a09e08ae025c5506f6ebe961c29", # noqa: E501
  25. "http://www.openslr.org/resources/12/train-clean-100.tar.gz": "d4ddd1d5a6ab303066f14971d768ee43278a5f2a0aa43dc716b0e64ecbbbf6e2", # noqa: E501
  26. "http://www.openslr.org/resources/12/train-clean-360.tar.gz": "146a56496217e96c14334a160df97fffedd6e0a04e66b9c5af0d40be3c792ecf", # noqa: E501
  27. "http://www.openslr.org/resources/12/train-other-500.tar.gz": "ddb22f27f96ec163645d53215559df6aa36515f26e01dd70798188350adcb6d2", # noqa: E501
  28. }
  29. def download_librispeech(root, url):
  30. base_url = "http://www.openslr.org/resources/12/"
  31. ext_archive = ".tar.gz"
  32. filename = url + ext_archive
  33. archive = os.path.join(root, filename)
  34. download_url = os.path.join(base_url, filename)
  35. if not os.path.isfile(archive):
  36. checksum = _CHECKSUMS.get(download_url, None)
  37. download_url_to_file(download_url, archive, hash_prefix=checksum)
  38. extract_archive(archive)
  39. def load_librispeech_item(
  40. fileid: str, path: str, ext_audio: str, ext_txt: str
  41. ) -> Tuple[Tensor, int, str, int, int, int]:
  42. speaker_id, chapter_id, utterance_id = fileid.split("-")
  43. # Load audio
  44. fileid_audio = f"{speaker_id}-{chapter_id}-{utterance_id}"
  45. file_audio = fileid_audio + ext_audio
  46. file_audio = os.path.join(path, speaker_id, chapter_id, file_audio)
  47. waveform, sample_rate = torchaudio.load(file_audio)
  48. # Load text
  49. file_text = f"{speaker_id}-{chapter_id}{ext_txt}"
  50. file_text = os.path.join(path, speaker_id, chapter_id, file_text)
  51. with open(file_text) as ft:
  52. for line in ft:
  53. fileid_text, transcript = line.strip().split(" ", 1)
  54. if fileid_audio == fileid_text:
  55. break
  56. else:
  57. # Translation not found
  58. raise FileNotFoundError(f"Translation not found for {fileid_audio}")
  59. return (
  60. waveform,
  61. sample_rate,
  62. transcript,
  63. int(speaker_id),
  64. int(chapter_id),
  65. int(utterance_id),
  66. )
  67. class LIBRISPEECH(Dataset):
  68. """Create a Dataset for *LibriSpeech* [:footcite:`7178964`].
  69. Args:
  70. root (str or Path): Path to the directory where the dataset is found or downloaded.
  71. url (str, optional): The URL to download the dataset from,
  72. or the type of the dataset to dowload.
  73. Allowed type values are ``"dev-clean"``, ``"dev-other"``, ``"test-clean"``,
  74. ``"test-other"``, ``"train-clean-100"``, ``"train-clean-360"`` and
  75. ``"train-other-500"``. (default: ``"train-clean-100"``)
  76. folder_in_archive (str, optional):
  77. The top-level directory of the dataset. (default: ``"LibriSpeech"``)
  78. download (bool, optional):
  79. Whether to download the dataset if it is not found at root path. (default: ``False``).
  80. """
  81. _ext_txt = ".trans.txt"
  82. _ext_audio = ".flac"
  83. def __init__(
  84. self,
  85. root: Union[str, Path],
  86. url: str = URL,
  87. folder_in_archive: str = FOLDER_IN_ARCHIVE,
  88. download: bool = False,
  89. ) -> None:
  90. if url not in _DATA_SUBSETS:
  91. raise ValueError(f"Invalid url '{url}' given; please provide one of {_DATA_SUBSETS}.")
  92. root = os.fspath(root)
  93. self._path = os.path.join(root, folder_in_archive, url)
  94. if not os.path.isdir(self._path):
  95. if download:
  96. download_librispeech(root, url)
  97. else:
  98. raise RuntimeError(
  99. f"Dataset not found at {self._path}. Please set `download=True` to download the dataset."
  100. )
  101. self._walker = sorted(str(p.stem) for p in Path(self._path).glob("*/*/*" + self._ext_audio))
  102. def __getitem__(self, n: int) -> Tuple[Tensor, int, str, int, int, int]:
  103. """Load the n-th sample from the dataset.
  104. Args:
  105. n (int): The index of the sample to be loaded
  106. Returns:
  107. (Tensor, int, str, int, int, int):
  108. ``(waveform, sample_rate, transcript, speaker_id, chapter_id, utterance_id)``
  109. """
  110. fileid = self._walker[n]
  111. return load_librispeech_item(fileid, self._path, self._ext_audio, self._ext_txt)
  112. def __len__(self) -> int:
  113. return len(self._walker)