File size: 10,374 Bytes
6a84b27 c5a1f93 6a84b27 c5a1f93 6a84b27 c5a1f93 6a84b27 c5a1f93 6a84b27 c5a1f93 6a84b27 c5a1f93 6a84b27 c5a1f93 6a84b27 |
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 |
# coding=utf-8
# Copyright 2020 The HuggingFace Datasets Authors and the current dataset script contributor.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""No Language Left Behind (NLLB)
The "No Language Left Behind" paper is a dataset with translation examples across 200 languages.
This paper reuses prior work, and for some language pairs is just reusing CC-Matrix published on statmt.org.
Depending on the language pair chosen, this script will fetch either the original
version from statmt.org, or the new one from AllenAI.
"""
import datasets
import typing as tp
NLLB_CITATION = (
"@article{team2022NoLL,"
"title={No Language Left Behind: Scaling Human-Centered Machine Translation},"
r"author={Nllb team and Marta Ruiz Costa-juss{\`a} and James Cross and Onur Celebi and Maha Elbayad and Kenneth Heafield and Kevin Heffernan and Elahe Kalbassi and Janice Lam and Daniel Licht and Jean Maillard and Anna Sun and Skyler Wang and Guillaume Wenzek and Alison Youngblood and Bapi Akula and Lo{\"i}c Barrault and Gabriel Mejia Gonzalez and Prangthip Hansanti and John Hoffman and Semarley Jarrett and Kaushik Ram Sadagopan and Dirk Rowe and Shannon L. Spruit and C. Tran and Pierre Andrews and Necip Fazil Ayan and Shruti Bhosale and Sergey Edunov and Angela Fan and Cynthia Gao and Vedanuj Goswami and Francisco Guzm'an and Philipp Koehn and Alexandre Mourachko and Christophe Ropers and Safiyyah Saleem and Holger Schwenk and Jeff Wang},"
"journal={ArXiv},"
"year={2022},"
"volume={abs/2207.04672}"
"}"
)
CCMATRIX_CITATION = (
"@inproceedings{schwenk2021ccmatrix,"
"title={CCMatrix: Mining Billions of High-Quality Parallel Sentences on the Web},"
"author={Schwenk, Holger and Wenzek, Guillaume and Edunov, Sergey and Grave, {'E}douard and Joulin, Armand and Fan, Angela},"
"booktitle={Proceedings of the 59th Annual Meeting of the Association for Computational Linguistics and the 11th International Joint Conference on Natural Language Processing (Volume 1: Long Papers)},"
"pages={6490--6500},"
"year={2021}"
)
_DESCRIPTION = "" # TODO
_HOMEPAGE = "" # TODO
_LICENSE = "https://opendatacommons.org/licenses/by/1-0/"
from .nllb_lang_pairs import NLLB_PAIRS, CCMATRIX_PAIRS, CCMATRIX_MAPPING
_ALLENAI_URL = "https://storage.googleapis.com/allennlp-data-bucket/nllb/"
_STATMT_URL = "http://data.statmt.org/cc-matrix/"
class NLLBTaskConfig(datasets.BuilderConfig):
"""BuilderConfig for No Language Left Behind Dataset."""
def __init__(self, src_lg, tgt_lg, url, **kwargs):
super(NLLBTaskConfig, self).__init__(**kwargs)
self.src_lg = src_lg
self.tgt_lg = tgt_lg
self.url = url
self.source = "statmt" if url.startswith(_STATMT_URL) else "allenai"
def _builder_configs() -> tp.List[NLLBTaskConfig]:
"""
Creates the dataset used for training NLLB model.
Note we always return data from AllenAI if possible because CC-Matrix data
is older, and most language pairs have been improved between the two versions.
"""
configs = {}
for (src_lg, tgt_lg) in NLLB_PAIRS:
assert (src_lg, tgt_lg) not in configs
configs[(src_lg, tgt_lg)] = NLLBTaskConfig(
name=f"{src_lg}-{tgt_lg}",
version=datasets.Version("1.0.0"),
description=f"No Language Left Behind (NLLB): {src_lg} - {tgt_lg}",
src_lg=src_lg,
tgt_lg=tgt_lg,
url=f"{_ALLENAI_URL}{src_lg}-{tgt_lg}.gz",
)
for (src_lg, tgt_lg) in CCMATRIX_PAIRS:
# Prevent accidental override
# Note: the lang pairs are not consistently alphabetically sorted,
# because CCMatrix was using other language code which may swap the order.
# Let's keep the original order because they correspond to the column order in the file.
assert (src_lg, tgt_lg) not in configs
assert (tgt_lg, src_lg) not in configs
src_cc, tgt_cc = CCMATRIX_MAPPING[src_lg], CCMATRIX_MAPPING[tgt_lg]
configs[(src_lg, tgt_lg)] = NLLBTaskConfig(
name=f"{src_lg}-{tgt_lg}",
version=datasets.Version("1.0.0"),
description=f"No Language Left Behind (NLLB): {src_lg} - {tgt_lg}",
src_lg=src_lg,
tgt_lg=tgt_lg,
# Use CCMatrix language code to fetch from statmt
url=f"{_STATMT_URL}{src_cc}-{tgt_cc}.bitextf.tsv.gz",
)
return list(configs.values())
class NLLB(datasets.GeneratorBasedBuilder):
"""No Language Left Behind Dataset."""
BUILDER_CONFIGS = _builder_configs()
BUILDER_CONFIG_CLASS = NLLBTaskConfig
def _info(self):
# define feature types
citation = NLLB_CITATION
features = datasets.Features(
{
"translation": datasets.Translation(
languages=(self.config.src_lg, self.config.tgt_lg)
),
"laser_score": datasets.Value("float32"),
"source_sentence_lid": datasets.Value("float32"),
"target_sentence_lid": datasets.Value("float32"),
"source_sentence_source": datasets.Value("string"),
"source_sentence_perplexity": datasets.Value("float32"),
"source_sentence_url": datasets.Value("string"),
"target_sentence_source": datasets.Value("string"),
"target_sentence_perplexity": datasets.Value("float32"),
"target_sentence_url": datasets.Value("string"),
}
)
if self.config.source == "statmt":
citation = CCMATRIX_CITATION
# MT stats didn't published all the metadata
features = datasets.Features(
{
"translation": datasets.Translation(
languages=(self.config.src_lg, self.config.tgt_lg)
),
"laser_score": datasets.Value("float32"),
}
)
return datasets.DatasetInfo(
description=_DESCRIPTION,
features=features,
supervised_keys=None,
homepage=_HOMEPAGE,
license=_LICENSE,
citation=citation,
)
def _split_generators(self, dl_manager):
"""Returns one training generator. NLLB200 is meant for training.
If you're interested in evaluation look at https://huggingface.co/datasets/facebook/flores
"""
local_file = dl_manager.download_and_extract(self.config.url)
return [
datasets.SplitGenerator(
name=datasets.Split.TRAIN,
gen_kwargs={
"filepath": local_file,
"source_lg": self.config.src_lg,
"target_lg": self.config.tgt_lg,
},
)
]
def _generate_examples(self, filepath, source_lg, target_lg, source_max_perplexity=None, target_max_perplexity=None):
if self.config.source == "statmt":
# MT stats didn't published all the metadata
return self._generate_minimal_examples(filepath, source_lg, target_lg)
return self._generate_full_examples(filepath, source_lg, target_lg, source_max_perplexity=source_max_perplexity, target_max_perplexity=target_max_perplexity)
def _generate_full_examples(self, filepath, source_lg, target_lg, source_max_perplexity=None, target_max_perplexity=None):
with open(filepath, encoding="utf-8") as f:
# reader = csv.reader(f, delimiter="\t")
for id_, example in enumerate(f):
try:
datarow = example.rstrip("\n").split("\t")
row = {}
# create translation json
row["translation"] = {
source_lg: datarow[0],
target_lg: datarow[1],
}
row["source_sentence_perplexity"] = None # TODO: compute the perplexity for the source sentence here
row["target_sentence_perplexity"] = None # TODO: compute the perplexity for the target sentence here
row["laser_score"] = float(datarow[2])
row["source_sentence_lid"] = float(datarow[3])
row["target_sentence_lid"] = float(datarow[4])
row["source_sentence_source"] = datarow[5]
row["source_sentence_url"] = datarow[6]
row["target_sentence_source"] = datarow[7]
row["target_sentence_url"] = datarow[8]
# replace empty values
row = {k: None if not v else v for k, v in row.items()}
except:
print(datarow)
raise
if source_max_perplexity is not None and row["source_sentence_perplexity"] > source_max_perplexity:
continue
if target_max_perplexity is not None and row["target_sentence_perplexity"] > target_max_perplexity:
continue
yield id_, row
def _generate_minimal_examples(self, filepath, source_lg, target_lg):
with open(filepath, encoding="utf-8") as f:
for i, example in enumerate(f):
try:
(score, src, tgt) = example.rstrip("\n").split("\t")
row = {
"translation": {
source_lg: src,
target_lg: tgt,
},
"laser_score": score,
}
except:
print(example)
raise
yield i, row
# to test the script, go to the root folder of the repo (nllb) and run:
# datasets-cli test nllb --save_infos --all_configs
|