system HF staff commited on
Commit
8c32667
0 Parent(s):

Update files from the datasets library (from 1.2.0)

Browse files

Release notes: https://github.com/huggingface/datasets/releases/tag/1.2.0

.gitattributes ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bin.* filter=lfs diff=lfs merge=lfs -text
5
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.model filter=lfs diff=lfs merge=lfs -text
12
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
13
+ *.onnx filter=lfs diff=lfs merge=lfs -text
14
+ *.ot filter=lfs diff=lfs merge=lfs -text
15
+ *.parquet filter=lfs diff=lfs merge=lfs -text
16
+ *.pb filter=lfs diff=lfs merge=lfs -text
17
+ *.pt filter=lfs diff=lfs merge=lfs -text
18
+ *.pth filter=lfs diff=lfs merge=lfs -text
19
+ *.rar filter=lfs diff=lfs merge=lfs -text
20
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
21
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
22
+ *.tflite filter=lfs diff=lfs merge=lfs -text
23
+ *.tgz filter=lfs diff=lfs merge=lfs -text
24
+ *.xz filter=lfs diff=lfs merge=lfs -text
25
+ *.zip filter=lfs diff=lfs merge=lfs -text
26
+ *.zstandard filter=lfs diff=lfs merge=lfs -text
27
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,233 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ annotations_creators:
3
+ - crowdsourced
4
+ - machine-generated
5
+ language_creators:
6
+ - crowdsourced
7
+ languages:
8
+ - fr
9
+ licenses:
10
+ - unknown
11
+ multilinguality:
12
+ - monolingual
13
+ size_categories:
14
+ - 10K<n<100K
15
+ source_datasets:
16
+ - original
17
+ task_categories:
18
+ - text-classification
19
+ task_ids:
20
+ PAWS-X:
21
+ - intent-classification
22
+ XNLI:
23
+ - semantic-similarity-classification
24
+ CLS:
25
+ - sentiment-classification
26
+ WSD-V:
27
+ - text-classification-other-Word Sense Disambiguation for Verbs
28
+ ---
29
+
30
+ # Dataset Card for FLUE
31
+
32
+ ## Table of Contents
33
+ - [Dataset Description](#dataset-description)
34
+ - [Dataset Summary](#dataset-summary)
35
+ - [Supported Tasks](#supported-tasks-and-leaderboards)
36
+ - [Languages](#languages)
37
+ - [Dataset Structure](#dataset-structure)
38
+ - [Text Classification (CLS)](#text-classification-(cls))
39
+ - [Data Instances](#data-instances)
40
+ - [Data Fields](#data-instances)
41
+ - [Data Splits](#data-instances)
42
+ - [Paraphrasing (PAWS-X)](#paraphrasing-(paws-x))
43
+ - [Data Instances](#data-instances)
44
+ - [Data Fields](#data-instances)
45
+ - [Data Splits](#data-instances)
46
+ - [Natural Language Inference (XNLI)](#natural-language-inference-(xnli))
47
+ - [Data Instances](#data-instances)
48
+ - [Data Fields](#data-instances)
49
+ - [Data Splits](#data-instances)
50
+ - [Word Sense Disambiguation for Verbs (WSD-V)](#word-sense-disambiguation-for-verbs-(wsd-v))
51
+ - [Data Instances](#data-instances)
52
+ - [Data Fields](#data-instances)
53
+ - [Data Splits](#data-instances)
54
+ - [Dataset Creation](#dataset-creation)
55
+ - [Curation Rationale](#curation-rationale)
56
+ - [Source Data](#source-data)
57
+ - [Annotations](#annotations)
58
+ - [Personal and Sensitive Information](#personal-and-sensitive-information)
59
+ - [Considerations for Using the Data](#considerations-for-using-the-data)
60
+ - [Social Impact of Dataset](#social-impact-of-dataset)
61
+ - [Discussion of Biases](#discussion-of-biases)
62
+ - [Other Known Limitations](#other-known-limitations)
63
+ - [Additional Information](#additional-information)
64
+ - [Dataset Curators](#dataset-curators)
65
+ - [Licensing Information](#licensing-information)
66
+ - [Citation Information](#citation-information)
67
+
68
+ ## Dataset Description
69
+
70
+ - **Homepage:** [homepage](https://github.com/getalp/Flaubert/tree/master/flue)
71
+ - **Repository:**[github](https://github.com/getalp/Flaubert/tree/master/flue)
72
+ - **Paper:**[paper](https://arxiv.org/abs/1912.05372)
73
+ - **Leaderboard:**[leaderboard](https://github.com/getalp/Flaubert/tree/master/flue/leaderboard)
74
+ - **Point of Contact:**[Hang Le](thi-phuong-hang.le@univ-grenoble-alpes.fr)
75
+
76
+ ### Dataset Summary
77
+
78
+ FLUE is an evaluation setup for French NLP systems similar to the popular GLUE benchmark. The goal is to enable further reproducible experiments in the future and to share models and progress on the French language. The tasks and data are obtained from existing works, please refer to our Flaubert paper for a complete list of references.
79
+
80
+ ### Supported Tasks and Leaderboards
81
+
82
+ The supported tasks are: Text Classification, Paraphrasing, Natural Language Inference, Constituency Parsing, Dependency Parsing, Verb Sense Disambiguation and Noun Sense Disambiguation
83
+
84
+ ### Languages
85
+
86
+ The datasets are all in French.
87
+
88
+ ## Dataset Structure
89
+
90
+ ### Text Classification (CLS)
91
+
92
+ This is a binary classification task. It consists in classifying Amazon reviews for three product categories: books, DVD, and music. Each sample contains a review text and the associated rating from 1 to 5 stars. Reviews rated above 3 is labeled as positive, and those rated less than 3 is labeled as negative.
93
+
94
+ #### Data Instances
95
+
96
+ An instance looks like:
97
+
98
+ ```
99
+ {
100
+ 'idx': 1,
101
+ 'label': 0,
102
+ 'text': 'Bilan plus que mitigé pour cet album fourre-tout qui mêle quelques bonnes idées (les parodies d\'oeuvres d\'art) et des scènetes qui ne font que faire écho paresseusement aux précédents albums. Uderzo n\'a pas pris de risque pour cet album, mais, au vu des précédents, on se dit que c\'est peut-être un moindre mal ... L\'album semble n\'avoir été fait que pour permettre à Uderzo de rappeler avec une insistance suspecte qu\'il est bien l\'un des créateurs d\'Astérix (comme lorsqu\'il se met en scène lui même dans la BD) et de traiter ses critiques d\' "imbéciles" dans une préface un rien aigrie signée "Astérix". Préface dans laquelle Uderzo feint de croire que ce qu\'on lui reproche est d\'avoir fait survivre Asterix à la disparition de Goscinny (reproche naturellement démenti par la fidélité des lecteurs - démonstration imparable !). On aurait tant aimé qu\'Uderzo accepte de s\'entourer d\'un scénariste compétent et respectueux de l\'esprit Goscinnien (cela doit se trouver !) et nous propose des albums plus ambitieux ...'
103
+ }
104
+ ```
105
+
106
+ #### Data Fields
107
+
108
+ The dataset is composed of two fields:
109
+ - **text**: the field that represents the text to classify.
110
+ - **label**: the sentiment represented by the text, here **positive** or **negative**.
111
+
112
+ #### Data Splits
113
+
114
+ The train and test sets are balanced, including around 1k positive and 1k negative reviews for a total of 2k reviews in each dataset. We take the French portion to create the binary text classification task in FLUE and report the accuracy on the test set.
115
+
116
+ ### Paraphrasing (PAWS-X)
117
+
118
+ The task consists in identifying whether the two sentences in a pair are semantically equivalent or not.
119
+
120
+ #### Data Instances
121
+
122
+ An instance looks like:
123
+
124
+ ```
125
+ {
126
+ 'idx': 1,
127
+ 'label': 0,
128
+ 'sentence1': "À Paris, en octobre 1560, il rencontra secrètement l'ambassadeur d'Angleterre, Nicolas Throckmorton, lui demandant un passeport pour retourner en Angleterre en passant par l'Écosse.",
129
+ 'sentence2': "En octobre 1560, il rencontra secrètement l'ambassadeur d'Angleterre, Nicolas Throckmorton, à Paris, et lui demanda un passeport pour retourner en Écosse par l'Angleterre."
130
+ }
131
+ ```
132
+
133
+ #### Data Fields
134
+
135
+ The dataset is compososed of three fields:
136
+ - **sentence1**: The first sentence of an example
137
+ - **sentence2**: The second sentence of an example
138
+ - **lalel**: **0** if the two sentences are not paraphrasing each other, **1** otherwise.
139
+
140
+ #### Data Splits
141
+
142
+ The train set includes 49.4k examples, the dev and test sets each comprises nearly 2k examples. We take the related datasets for French to perform the paraphrasing task and report the accuracy on the test set.
143
+
144
+ ### Natural Language Inference (XNLI)
145
+
146
+ The Natural Language Inference (NLI) task, also known as recognizing textual entailment (RTE), is to determine whether a premise entails, contradicts or neither entails nor contradicts a hypothesis. We take the French part of the XNLI corpus to form the development and test sets for the NLI task in FLUE.
147
+
148
+ #### Data Instances
149
+
150
+ An instance looks like:
151
+
152
+ ```
153
+ {
154
+ 'idx': 1,
155
+ 'label': 2,
156
+ 'hypo': 'Le produit et la géographie sont ce qui fait travailler la crème de la crème .',
157
+ 'premise': "L' écrémage conceptuel de la crème a deux dimensions fondamentales : le produit et la géographie ."
158
+ }
159
+ ```
160
+
161
+ #### Data Fields
162
+
163
+ The dataset is composed of three fields:
164
+ - **premise**: Premise sentence.
165
+ - **hypo**: Hypothesis sentence.
166
+ - **label**: **contradiction** if the two sentences are contradictory, **entailment** if the two sentences entails, **neutral** if they neither entails or contradict each other.
167
+
168
+ #### Data Splits
169
+
170
+ The train set includes 392.7k examples, the dev and test sets comprises 2.5k and 5k examples respectively. We take the related datasets for French to perform the NLI task and report the accuracy on the test set.
171
+
172
+ ### Word Sense Disambiguation for Verbs (WSD-V)
173
+
174
+ The FrenchSemEval (FSE) dataset aims to evaluate the Word Sense Disambiguation for Verbs task for the French language. Extracted from Wiktionary.
175
+
176
+ #### Data Instances
177
+
178
+ An instance looks like:
179
+
180
+ ```
181
+ {
182
+ 'idx': 'd000.s001',
183
+ 'sentence': ['"', 'Ce', 'ne', 'fut', 'pas', 'une', 'révolution', '2.0', ',', 'ce', 'fut', 'une', 'révolution', 'de', 'rue', '.'],
184
+ 'fine_pos_tags': [27, 26, 18, 13, 18, 0, 6, 22, 27, 26, 13, 0, 6, 4, 6, 27],
185
+ 'lemmas': ['"', 'ce', 'ne', 'être', 'pas', 'un', 'révolution', '2.0', ',', 'ce', 'être', 'un', 'révolution', 'de', 'rue', '.'],
186
+ 'pos_tags': [13, 11, 14, 0, 14, 9, 15, 4, 13, 11, 0, 9, 15, 7, 15, 13],
187
+ 'disambiguate_labels': ['__ws_1_2.0__adj__1'],
188
+ 'disambiguate_tokens_ids': [7],
189
+ }
190
+ ```
191
+
192
+ #### Data Fields
193
+
194
+ The dataset is composed of six fields:
195
+ - **sentence**: The sentence to process split in tokens.
196
+ - **pos_tags**: The corresponding POS tags for each tokens.
197
+ - **lemmas**: The corresponding lemma for each tokens.
198
+ - **fine_pos_tags**: Fined (more specific) POS tags for each tokens.
199
+ - **disambiguate_tokens_ids**: The ID of the token in the sentence to disambiguate.
200
+ - **disambiguate_labels**: The label in the form of **sentenceID __ws_sentence-number_token__pos__number-of-time-the-token-appeared-across-all-the-sentences** (i.e. **d000.s404.t000 __ws_2_agir__verb__1**).
201
+
202
+ #### Data Splits
203
+
204
+ The train set includes 269821 examples, the test set includes 3121 examples.
205
+
206
+ ## Considerations for Using the Data
207
+
208
+ ### Social Impact of Dataset
209
+
210
+ The goal is to enable further reproducible experiments in the future and to share models and progress on the French language.
211
+
212
+ ## Additional Information
213
+
214
+ ### Licensing Information
215
+
216
+ The licenses are:
217
+ - The licensing status of the data, especially the news source text, is unknown for CLS
218
+ - *The dataset may be freely used for any purpose, although acknowledgement of Google LLC ("Google") as the data source would be appreciated. The dataset is provided "AS IS" without any warranty, express or implied. Google disclaims all liability for any damages, direct or indirect, resulting from the use of the dataset.* for PAWS-X
219
+ - CC BY-NC 4.0 for XNLI
220
+ - The licensing status of the data, especially the news source text, is unknown for Verb Sense Disambiguation
221
+
222
+ ### Citation Information
223
+
224
+ ```
225
+ @misc{le2019flaubert,
226
+ title={FlauBERT: Unsupervised Language Model Pre-training for French},
227
+ author={Hang Le and Loïc Vial and Jibril Frej and Vincent Segonne and Maximin Coavoux and Benjamin Lecouteux and Alexandre Allauzen and Benoît Crabbé and Laurent Besacier and Didier Schwab},
228
+ year={2019},
229
+ eprint={1912.05372},
230
+ archivePrefix={arXiv},
231
+ primaryClass={cs.CL}
232
+ }
233
+ ```
dataset_infos.json ADDED
@@ -0,0 +1 @@
 
1
+ {"CLS": {"description": "FLUE is an evaluation setup for French NLP systems similar to the popular GLUE benchmark. The goal is to enable further reproducible experiments in the future and to share models and progress on the French language.\n", "citation": "\n@misc{le2019flaubert,\n title={FlauBERT: Unsupervised Language Model Pre-training for French},\n author={Hang Le and Lo\u00efc Vial and Jibril Frej and Vincent Segonne and Maximin Coavoux and Benjamin Lecouteux and Alexandre Allauzen and Beno\u00eet Crabb\u00e9 and Laurent Besacier and Didier Schwab},\n year={2019},\n eprint={1912.05372},\n archivePrefix={arXiv},\n primaryClass={cs.CL}\n}\n", "homepage": "", "license": "", "features": {"text": {"dtype": "string", "id": null, "_type": "Value"}, "label": {"num_classes": 2, "names": ["negative", "positive"], "names_file": null, "id": null, "_type": "ClassLabel"}, "idx": {"dtype": "int32", "id": null, "_type": "Value"}}, "post_processed": null, "supervised_keys": null, "builder_name": "flue", "config_name": "CLS", "version": {"version_str": "1.0.0", "description": "", "major": 1, "minor": 0, "patch": 0}, "splits": {"train": {"name": "train", "num_bytes": 3853279, "num_examples": 5997, "dataset_name": "flue"}, "test": {"name": "test", "num_bytes": 3852344, "num_examples": 5999, "dataset_name": "flue"}}, "download_checksums": {"https://zenodo.org/record/3251672/files/cls-acl10-unprocessed.tar.gz": {"num_bytes": 314687066, "checksum": "51504dea54dfad525ec5373db0606a263393feb9182ffc50c276682936e14ee5"}}, "download_size": 314687066, "post_processing_size": null, "dataset_size": 7705623, "size_in_bytes": 322392689}, "PAWS-X": {"description": "FLUE is an evaluation setup for French NLP systems similar to the popular GLUE benchmark. The goal is to enable further reproducible experiments in the future and to share models and progress on the French language.\n", "citation": "@InProceedings{pawsx2019emnlp,\n title = {{PAWS-X: A Cross-lingual Adversarial Dataset for Paraphrase Identification}},\n author = {Yang, Yinfei and Zhang, Yuan and Tar, Chris and Baldridge, Jason},\n booktitle = {Proc. of EMNLP},\n year = {2019}\n}\n@misc{le2019flaubert,\n title={FlauBERT: Unsupervised Language Model Pre-training for French},\n author={Hang Le and Lo\u00efc Vial and Jibril Frej and Vincent Segonne and Maximin Coavoux and Benjamin Lecouteux and Alexandre Allauzen and Beno\u00eet Crabb\u00e9 and Laurent Besacier and Didier Schwab},\n year={2019},\n eprint={1912.05372},\n archivePrefix={arXiv},\n primaryClass={cs.CL}\n}\n", "homepage": "https://github.com/google-research-datasets/paws/tree/master/pawsx", "license": "", "features": {"sentence1": {"dtype": "string", "id": null, "_type": "Value"}, "sentence2": {"dtype": "string", "id": null, "_type": "Value"}, "label": {"dtype": "int32", "id": null, "_type": "Value"}, "idx": {"dtype": "int32", "id": null, "_type": "Value"}}, "post_processed": null, "supervised_keys": null, "builder_name": "flue", "config_name": "PAWS-X", "version": {"version_str": "1.0.0", "description": "", "major": 1, "minor": 0, "patch": 0}, "splits": {"validation": {"name": "validation", "num_bytes": 522013, "num_examples": 1988, "dataset_name": "flue"}, "test": {"name": "test", "num_bytes": 526953, "num_examples": 2000, "dataset_name": "flue"}, "train": {"name": "train", "num_bytes": 13096677, "num_examples": 49399, "dataset_name": "flue"}}, "download_checksums": {"https://storage.googleapis.com/paws/pawsx/x-final.tar.gz": {"num_bytes": 30282057, "checksum": "4146db499101d66e68ae4c8ed3cf9dadecd625f44b7d8cf3d4a0fe93afc4fd9f"}}, "download_size": 30282057, "post_processing_size": null, "dataset_size": 14145643, "size_in_bytes": 44427700}, "XNLI": {"description": "FLUE is an evaluation setup for French NLP systems similar to the popular GLUE benchmark. The goal is to enable further reproducible experiments in the future and to share models and progress on the French language.\n", "citation": "@InProceedings{conneau2018xnli,\nauthor = {Conneau, Alexis\n and Rinott, Ruty\n and Lample, Guillaume\n and Williams, Adina\n and Bowman, Samuel R.\n and Schwenk, Holger\n and Stoyanov, Veselin},\ntitle = {XNLI: Evaluating Cross-lingual Sentence Representations},\nbooktitle = {Proceedings of the 2018 Conference on Empirical Methods\n in Natural Language Processing},\nyear = {2018},\npublisher = {Association for Computational Linguistics},\nlocation = {Brussels, Belgium},\n}\n@misc{le2019flaubert,\n title={FlauBERT: Unsupervised Language Model Pre-training for French},\n author={Hang Le and Lo\u00efc Vial and Jibril Frej and Vincent Segonne and Maximin Coavoux and Benjamin Lecouteux and Alexandre Allauzen and Beno\u00eet Crabb\u00e9 and Laurent Besacier and Didier Schwab},\n year={2019},\n eprint={1912.05372},\n archivePrefix={arXiv},\n primaryClass={cs.CL}\n}\n", "homepage": "https://www.nyu.edu/projects/bowman/xnli/", "license": "", "features": {"premise": {"dtype": "string", "id": null, "_type": "Value"}, "hypo": {"dtype": "string", "id": null, "_type": "Value"}, "label": {"num_classes": 3, "names": ["contradiction", "entailment", "neutral"], "names_file": null, "id": null, "_type": "ClassLabel"}, "idx": {"dtype": "int32", "id": null, "_type": "Value"}}, "post_processed": null, "supervised_keys": null, "builder_name": "flue", "config_name": "XNLI", "version": {"version_str": "1.0.0", "description": "", "major": 1, "minor": 0, "patch": 0}, "splits": {"validation": {"name": "validation", "num_bytes": 520022, "num_examples": 2490, "dataset_name": "flue"}, "test": {"name": "test", "num_bytes": 1048999, "num_examples": 5010, "dataset_name": "flue"}, "train": {"name": "train", "num_bytes": 87373154, "num_examples": 392702, "dataset_name": "flue"}}, "download_checksums": {"https://dl.fbaipublicfiles.com/XNLI/XNLI-MT-1.0.zip": {"num_bytes": 466098360, "checksum": "f732517ba2fb1d550e9f3c2aabaef6017c91ee2dcec90e878f138764d224db05"}, "https://dl.fbaipublicfiles.com/XNLI/XNLI-1.0.zip": {"num_bytes": 17865352, "checksum": "4ba1d5e1afdb7161f0f23c66dc787802ccfa8a25a3ddd3b165a35e50df346ab1"}}, "download_size": 483963712, "post_processing_size": null, "dataset_size": 88942175, "size_in_bytes": 572905887}, "WSD-V": {"description": "FLUE is an evaluation setup for French NLP systems similar to the popular GLUE benchmark. The goal is to enable further reproducible experiments in the future and to share models and progress on the French language.\n", "citation": "\n@misc{le2019flaubert,\n title={FlauBERT: Unsupervised Language Model Pre-training for French},\n author={Hang Le and Lo\u00efc Vial and Jibril Frej and Vincent Segonne and Maximin Coavoux and Benjamin Lecouteux and Alexandre Allauzen and Beno\u00eet Crabb\u00e9 and Laurent Besacier and Didier Schwab},\n year={2019},\n eprint={1912.05372},\n archivePrefix={arXiv},\n primaryClass={cs.CL}\n}\n", "homepage": "http://www.llf.cnrs.fr/dataset/fse/", "license": "", "features": {"sentence": {"feature": {"dtype": "string", "id": null, "_type": "Value"}, "length": -1, "id": null, "_type": "Sequence"}, "pos_tags": {"feature": {"dtype": "string", "id": null, "_type": "Value"}, "length": -1, "id": null, "_type": "Sequence"}, "lemmas": {"feature": {"dtype": "string", "id": null, "_type": "Value"}, "length": -1, "id": null, "_type": "Sequence"}, "fine_pos_tags": {"feature": {"dtype": "string", "id": null, "_type": "Value"}, "length": -1, "id": null, "_type": "Sequence"}, "disambiguate_tokens_ids": {"feature": {"dtype": "int32", "id": null, "_type": "Value"}, "length": -1, "id": null, "_type": "Sequence"}, "disambiguate_labels": {"feature": {"dtype": "string", "id": null, "_type": "Value"}, "length": -1, "id": null, "_type": "Sequence"}, "idx": {"dtype": "string", "id": null, "_type": "Value"}}, "post_processed": null, "supervised_keys": null, "builder_name": "flue", "config_name": "WSD-V", "version": {"version_str": "1.0.0", "description": "", "major": 1, "minor": 0, "patch": 0}, "splits": {"train": {"name": "train", "num_bytes": 206869215, "num_examples": 269821, "dataset_name": "flue"}, "test": {"name": "test", "num_bytes": 2722232, "num_examples": 3121, "dataset_name": "flue"}}, "download_checksums": {"http://www.llf.cnrs.fr/dataset/fse/FSE-1.1-10_12_19.tar.gz": {"num_bytes": 38303600, "checksum": "54200bc7c697029f5669df1226edfe6e544af2611c06604c74e33647a0ec7815"}}, "download_size": 38303600, "post_processing_size": null, "dataset_size": 209591447, "size_in_bytes": 247895047}}
dummy/CLS/1.0.0/dummy_data.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7525226095b85859b6cf9a822ac5e120387fe806d5084db38318b3b1c0101117
3
+ size 20292
dummy/PAWS-X/1.0.0/dummy_data.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:410319c7b9cb2002e43c5106e532b9baf0c9c4cbe7b3bddac5f6c5c7ce1ff8ad
3
+ size 14168
dummy/WSD-V/1.0.0/dummy_data.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a88fb2e49dc91e98d677e83eb3980a1f17bb4990deffd70828204fcb2684417f
3
+ size 2218
dummy/XNLI/1.0.0/dummy_data.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b283a709ae7ccd66d4ea25e92cf09afbecb6af9267e1d500ef846e4997503f14
3
+ size 17620
flue.py ADDED
@@ -0,0 +1,645 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 French Language Understanding Evaluation (FLUE) benchmark."""
18
+
19
+ from __future__ import absolute_import, division, print_function
20
+
21
+ import csv
22
+ import os
23
+ import re
24
+ import textwrap
25
+ import unicodedata
26
+ from shutil import copyfile
27
+
28
+ import six
29
+ from lxml import etree
30
+
31
+ import datasets
32
+
33
+
34
+ _FLUE_CITATION = """\
35
+ @misc{le2019flaubert,
36
+ title={FlauBERT: Unsupervised Language Model Pre-training for French},
37
+ author={Hang Le and Loïc Vial and Jibril Frej and Vincent Segonne and Maximin Coavoux and Benjamin Lecouteux and Alexandre Allauzen and Benoît Crabbé and Laurent Besacier and Didier Schwab},
38
+ year={2019},
39
+ eprint={1912.05372},
40
+ archivePrefix={arXiv},
41
+ primaryClass={cs.CL}
42
+ }
43
+ """
44
+
45
+ _FLUE_DESCRIPTION = """\
46
+ FLUE is an evaluation setup for French NLP systems similar to the popular GLUE benchmark. The goal is to enable further reproducible experiments in the future and to share models and progress on the French language.
47
+ """
48
+
49
+
50
+ class FlueConfig(datasets.BuilderConfig):
51
+ """BuilderConfig for FLUE."""
52
+
53
+ def __init__(
54
+ self,
55
+ text_features,
56
+ label_column,
57
+ data_url,
58
+ data_dir,
59
+ citation,
60
+ url,
61
+ label_classes=None,
62
+ process_label=lambda x: x,
63
+ **kwargs,
64
+ ):
65
+ """BuilderConfig for FLUE.
66
+
67
+ Args:
68
+ text_features: `dict[string, string]`, map from the name of the feature
69
+ dict for each text field to the name of the column in the tsv file
70
+ label_column: `string`, name of the column in the tsv file corresponding
71
+ to the label
72
+ data_url: `string`, url to download the zip file from
73
+ data_dir: `string`, the path to the folder containing the tsv files in the
74
+ downloaded zip
75
+ citation: `string`, citation for the data set
76
+ url: `string`, url for information about the data set
77
+ label_classes: `list[string]`, the list of classes if the label is
78
+ categorical. If not provided, then the label will be of type
79
+ `datasets.Value('float32')`.
80
+ process_label: `Function[string, any]`, function taking in the raw value
81
+ of the label and processing it to the form required by the label feature
82
+ **kwargs: keyword arguments forwarded to super.
83
+ """
84
+ super(FlueConfig, self).__init__(version=datasets.Version("1.0.0", ""), **kwargs)
85
+ self.text_features = text_features
86
+ self.label_column = label_column
87
+ self.label_classes = label_classes
88
+ self.data_url = data_url
89
+ self.data_dir = data_dir
90
+ self.citation = citation
91
+ self.url = url
92
+ self.process_label = process_label
93
+
94
+
95
+ class Flue(datasets.GeneratorBasedBuilder):
96
+ """The French Language Understanding Evaluation (FLUE) benchmark."""
97
+
98
+ BUILDER_CONFIGS = [
99
+ FlueConfig(
100
+ name="CLS",
101
+ description=textwrap.dedent(
102
+ """\
103
+ This is a binary classification task. It consists in classifying Amazon reviews for three product categories:
104
+ books, DVD, and music. Each sample contains a review text and the associated rating from 1 to 5 stars. Reviews
105
+ rated above 3 is labeled as positive, and those rated less than 3 is labeled as negative. The train and test sets
106
+ are balanced, including around 1k positive and 1k negative reviews for a total of 2k reviews in each dataset. Only
107
+ the French portion is taken to create the binary text classification task in FLUE and report the accuracy on the test set."""
108
+ ),
109
+ text_features={"text": "text"},
110
+ label_classes=["negative", "positive"],
111
+ label_column="label",
112
+ data_url="https://zenodo.org/record/3251672/files/cls-acl10-unprocessed.tar.gz",
113
+ data_dir="",
114
+ url="",
115
+ citation="",
116
+ ),
117
+ FlueConfig(
118
+ name="PAWS-X",
119
+ description=textwrap.dedent(
120
+ """\
121
+ This dataset contains 23,659 human translated PAWS evaluation pairs and 296,406 machine translated training
122
+ pairs in six typologically distinct languages: French, Spanish, German, Chinese, Japanese, and Korean. All
123
+ translated pairs are sourced from examples in PAWS-Wiki. Only the related dataset for French is taken to perform
124
+ the paraphrasing task and report the accuracy on the test set."""
125
+ ),
126
+ text_features={"sentence1": "sentence1", "sentence2": "sentence2"},
127
+ data_url="https://storage.googleapis.com/paws/pawsx/x-final.tar.gz",
128
+ label_column="label",
129
+ data_dir="",
130
+ url="https://github.com/google-research-datasets/paws/tree/master/pawsx",
131
+ citation=textwrap.dedent(
132
+ """\
133
+ @InProceedings{pawsx2019emnlp,
134
+ title = {{PAWS-X: A Cross-lingual Adversarial Dataset for Paraphrase Identification}},
135
+ author = {Yang, Yinfei and Zhang, Yuan and Tar, Chris and Baldridge, Jason},
136
+ booktitle = {Proc. of EMNLP},
137
+ year = {2019}
138
+ }"""
139
+ ),
140
+ ),
141
+ FlueConfig(
142
+ name="XNLI",
143
+ description=textwrap.dedent(
144
+ """
145
+ The Cross-lingual Natural Language Inference (XNLI) corpus is a crowd-sourced collection of 5,000 test and
146
+ 2,500 dev pairs for the MultiNLI corpus. The pairs are annotated with textual entailment and translated into
147
+ 14 languages: French, Spanish, German, Greek, Bulgarian, Russian, Turkish, Arabic, Vietnamese, Thai, Chinese,
148
+ Hindi, Swahili and Urdu. This results in 112.5k annotated pairs. Each premise can be associated with the
149
+ corresponding hypothesis in the 15 languages, summing up to more than 1.5M combinations. The corpus is made to
150
+ evaluate how to perform inference in any language (including low-resources ones like Swahili or Urdu) when only
151
+ English NLI data is available at training time. One solution is cross-lingual sentence encoding, for which XNLI
152
+ is an evaluation benchmark. Only the related datasets for French is taken to perform the NLI task and report
153
+ the accuracy on the test set."""
154
+ ),
155
+ text_features={"premise": "premise", "hypo": "hypo"},
156
+ data_url={
157
+ "train": "https://dl.fbaipublicfiles.com/XNLI/XNLI-MT-1.0.zip",
158
+ "dev_test": "https://dl.fbaipublicfiles.com/XNLI/XNLI-1.0.zip",
159
+ },
160
+ label_classes=["contradiction", "entailment", "neutral"],
161
+ label_column="label",
162
+ data_dir="",
163
+ url="https://www.nyu.edu/projects/bowman/xnli/",
164
+ citation=textwrap.dedent(
165
+ """\
166
+ @InProceedings{conneau2018xnli,
167
+ author = {Conneau, Alexis
168
+ and Rinott, Ruty
169
+ and Lample, Guillaume
170
+ and Williams, Adina
171
+ and Bowman, Samuel R.
172
+ and Schwenk, Holger
173
+ and Stoyanov, Veselin},
174
+ title = {XNLI: Evaluating Cross-lingual Sentence Representations},
175
+ booktitle = {Proceedings of the 2018 Conference on Empirical Methods
176
+ in Natural Language Processing},
177
+ year = {2018},
178
+ publisher = {Association for Computational Linguistics},
179
+ location = {Brussels, Belgium},
180
+ }"""
181
+ ),
182
+ ),
183
+ FlueConfig(
184
+ name="WSD-V",
185
+ description=textwrap.dedent(
186
+ """
187
+ French Verb Sense Disambiguation task."""
188
+ ),
189
+ text_features={
190
+ "sentence": "sentence",
191
+ "pos_tags": "pos_tags",
192
+ "lemmas": "lemmas",
193
+ "fine_pos_tags": "fine_pos_tags",
194
+ },
195
+ data_url="http://www.llf.cnrs.fr/dataset/fse/FSE-1.1-10_12_19.tar.gz",
196
+ label_classes=["disambiguate_tokens_ids", "disambiguate_labels"],
197
+ label_column="disambiguate_labels",
198
+ data_dir="FSE-1.1-191210",
199
+ url="http://www.llf.cnrs.fr/dataset/fse/",
200
+ citation="",
201
+ ),
202
+ ]
203
+
204
+ def _info(self):
205
+ if self.config.name == "CLS" or self.config.name == "XNLI":
206
+ features = {
207
+ text_feature: datasets.Value("string") for text_feature in six.iterkeys(self.config.text_features)
208
+ }
209
+ features[self.config.label_column] = datasets.features.ClassLabel(names=self.config.label_classes)
210
+ features["idx"] = datasets.Value("int32")
211
+ elif self.config.name == "WSD-V":
212
+ features = {
213
+ text_feature: datasets.Sequence(datasets.Value("string"))
214
+ for text_feature in six.iterkeys(self.config.text_features)
215
+ }
216
+ features["fine_pos_tags"] = datasets.Sequence(
217
+ datasets.features.ClassLabel(
218
+ names=[
219
+ "DET",
220
+ "P+D",
221
+ "CC",
222
+ "VS",
223
+ "P",
224
+ "CS",
225
+ "NC",
226
+ "NPP",
227
+ "ADJWH",
228
+ "VINF",
229
+ "VPP",
230
+ "ADVWH",
231
+ "PRO",
232
+ "V",
233
+ "CLO",
234
+ "PREF",
235
+ "VPR",
236
+ "PROREL",
237
+ "ADV",
238
+ "PROWH",
239
+ "N",
240
+ "DETWH",
241
+ "ADJ",
242
+ "P+PRO",
243
+ "ET",
244
+ "VIMP",
245
+ "CLS",
246
+ "PONCT",
247
+ "I",
248
+ "CLR",
249
+ ]
250
+ )
251
+ )
252
+ features["pos_tags"] = datasets.Sequence(
253
+ datasets.features.ClassLabel(
254
+ names=[
255
+ "V",
256
+ "PREF",
257
+ "P+D",
258
+ "I",
259
+ "A",
260
+ "P+PRO",
261
+ "PRO",
262
+ "P",
263
+ "anonyme",
264
+ "D",
265
+ "C",
266
+ "CL",
267
+ "ET",
268
+ "PONCT",
269
+ "ADV",
270
+ "N",
271
+ ]
272
+ )
273
+ )
274
+ features["disambiguate_tokens_ids"] = datasets.Sequence(datasets.Value("int32"))
275
+ features["disambiguate_labels"] = datasets.Sequence(datasets.Value("string"))
276
+ features["idx"] = datasets.Value("string")
277
+ else:
278
+ features = {
279
+ text_feature: datasets.Value("string") for text_feature in six.iterkeys(self.config.text_features)
280
+ }
281
+ features[self.config.label_column] = datasets.Value("int32")
282
+ features["idx"] = datasets.Value("int32")
283
+ return datasets.DatasetInfo(
284
+ description=_FLUE_DESCRIPTION,
285
+ features=datasets.Features(features),
286
+ homepage=self.config.url,
287
+ citation=self.config.citation + "\n" + _FLUE_CITATION,
288
+ )
289
+
290
+ def _split_generators(self, dl_manager):
291
+ if self.config.name == "CLS":
292
+ data_folder = dl_manager.download_and_extract(self.config.data_url)
293
+
294
+ return [
295
+ datasets.SplitGenerator(
296
+ name=datasets.Split.TRAIN,
297
+ gen_kwargs={
298
+ "data_file": os.path.join(data_folder, "cls-acl10-unprocessed", "fr"),
299
+ "split": "train",
300
+ },
301
+ ),
302
+ datasets.SplitGenerator(
303
+ name=datasets.Split.TEST,
304
+ gen_kwargs={
305
+ "data_file": os.path.join(data_folder, "cls-acl10-unprocessed", "fr"),
306
+ "split": "test",
307
+ },
308
+ ),
309
+ ]
310
+ elif self.config.name == "PAWS-X":
311
+ data_folder = dl_manager.download_and_extract(self.config.data_url)
312
+
313
+ return [
314
+ datasets.SplitGenerator(
315
+ name=datasets.Split.VALIDATION,
316
+ gen_kwargs={
317
+ "data_file": os.path.join(data_folder, "x-final", "fr", "dev_2k.tsv"),
318
+ "split": "",
319
+ },
320
+ ),
321
+ datasets.SplitGenerator(
322
+ name=datasets.Split.TEST,
323
+ gen_kwargs={
324
+ "data_file": os.path.join(data_folder, "x-final", "fr", "test_2k.tsv"),
325
+ "split": "",
326
+ },
327
+ ),
328
+ datasets.SplitGenerator(
329
+ name=datasets.Split.TRAIN,
330
+ gen_kwargs={
331
+ "data_file": os.path.join(data_folder, "x-final", "fr", "translated_train.tsv"),
332
+ "split": "",
333
+ },
334
+ ),
335
+ ]
336
+ elif self.config.name == "XNLI":
337
+ data_folder = dl_manager.download_and_extract(self.config.data_url)
338
+ return [
339
+ datasets.SplitGenerator(
340
+ name=datasets.Split.VALIDATION,
341
+ gen_kwargs={
342
+ "data_file": os.path.join(data_folder["dev_test"], "XNLI-1.0", "xnli.dev.tsv"),
343
+ "split": "dev",
344
+ },
345
+ ),
346
+ datasets.SplitGenerator(
347
+ name=datasets.Split.TEST,
348
+ gen_kwargs={
349
+ "data_file": os.path.join(data_folder["dev_test"], "XNLI-1.0", "xnli.test.tsv"),
350
+ "split": "test",
351
+ },
352
+ ),
353
+ datasets.SplitGenerator(
354
+ name=datasets.Split.TRAIN,
355
+ gen_kwargs={
356
+ "data_file": os.path.join(
357
+ data_folder["train"], "XNLI-MT-1.0", "multinli", "multinli.train.fr.tsv"
358
+ ),
359
+ "split": "train",
360
+ },
361
+ ),
362
+ ]
363
+ elif self.config.name == "WSD-V":
364
+ data_folder = dl_manager.download_and_extract(self.config.data_url)
365
+ self._wsdv_prepare_data(os.path.join(data_folder, self.config.data_dir))
366
+
367
+ return [
368
+ datasets.SplitGenerator(
369
+ name=datasets.Split.TRAIN,
370
+ gen_kwargs={
371
+ "data_file": os.path.join(data_folder, self.config.data_dir),
372
+ "split": "train",
373
+ },
374
+ ),
375
+ datasets.SplitGenerator(
376
+ name=datasets.Split.TEST,
377
+ gen_kwargs={
378
+ "data_file": os.path.join(data_folder, self.config.data_dir),
379
+ "split": "test",
380
+ },
381
+ ),
382
+ ]
383
+
384
+ def _generate_examples(self, data_file, split):
385
+ if self.config.name == "CLS":
386
+ for category in ["books", "dvd", "music"]:
387
+ file_path = os.path.join(data_file, category, split + ".review")
388
+ with open(file_path, "rt", encoding="utf-8") as f:
389
+ next(f)
390
+ id = 0
391
+ text = f.read()
392
+ for id_, line in enumerate(text.split("\n\n")):
393
+ if len(line) > 9:
394
+ id += 1
395
+ review_text, label = self._cls_extractor(line)
396
+ yield id_, {"idx": id, "text": review_text, "label": label}
397
+ elif self.config.name == "PAWS-X":
398
+ with open(data_file, encoding="utf-8") as f:
399
+ data = csv.reader(f, delimiter="\t")
400
+ next(data) # skip header
401
+ id = 0
402
+ for id_, row in enumerate(data):
403
+ if len(row) == 4:
404
+ id += 1
405
+ yield id_, {
406
+ "idx": id,
407
+ "sentence1": self._cleaner(row[1]),
408
+ "sentence2": self._cleaner(row[2]),
409
+ "label": int(row[3].strip()),
410
+ }
411
+ elif self.config.name == "XNLI":
412
+ with open(data_file, encoding="utf-8") as f:
413
+ data = csv.reader(f, delimiter="\t", quoting=csv.QUOTE_NONE)
414
+ next(data)
415
+ id = 0
416
+ for id_, row in enumerate(data):
417
+ if split == "train":
418
+ id += 1
419
+ yield id_, {
420
+ "idx": id,
421
+ "premise": self._cleaner(row[0]),
422
+ "hypo": self._cleaner(row[1]),
423
+ "label": row[2].strip().replace("contradictory", "contradiction"),
424
+ }
425
+ else:
426
+ if row[0] == "fr":
427
+ id += 1
428
+ yield id_, {
429
+ "idx": id,
430
+ "premise": self._cleaner(row[6]),
431
+ "hypo": self._cleaner(row[7]),
432
+ "label": row[1].strip(), # the label is already "contradiction" in the dev/test
433
+ }
434
+ elif self.config.name == "WSD-V":
435
+ wsd_rdr = WSDDatasetReader()
436
+ for inst in wsd_rdr.read_from_data_dirs([os.path.join(data_file, split)]):
437
+ yield inst[0], {
438
+ "idx": inst[0],
439
+ "sentence": inst[1],
440
+ "pos_tags": inst[2],
441
+ "lemmas": inst[3],
442
+ "fine_pos_tags": inst[4],
443
+ "disambiguate_tokens_ids": inst[5],
444
+ "disambiguate_labels": inst[6],
445
+ }
446
+
447
+ def _cls_extractor(self, line):
448
+ """
449
+ Extract review and label for CLS dataset
450
+ from: https://github.com/getalp/Flaubert/blob/master/flue/extract_split_cls.py
451
+ """
452
+ m = re.search(r"(?<=<rating>)\d+.\d+(?=<\/rating>)", line)
453
+ label = "positive" if int(float(m.group(0))) > 3 else "negative" # rating == 3 are already removed
454
+ category = re.search(r"(?<=<category>)\w+(?=<\/category>)", line)
455
+
456
+ if category == "dvd":
457
+ m = re.search(r"(?<=\/url><text>)(.|\n|\t|\f)+(?=\<\/title><summary>)", line)
458
+ else:
459
+ m = re.search(r"(?<=\/url><text>)(.|\n|\t|\f)+(?=\<\/text><title>)", line)
460
+
461
+ review_text = m.group(0)
462
+
463
+ return self._cleaner(review_text), label
464
+
465
+ def _convert_to_unicode(self, text):
466
+ """
467
+ Converts `text` to Unicode (if it's not already), assuming UTF-8 input.
468
+ from: https://github.com/getalp/Flaubert/blob/master/tools/clean_text.py
469
+ """
470
+ # six_ensure_text is copied from https://github.com/benjaminp/six
471
+ def six_ensure_text(s, encoding="utf-8", errors="strict"):
472
+ if isinstance(s, six.binary_type):
473
+ return s.decode(encoding, errors)
474
+ elif isinstance(s, six.text_type):
475
+ return s
476
+ else:
477
+ raise TypeError("not expecting type '%s'" % type(s))
478
+
479
+ return six_ensure_text(text, encoding="utf-8", errors="ignore")
480
+
481
+ def _cleaner(self, text):
482
+ """
483
+ Clean up an input text
484
+ from: https://github.com/getalp/Flaubert/blob/master/tools/clean_text.py
485
+ """
486
+ # Convert and normalize the unicode underlying representation
487
+ text = self._convert_to_unicode(text)
488
+ text = unicodedata.normalize("NFC", text)
489
+
490
+ # Normalize whitespace characters and remove carriage return
491
+ remap = {ord("\f"): " ", ord("\r"): "", ord("\n"): "", ord("\t"): ""}
492
+ text = text.translate(remap)
493
+
494
+ # Normalize URL links
495
+ pattern = re.compile(r"(?:www|http)\S+|<\S+|\w+\/*>")
496
+ text = re.sub(pattern, "", text)
497
+
498
+ # remove multiple spaces in text
499
+ pattern = re.compile(r"( ){2,}")
500
+ text = re.sub(pattern, r" ", text)
501
+
502
+ return text
503
+
504
+ def _wsdv_prepare_data(self, dirpath):
505
+ """ Get data paths from FSE dir"""
506
+ paths = {}
507
+
508
+ for f in os.listdir(dirpath):
509
+ if f.startswith("FSE"):
510
+ data = "test"
511
+ else:
512
+ data = "train"
513
+
514
+ paths["_".join((data, f))] = os.path.join(dirpath, f)
515
+
516
+ test_dirpath = os.path.join(dirpath, "test")
517
+ os.makedirs(test_dirpath, exist_ok=True)
518
+ train_dirpath = os.path.join(dirpath, "train")
519
+ os.makedirs(train_dirpath, exist_ok=True)
520
+ # copy FSE file to new test directory
521
+ for k, v in paths.items():
522
+ data = k.split("_")[0]
523
+ filename = k.split("_")[1]
524
+ copyfile(v, os.path.join(dirpath, data, filename))
525
+
526
+
527
+ # The WSDDatasetReader classes come from https://github.com/getalp/Flaubert/blob/master/flue/wsd/verbs/modules/dataset.py
528
+ class WSDDatasetReader:
529
+ """ Class to read a WSD data directory. The directory should contain .data.xml and .gold.key.txt files"""
530
+
531
+ def get_data_paths(self, indir):
532
+ """ Get file paths from WSD dir """
533
+ xml_fpath, gold_fpath = None, None
534
+
535
+ for f in os.listdir(indir):
536
+ if f.endswith(".data.xml"):
537
+ xml_fpath = os.path.join(indir, f)
538
+ if f.endswith(".gold.key.txt"):
539
+ gold_fpath = os.path.join(indir, f)
540
+ return xml_fpath, gold_fpath
541
+
542
+ def read_gold(self, infile):
543
+ """Read .gold.key.txt and return data as dict.
544
+ :param infile: fpath to .gold.key.txt file
545
+ :type infile: str
546
+ :return: return data into dict format : {str(instance_id): set(label)}
547
+ :rtype: dict
548
+ """
549
+ return {
550
+ line.split()[0]: tuple(line.rstrip("\n").split()[1:])
551
+ for line in open(infile, encoding="utf-8").readlines()
552
+ }
553
+
554
+ def read_from_data_dirs(self, data_dirs):
555
+ """ Read WSD data and return as WSDDataset """
556
+ for d in data_dirs:
557
+ xml_fpath, gold_fpath = self.get_data_paths(d)
558
+
559
+ # read gold file
560
+ id2gold = self.read_gold(gold_fpath)
561
+
562
+ sentences = self.read_sentences(d)
563
+
564
+ # Parse xml
565
+ tree = etree.parse(xml_fpath)
566
+ corpus = tree.getroot()
567
+
568
+ # process data
569
+ # iterate over document
570
+ for text in corpus:
571
+ # iterates over sentences
572
+ for sentence in text:
573
+ sent_id = sentence.get("id") # sentence id
574
+ sent = next(sentences) # get sentence
575
+ pos_tags = []
576
+ lemmas = []
577
+ fine_pos_tags = []
578
+ disambiguate_tokens_ids = []
579
+ disambiguate_labels = []
580
+ tok_idx = 0
581
+
582
+ # iterate over tokens
583
+ for tok in sentence:
584
+ lemma, pos, fine_pos_tag = tok.get("lemma"), tok.get("pos"), tok.get("fine_pos")
585
+
586
+ pos_tags.append(pos)
587
+ lemmas.append(lemma)
588
+ fine_pos_tags.append(fine_pos_tag)
589
+ wf = tok.text
590
+ subtokens = wf.split(" ")
591
+
592
+ # add sense annotated token
593
+ if tok.tag == "instance":
594
+ id = tok.get("id")
595
+
596
+ target_labels = id2gold[id]
597
+ target_first_label = target_labels[0]
598
+
599
+ # We focus on the head of the target mwe instance
600
+ if pos == "VERB":
601
+ tgt_idx = tok_idx # head is mostly the first token as most mwe verb targets are phrasal verbs (i.g lift up)
602
+ else:
603
+ tgt_idx = (
604
+ tok_idx + len(subtokens) - 1
605
+ ) # other pos head are generally the last token of the mwe (i.g European Union)
606
+
607
+ disambiguate_tokens_ids.append(tgt_idx)
608
+ disambiguate_labels.append(target_first_label)
609
+
610
+ tok_idx += 1
611
+
612
+ yield (
613
+ sent_id,
614
+ sent,
615
+ pos_tags,
616
+ lemmas,
617
+ fine_pos_tags,
618
+ disambiguate_tokens_ids,
619
+ disambiguate_labels,
620
+ )
621
+
622
+ def read_sentences(self, data_dir, keep_mwe=True):
623
+ """ Read sentences from WSD data"""
624
+
625
+ xml_fpath, _ = self.get_data_paths(data_dir)
626
+ return self.read_sentences_from_xml(xml_fpath, keep_mwe=keep_mwe)
627
+
628
+ def read_sentences_from_xml(self, infile, keep_mwe=False):
629
+ """ Read sentences from xml file """
630
+
631
+ # Parse xml
632
+ tree = etree.parse(infile)
633
+ corpus = tree.getroot()
634
+
635
+ for text in corpus:
636
+ for sentence in text:
637
+ if keep_mwe:
638
+ sent = [tok.text.replace(" ", "_") for tok in sentence]
639
+ else:
640
+ sent = [subtok for tok in sentence for subtok in tok.text.split(" ")]
641
+ yield sent
642
+
643
+ def read_target_keys(self, infile):
644
+ """ Read target keys """
645
+ return [x.rstrip("\n") for x in open(infile, encoding="utf-8").readlines()]