holylovenia commited on
Commit
40f028e
·
verified ·
1 Parent(s): d0003e8

Upload phost.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. phost.py +214 -0
phost.py ADDED
@@ -0,0 +1,214 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from pathlib import Path
3
+ from typing import Dict, List, Tuple
4
+ from zipfile import ZipFile
5
+
6
+ import datasets
7
+ import yaml
8
+
9
+ from seacrowd.utils import schemas
10
+ from seacrowd.utils.configs import SEACrowdConfig
11
+ from seacrowd.utils.constants import Licenses, Tasks
12
+
13
+ _CITATION = """\
14
+ @inproceedings{PhoST,
15
+ title = {{A High-Quality and Large-Scale Dataset for English-Vietnamese Speech Translation}},
16
+ author = {Linh The Nguyen and Nguyen Luong Tran and Long Doan and Manh Luong and Dat Quoc Nguyen},
17
+ booktitle = {Proceedings of the 23rd Annual Conference of the International Speech Communication Association (INTERSPEECH)},
18
+ year = {2022}
19
+ }
20
+ """
21
+
22
+ _DATASETNAME = "phost"
23
+
24
+ _DESCRIPTION = """\
25
+ PhoST is a high-quality and large-scale benchmark dataset for English-Vietnamese speech translation
26
+ with 508 audio hours, consisting of 331K triplets of (sentence-lengthed audio, English source
27
+ transcript sentence, Vietnamese target subtitle sentence).
28
+ """
29
+
30
+ _HOMEPAGE = "https://github.com/VinAIResearch/PhoST"
31
+
32
+ _LICENSE = Licenses.CC_BY_NC_ND_4_0.value
33
+
34
+ _LOCAL = True
35
+
36
+ _SUPPORTED_TASKS = [Tasks.SPEECH_RECOGNITION, Tasks.SPEECH_TO_TEXT_TRANSLATION, Tasks.MACHINE_TRANSLATION]
37
+
38
+ _SOURCE_VERSION = "1.0.0"
39
+
40
+ _SEACROWD_VERSION = "2024.06.20"
41
+
42
+ _LANGUAGES = ["eng", "vie"]
43
+
44
+
45
+ def seacrowd_config_constructor(src_lang, tgt_lang, schema, version):
46
+ if src_lang == "" or tgt_lang == "":
47
+ raise ValueError(f"Invalid src_lang {src_lang} or tgt_lang {tgt_lang}")
48
+
49
+ if schema not in ["source", "seacrowd_sptext", "seacrowd_t2t"]:
50
+ raise ValueError(f"Invalid schema: {schema}")
51
+
52
+ return SEACrowdConfig(
53
+ name="phost_{src}_{tgt}_{schema}".format(src=src_lang, tgt=tgt_lang, schema=schema),
54
+ version=datasets.Version(version),
55
+ description="phost schema for {schema} from {src} to {tgt}".format(schema=schema, src=src_lang, tgt=tgt_lang),
56
+ schema=schema,
57
+ subset_id="phost_{src}_{tgt}".format(src=src_lang, tgt=tgt_lang),
58
+ )
59
+
60
+
61
+ class Phost(datasets.GeneratorBasedBuilder):
62
+ """
63
+ PhoST is a high-quality and large-scale benchmark dataset for English-Vietnamese speech translation
64
+ with 508 audio hours, consisting of 331K triplets of (sentence-lengthed audio, English source
65
+ transcript sentence, Vietnamese target subtitle sentence).
66
+ """
67
+
68
+ SOURCE_VERSION = datasets.Version(_SOURCE_VERSION)
69
+ SEACROWD_VERSION = datasets.Version(_SEACROWD_VERSION)
70
+
71
+ BUILDER_CONFIGS = [
72
+ seacrowd_config_constructor("en", "vi", "source", _SOURCE_VERSION),
73
+ seacrowd_config_constructor("en", "vi", "seacrowd_sptext", _SEACROWD_VERSION),
74
+ seacrowd_config_constructor("en", "vi", "seacrowd_t2t", _SEACROWD_VERSION),
75
+ ]
76
+
77
+ DEFAULT_CONFIG_NAME = "phost_en_vi_source"
78
+
79
+ def _info(self) -> datasets.DatasetInfo:
80
+ if self.config.schema == "source":
81
+ features = datasets.Features(
82
+ {
83
+ "file": datasets.Value("string"),
84
+ "audio": datasets.Audio(sampling_rate=16_000),
85
+ "en_text": datasets.Value("string"),
86
+ "vi_text": datasets.Value("string"),
87
+ "timing": datasets.Sequence(datasets.Value("string")),
88
+ }
89
+ )
90
+ elif self.config.schema == "seacrowd_sptext":
91
+ features = schemas.speech_text_features
92
+ elif self.config.schema == "seacrowd_t2t":
93
+ features = schemas.text2text_features
94
+
95
+ return datasets.DatasetInfo(
96
+ description=_DESCRIPTION,
97
+ features=features,
98
+ homepage=_HOMEPAGE,
99
+ license=_LICENSE,
100
+ citation=_CITATION,
101
+ )
102
+
103
+ def _split_generators(self, dl_manager: datasets.DownloadManager) -> List[datasets.SplitGenerator]:
104
+ """Returns SplitGenerators."""
105
+ if self.config.data_dir is None:
106
+ raise ValueError("This is a local dataset. Please pass the data_dir kwarg to load_dataset.")
107
+ else:
108
+ data_dir = self.config.data_dir
109
+
110
+ aud_path = os.path.join(data_dir, "audio_data")
111
+ if not os.path.exists(aud_path):
112
+ os.makedirs(aud_path)
113
+
114
+ # loading the temp.zip and creating a zip object
115
+ with ZipFile(os.path.join(data_dir, "train_audio.zip"), "r") as zObject:
116
+ for member in zObject.namelist():
117
+ if not os.path.exists(os.path.join(aud_path, "train", member)) or not os.path.isfile(os.path.join(aud_path, "train", member)):
118
+ zObject.extract(member, os.path.join(aud_path, "train"))
119
+
120
+ # dev audio files
121
+ with ZipFile(os.path.join(data_dir, "dev_audio.zip"), "r") as zObject:
122
+ for member in zObject.namelist():
123
+ if not os.path.exists(os.path.join(aud_path, "dev", member)) or not os.path.isfile(os.path.join(aud_path, "dev", member)):
124
+ zObject.extract(member, aud_path)
125
+ # test audio files
126
+ with ZipFile(os.path.join(data_dir, "test_audio.zip"), "r") as zObject:
127
+ for member in zObject.namelist():
128
+ if not os.path.exists(os.path.join(aud_path, "test", member)) or not os.path.isfile(os.path.join(aud_path, "test", member)):
129
+ zObject.extract(member, aud_path)
130
+ # text data
131
+ with ZipFile(os.path.join(data_dir, "text_data.zip"), "r") as zObject:
132
+ for member in zObject.namelist():
133
+ if not os.path.exists(os.path.join(data_dir, member)) or not os.path.isfile(os.path.join(data_dir, member)):
134
+ zObject.extract(member, data_dir)
135
+
136
+ return [
137
+ datasets.SplitGenerator(
138
+ name=datasets.Split.TRAIN,
139
+ gen_kwargs={
140
+ "filepath": {"audio": os.path.join(aud_path, "train", "wav"), "text": os.path.join(data_dir, "text_data", "train")},
141
+ "split": "train",
142
+ },
143
+ ),
144
+ datasets.SplitGenerator(
145
+ name=datasets.Split.TEST,
146
+ gen_kwargs={
147
+ "filepath": {"audio": os.path.join(aud_path, "test", "wav"), "text": os.path.join(data_dir, "text_data", "test")},
148
+ "split": "test",
149
+ },
150
+ ),
151
+ datasets.SplitGenerator(
152
+ name=datasets.Split.VALIDATION,
153
+ gen_kwargs={
154
+ "filepath": {"audio": os.path.join(aud_path, "dev", "wav"), "text": os.path.join(data_dir, "text_data", "dev")},
155
+ "split": "dev",
156
+ },
157
+ ),
158
+ ]
159
+
160
+ def _generate_examples(self, filepath: Path, split: str) -> Tuple[int, Dict]:
161
+ """Yields examples as (key, example) tuples."""
162
+ config_names_split = self.config.name.split("_")
163
+ src_lang = config_names_split[1]
164
+ tgt_lang = config_names_split[2]
165
+ track_ids = os.listdir(filepath["text"])
166
+ timing = []
167
+ en_sub = []
168
+ vi_sub = []
169
+ counter = 0
170
+ for key, track_id in enumerate(track_ids):
171
+ with open(os.path.join(filepath["text"], track_id, track_id + ".yaml")) as timing_file:
172
+ timing = yaml.safe_load(timing_file)
173
+ with open(os.path.join(filepath["text"], track_id, track_id + ".en")) as en_text:
174
+ en_sub = [line.strip() for line in en_text]
175
+ with open(
176
+ os.path.join(filepath["text"], track_id, track_id + ".vi"),
177
+ ) as vi_text:
178
+ vi_sub = [line.strip() for line in vi_text]
179
+
180
+ if self.config.schema == "source":
181
+ yield key, {"file": os.path.join(filepath["audio"], track_id + ".wav"), "audio": os.path.join(filepath["audio"], track_id + ".wav"), "en_text": " ".join(en_sub), "vi_text": " ".join(vi_sub), "timing": timing}
182
+
183
+ elif self.config.schema == "seacrowd_sptext":
184
+ if tgt_lang not in ["en", "vi"]:
185
+ raise NotImplementedError(f"Target language '{tgt_lang}' is not defined.")
186
+
187
+ yield key, {
188
+ "id": track_id,
189
+ "path": os.path.join(filepath["audio"], track_id + ".wav"),
190
+ "audio": os.path.join(filepath["audio"], track_id + ".wav"),
191
+ "text": " ".join(en_sub) if tgt_lang == "en" else " ".join(vi_sub),
192
+ "speaker_id": None,
193
+ "metadata": {
194
+ "speaker_age": None,
195
+ "speaker_gender": None,
196
+ },
197
+ }
198
+
199
+ elif self.config.schema == "seacrowd_t2t":
200
+ if src_lang not in ["en", "vi"]:
201
+ raise NotImplementedError(f"Source language '{src_lang}' is not defined.")
202
+ if tgt_lang not in ["en", "vi"]:
203
+ raise NotImplementedError(f"Target language '{tgt_lang}' is not defined.")
204
+ for en_line, vi_line in zip(en_sub, vi_sub):
205
+ yield counter, {
206
+ "id": f"{track_id}_{str(counter)}",
207
+ "text_1": en_line if src_lang == "en" else vi_line,
208
+ "text_2": en_line if tgt_lang == "en" else vi_line,
209
+ "text_1_name": src_lang,
210
+ "text_2_name": tgt_lang,
211
+ }
212
+ counter += 1
213
+ else:
214
+ raise NotImplementedError(f"Schema '{self.config.schema}' is not defined.")