msharma95 commited on
Commit
fc64fc2
·
verified ·
1 Parent(s): 8ef1ea3

Upload xglue_mirror.py

Browse files
Files changed (1) hide show
  1. xglue_mirror.py +585 -0
xglue_mirror.py ADDED
@@ -0,0 +1,585 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """The General Language Understanding Evaluation (GLUE) benchmark."""
18
+
19
+
20
+ import json
21
+ import textwrap
22
+
23
+ import datasets
24
+
25
+
26
+ _XGLUE_CITATION = """\
27
+ @article{Liang2020XGLUEAN,
28
+ title={XGLUE: A New Benchmark Dataset for Cross-lingual Pre-training, Understanding and Generation},
29
+ author={Yaobo Liang and Nan Duan and Yeyun Gong and Ning Wu and Fenfei Guo and Weizhen Qi
30
+ and Ming Gong and Linjun Shou and Daxin Jiang and Guihong Cao and Xiaodong Fan and Ruofei
31
+ Zhang and Rahul Agrawal and Edward Cui and Sining Wei and Taroon Bharti and Ying Qiao
32
+ and Jiun-Hung Chen and Winnie Wu and Shuguang Liu and Fan Yang and Daniel Campos
33
+ and Rangan Majumder and Ming Zhou},
34
+ journal={arXiv},
35
+ year={2020},
36
+ volume={abs/2004.01401}
37
+ }
38
+ """
39
+
40
+ _XGLUE_DESCRIPTION = """\
41
+ XGLUE is a new benchmark dataset to evaluate the performance of cross-lingual pre-trained
42
+ models with respect to cross-lingual natural language understanding and generation.
43
+ The benchmark is composed of the following 11 tasks:
44
+ - NER
45
+ - POS Tagging (POS)
46
+ - News Classification (NC)
47
+ - MLQA
48
+ - XNLI
49
+ - PAWS-X
50
+ - Query-Ad Matching (QADSM)
51
+ - Web Page Ranking (WPR)
52
+ - QA Matching (QAM)
53
+ - Question Generation (QG)
54
+ - News Title Generation (NTG)
55
+
56
+ For more information, please take a look at https://microsoft.github.io/XGLUE/.
57
+ """
58
+
59
+ _XGLUE_ALL_DATA = "https://1drv.ms/u/s!Amt8n9AJEyxchJtmUXkNFaTXLCbVOQ?e=2jYlMZ"
60
+
61
+ _LANGUAGES = {
62
+ "ner": ["en", "de", "es", "nl"],
63
+ "pos": ["en", "de", "es", "nl", "bg", "el", "fr", "pl", "tr", "vi", "zh", "ur", "hi", "it", "ar", "ru", "th"],
64
+ "mlqa": ["en", "de", "ar", "es", "hi", "vi", "zh"],
65
+ "nc": ["en", "de", "es", "fr", "ru"],
66
+ "xnli": ["en", "ar", "bg", "de", "el", "es", "fr", "hi", "ru", "sw", "th", "tr", "ur", "vi", "zh"],
67
+ "paws-x": ["en", "de", "es", "fr"],
68
+ "qadsm": ["en", "de", "fr"],
69
+ "wpr": ["en", "de", "es", "fr", "it", "pt", "zh"],
70
+ "qam": ["en", "de", "fr"],
71
+ "qg": ["en", "de", "es", "fr", "it", "pt"],
72
+ "ntg": ["en", "de", "es", "fr", "ru"],
73
+ }
74
+
75
+ _PATHS = {
76
+ "mlqa": {
77
+ "train": "squad1.1/train-v1.1.json",
78
+ "dev": "MLQA_V1/dev/dev-context-{0}-question-{0}.json",
79
+ "test": "MLQA_V1/test/test-context-{0}-question-{0}.json",
80
+ },
81
+ "xnli": {"train": "multinli.train.en.tsv", "dev": "{}.dev", "test": "{}.test"},
82
+ "paws-x": {
83
+ "train": "en/train.tsv",
84
+ "dev": "{}/dev_2k.tsv",
85
+ "test": "{}/test_2k.tsv",
86
+ },
87
+ }
88
+ for name in ["ner", "pos"]:
89
+ _PATHS[name] = {"train": "en.train", "dev": "{}.dev", "test": "{}.test"}
90
+ for name in ["nc", "qadsm", "wpr", "qam"]:
91
+ _PATHS[name] = {
92
+ "train": "xglue." + name + ".en.train",
93
+ "dev": "xglue." + name + ".{}.dev",
94
+ "test": "xglue." + name + ".{}.test",
95
+ }
96
+ for name in ["qg", "ntg"]:
97
+ _PATHS[name] = {"train": "xglue." + name + ".en", "dev": "xglue." + name + ".{}", "test": "xglue." + name + ".{}"}
98
+
99
+
100
+ class XGlueConfig(datasets.BuilderConfig):
101
+ """BuilderConfig for XGLUE."""
102
+
103
+ def __init__(
104
+ self,
105
+ data_dir,
106
+ citation,
107
+ url,
108
+ **kwargs,
109
+ ):
110
+ """BuilderConfig for XGLUE.
111
+
112
+ Args:
113
+ data_dir: `string`, the path to the folder containing the files in the
114
+ downloaded .tar
115
+ citation: `string`, citation for the data set
116
+ url: `string`, url for information about the data set
117
+ **kwargs: keyword arguments forwarded to super.
118
+ """
119
+ super(XGlueConfig, self).__init__(version=datasets.Version("1.0.0", ""), **kwargs)
120
+ self.data_dir = data_dir
121
+ self.citation = citation
122
+ self.url = url
123
+
124
+
125
+ class XGlue(datasets.GeneratorBasedBuilder):
126
+ """The Cross-lingual Pre-training, Understanding and Generation (XGlue) Benchmark."""
127
+
128
+ BUILDER_CONFIGS = [
129
+ XGlueConfig(
130
+ name="ner",
131
+ description=textwrap.dedent(
132
+ """\
133
+ The shared task of CoNLL-2003 concerns language-independent named entity recognition.
134
+ We will concentrate on four types of named entities:
135
+ persons, locations, organizations and names of miscellaneous entities
136
+ that do not belong to the previous three groups.
137
+ """
138
+ ),
139
+ data_dir="NER",
140
+ citation=textwrap.dedent(
141
+ """\
142
+ @article{Sang2003IntroductionTT,
143
+ title={Introduction to the CoNLL-2003 Shared Task: Language-Independent Named Entity Recognition},
144
+ author={Erik F. Tjong Kim Sang and Fien De Meulder},
145
+ journal={ArXiv},
146
+ year={2003},
147
+ volume={cs.CL/0306050}
148
+ },
149
+ @article{Sang2002IntroductionTT,
150
+ title={Introduction to the CoNLL-2002 Shared Task: Language-Independent Named Entity Recognition},
151
+ author={Erik F. Tjong Kim Sang},
152
+ journal={ArXiv},
153
+ year={2002},
154
+ volume={cs.CL/0209010}
155
+ }"""
156
+ ),
157
+ url="https://www.clips.uantwerpen.be/conll2003/ner/",
158
+ ),
159
+ XGlueConfig(
160
+ name="pos",
161
+ description=textwrap.dedent(
162
+ """\
163
+ Universal Dependencies (UD) is a project that is developing cross-linguistically consistent treebank
164
+ annotation for many languages, with the goal of facilitating multilingual parser development, cross-lingual
165
+ learning, and parsing research from a language typology perspective. The annotation scheme is based on an
166
+ evolution of (universal) Stanford dependencies (de Marneffe et al., 2006, 2008, 2014), Google universal
167
+ part-of-speech tags (Petrov et al., 2012), and the Interset interlingua for morphosyntactic tagsets
168
+ (Zeman, 2008). The general philosophy is to provide a universal inventory of categories and guidelines
169
+ to facilitate consistent annotation of similar constructions across languages, while
170
+ allowing language-specific extensions when necessary.
171
+ """
172
+ ),
173
+ data_dir="POS",
174
+ citation=textwrap.dedent(
175
+ """\
176
+ @misc{11234/1-3105,
177
+ title={Universal Dependencies 2.5},
178
+ author={Zeman, Daniel and Nivre, Joakim and Abrams, Mitchell and Aepli, et al.},
179
+ url={http://hdl.handle.net/11234/1-3105},
180
+ note={{LINDAT}/{CLARIAH}-{CZ} digital library at the Institute of Formal and Applied Linguistics ({{\'U}FAL}), Faculty of Mathematics and Physics, Charles University},
181
+ copyright={Licence Universal Dependencies v2.5},
182
+ year={2019}
183
+ }"""
184
+ ),
185
+ url="https://universaldependencies.org/",
186
+ ),
187
+ XGlueConfig(
188
+ name="mlqa",
189
+ description=textwrap.dedent(
190
+ """\
191
+ MLQA (MultiLingual Question Answering) is a benchmark dataset for evaluating cross-lingual question answering
192
+ performance. MLQA consists of over 5K extractive QA instances (12K in English) in SQuAD format in seven languages
193
+ - English, Arabic, German, Spanish, Hindi, Vietnamese and Simplified Chinese.
194
+ MLQA is highly parallel, with QA instances parallel between 4 different languages on average.
195
+ """
196
+ ),
197
+ data_dir="MLQA",
198
+ citation=textwrap.dedent(
199
+ """\
200
+ @article{Lewis2019MLQAEC,
201
+ title={MLQA: Evaluating Cross-lingual Extractive Question Answering},
202
+ author={Patrick Lewis and Barlas Oguz and Ruty Rinott and Sebastian Riedel and Holger Schwenk},
203
+ journal={ArXiv},
204
+ year={2019},
205
+ volume={abs/1910.07475}
206
+ }"""
207
+ ),
208
+ url="https://github.com/facebookresearch/MLQA",
209
+ ),
210
+ XGlueConfig(
211
+ name="nc",
212
+ description=textwrap.dedent(
213
+ """\
214
+ This task aims to predict the category given a news article. It covers
215
+ 5 languages, including English, Spanish, French,
216
+ German and Russian. Each labeled instance is a
217
+ 3-tuple: <news title, news body, category>. The
218
+ category number is 10. We crawl this dataset from
219
+ a commercial news website. Accuracy (ACC) of
220
+ the multi-class classification is used as the metric.
221
+ """
222
+ ),
223
+ data_dir="NC",
224
+ citation="",
225
+ url="",
226
+ ),
227
+ XGlueConfig(
228
+ name="xnli",
229
+ description=textwrap.dedent(
230
+ """\
231
+ XNLI is a subset of a few thousand examples from MNLI which has been translated
232
+ into a 14 different languages (some low-ish resource). As with MNLI, the goal is
233
+ to predict textual entailment (does sentence A imply/contradict/neither sentence
234
+ B) and is a classification task (given two sentences, predict one of three
235
+ labels).
236
+ """
237
+ ),
238
+ data_dir="XNLI",
239
+ citation=textwrap.dedent(
240
+ """\
241
+ @inproceedings{Conneau2018XNLIEC,
242
+ title={XNLI: Evaluating Cross-lingual Sentence Representations},
243
+ author={Alexis Conneau and Guillaume Lample and Ruty Rinott and Adina Williams and Samuel R. Bowman and Holger Schwenk and Veselin Stoyanov},
244
+ booktitle={EMNLP},
245
+ year={2018}
246
+ }"""
247
+ ),
248
+ url="https://github.com/facebookresearch/XNLI",
249
+ ),
250
+ XGlueConfig(
251
+ name="paws-x",
252
+ description=textwrap.dedent(
253
+ """\
254
+ PAWS-X contains 23,659 human translated PAWS (Paraphrase Adversaries from Word Scrambling) evaluation pairs and 296,406 machine translated training pairs in six typologically distinct languages: French, Spanish, German, Chinese, Japanese, and Korean. All translated pairs are sourced from examples in PAWS-Wiki.
255
+ """
256
+ ),
257
+ data_dir="PAWSX",
258
+ citation=textwrap.dedent(
259
+ """\
260
+ @article{Yang2019PAWSXAC,
261
+ title={PAWS-X: A Cross-lingual Adversarial Dataset for Paraphrase Identification},
262
+ author={Yinfei Yang and Yuan Zhang and Chris Tar and Jason Baldridge},
263
+ journal={ArXiv},
264
+ year={2019},
265
+ volume={abs/1908.11828}
266
+ }"""
267
+ ),
268
+ url="https://github.com/google-research-datasets/paws/tree/master/pawsx",
269
+ ),
270
+ XGlueConfig(
271
+ name="qadsm",
272
+ description=textwrap.dedent(
273
+ """\
274
+ Query-Ad Matching (QADSM) task aims
275
+ to predict whether an advertisement (ad) is relevant to an input query. It covers 3 languages, including English, French and German. Each labeled instance is a 4-tuple: <query, ad title, ad description, label>. The label indicates whether the
276
+ ad is relevant to the query (Good), or not (Bad).
277
+ This dataset was constructed based on a commercial search engine. Accuracy (ACC) of the binary classification should be used as the metric.
278
+ """
279
+ ),
280
+ data_dir="QADSM",
281
+ citation="",
282
+ url="",
283
+ ),
284
+ XGlueConfig(
285
+ name="wpr",
286
+ description=textwrap.dedent(
287
+ """\
288
+ Tthe Web Page Ranking (WPR) task aims to
289
+ predict whether a web page is relevant to an input query. It covers 7 languages, including English, German, French, Spanish, Italian, Portuguese and Chinese. Each labeled instance is a
290
+ 4-tuple: <query, web page title, web page snippet, label>. The relevance label contains 5 ratings: Perfect (4), Excellent (3), Good (2), Fair (1)
291
+ and Bad (0). The dataset is constructed based on a
292
+ commercial search engine. Normalize Discounted
293
+ Cumulative Gain (nDCG) should be used as the metric.
294
+ """
295
+ ),
296
+ data_dir="WPR",
297
+ citation="",
298
+ url="",
299
+ ),
300
+ XGlueConfig(
301
+ name="qam",
302
+ description=textwrap.dedent(
303
+ """\
304
+ The QA Matching (QAM) task aims to predict whether a <question, passage> pair is a QA pair.
305
+ It covers 3 languages, including English, French
306
+ and German. Each labeled instance is a 3-tuple:
307
+ <question, passage, label>. The label indicates
308
+ whether the passage is the answer of the question
309
+ (1), or not (0). This dataset is constructed based on
310
+ a commercial search engine. Accuracy (ACC) of
311
+ the binary classification should be used as the metric.
312
+ """
313
+ ),
314
+ data_dir="QAM",
315
+ citation="",
316
+ url="",
317
+ ),
318
+ XGlueConfig(
319
+ name="qg",
320
+ description=textwrap.dedent(
321
+ """\
322
+ The Question Generation (QG) task aims to
323
+ generate a question for a given passage. <passage, question> pairs were collected from a commercial search engine. It covers 6 languages, including English, French, German, Spanish, Italian and
324
+ Portuguese. BLEU-4 score should be used as the metric.
325
+ """
326
+ ),
327
+ data_dir="QG",
328
+ citation="",
329
+ url="",
330
+ ),
331
+ XGlueConfig(
332
+ name="ntg",
333
+ description=textwrap.dedent(
334
+ """\
335
+ News Title Generation (NTG) task aims
336
+ to generate a proper title for a given news body.
337
+ We collect <news body, news title> pairs from a
338
+ commercial news website. It covers 5 languages,
339
+ including German, English, French, Spanish and
340
+ Russian. BLEU-4 score should be used as the metric.
341
+ """
342
+ ),
343
+ data_dir="NTG",
344
+ citation="",
345
+ url="",
346
+ ),
347
+ ]
348
+
349
+ def _info(self):
350
+ if self.config.name == "ner":
351
+ features = {
352
+ "words": datasets.Sequence(datasets.Value("string")),
353
+ "ner": datasets.Sequence(
354
+ datasets.features.ClassLabel(
355
+ names=[
356
+ "O",
357
+ "B-PER",
358
+ "I-PER",
359
+ "B-ORG",
360
+ "I-ORG",
361
+ "B-LOC",
362
+ "I-LOC",
363
+ "B-MISC",
364
+ "I-MISC",
365
+ ]
366
+ )
367
+ ),
368
+ }
369
+ elif self.config.name == "pos":
370
+ features = {
371
+ "words": datasets.Sequence(datasets.Value("string")),
372
+ "pos": datasets.Sequence(
373
+ datasets.features.ClassLabel(
374
+ names=[
375
+ "ADJ",
376
+ "ADP",
377
+ "ADV",
378
+ "AUX",
379
+ "CCONJ",
380
+ "DET",
381
+ "INTJ",
382
+ "NOUN",
383
+ "NUM",
384
+ "PART",
385
+ "PRON",
386
+ "PROPN",
387
+ "PUNCT",
388
+ "SCONJ",
389
+ "SYM",
390
+ "VERB",
391
+ "X",
392
+ ]
393
+ )
394
+ ),
395
+ }
396
+ elif self.config.name == "mlqa":
397
+ features = {
398
+ "context": datasets.Value("string"),
399
+ "question": datasets.Value("string"),
400
+ "answers": datasets.features.Sequence(
401
+ {"answer_start": datasets.Value("int32"), "text": datasets.Value("string")}
402
+ ),
403
+ # These are the features of your dataset like images, labels ...
404
+ }
405
+ elif self.config.name == "nc":
406
+ features = {
407
+ "news_title": datasets.Value("string"),
408
+ "news_body": datasets.Value("string"),
409
+ "news_category": datasets.ClassLabel(
410
+ names=[
411
+ "foodanddrink",
412
+ "sports",
413
+ "travel",
414
+ "finance",
415
+ "lifestyle",
416
+ "news",
417
+ "entertainment",
418
+ "health",
419
+ "video",
420
+ "autos",
421
+ ]
422
+ ),
423
+ }
424
+ elif self.config.name == "xnli":
425
+ features = {
426
+ "premise": datasets.Value("string"),
427
+ "hypothesis": datasets.Value("string"),
428
+ "label": datasets.features.ClassLabel(names=["entailment", "neutral", "contradiction"]),
429
+ }
430
+ elif self.config.name == "paws-x":
431
+ features = {
432
+ "sentence1": datasets.Value("string"),
433
+ "sentence2": datasets.Value("string"),
434
+ "label": datasets.features.ClassLabel(names=["different", "same"]),
435
+ }
436
+ elif self.config.name == "qadsm":
437
+ features = {
438
+ "query": datasets.Value("string"),
439
+ "ad_title": datasets.Value("string"),
440
+ "ad_description": datasets.Value("string"),
441
+ "relevance_label": datasets.features.ClassLabel(names=["Bad", "Good"]),
442
+ }
443
+ elif self.config.name == "wpr":
444
+ features = {
445
+ "query": datasets.Value("string"),
446
+ "web_page_title": datasets.Value("string"),
447
+ "web_page_snippet": datasets.Value("string"),
448
+ "relavance_label": datasets.features.ClassLabel(names=["Bad", "Fair", "Good", "Excellent", "Perfect"]),
449
+ }
450
+ elif self.config.name == "qam":
451
+ features = {
452
+ "question": datasets.Value("string"),
453
+ "answer": datasets.Value("string"),
454
+ "label": datasets.features.ClassLabel(names=["False", "True"]),
455
+ }
456
+ elif self.config.name == "qg":
457
+ features = {
458
+ "answer_passage": datasets.Value("string"),
459
+ "question": datasets.Value("string"),
460
+ }
461
+ elif self.config.name == "ntg":
462
+ features = {
463
+ "news_body": datasets.Value("string"),
464
+ "news_title": datasets.Value("string"),
465
+ }
466
+
467
+ return datasets.DatasetInfo(
468
+ description=_XGLUE_DESCRIPTION,
469
+ features=datasets.Features(features),
470
+ homepage=self.config.url,
471
+ citation=self.config.citation + "\n" + _XGLUE_CITATION,
472
+ )
473
+
474
+ def _split_generators(self, dl_manager):
475
+ archive = dl_manager.download(_XGLUE_ALL_DATA)
476
+ data_folder = f"xglue_full_dataset/{self.config.data_dir}"
477
+ name = self.config.name
478
+
479
+ languages = _LANGUAGES[name]
480
+ return (
481
+ [
482
+ datasets.SplitGenerator(
483
+ name=datasets.Split.TRAIN,
484
+ gen_kwargs={
485
+ "archive": dl_manager.iter_archive(archive),
486
+ "data_path": f"{data_folder}/{_PATHS[name]['train']}",
487
+ "split": "train",
488
+ },
489
+ ),
490
+ ]
491
+ + [
492
+ datasets.SplitGenerator(
493
+ name=datasets.Split(f"validation.{lang}"),
494
+ gen_kwargs={
495
+ "archive": dl_manager.iter_archive(archive),
496
+ "data_path": f"{data_folder}/{_PATHS[name]['dev'].format(lang)}",
497
+ "split": "dev",
498
+ },
499
+ )
500
+ for lang in languages
501
+ ]
502
+ + [
503
+ datasets.SplitGenerator(
504
+ name=datasets.Split(f"test.{lang}"),
505
+ gen_kwargs={
506
+ "archive": dl_manager.iter_archive(archive),
507
+ "data_path": f"{data_folder}/{_PATHS[name]['test'].format(lang)}",
508
+ "split": "test",
509
+ },
510
+ )
511
+ for lang in languages
512
+ ]
513
+ )
514
+
515
+ def _generate_examples(self, archive, data_path, split=None):
516
+ keys = list(self._info().features.keys())
517
+ src_f = tgt_f = None
518
+ for path, file in archive:
519
+ if self.config.name == "mlqa":
520
+ if path == data_path:
521
+ data = json.load(file)
522
+ for examples in data["data"]:
523
+ for example in examples["paragraphs"]:
524
+ context = example["context"]
525
+ for qa in example["qas"]:
526
+ question = qa["question"]
527
+ id_ = qa["id"]
528
+ answers = qa["answers"]
529
+ answers_start = [answer["answer_start"] for answer in answers]
530
+ answers_text = [answer["text"] for answer in answers]
531
+ yield id_, {
532
+ "context": context,
533
+ "question": question,
534
+ "answers": {"answer_start": answers_start, "text": answers_text},
535
+ }
536
+ elif self.config.name in ["ner", "pos"]:
537
+ if path == data_path:
538
+ words = []
539
+ result = []
540
+ idx = -1
541
+ for line in file:
542
+ line = line.decode("utf-8")
543
+ if line.strip() == "":
544
+ if len(words) > 0:
545
+ out_dict = {keys[0]: words, keys[1]: result}
546
+ words = []
547
+ result = []
548
+ idx += 1
549
+ yield idx, out_dict
550
+ else:
551
+ splits = line.strip().split(" ")
552
+ words.append(splits[0])
553
+ result.append(splits[1])
554
+ elif self.config.name in ["ntg", "qg"]:
555
+ if path == data_path + ".src." + split:
556
+ src_f = [line.decode("utf-8") for line in file]
557
+ elif path == data_path + ".tgt." + split:
558
+ tgt_f = [line.decode("utf-8") for line in file]
559
+ if src_f and tgt_f:
560
+ for idx, (src_line, tgt_line) in enumerate(zip(src_f, tgt_f)):
561
+ yield idx, {keys[0]: src_line.strip(), keys[1]: tgt_line.strip()}
562
+ else:
563
+ _process_dict = {
564
+ "paws-x": {"0": "different", "1": "same"},
565
+ "xnli": {"contradictory": "contradiction"},
566
+ "qam": {"0": "False", "1": "True"},
567
+ "wpr": {"0": "Bad", "1": "Fair", "2": "Good", "3": "Excellent", "4": "Perfect"},
568
+ }
569
+
570
+ def _process(value):
571
+ if self.config.name in _process_dict and value in _process_dict[self.config.name]:
572
+ return _process_dict[self.config.name][value]
573
+ return value
574
+
575
+ if path == data_path:
576
+ for idx, line in enumerate(file):
577
+ line = line.decode("utf-8")
578
+ if data_path.split(".")[-1] == "tsv" and idx == 0:
579
+ continue
580
+ items = line.strip().split("\t")
581
+ yield idx, {
582
+ key: _process(value)
583
+ for key, value in zip(keys, items[1:] if self.config.name == "paws-x" else items)
584
+ }
585
+