gsarti commited on
Commit
40be566
1 Parent(s): b056c37

Added load script

Browse files
Files changed (1) hide show
  1. mt_geneval.py +235 -0
mt_geneval.py ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """MT-GenEval: A Counterfactual and Contextual Dataset for Evaluating Gender Accuracy in Machine Translation"""
16
+
17
+ import re
18
+ from pathlib import Path
19
+ from typing import Dict
20
+
21
+ import datasets
22
+ from datasets.utils.download_manager import DownloadManager
23
+
24
+
25
+ _CITATION = """\
26
+ @inproceedings{currey-etal-2022-mtgeneval,
27
+ title = "{MT-GenEval}: {A} Counterfactual and Contextual Dataset for Evaluating Gender Accuracy in Machine Translation",
28
+ author = "Currey, Anna and
29
+ Nadejde, Maria and
30
+ Pappagari, Raghavendra and
31
+ Mayer, Mia and
32
+ Lauly, Stanislas, and
33
+ Niu, Xing and
34
+ Hsu, Benjamin and
35
+ Dinu, Georgiana",
36
+ booktitle = "Proceedings of the 2022 Conference on Empirical Methods in Natural Language Processing",
37
+ month = dec,
38
+ year = "2022",
39
+ publisher = "Association for Computational Linguistics",
40
+ url = ""https://arxiv.org/pdf/2211.01355.pdf,
41
+ }
42
+ """
43
+
44
+ _DESCRIPTION = """\
45
+ The MT-GenEval benchmark evaluates gender translation accuracy on English -> {Arabic, French, German, Hindi, Italian,
46
+ Portuguese, Russian, Spanish}. The dataset contains individual sentences with annotations on the gendered target words,
47
+ and contrastive original-invertend translations with additional preceding context.
48
+ """
49
+
50
+ _HOMEPAGE = "https://github.com/amazon-science/machine-translation-gender-eval"
51
+
52
+ _LICENSE = "Creative Commons Attribution Share Alike 3.0"
53
+
54
+ _URL = "https://github.com/amazon-science/machine-translation-gender-eval/raw/main/data"
55
+
56
+ _CONFIGS = ["sentences", "context"]
57
+ _LANGS = ["ar", "fr", "de", "hi", "it", "pt", "ru", "es"]
58
+
59
+ r = re.compile('<p>(.+?)</p>')
60
+
61
+ class MTGenEvalConfig(datasets.BuilderConfig):
62
+ def __init__(
63
+ self,
64
+ data_type: str,
65
+ source_language: str,
66
+ target_language: str,
67
+ **kwargs
68
+ ):
69
+ """BuilderConfig for MT-GenEval.
70
+
71
+ Args:
72
+ source_language: `str`, source language for translation.
73
+ target_language: `str`, translation language.
74
+ **kwargs: keyword arguments forwarded to super.
75
+ """
76
+ super().__init__(**kwargs)
77
+ self.data_type = data_type
78
+ self.source_language = source_language
79
+ self.target_language = target_language
80
+
81
+
82
+ class WmtVat(datasets.GeneratorBasedBuilder):
83
+
84
+ VERSION = datasets.Version("1.0.0")
85
+
86
+ BUILDER_CONFIGS = [
87
+ MTGenEvalConfig(
88
+ name=f"{cfg}_en_{lang}",
89
+ data_type=cfg,
90
+ source_language="en",
91
+ target_language=lang,
92
+ ) for lang in _LANGS for cfg in _CONFIGS
93
+ ]
94
+
95
+ def _info(self):
96
+ if self.config.name.startswith("sentences"):
97
+ features = datasets.Features(
98
+ {
99
+ "orig_id": datasets.Value("int32"),
100
+ "source_feminine": datasets.Value("string"),
101
+ "reference_feminine": datasets.Value("string"),
102
+ "source_masculine": datasets.Value("string"),
103
+ "reference_masculine": datasets.Value("string"),
104
+ "source_feminine_annotated": datasets.Value("string"),
105
+ "reference_feminine_annotated": datasets.Value("string"),
106
+ "source_masculine_annotated": datasets.Value("string"),
107
+ "reference_masculine_annotated": datasets.Value("string"),
108
+ "source_feminine_keywords": datasets.Value("string"),
109
+ "reference_feminine_keywords": datasets.Value("string"),
110
+ "source_masculine_keywords": datasets.Value("string"),
111
+ "reference_masculine_keywords": datasets.Value("string")
112
+ }
113
+ )
114
+ else:
115
+ features = datasets.Features(
116
+ {
117
+ "orig_id": datasets.Value("int32"),
118
+ "context": datasets.Value("string"),
119
+ "source": datasets.Value("string"),
120
+ "reference_original": datasets.Value("string"),
121
+ "reference_flipped": datasets.Value("string")
122
+ }
123
+ )
124
+ return datasets.DatasetInfo(
125
+ description=_DESCRIPTION,
126
+ features=features,
127
+ homepage=_HOMEPAGE,
128
+ license=_LICENSE,
129
+ citation=_CITATION,
130
+ )
131
+
132
+ def _split_generators(self, dl_manager: DownloadManager):
133
+ """Returns SplitGenerators."""
134
+ base_path = Path(_URL) / self.config.data_type
135
+ filepaths = {}
136
+ for split in ["dev", "test"]:
137
+ filepaths[split] = {}
138
+ if self.config.name.startswith("sentences"):
139
+ for curr_lang in [self.config.source_language, self.config.target_language]:
140
+ for gender in ["feminine", "masculine"]:
141
+ fname = f"geneval-sentences-{gender}-{split}.en_{self.config.target_language}.{curr_lang}"
142
+ langname = "source" if curr_lang == self.config.source_language else "reference"
143
+ url = base_path / split / fname
144
+ filepaths[split][f"{langname}_{gender}"] = dl_manager.download_and_extract(url)
145
+ annotated_url = base_path / split / "annotated" / fname
146
+ filepaths[split][f"{langname}_{gender}_annotated"] = dl_manager.download_and_extract(annotated_url)
147
+ else:
148
+ ftypes = ["2to1", "original", "flipped"]
149
+ for ftype in ftypes:
150
+ curr_lang = self.config.source_language if ftype == "2to1" else self.config.target_language
151
+ fname = f"geneval-context-wikiprofessions-{ftype}-{split}.en_{self.config.target_language}.{curr_lang}"
152
+ url = base_path / fname
153
+ filepaths[split][ftype] = dl_manager.download_and_extract(url)
154
+ return [
155
+ datasets.SplitGenerator(
156
+ name=datasets.Split.TRAIN,
157
+ gen_kwargs={
158
+ "filepaths": filepaths["dev"],
159
+ "cfg_name": self.config.data_type
160
+ },
161
+ ),
162
+ datasets.SplitGenerator(
163
+ name=datasets.Split.TEST,
164
+ gen_kwargs={
165
+ "filepaths": filepaths["test"],
166
+ "cfg_name": self.config.data_type
167
+ },
168
+ ),
169
+ ]
170
+
171
+
172
+ def _generate_examples(
173
+ self, filepaths: Dict[str, str], cfg_name: str
174
+ ):
175
+ """ Yields examples as (key, example) tuples. """
176
+ if cfg_name == "sentences":
177
+ with open(filepaths["source_feminine"]) as f:
178
+ source_feminine = f.read().splitlines()
179
+ with open(filepaths["reference_feminine"]) as f:
180
+ reference_feminine = f.read().splitlines()
181
+ with open(filepaths["source_masculine"]) as f:
182
+ source_masculine = f.read().splitlines()
183
+ with open(filepaths["reference_masculine"]) as f:
184
+ reference_masculine = f.read().splitlines()
185
+ with open(filepaths["source_feminine_annotated"]) as f:
186
+ source_feminine_annotated = f.read().splitlines()
187
+ with open(filepaths["reference_feminine_annotated"]) as f:
188
+ reference_feminine_annotated = f.read().splitlines()
189
+ with open(filepaths["source_masculine_annotated"]) as f:
190
+ source_masculine_annotated = f.read().splitlines()
191
+ with open(filepaths["reference_masculine_annotated"]) as f:
192
+ reference_masculine_annotated = f.read().splitlines()
193
+ source_feminine_keywords = [r.findall(s) for s in source_feminine_annotated]
194
+ reference_feminine_keywords = [r.findall(s) for s in reference_feminine_annotated]
195
+ source_masculine_keywords = [r.findall(s) for s in source_masculine_annotated]
196
+ reference_masculine_keywords = [r.findall(s) for s in reference_masculine_annotated]
197
+ for i, (sf, rf, sm, rm, sfa, rfa, sma, rma, sfk, rfk, smk, rmk) in enumerate(
198
+ zip(
199
+ source_feminine, reference_feminine, source_masculine, reference_masculine,
200
+ source_feminine_annotated, reference_feminine_annotated, source_masculine_annotated, reference_masculine_annotated,
201
+ source_feminine_keywords, reference_feminine_keywords, source_masculine_keywords, reference_masculine_keywords
202
+ )
203
+ ):
204
+ yield i, {
205
+ "orig_id": i,
206
+ "source_feminine": sf,
207
+ "reference_feminine": rf,
208
+ "source_masculine": sm,
209
+ "reference_masculine": rm,
210
+ "source_feminine_annotated": sfa,
211
+ "reference_feminine_annotated": rfa,
212
+ "source_masculine_annotated": sma,
213
+ "reference_masculine_annotated": rma,
214
+ "source_feminine_keywords": sfk,
215
+ "reference_feminine_keywords": rfk,
216
+ "source_masculine_keywords": smk,
217
+ "reference_masculine_keywords": rmk
218
+ }
219
+ else:
220
+ with open(filepaths["2to1"]) as f:
221
+ context_and_source = f.read().splitlines()
222
+ with open(filepaths["original"]) as f:
223
+ orig_ref = f.read().splitlines()
224
+ with open(filepaths["flipped"]) as f:
225
+ flipped_ref = f.read().splitlines()
226
+ context = [s.split(" <sep> ")[0] for s in context_and_source]
227
+ source = [s.split(" <sep> ")[1] for s in context_and_source]
228
+ for i, (c, s, oref, fref) in enumerate(zip(context, source, orig_ref, flipped_ref)):
229
+ yield i, {
230
+ "orig_id": i,
231
+ "context": c,
232
+ "source": s,
233
+ "reference_original": oref,
234
+ "reference_flipped": fref
235
+ }