vgaraujov commited on
Commit
f8d90d7
1 Parent(s): 3e94759

Upload 4 files

Browse files
americasnlp-mt-21.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2020 The TensorFlow Datasets Authors and the HuggingFace Datasets Authors.
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
+ # Lint as: python3
17
+ """AmericasNLP 2021 Shared Task on Open Machine Translation."""
18
+
19
+ import datasets
20
+
21
+ from .wmt_utils import Wmt, WmtConfig
22
+
23
+
24
+ _URL = "https://turing.iimas.unam.mx/americasnlp/2021/st.html"
25
+ _CITATION = """
26
+ @inproceedings{mager-etal-2021-findings,
27
+ title = "Findings of the {A}mericas{NLP} 2021 Shared Task on Open Machine Translation for Indigenous Languages of the {A}mericas",
28
+ author = "Mager, Manuel and
29
+ Oncevay, Arturo and
30
+ Ebrahimi, Abteen and
31
+ Ortega, John and
32
+ Rios, Annette and
33
+ Fan, Angela and
34
+ Gutierrez-Vasques, Ximena and
35
+ Chiruzzo, Luis and
36
+ Gim{\'e}nez-Lugo, Gustavo and
37
+ Ramos, Ricardo and
38
+ Meza Ruiz, Ivan Vladimir and
39
+ Coto-Solano, Rolando and
40
+ Palmer, Alexis and
41
+ Mager-Hois, Elisabeth and
42
+ Chaudhary, Vishrav and
43
+ Neubig, Graham and
44
+ Vu, Ngoc Thang and
45
+ Kann, Katharina",
46
+ booktitle = "Proceedings of the First Workshop on Natural Language Processing for Indigenous Languages of the Americas",
47
+ month = jun,
48
+ year = "2021",
49
+ address = "Online",
50
+ publisher = "Association for Computational Linguistics",
51
+ url = "https://aclanthology.org/2021.americasnlp-1.23",
52
+ doi = "10.18653/v1/2021.americasnlp-1.23",
53
+ pages = "202--217",
54
+ abstract = "This paper presents the results of the 2021 Shared Task on Open Machine Translation for Indigenous Languages of the Americas. The shared task featured two independent tracks, and participants submitted machine translation systems for up to 10 indigenous languages. Overall, 8 teams participated with a total of 214 submissions. We provided training sets consisting of data collected from various sources, as well as manually translated sentences for the development and test sets. An official baseline trained on this data was also provided. Team submissions featured a variety of architectures, including both statistical and neural models, and for the majority of languages, many teams were able to considerably improve over the baseline. The best performing systems achieved 12.97 ChrF higher than baseline, when averaged across languages.",
55
+ }
56
+ """
57
+
58
+ _LANGUAGE_PAIRS = [(lang, "es") for lang in ["aym", "bzd", "cni", "gn", "nah", "oto", "quy", "shp"]]
59
+
60
+
61
+ class AmericasNLPMT21(Wmt):
62
+ """AmericasNLP translation datasets for all {xx, "es"} language pairs."""
63
+
64
+ BUILDER_CONFIGS = [
65
+ WmtConfig( # pylint:disable=g-complex-comprehension
66
+ description="AmericasNLP 2021 %s-%s translation task dataset." % (l1, l2),
67
+ url=_URL,
68
+ citation=_CITATION,
69
+ language_pair=(l1, l2),
70
+ version=datasets.Version("1.0.0"),
71
+ )
72
+ for l1, l2 in _LANGUAGE_PAIRS
73
+ ]
74
+
75
+ @property
76
+ def _subsets(self):
77
+ return {
78
+ datasets.Split.TRAIN: [
79
+ "americasnlp2021",
80
+ ],
81
+ datasets.Split.VALIDATION: ["dev2021"],
82
+ datasets.Split.TEST: ["test2021"],
83
+ }
data/americasnlp2021.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c781d22a46fc51f0158200817032cb8f9078a0ac4b1eaafa8602b7a7e508d369
3
+ size 14309429
data/test2021.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3e75bd6a8c60fecbf6b12b2b02d69e60153daadcd407c086279f15d6e927d4a2
3
+ size 222057
wmt_utils.py ADDED
@@ -0,0 +1,541 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2020 The TensorFlow Datasets Authors and the HuggingFace Datasets Authors.
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
+ # Script borrewed and adapted from https://huggingface.co/datasets/wmt16.
17
+
18
+ # Lint as: python3
19
+ """WMT: Translate dataset."""
20
+
21
+
22
+ import codecs
23
+ import functools
24
+ import glob
25
+ import gzip
26
+ import itertools
27
+ import os
28
+ import re
29
+ import xml.etree.cElementTree as ElementTree
30
+
31
+ import datasets
32
+
33
+
34
+ logger = datasets.logging.get_logger(__name__)
35
+
36
+
37
+ _DESCRIPTION = """\
38
+ Translation dataset based on the data from statmt.org.
39
+
40
+ Versions exist for different years using a combination of data
41
+ sources. The base `wmt` allows you to create a custom dataset by choosing
42
+ your own data/language pair. This can be done as follows:
43
+
44
+ ```python
45
+ from datasets import inspect_dataset, load_dataset_builder
46
+
47
+ inspect_dataset("wmt16", "path/to/scripts")
48
+ builder = load_dataset_builder(
49
+ "path/to/scripts/wmt_utils.py",
50
+ language_pair=("fr", "de"),
51
+ subsets={
52
+ datasets.Split.TRAIN: ["commoncrawl_frde"],
53
+ datasets.Split.VALIDATION: ["euelections_dev2019"],
54
+ },
55
+ )
56
+
57
+ # Standard version
58
+ builder.download_and_prepare()
59
+ ds = builder.as_dataset()
60
+
61
+ # Streamable version
62
+ ds = builder.as_streaming_dataset()
63
+ ```
64
+
65
+ """
66
+
67
+
68
+ class SubDataset:
69
+ """Class to keep track of information on a sub-dataset of WMT."""
70
+
71
+ def __init__(self, name, target, sources, url, path, manual_dl_files=None):
72
+ """Sub-dataset of WMT.
73
+
74
+ Args:
75
+ name: `string`, a unique dataset identifier.
76
+ target: `string`, the target language code.
77
+ sources: `set<string>`, the set of source language codes.
78
+ url: `string` or `(string, string)`, URL(s) or URL template(s) specifying
79
+ where to download the raw data from. If two strings are provided, the
80
+ first is used for the source language and the second for the target.
81
+ Template strings can either contain '{src}' placeholders that will be
82
+ filled in with the source language code, '{0}' and '{1}' placeholders
83
+ that will be filled in with the source and target language codes in
84
+ alphabetical order, or all 3.
85
+ path: `string` or `(string, string)`, path(s) or path template(s)
86
+ specifing the path to the raw data relative to the root of the
87
+ downloaded archive. If two strings are provided, the dataset is assumed
88
+ to be made up of parallel text files, the first being the source and the
89
+ second the target. If one string is provided, both languages are assumed
90
+ to be stored within the same file and the extension is used to determine
91
+ how to parse it. Template strings should be formatted the same as in
92
+ `url`.
93
+ manual_dl_files: `<list>(string)` (optional), the list of files that must
94
+ be manually downloaded to the data directory.
95
+ """
96
+ self._paths = (path,) if isinstance(path, str) else path
97
+ self._urls = (url,) if isinstance(url, str) else url
98
+ self._manual_dl_files = manual_dl_files if manual_dl_files else []
99
+ self.name = name
100
+ self.target = target
101
+ self.sources = set(sources)
102
+
103
+ def _inject_language(self, src, strings):
104
+ """Injects languages into (potentially) template strings."""
105
+ if src not in self.sources:
106
+ raise ValueError(f"Invalid source for '{self.name}': {src}")
107
+
108
+ def _format_string(s):
109
+ if "{0}" in s and "{1}" and "{src}" in s:
110
+ return s.format(*sorted([src, self.target]), src=src)
111
+ elif "{0}" in s and "{1}" in s:
112
+ return s.format(*sorted([src, self.target]))
113
+ elif "{src}" in s:
114
+ return s.format(src=src)
115
+ else:
116
+ return s
117
+
118
+ return [_format_string(s) for s in strings]
119
+
120
+ def get_url(self, src):
121
+ return self._inject_language(src, self._urls)
122
+
123
+ def get_manual_dl_files(self, src):
124
+ return self._inject_language(src, self._manual_dl_files)
125
+
126
+ def get_path(self, src):
127
+ return self._inject_language(src, self._paths)
128
+
129
+
130
+ # Subsets used in the training sets for AmericasNLP 2021 Shared Task on Machine Translation.
131
+ _TRAIN_SUBSETS = [
132
+ SubDataset(
133
+ name="americasnlp2021",
134
+ target="es",
135
+ sources={"aym", "bzd", "cni", "gn", "nah", "oto", "quy", "shp"},
136
+ url="https://huggingface.co/datasets/vgaraujov/americasnlp-mt-21/resolve/main/data/americasnlp2021.zip",
137
+ path=("train.{src}-es.{src}", "train.{src}-es.es"),
138
+ ),
139
+ ]
140
+
141
+ _DEV_SUBSETS = [
142
+ SubDataset(
143
+ name="dev2021",
144
+ target="es",
145
+ sources={"aym", "bzd", "cni", "gn", "nah", "oto", "quy", "shp"},
146
+ url="https://huggingface.co/datasets/vgaraujov/americasnlp-mt-21/resolve/main/data/americasnlp2021.zip",
147
+ path=("dev.{src}-es.{src}", "dev.{src}-es.es"),
148
+ ),
149
+ SubDataset(
150
+ name="test2021",
151
+ target="es",
152
+ sources={"aym", "bzd", "cni", "gn", "nah", "oto", "quy", "shp"},
153
+ url="https://huggingface.co/datasets/vgaraujov/americasnlp-mt-21/resolve/main/data/test2021.zip",
154
+ path=("test.{src}", "test.es"),
155
+ ),
156
+ ]
157
+
158
+ DATASET_MAP = {dataset.name: dataset for dataset in _TRAIN_SUBSETS + _DEV_SUBSETS}
159
+
160
+
161
+ class WmtConfig(datasets.BuilderConfig):
162
+ """BuilderConfig for WMT."""
163
+
164
+ def __init__(self, url=None, citation=None, description=None, language_pair=(None, None), subsets=None, **kwargs):
165
+ """BuilderConfig for WMT.
166
+
167
+ Args:
168
+ url: The reference URL for the dataset.
169
+ citation: The paper citation for the dataset.
170
+ description: The description of the dataset.
171
+ language_pair: pair of languages that will be used for translation. Should
172
+ contain 2 letter coded strings. For example: ("en", "de").
173
+ configuration for the `datasets.features.text.TextEncoder` used for the
174
+ `datasets.features.text.Translation` features.
175
+ subsets: Dict[split, list[str]]. List of the subset to use for each of the
176
+ split. Note that WMT subclasses overwrite this parameter.
177
+ **kwargs: keyword arguments forwarded to super.
178
+ """
179
+ name = "%s-%s" % (language_pair[0], language_pair[1])
180
+ if "name" in kwargs: # Add name suffix for custom configs
181
+ name += "." + kwargs.pop("name")
182
+
183
+ super(WmtConfig, self).__init__(name=name, description=description, **kwargs)
184
+
185
+ self.url = url or "http://www.statmt.org"
186
+ self.citation = citation
187
+ self.language_pair = language_pair
188
+ self.subsets = subsets
189
+
190
+ # TODO(PVP): remove when manual dir works
191
+ # +++++++++++++++++++++
192
+ if language_pair[1] in ["cs", "hi", "ru"]:
193
+ assert NotImplementedError(f"The dataset for {language_pair[1]}-en is currently not fully supported.")
194
+ # +++++++++++++++++++++
195
+
196
+
197
+ class Wmt(datasets.GeneratorBasedBuilder):
198
+ """WMT translation dataset."""
199
+
200
+ BUILDER_CONFIG_CLASS = WmtConfig
201
+
202
+ def __init__(self, *args, **kwargs):
203
+ super(Wmt, self).__init__(*args, **kwargs)
204
+
205
+ @property
206
+ def _subsets(self):
207
+ """Subsets that make up each split of the dataset."""
208
+ raise NotImplementedError("This is a abstract method")
209
+
210
+ @property
211
+ def subsets(self):
212
+ """Subsets that make up each split of the dataset for the language pair."""
213
+ source, target = self.config.language_pair
214
+ filtered_subsets = {}
215
+ subsets = self._subsets if self.config.subsets is None else self.config.subsets
216
+ for split, ss_names in subsets.items():
217
+ filtered_subsets[split] = []
218
+ for ss_name in ss_names:
219
+ dataset = DATASET_MAP[ss_name]
220
+ if dataset.target != target or source not in dataset.sources:
221
+ logger.info("Skipping sub-dataset that does not include language pair: %s", ss_name)
222
+ else:
223
+ filtered_subsets[split].append(ss_name)
224
+ logger.info("Using sub-datasets: %s", filtered_subsets)
225
+ return filtered_subsets
226
+
227
+ def _info(self):
228
+ src, target = self.config.language_pair
229
+ return datasets.DatasetInfo(
230
+ description=_DESCRIPTION,
231
+ features=datasets.Features(
232
+ {"translation": datasets.features.Translation(languages=self.config.language_pair)}
233
+ ),
234
+ supervised_keys=(src, target),
235
+ homepage=self.config.url,
236
+ citation=self.config.citation,
237
+ )
238
+
239
+ def _vocab_text_gen(self, split_subsets, extraction_map, language):
240
+ for _, ex in self._generate_examples(split_subsets, extraction_map, with_translation=False):
241
+ yield ex[language]
242
+
243
+ def _split_generators(self, dl_manager):
244
+ source, _ = self.config.language_pair
245
+ manual_paths_dict = {}
246
+ urls_to_download = {}
247
+ for ss_name in itertools.chain.from_iterable(self.subsets.values()):
248
+
249
+ # get dataset
250
+ dataset = DATASET_MAP[ss_name]
251
+ if dataset.get_manual_dl_files(source):
252
+ # TODO(PVP): following two lines skip configs that are incomplete for now
253
+ # +++++++++++++++++++++
254
+ logger.info("Skipping {dataset.name} for now. Incomplete dataset for {self.config.name}")
255
+ continue
256
+ # +++++++++++++++++++++
257
+
258
+ manual_dl_files = dataset.get_manual_dl_files(source)
259
+ manual_paths = [
260
+ os.path.join(os.path.abspath(os.path.expanduser(dl_manager.manual_dir)), fname)
261
+ for fname in manual_dl_files
262
+ ]
263
+ assert all(
264
+ os.path.exists(path) for path in manual_paths
265
+ ), f"For {dataset.name}, you must manually download the following file(s) from {dataset.get_url(source)} and place them in {dl_manager.manual_dir}: {', '.join(manual_dl_files)}"
266
+
267
+ # set manual path for correct subset
268
+ manual_paths_dict[ss_name] = manual_paths
269
+ else:
270
+ urls_to_download[ss_name] = dataset.get_url(source)
271
+
272
+ # Download and extract files from URLs.
273
+ downloaded_files = dl_manager.download_and_extract(urls_to_download)
274
+ # Extract manually downloaded files.
275
+ manual_files = dl_manager.extract(manual_paths_dict)
276
+ extraction_map = dict(downloaded_files, **manual_files)
277
+
278
+ for language in self.config.language_pair:
279
+ self._vocab_text_gen(self.subsets[datasets.Split.TRAIN], extraction_map, language)
280
+
281
+ return [
282
+ datasets.SplitGenerator( # pylint:disable=g-complex-comprehension
283
+ name=split, gen_kwargs={"split_subsets": split_subsets, "extraction_map": extraction_map}
284
+ )
285
+ for split, split_subsets in self.subsets.items()
286
+ ]
287
+
288
+ def _generate_examples(self, split_subsets, extraction_map, with_translation=True):
289
+ """Returns the examples in the raw (text) form."""
290
+ source, _ = self.config.language_pair
291
+
292
+ def _get_local_paths(dataset, extract_dirs):
293
+ rel_paths = dataset.get_path(source)
294
+ if len(extract_dirs) == 1:
295
+ extract_dirs = extract_dirs * len(rel_paths)
296
+ return [
297
+ os.path.join(ex_dir, rel_path) if rel_path else ex_dir
298
+ for ex_dir, rel_path in zip(extract_dirs, rel_paths)
299
+ ]
300
+
301
+ def _get_filenames(dataset):
302
+ rel_paths = dataset.get_path(source)
303
+ urls = dataset.get_url(source)
304
+ if len(urls) == 1:
305
+ urls = urls * len(rel_paths)
306
+ return [rel_path if rel_path else os.path.basename(url) for url, rel_path in zip(urls, rel_paths)]
307
+
308
+ for ss_name in split_subsets:
309
+ # TODO(PVP) remove following five lines when manual data works
310
+ # +++++++++++++++++++++
311
+ dataset = DATASET_MAP[ss_name]
312
+ source, _ = self.config.language_pair
313
+ if dataset.get_manual_dl_files(source):
314
+ logger.info(f"Skipping {dataset.name} for now. Incomplete dataset for {self.config.name}")
315
+ continue
316
+ # +++++++++++++++++++++
317
+
318
+ logger.info("Generating examples from: %s", ss_name)
319
+ dataset = DATASET_MAP[ss_name]
320
+ extract_dirs = extraction_map[ss_name]
321
+ files = _get_local_paths(dataset, extract_dirs)
322
+ filenames = _get_filenames(dataset)
323
+
324
+ sub_generator_args = tuple(files)
325
+
326
+ if ss_name.startswith("czeng"):
327
+ if ss_name.endswith("16pre"):
328
+ sub_generator = functools.partial(_parse_tsv, language_pair=("en", "cs"))
329
+ sub_generator_args += tuple(filenames)
330
+ else:
331
+ sub_generator = _parse_czeng
332
+ elif ss_name == "hindencorp_01":
333
+ sub_generator = _parse_hindencorp
334
+ elif len(files) == 2:
335
+ if ss_name.endswith("_frde"):
336
+ sub_generator = _parse_frde_bitext
337
+ else:
338
+ sub_generator = _parse_parallel_sentences
339
+ sub_generator_args += tuple(filenames)
340
+ elif len(files) == 1:
341
+ fname = filenames[0]
342
+ # Note: Due to formatting used by `download_manager`, the file
343
+ # extension may not be at the end of the file path.
344
+ if ".tsv" in fname:
345
+ sub_generator = _parse_tsv
346
+ sub_generator_args += tuple(filenames)
347
+ elif (
348
+ ss_name.startswith("newscommentary_v14")
349
+ or ss_name.startswith("europarl_v9")
350
+ or ss_name.startswith("wikititles_v1")
351
+ ):
352
+ sub_generator = functools.partial(_parse_tsv, language_pair=self.config.language_pair)
353
+ sub_generator_args += tuple(filenames)
354
+ elif "tmx" in fname or ss_name.startswith("paracrawl_v3"):
355
+ sub_generator = _parse_tmx
356
+ elif ss_name.startswith("wikiheadlines"):
357
+ sub_generator = _parse_wikiheadlines
358
+ else:
359
+ raise ValueError("Unsupported file format: %s" % fname)
360
+ else:
361
+ raise ValueError("Invalid number of files: %d" % len(files))
362
+
363
+ for sub_key, ex in sub_generator(*sub_generator_args):
364
+ if not all(ex.values()):
365
+ continue
366
+ # TODO(adarob): Add subset feature.
367
+ # ex["subset"] = subset
368
+ key = f"{ss_name}/{sub_key}"
369
+ if with_translation is True:
370
+ ex = {"translation": ex}
371
+ yield key, ex
372
+
373
+
374
+ def _parse_parallel_sentences(f1, f2, filename1, filename2):
375
+ """Returns examples from parallel SGML or text files, which may be gzipped."""
376
+
377
+ def _parse_text(path, original_filename):
378
+ """Returns the sentences from a single text file, which may be gzipped."""
379
+ split_path = original_filename.split(".")
380
+
381
+ if split_path[-1] == "gz":
382
+ lang = split_path[-2]
383
+
384
+ def gen():
385
+ with open(path, "rb") as f, gzip.GzipFile(fileobj=f) as g:
386
+ for line in g:
387
+ yield line.decode("utf-8").rstrip()
388
+
389
+ return gen(), lang
390
+
391
+ if split_path[-1] == "txt":
392
+ # CWMT
393
+ lang = split_path[-2].split("_")[-1]
394
+ lang = "zh" if lang in ("ch", "cn", "c[hn]") else lang
395
+ else:
396
+ lang = split_path[-1]
397
+
398
+ def gen():
399
+ with open(path, "rb") as f:
400
+ for line in f:
401
+ yield line.decode("utf-8").rstrip()
402
+
403
+ return gen(), lang
404
+
405
+ def _parse_sgm(path, original_filename):
406
+ """Returns sentences from a single SGML file."""
407
+ lang = original_filename.split(".")[-2]
408
+ # Note: We can't use the XML parser since some of the files are badly
409
+ # formatted.
410
+ seg_re = re.compile(r"<seg id=\"\d+\">(.*)</seg>")
411
+
412
+ def gen():
413
+ with open(path, encoding="utf-8") as f:
414
+ for line in f:
415
+ seg_match = re.match(seg_re, line)
416
+ if seg_match:
417
+ assert len(seg_match.groups()) == 1
418
+ yield seg_match.groups()[0]
419
+
420
+ return gen(), lang
421
+
422
+ parse_file = _parse_sgm if os.path.basename(f1).endswith(".sgm") else _parse_text
423
+
424
+ # Some datasets (e.g., CWMT) contain multiple parallel files specified with
425
+ # a wildcard. We sort both sets to align them and parse them one by one.
426
+ f1_files = sorted(glob.glob(f1))
427
+ f2_files = sorted(glob.glob(f2))
428
+
429
+ assert f1_files and f2_files, "No matching files found: %s, %s." % (f1, f2)
430
+ assert len(f1_files) == len(f2_files), "Number of files do not match: %d vs %d for %s vs %s." % (
431
+ len(f1_files),
432
+ len(f2_files),
433
+ f1,
434
+ f2,
435
+ )
436
+
437
+ for f_id, (f1_i, f2_i) in enumerate(zip(sorted(f1_files), sorted(f2_files))):
438
+ l1_sentences, l1 = parse_file(f1_i, filename1)
439
+ l2_sentences, l2 = parse_file(f2_i, filename2)
440
+
441
+ for line_id, (s1, s2) in enumerate(zip(l1_sentences, l2_sentences)):
442
+ key = f"{f_id}/{line_id}"
443
+ yield key, {l1: s1, l2: s2}
444
+
445
+
446
+ def _parse_frde_bitext(fr_path, de_path):
447
+ with open(fr_path, encoding="utf-8") as fr_f:
448
+ with open(de_path, encoding="utf-8") as de_f:
449
+ for line_id, (s1, s2) in enumerate(zip(fr_f, de_f)):
450
+ yield line_id, {"fr": s1.rstrip(), "de": s2.rstrip()}
451
+
452
+
453
+ def _parse_tmx(path):
454
+ """Generates examples from TMX file."""
455
+
456
+ def _get_tuv_lang(tuv):
457
+ for k, v in tuv.items():
458
+ if k.endswith("}lang"):
459
+ return v
460
+ raise AssertionError("Language not found in `tuv` attributes.")
461
+
462
+ def _get_tuv_seg(tuv):
463
+ segs = tuv.findall("seg")
464
+ assert len(segs) == 1, "Invalid number of segments: %d" % len(segs)
465
+ return segs[0].text
466
+
467
+ with open(path, "rb") as f:
468
+ # Workaround due to: https://github.com/tensorflow/tensorflow/issues/33563
469
+ utf_f = codecs.getreader("utf-8")(f)
470
+ for line_id, (_, elem) in enumerate(ElementTree.iterparse(utf_f)):
471
+ if elem.tag == "tu":
472
+ yield line_id, {_get_tuv_lang(tuv): _get_tuv_seg(tuv) for tuv in elem.iterfind("tuv")}
473
+ elem.clear()
474
+
475
+
476
+ def _parse_tsv(path, filename, language_pair=None):
477
+ """Generates examples from TSV file."""
478
+ if language_pair is None:
479
+ lang_match = re.match(r".*\.([a-z][a-z])-([a-z][a-z])\.tsv", filename)
480
+ assert lang_match is not None, "Invalid TSV filename: %s" % filename
481
+ l1, l2 = lang_match.groups()
482
+ else:
483
+ l1, l2 = language_pair
484
+ with open(path, encoding="utf-8") as f:
485
+ for j, line in enumerate(f):
486
+ cols = line.split("\t")
487
+ if len(cols) != 2:
488
+ logger.warning("Skipping line %d in TSV (%s) with %d != 2 columns.", j, path, len(cols))
489
+ continue
490
+ s1, s2 = cols
491
+ yield j, {l1: s1.strip(), l2: s2.strip()}
492
+
493
+
494
+ def _parse_wikiheadlines(path):
495
+ """Generates examples from Wikiheadlines dataset file."""
496
+ lang_match = re.match(r".*\.([a-z][a-z])-([a-z][a-z])$", path)
497
+ assert lang_match is not None, "Invalid Wikiheadlines filename: %s" % path
498
+ l1, l2 = lang_match.groups()
499
+ with open(path, encoding="utf-8") as f:
500
+ for line_id, line in enumerate(f):
501
+ s1, s2 = line.split("|||")
502
+ yield line_id, {l1: s1.strip(), l2: s2.strip()}
503
+
504
+
505
+ def _parse_czeng(*paths, **kwargs):
506
+ """Generates examples from CzEng v1.6, with optional filtering for v1.7."""
507
+ filter_path = kwargs.get("filter_path", None)
508
+ if filter_path:
509
+ re_block = re.compile(r"^[^-]+-b(\d+)-\d\d[tde]")
510
+ with open(filter_path, encoding="utf-8") as f:
511
+ bad_blocks = {blk for blk in re.search(r"qw{([\s\d]*)}", f.read()).groups()[0].split()}
512
+ logger.info("Loaded %d bad blocks to filter from CzEng v1.6 to make v1.7.", len(bad_blocks))
513
+
514
+ for path in paths:
515
+ for gz_path in sorted(glob.glob(path)):
516
+ with open(gz_path, "rb") as g, gzip.GzipFile(fileobj=g) as f:
517
+ filename = os.path.basename(gz_path)
518
+ for line_id, line in enumerate(f):
519
+ line = line.decode("utf-8") # required for py3
520
+ if not line.strip():
521
+ continue
522
+ id_, unused_score, cs, en = line.split("\t")
523
+ if filter_path:
524
+ block_match = re.match(re_block, id_)
525
+ if block_match and block_match.groups()[0] in bad_blocks:
526
+ continue
527
+ sub_key = f"{filename}/{line_id}"
528
+ yield sub_key, {
529
+ "cs": cs.strip(),
530
+ "en": en.strip(),
531
+ }
532
+
533
+
534
+ def _parse_hindencorp(path):
535
+ with open(path, encoding="utf-8") as f:
536
+ for line_id, line in enumerate(f):
537
+ split_line = line.split("\t")
538
+ if len(split_line) != 5:
539
+ logger.warning("Skipping invalid HindEnCorp line: %s", line)
540
+ continue
541
+ yield line_id, {"translation": {"en": split_line[3].strip(), "hi": split_line[4].strip()}}