Datasets:
GEM
/

Tasks:
Other
Languages:
Finnish
Multilinguality:
unknown
Size Categories:
unknown
Language Creators:
unknown
Annotations Creators:
expert-created
Source Datasets:
original
License:
jmnybl commited on
Commit
4a9de96
1 Parent(s): b73bcc6

data loader

Browse files
Files changed (1) hide show
  1. turku_paraphrase_corpus.py +242 -0
turku_paraphrase_corpus.py ADDED
@@ -0,0 +1,242 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2020 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
+ """Data Loader for Turku Paraphrase Corpus"""
16
+
17
+
18
+ import csv
19
+ import json
20
+ import os
21
+
22
+ import datasets
23
+
24
+
25
+ # Find for instance the citation on arxiv or on the dataset repo/website
26
+ _CITATION = """\
27
+ @inproceedings{kanerva-etal-2021-finnish,
28
+ title = {Finnish Paraphrase Corpus},
29
+ author = {Kanerva, Jenna and Ginter, Filip and Chang, Li-Hsin and Rastas, Iiro and Skantsi, Valtteri and Kilpeläinen, Jemina and Kupari, Hanna-Mari and Saarni, Jenna and Sevón, Maija and Tarkka, Otto},
30
+ booktitle = {Proceedings of the 23rd Nordic Conference on Computational Linguistics (NoDaLiDa'21)},
31
+ year = {2021},
32
+ publisher = {Linköping University Electronic Press, Sweden},
33
+ url = {https://aclanthology.org/2021.nodalida-main.29},
34
+ pages = {288--298}
35
+ }
36
+ """
37
+
38
+
39
+ # You can copy an official description
40
+ _DESCRIPTION = """\
41
+ Turku Paraphrase Corpus is a dataset of 104,645 manually annotated Finnish paraphrases. The vast majority of the data is classified as a paraphrase either in the given context, or universally.
42
+ """
43
+
44
+ _HOMEPAGE = "https://turkunlp.org/paraphrase.html"
45
+
46
+ _LICENSE = "Creative Commons Attribution-ShareAlike 4.0 International (CC BY-SA 4.0)"
47
+
48
+
49
+ # The HuggingFace dataset library don't host the datasets but only point to the original files
50
+ # This can be an arbitrary nested dict/list of URLs (see below in `_split_generators` method)
51
+ _URLs = {
52
+ 'train': 'https://raw.githubusercontent.com/TurkuNLP/Turku-paraphrase-corpus/main/data-fi/train.json',
53
+ 'validation': 'https://raw.githubusercontent.com/TurkuNLP/Turku-paraphrase-corpus/main/data-fi/dev.json',
54
+ 'test': 'https://raw.githubusercontent.com/TurkuNLP/Turku-paraphrase-corpus/main/data-fi/test.json'
55
+ }
56
+
57
+
58
+
59
+ class TurkuParaphraseCorpus(datasets.GeneratorBasedBuilder):
60
+ """Turku Paraphrase Corpus is a dataset of 104,645 manually annotated Finnish paraphrases."""
61
+
62
+ VERSION = datasets.Version("1.1.0")
63
+
64
+ # This is an example of a dataset with multiple configurations.
65
+ # If you don't want/need to define several sub-sets in your dataset,
66
+ # just remove the BUILDER_CONFIG_CLASS and the BUILDER_CONFIGS attributes.
67
+
68
+ # If you need to make complex sub-parts in the datasets with configurable options
69
+ # You can create your own builder configuration class to store attribute, inheriting from datasets.BuilderConfig
70
+ # BUILDER_CONFIG_CLASS = MyBuilderConfig
71
+
72
+ # You will be able to load one or the other configurations in the following list with
73
+ # data = datasets.load_dataset('my_dataset', 'first_domain')
74
+ # data = datasets.load_dataset('my_dataset', 'second_domain')
75
+ BUILDER_CONFIGS = [
76
+ datasets.BuilderConfig(name="plain", version=VERSION, description="This loads the dataset in its plain format without any additional data transformations. In case of applying the dataset to a task (e.g. paraphrase classification or generation), some additional data transformations are suggested depending on the task (see 'classification' and 'generation' for ready made transformations for paraphrase classification and paraphrase generation)."),
77
+ datasets.BuilderConfig(name="classification", version=VERSION, description="This loads the dataset in a format directly suitable for paraphrase classification. Each example is introduced twice with different order of the text passages, (text1, text2, label) and (text2, text1, label)"),
78
+ datasets.BuilderConfig(name="generation", version=VERSION, description="This loads the dataset in a format suitable for paraphrase generation, where examples not considered suitable for generation models are discarded. Paraphrases without directionality are generated in both directions, while directional paraphrases (subsumption flag) are only generated from more detailed to more general one. Labels 2 (related but not a paraphrase), 3 (context dependent paraphrase), flag i (minor deviation), and flag s (style difference) are discarded."),
79
+ ]
80
+
81
+ #DEFAULT_CONFIG_NAME = "plain" # It's not mandatory to have a default configuration. Just use one if it make sense.
82
+
83
+ def _info(self):
84
+ # This method specifies the datasets.DatasetInfo object which contains informations and typings for the dataset
85
+ if self.config.name == "generation": # This is the name of the configuration selected in BUILDER_CONFIGS above
86
+ features = datasets.Features(
87
+ {
88
+ "gem_id": datasets.Value("string"),
89
+ "goeswith": datasets.Value("string"),
90
+ "fold": datasets.Value("int32"),
91
+ "input": datasets.Value("string"),
92
+ "output": datasets.Value("string"),
93
+ "label": datasets.Value("string"),
94
+ "binary_label": datasets.Value("string"),
95
+ "is_rewrite": datasets.Value("bool"),
96
+ }
97
+ )
98
+ else: # same format for classification/original
99
+ features = datasets.Features(
100
+ {
101
+ "gem_id": datasets.Value("string"),
102
+ "goeswith": datasets.Value("string"),
103
+ "fold": datasets.Value("int32"),
104
+ "text1": datasets.Value("string"),
105
+ "text2": datasets.Value("string"),
106
+ "label": datasets.Value("string"),
107
+ "binary_label": datasets.Value("string"),
108
+ "is_rewrite": datasets.Value("bool"),
109
+ }
110
+ )
111
+ return datasets.DatasetInfo(
112
+ description=_DESCRIPTION,
113
+ features=features,
114
+ # If there's a common (input, target) tuple from the features,
115
+ # specify them here. They'll be used if as_supervised=True in
116
+ # builder.as_dataset.
117
+ supervised_keys=None,
118
+ homepage=_HOMEPAGE,
119
+ license=_LICENSE,
120
+ citation=_CITATION,
121
+ )
122
+
123
+ def _split_generators(self, dl_manager):
124
+ """Returns SplitGenerators."""
125
+ # If several configurations are possible (listed in BUILDER_CONFIGS), the configuration selected by the user is in self.config.name
126
+
127
+ # dl_manager is a datasets.download.DownloadManager that can be used to download and extract URLs
128
+ # It can accept any type or nested list/dict and will give back the same structure with the url replaced with path to local files.
129
+ # By default the archives will be extracted and a path to a cached folder where they are extracted is returned instead of the archive
130
+
131
+ my_urls = _URLs
132
+ data_dir = dl_manager.download_and_extract(my_urls)
133
+ return [
134
+ datasets.SplitGenerator(name=datasets.Split.TRAIN, gen_kwargs={"filepath": data_dir["train"], "split": "train"}),
135
+ datasets.SplitGenerator(name=datasets.Split.VALIDATION, gen_kwargs={"filepath": data_dir["validation"], "split": "validation"}),
136
+ datasets.SplitGenerator(name=datasets.Split.TEST, gen_kwargs={"filepath": data_dir["test"], "split": "test"})
137
+ ]
138
+
139
+ def _generate_examples(self, filepath, split):
140
+ """ Yields examples as (key, example) tuples. """
141
+ # This method handles input defined in _split_generators to yield (key, example) tuples from the dataset.
142
+ # The `key` is here for legacy reason (tfds) and is not important in itself.
143
+
144
+ with open(filepath, "rt", encoding="utf-8") as f:
145
+ data = json.load(f)
146
+ counter = 0
147
+ for example in data:
148
+ if self.config.name == "generation":
149
+ examples = self._prepare_for_generation(example)
150
+ else:
151
+ examples = self._prepare_plain_and_classification(example)
152
+ for e in examples:
153
+ e["gem_id"] = f"gem-turku_paraphrase_corpus-{split}-{counter}" # fill in gem_id
154
+ yield counter, e
155
+ counter += 1
156
+
157
+
158
+ #### HELPER FUNCTIONS ####
159
+
160
+ def _skip_in_generation(self, label):
161
+ """ define here which examples should be skipped when doing paraphrase generation """
162
+ skip_labels = ["2", "3", "i", "s"]
163
+ for l in skip_labels:
164
+ if l in label:
165
+ return True
166
+ return False
167
+
168
+ def _prepare_for_generation(self, orig_example):
169
+ """ turn examples into generation format """
170
+ processed = []
171
+ d = {
172
+ "gem_id": "placeholder", # fill in later
173
+ "goeswith": orig_example["goeswith"] if orig_example["goeswith"]!=None else "not available",
174
+ "fold": orig_example["fold"],
175
+ "input": orig_example["txt1"],
176
+ "output": orig_example["txt2"],
177
+ "label": orig_example["label"],
178
+ "binary_label": "positive" if orig_example["label"] != "2" else "negative",
179
+ "is_rewrite": False}
180
+
181
+ label = d["label"]
182
+ if self._skip_in_generation(label) == False:
183
+ if ">" in label:
184
+ processed.append(d)
185
+ elif "<" in label:
186
+ processed.append(self._flip_example(d, "input", "output"))
187
+ else:
188
+ processed.append(d)
189
+ processed.append(self._flip_example(d, "input", "output"))
190
+
191
+ for rew in orig_example["rewrites"]:
192
+ r = self._generate_rew(d, rew, "input", "output")
193
+ processed.append(r)
194
+ processed.append(self._flip_example(r, "input", "output"))
195
+ return processed
196
+
197
+ def _prepare_plain_and_classification(self, orig_example):
198
+ """ turn examples into classification format """
199
+ processed = []
200
+ d = {
201
+ "gem_id": "placeholder", # fill in later
202
+ "goeswith": orig_example["goeswith"] if orig_example["goeswith"]!=None else "not available",
203
+ "fold": orig_example["fold"],
204
+ "text1": orig_example["txt1"],
205
+ "text2": orig_example["txt2"],
206
+ "label": orig_example["label"],
207
+ "binary_label": "positive" if orig_example["label"] != "2" else "negative",
208
+ "is_rewrite": False}
209
+ processed.append(d)
210
+ if self.config.name == "classification":
211
+ processed.append(self._flip_example(d, "text1", "text2"))
212
+ for rew in orig_example["rewrites"]:
213
+ r = self._generate_rew(d, rew, "text1", "text2")
214
+ processed.append(r)
215
+ if self.config.name == "classification":
216
+ processed.append(self._flip_example(d, "text1", "text2"))
217
+ return processed
218
+
219
+ def _generate_rew(self, orig, rew, field1, field2):
220
+ """ turn rewrite into individual example """
221
+ d = {
222
+ "gem_id": "placeholder", # fill in later
223
+ "goeswith": orig["goeswith"],
224
+ "fold": orig["fold"],
225
+ field1: rew[0],
226
+ field2: rew[1],
227
+ "label": "4",
228
+ "binary_label": "positive",
229
+ "is_rewrite": True}
230
+ return d
231
+
232
+ def _flip_example(self, example, field1, field2):
233
+ """ flip the example (text1, text2, label) --> (text2, text1, label) """
234
+ flipped = example.copy()
235
+ if "<" in example["label"]: # label needs to be flipped
236
+ flipped["label"] = example["label"].replace("<", ">")
237
+ if ">" in example["label"]:
238
+ flipped["label"] = example["label"].replace(">", "<")
239
+ flipped[field1] = example[field2]
240
+ flipped[field2] = example[field1]
241
+ return flipped
242
+