Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

dataset.py 7.5 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
  1. # Copyright (c) Meta Platforms, Inc. and affiliates
  2. # All rights reserved.
  3. #
  4. # This source code is licensed under the license found in the
  5. # MIT_LICENSE file in the root directory of this source tree.
  6. import argparse
  7. import dataclasses
  8. import json
  9. import logging
  10. import os
  11. from pathlib import Path
  12. from tqdm import tqdm
  13. import torch
  14. from datasets import load_dataset
  15. from seamless_communication.datasets.huggingface import (
  16. Speech2SpeechFleursDatasetBuilder,
  17. SpeechTokenizer,
  18. )
  19. from seamless_communication.models.unit_extractor import UnitExtractor
  20. logging.basicConfig(
  21. level=logging.INFO,
  22. format="%(asctime)s %(levelname)s -- %(name)s: %(message)s",
  23. )
  24. logger = logging.getLogger("dataset")
  25. SUPPORTED_DATASETS = ['google/fleurs', 'speechcolab/gigaspeech']
  26. """ List of Huggingface Datasets that we support at the moment
  27. """
  28. # Full list of FLEURS langcodes is available at https://huggingface.co/datasets/google/fleurs
  29. # Full list of M4T langcodes is available
  30. # in paper "SeamlessM4T—Massively Multilingual & Multimodal Machine Translation" (Table 5)
  31. UNITY_TO_FLEURS_LANG_MAPPING = {
  32. "eng": "en_us",
  33. "ita": "it_it",
  34. "afr": "af_za",
  35. "asm": "as_in",
  36. "bel": "be_by",
  37. "bul": "bg_bg",
  38. "ben": "bn_in",
  39. "cat": "ca_es",
  40. "ces": "cs_cz",
  41. "dan": "da_dk",
  42. "deu": "de_de",
  43. "ell": "el_gr",
  44. "fin": "fi_fi",
  45. "fra": "fr_fr",
  46. "glg": "gl_es",
  47. "heb": "he_il",
  48. "hin": "hi_in",
  49. "hrv": "hr_hr",
  50. "hun": "hu_hu",
  51. "ind": "id_id",
  52. "ibo": "ig_ng",
  53. "isl": "is_is",
  54. "ita": "it_it",
  55. "jpn": "ja_jp",
  56. "jav": "jv_id",
  57. "kaz": "kk_kz",
  58. "kan": "kn_in",
  59. "kir": "ky_kg",
  60. "kor": "ko_kr",
  61. "lit": "lt_lt",
  62. "mkd": "mk_mk",
  63. "mlt": "mt_mt",
  64. "mya": "my_mm",
  65. "nld": "nl_nl",
  66. "pan": "pa_in",
  67. "pol": "pl_pl",
  68. "ron": "ro_ro",
  69. "rus": "ru_ru",
  70. "snd": "sd_in",
  71. "slk": "sk_sk",
  72. "spa": "es_419",
  73. "srp": "sr_rs",
  74. "swh": "sw_ke",
  75. "tam": "ta_in",
  76. "tel": "te_in",
  77. "tha": "th_th",
  78. "tur": "tr_tr",
  79. "ukr": "uk_ua",
  80. "urd": "ur_pk",
  81. "uzn": "uz_uz",
  82. "vie": "vi_vn",
  83. "yor": "yo_ng",
  84. "zul": "zu_za",
  85. }
  86. def _check_lang_code_mapping(lang: str) -> None:
  87. if lang not in UNITY_TO_FLEURS_LANG_MAPPING:
  88. raise ValueError(
  89. f"No language code mapping for {lang}(M4T)->??(FLEURs). "
  90. "Please expand `UNITY_TO_FLEURS_LANG_MAPPING`"
  91. )
  92. class UnitSpeechTokenizer(SpeechTokenizer):
  93. MODEL_NAME = "xlsr2_1b_v2"
  94. KMEANS_MODEL_URI = "https://dl.fbaipublicfiles.com/seamlessM4T/models/unit_extraction/kmeans_10k.npy"
  95. OUTPUT_LAYER_IDX = 34
  96. def __init__(self, device: torch.device):
  97. super().__init__()
  98. self.device = device
  99. self.unit_extractor = UnitExtractor(
  100. model_name_or_card=self.MODEL_NAME,
  101. kmeans_uri=self.KMEANS_MODEL_URI,
  102. device=self.device,
  103. )
  104. def encode(self, wav: torch.Tensor, sample_rate: int) -> torch.Tensor:
  105. return self.unit_extractor.predict(
  106. wav.to(self.device),
  107. out_layer_idx=self.OUTPUT_LAYER_IDX,
  108. sample_rate=sample_rate,
  109. )
  110. def download_fleurs(
  111. source_lang: str,
  112. target_lang: str,
  113. split: str,
  114. save_directory: str,
  115. ):
  116. _check_lang_code_mapping(source_lang)
  117. _check_lang_code_mapping(target_lang)
  118. device = (
  119. torch.device("cuda:0") if torch.cuda.device_count() > 0 else torch.device("cpu")
  120. )
  121. tokenizer = UnitSpeechTokenizer(device=device)
  122. dataset_iterator = Speech2SpeechFleursDatasetBuilder(
  123. source_lang=UNITY_TO_FLEURS_LANG_MAPPING[source_lang],
  124. target_lang=UNITY_TO_FLEURS_LANG_MAPPING[target_lang],
  125. dataset_cache_dir=save_directory,
  126. speech_tokenizer=tokenizer,
  127. skip_source_audio=True, # don't extract units from source audio
  128. skip_target_audio=False,
  129. split=split,
  130. )
  131. manifest_path: str = os.path.join(save_directory, f"{split}_manifest.json")
  132. with open(manifest_path, "w") as fp_out:
  133. for idx, sample in enumerate(dataset_iterator.__iter__(), start=1):
  134. # correction as FleursDatasetBuilder return fleurs lang codes
  135. sample.source.lang = source_lang
  136. sample.target.lang = target_lang
  137. sample.target.waveform = None # already extracted units
  138. fp_out.write(json.dumps(dataclasses.asdict(sample)) + "\n")
  139. logger.info(f"Saved {idx} samples for split={split} to {manifest_path}")
  140. logger.info(f"Manifest saved to: {manifest_path}")
  141. def download_gigaspeech(subset: str, huggingface_token: str, save_directory: str):
  142. ds = load_dataset("speechcolab/gigaspeech", subset, cache_dir=save_directory, token=huggingface_token)
  143. for split in ds:
  144. manifest_path = os.path.join(save_directory, f"{subset}_{split}_manifest.json")
  145. logger.info(f"Preparing {split} split...")
  146. with open(manifest_path, "w") as f:
  147. for sample in tqdm(ds[split]):
  148. f.write(json.dumps({
  149. "source": {
  150. "id": sample["segment_id"],
  151. "text": sample["text"],
  152. "lang":"eng",
  153. "audio_local_path": sample["audio"]["path"],
  154. "sampling_rate": sample["audio"]["sampling_rate"],
  155. },
  156. "target": {
  157. "id": sample["segment_id"],
  158. "text": sample["text"],
  159. "lang": "eng",
  160. }
  161. }) + "\n")
  162. logger.info(f"Manifest for GigaSpeech-{subset}-{split} saved to: {manifest_path}")
  163. def init_parser() -> argparse.ArgumentParser:
  164. parser = argparse.ArgumentParser(
  165. description=(
  166. "Helper script to download training/evaluation dataset (FLEURS or GigaSpeech),"
  167. "extract units from target audio and save the dataset as a manifest "
  168. "consumable by `finetune.py`."
  169. )
  170. )
  171. parser.add_argument(
  172. "--name",
  173. type=str,
  174. required=True,
  175. help="HuggingFace name of the dataset to prepare.",
  176. )
  177. parser.add_argument(
  178. "--source_lang",
  179. type=str,
  180. required=True,
  181. help="M4T langcode of the dataset SOURCE language",
  182. )
  183. parser.add_argument(
  184. "--target_lang",
  185. type=str,
  186. required=True,
  187. help="M4T langcode of the dataset TARGET language",
  188. )
  189. parser.add_argument(
  190. "--split",
  191. type=str,
  192. required=True,
  193. help="Dataset split/shard to download (`train`, `validation`, `test`)",
  194. )
  195. parser.add_argument(
  196. "--save_dir",
  197. type=Path,
  198. required=True,
  199. help="Directory where the datastets will be stored with HuggingFace datasets cache files",
  200. )
  201. parser.add_argument(
  202. "--huggingface_token",
  203. type=str,
  204. required=False,
  205. default=None,
  206. help="Your HuggingFace token, this is necessary for some datasets like GigaSpeech.",
  207. )
  208. return parser
  209. def main() -> None:
  210. args = init_parser().parse_args()
  211. assert args.name in SUPPORTED_DATASETS, \
  212. f"The only supported datasets are `{SUPPORTED_DATASETS}`. Please use one of these in `--name`."
  213. if args.name == 'google/fleurs':
  214. download_fleurs(args.source_lang, args.target_lang, args.split, args.save_dir)
  215. elif args.name == 'speechcolab/gigaspeech':
  216. assert args.huggingface_token is not None, \
  217. "Your HuggingFace token is necessary for GigaSpeech. Please read the GigaSpeech agreement."
  218. download_gigaspeech(args.split, args.huggingface_token, args.save_dir)
  219. if __name__ == "__main__":
  220. main()
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...