holylovenia commited on
Commit
0036ce3
1 Parent(s): c93966f

Upload nllb_seed.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. nllb_seed.py +313 -0
nllb_seed.py ADDED
@@ -0,0 +1,313 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The HuggingFace Datasets Authors and the current dataset script contributor.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """
17
+ This template serves as a starting point for contributing a dataset to the Nusantara Dataset repo.
18
+
19
+ When modifying it for your dataset, look for TODO items that offer specific instructions.
20
+
21
+ Full documentation on writing dataset loading scripts can be found here:
22
+ https://huggingface.co/docs/datasets/add_dataset.html
23
+
24
+ To create a dataset loading script you will create a class and implement 3 methods:
25
+ * `_info`: Establishes the schema for the dataset, and returns a datasets.DatasetInfo object.
26
+ * `_split_generators`: Downloads and extracts data for each split (e.g. train/val/test) or associate local data with each split.
27
+ * `_generate_examples`: Creates examples from data on disk that conform to each schema defined in `_info`.
28
+
29
+ TODO: Before submitting your script, delete this doc string and replace it with a description of your dataset.
30
+
31
+ [nusantara_schema_name] = (kb, pairs, qa, text, t2t, entailment)
32
+ """
33
+ import os
34
+ from pathlib import Path
35
+ from typing import Dict, List, Tuple
36
+
37
+ import datasets
38
+
39
+ from nusacrowd.utils import schemas
40
+ from nusacrowd.utils.configs import NusantaraConfig
41
+ from nusacrowd.utils.constants import Tasks
42
+
43
+ # TODO: Add BibTeX citation
44
+ _CITATION = """\
45
+ @article{nllb2022,
46
+ author = {NLLB Team, Marta R. Costa-jussà, James Cross, Onur Çelebi, Maha Elbayad, Kenneth Heafield, Kevin Heffernan, Elahe Kalbassi, Janice Lam, Daniel Licht, Jean Maillard, Anna Sun, Skyler Wang, Guillaume Wenzek, Al Youngblood, Bapi Akula, Loic Barrault, Gabriel Mejia Gonzalez, Prangthip Hansanti, John Hoffman, Semarley Jarrett, Kaushik Ram Sadagopan, Dirk Rowe, Shannon Spruit, Chau Tran, Pierre Andrews, Necip Fazil Ayan, Shruti Bhosale, Sergey Edunov, Angela Fan, Cynthia Gao, Vedanuj Goswami, Francisco Guzmán, Philipp Koehn, Alexandre Mourachko, Christophe Ropers, Safiyyah Saleem, Holger Schwenk, Jeff Wang},
47
+ title = {No Language Left Behind: Scaling Human-Centered Machine Translation},
48
+ year = {2022}
49
+ }
50
+ """
51
+
52
+ # TODO: create a module level variable with your dataset name (should match script name)
53
+ # E.g. Hallmarks of Cancer: [dataset_name] --> hallmarks_of_cancer
54
+ _DATASETNAME = "nllb_seed"
55
+ _LANGUAGES = ["ace", "bjn", "bug", "eng"]
56
+ _LANGUAGE_MAP = {"ace": "Aceh", "bjn": "Banjar", "bug": "Bugis"}
57
+ _LANG_CODE_MAP = {"Aceh": "ace", "Banjar": "bjn", "Bugis": "bug"}
58
+ _LANGUAGE_PAIR = [("ace", "eng"), ("eng", "ace"), ("bjn", "eng"), ("eng", "bjn"), ("bug", "eng"), ("eng", "bug")]
59
+
60
+ # TODO: Add description of the dataset here
61
+ # You can copy an official description
62
+ _DESCRIPTION = """\
63
+ No Language Left Behind Seed Data
64
+ NLLB Seed is a set of professionally-translated sentences in the Wikipedia domain. Data for NLLB-Seed was sampled from Wikimedia’s List of articles every Wikipedia should have, a collection of topics in different fields of knowledge and human activity. NLLB-Seed consists of around six thousand sentences in 39 languages. NLLB-Seed is meant to be used for training rather than model evaluation. Due to this difference, NLLB-Seed does not go through the human quality assurance process present in FLORES-200.
65
+ """
66
+
67
+ # TODO: Add a link to an official homepage for the dataset here (if possible)
68
+ _HOMEPAGE = "https://github.com/facebookresearch/flores/tree/main/nllb_seed"
69
+
70
+ # TODO: Add the licence for the dataset here (if possible)
71
+ # Note that this doesn't have to be a common open source license.
72
+ # Some datasets have custom licenses. In this case, simply put the full license terms
73
+ # into `_LICENSE`
74
+ _LICENSE = "CC-BY-SA 4.0"
75
+
76
+ # TODO: Add links to the urls needed to download your dataset files.
77
+ # For local datasets, this variable can be an empty dictionary.
78
+
79
+ # For publicly available datasets you will most likely end up passing these URLs to dl_manager in _split_generators.
80
+ # In most cases the URLs will be the same for the source and nusantara config.
81
+ # However, if you need to access different files for each config you can have multiple entries in this dict.
82
+ # This can be an arbitrarily nested dict/list of URLs (see below in `_split_generators` method)
83
+ _URLS = {
84
+ _DATASETNAME: "https://tinyurl.com/NLLBSeed",
85
+ }
86
+
87
+ # TODO: add supported task by dataset. One dataset may support multiple tasks
88
+ _SUPPORTED_TASKS = [Tasks.MACHINE_TRANSLATION] # example: [Tasks.TRANSLATION, Tasks.NAMED_ENTITY_RECOGNITION, Tasks.RELATION_EXTRACTION]
89
+
90
+ # TODO: set this to a version that is associated with the dataset. if none exists use "1.0.0"
91
+ # This version doesn't have to be consistent with semantic versioning. Anything that is
92
+ # provided by the original dataset as a version goes.
93
+ _SOURCE_VERSION = "1.0.0"
94
+ _NUSANTARA_VERSION = "1.0.0"
95
+ _LOCAL = False
96
+
97
+
98
+ def nusantara_config_constructor(lang, schema, version):
99
+ if lang == "":
100
+ raise ValueError(f"Invalid lang {lang}")
101
+
102
+ if schema != "source" and schema != "nusantara_t2t":
103
+ raise ValueError(f"Invalid schema: {schema}")
104
+
105
+ return NusantaraConfig(
106
+ name="nllb_seed_{lang}_{schema}".format(lang=lang, schema=schema),
107
+ version=datasets.Version(version),
108
+ description="nllb_seed {schema} schema for {lang} language".format(lang=_LANGUAGE_MAP[lang], schema=schema),
109
+ schema=schema,
110
+ subset_id="nllb_seed",
111
+ )
112
+
113
+
114
+ # TODO: Name the dataset class to match the script name using CamelCase instead of snake_case
115
+ class NLLBSeed(datasets.GeneratorBasedBuilder):
116
+ """TODO: Short description of my dataset."""
117
+
118
+ SOURCE_VERSION = datasets.Version(_SOURCE_VERSION)
119
+ NUSANTARA_VERSION = datasets.Version(_NUSANTARA_VERSION)
120
+
121
+ # You will be able to load the "source" or "nusantara" configurations with
122
+ # ds_source = datasets.load_dataset('my_dataset', name='source')
123
+ # ds_nusantara = datasets.load_dataset('my_dataset', name='nusantara')
124
+
125
+ # For local datasets you can make use of the `data_dir` and `data_files` kwargs
126
+ # https://huggingface.co/docs/datasets/add_dataset.html#downloading-data-files-and-organizing-splits
127
+ # ds_source = datasets.load_dataset('my_dataset', name='source', data_dir="/path/to/data/files")
128
+ # ds_nusantara = datasets.load_dataset('my_dataset', name='nusantara', data_dir="/path/to/data/files")
129
+
130
+ # TODO: For each dataset, implement Config for Source and Nusantara;
131
+ # If dataset contains more than one subset (see nusantara/nusa_datasets/smsa.py) implement for EACH of them.
132
+ # Each of them should contain:
133
+ # - name: should be unique for each dataset config eg. smsa_(source|nusantara)_[nusantara_schema_name]
134
+ # - version: option = (SOURCE_VERSION|NUSANTARA_VERSION)
135
+ # - description: one line description for the dataset
136
+ # - schema: options = (source|nusantara_[nusantara_schema_name])
137
+ # - subset_id: subset id is the canonical name for the dataset (eg. smsa)
138
+ # where [nusantara_schema_name] = (kb, pairs, qa, text, t2t)
139
+
140
+ BUILDER_CONFIGS = [nusantara_config_constructor(lang, "source", _SOURCE_VERSION) for lang in _LANGUAGE_MAP] + [nusantara_config_constructor(lang, "nusantara_t2t", _NUSANTARA_VERSION) for lang in _LANGUAGE_MAP]
141
+ """
142
+ BUILDER_CONFIGS = [
143
+ NusantaraConfig(
144
+ name="nllb_seed_source",
145
+ version=SOURCE_VERSION,
146
+ description="nllb_seed source schema",
147
+ schema="source",
148
+ subset_id="nllb_seed",
149
+ ),
150
+ NusantaraConfig(
151
+ name="nllb_seed_nusantara_t2t",
152
+ version=NUSANTARA_VERSION,
153
+ description="nllb_seed Nusantara schema",
154
+ schema="nusantara_t2t",
155
+ subset_id="nllb_seed",
156
+ ),
157
+ ]
158
+ """
159
+ DEFAULT_CONFIG_NAME = "nllb_seed_ace_source"
160
+
161
+ def _info(self) -> datasets.DatasetInfo:
162
+
163
+ # Create the source schema; this schema will keep all keys/information/labels as close to the original dataset as possible.
164
+
165
+ # You can arbitrarily nest lists and dictionaries.
166
+ # For iterables, use lists over tuples or `datasets.Sequence`
167
+
168
+ if self.config.schema == "source":
169
+ # TODO: Create your source schema here
170
+ # raise NotImplementedError()
171
+
172
+ # EX: Arbitrary NER type dataset
173
+ # features = datasets.Features(
174
+ # {
175
+ # "doc_id": datasets.Value("string"),
176
+ # "text": datasets.Value("string"),
177
+ # "entities": [
178
+ # {
179
+ # "offsets": [datasets.Value("int64")],
180
+ # "text": datasets.Value("string"),
181
+ # "type": datasets.Value("string"),
182
+ # "entity_id": datasets.Value("string"),
183
+ # }
184
+ # ],
185
+ # }
186
+ # )
187
+ features = datasets.Features(
188
+ {
189
+ "id": datasets.Value("string"),
190
+ "src": [datasets.Value("string")],
191
+ "tgt": [datasets.Value("string")],
192
+ }
193
+ )
194
+
195
+ # Choose the appropriate nusantara schema for your task and copy it here. You can find information on the schemas in the CONTRIBUTING guide.
196
+
197
+ # In rare cases you may get a dataset that supports multiple tasks requiring multiple schemas. In that case you can define multiple nusantara configs with a nusantara_[nusantara_schema_name] format.
198
+
199
+ # For example nusantara_kb, nusantara_t2t
200
+ elif self.config.schema == "nusantara_t2t":
201
+ # e.g. features = schemas.kb_features
202
+ features = schemas.text2text_features
203
+ # TODO: Choose your nusantara schema here
204
+ # raise NotImplementedError()
205
+
206
+ return datasets.DatasetInfo(
207
+ description=_DESCRIPTION,
208
+ features=features,
209
+ homepage=_HOMEPAGE,
210
+ license=_LICENSE,
211
+ citation=_CITATION,
212
+ )
213
+
214
+ def _split_generators(self, dl_manager: datasets.DownloadManager) -> List[datasets.SplitGenerator]:
215
+ """Returns SplitGenerators."""
216
+ # TODO: This method is tasked with downloading/extracting the data and defining the splits depending on the configuration
217
+
218
+ # If you need to access the "source" or "nusantara" config choice, that will be in self.config.name
219
+
220
+ # LOCAL DATASETS: You do not need the dl_manager; you can ignore this argument. Make sure `gen_kwargs` in the return gets passed the right filepath
221
+
222
+ # PUBLIC DATASETS: Assign your data-dir based on the dl_manager.
223
+
224
+ # dl_manager is a datasets.download.DownloadManager that can be used to download and extract URLs; many examples use the download_and_extract method; see the DownloadManager docs here: https://huggingface.co/docs/datasets/package_reference/builder_classes.html#datasets.DownloadManager
225
+
226
+ # dl_manager can accept any type of nested list/dict and will give back the same structure with the url replaced with the path to local files.
227
+
228
+ # TODO: KEEP if your dataset is PUBLIC; remove if not
229
+ urls = _URLS[_DATASETNAME]
230
+ data_dir = Path(dl_manager.download_and_extract(urls)) / "NLLB-Seed"
231
+ data_subdir = {"ace": os.path.join(data_dir, "ace_Latn-eng_Latn"), "bjn": os.path.join(data_dir, "bjn_Latn-eng_Latn"), "bug": os.path.join(data_dir, "bug_Latn-eng_Latn")}
232
+ lang = self.config.name.split("_")[2]
233
+
234
+ """
235
+ # TODO: KEEP if your dataset is LOCAL; remove if NOT
236
+ if self.config.data_dir is None:
237
+ raise ValueError("This is a local dataset. Please pass the data_dir kwarg to load_dataset.")
238
+ else:
239
+ data_dir = self.config.data_dir
240
+
241
+ # Not all datasets have predefined canonical train/val/test splits.
242
+ # If your dataset has no predefined splits, use datasets.Split.TRAIN for all of the data.
243
+ """
244
+
245
+ return [
246
+ datasets.SplitGenerator(
247
+ name=datasets.Split.TRAIN,
248
+ # Whatever you put in gen_kwargs will be passed to _generate_examples
249
+ gen_kwargs={"filepath": {lang: os.path.join(data_subdir[lang], lang + "_Latn"), lang + "_eng": os.path.join(data_subdir[lang], "eng_Latn"), "split": "train"}},
250
+ )
251
+ ]
252
+
253
+ # method parameters are unpacked from `gen_kwargs` as given in `_split_generators`
254
+
255
+ # TODO: change the args of this function to match the keys in `gen_kwargs`. You may add any necessary kwargs.
256
+
257
+ def _generate_examples(self, filepath: Path) -> Tuple[int, Dict]:
258
+ """Yields examples as (key, example) tuples."""
259
+ # TODO: This method handles input defined in _split_generators to yield (key, example) tuples from the dataset.
260
+
261
+ # The `key` is for legacy reasons (tfds) and is not important in itself, but must be unique for each example.
262
+
263
+ # NOTE: For local datasets you will have access to self.config.data_dir and self.config.data_files
264
+ lang = self.config.name.split("_")[2]
265
+ lang_code = lang
266
+
267
+ eng_text = open(filepath[lang_code + "_eng"], "r").readlines()
268
+ lang_text = open(filepath[lang_code], "r").readlines()
269
+
270
+ eng_text = list(map(str.strip, eng_text))
271
+ lang_text = list(map(str.strip, lang_text))
272
+ """
273
+ if self.config.schema == "source":
274
+ # TODO: yield (key, example) tuples in the original dataset schema
275
+ for key, example in thing:
276
+ yield key, example
277
+
278
+ elif self.config.schema == "nusantara_t2t":
279
+ # TODO: yield (key, example) tuples in the nusantara schema
280
+ for key, example in thing:
281
+ yield key, example
282
+ """
283
+ if self.config.schema == "source":
284
+ for id, (src, tgt) in enumerate(zip(lang_text, eng_text)):
285
+ row = {
286
+ "id": str(id),
287
+ "src": [src],
288
+ "tgt": [tgt],
289
+ }
290
+ yield id, row
291
+
292
+ elif self.config.schema == "nusantara_t2t":
293
+ for id, (src, tgt) in enumerate(zip(lang_text, eng_text)):
294
+ row = {
295
+ "id": str(id),
296
+ "text_1": src,
297
+ "text_2": tgt,
298
+ "text_1_name": lang_code,
299
+ "text_2_name": "eng",
300
+ }
301
+ yield id, row
302
+ else:
303
+ raise ValueError(f"Invalid config: {self.config.name}")
304
+
305
+
306
+ # This template is based on the following template from the datasets package:
307
+ # https://github.com/huggingface/datasets/blob/master/templates/new_dataset_script.py
308
+
309
+
310
+ # This allows you to run your dataloader with `python [dataset_name].py` during development
311
+ # TODO: Remove this before making your PR
312
+ if __name__ == "__main__":
313
+ datasets.load_dataset(__file__)