Filip Ginter commited on
Commit
1c43d87
1 Parent(s): 820a12c

Initial push of v1.1.0

Browse files
Files changed (1) hide show
  1. turku_paraphrase_corpus.py +290 -0
turku_paraphrase_corpus.py ADDED
@@ -0,0 +1,290 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
53
+ 'train': 'https://github.com/TurkuNLP/Turku-paraphrase-corpus/raw/ver-1.1.0/data-fi/train.json',
54
+ 'validation': 'https://github.com/TurkuNLP/Turku-paraphrase-corpus/raw/ver-1.1.0/data-fi/dev.json',
55
+ 'test': 'https://github.com/TurkuNLP/Turku-paraphrase-corpus/raw/ver-1.1.0/data-fi/test.json',
56
+ 'doctexts': 'https://github.com/TurkuNLP/Turku-paraphrase-corpus/raw/ver-1.1.0/data-fi/texts.json.gz'
57
+ }
58
+
59
+
60
+
61
+ class TurkuParaphraseCorpus(datasets.GeneratorBasedBuilder):
62
+ """Turku Paraphrase Corpus is a dataset of 104,645 manually annotated Finnish paraphrases."""
63
+
64
+ VERSION = datasets.Version("1.1.0")
65
+
66
+ # This is an example of a dataset with multiple configurations.
67
+ # If you don't want/need to define several sub-sets in your dataset,
68
+ # just remove the BUILDER_CONFIG_CLASS and the BUILDER_CONFIGS attributes.
69
+
70
+ # If you need to make complex sub-parts in the datasets with configurable options
71
+ # You can create your own builder configuration class to store attribute, inheriting from datasets.BuilderConfig
72
+ # BUILDER_CONFIG_CLASS = MyBuilderConfig
73
+
74
+ # You will be able to load one or the other configurations in the following list with
75
+ # data = datasets.load_dataset('my_dataset', 'first_domain')
76
+ # data = datasets.load_dataset('my_dataset', 'second_domain')
77
+ BUILDER_CONFIGS = [
78
+ 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', 'classification-context', 'plain-context' and 'generation' for ready made transformations for paraphrase classification and paraphrase generation)."),
79
+ datasets.BuilderConfig(name="plain-context", 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', 'classification-context', 'plain' and 'generation' for ready made transformations for paraphrase classification and paraphrase generation). Unlike 'plain', this dataset includes the document contexts, which eats memory, but otherwise it is the same as 'plain'. This is useful for context-based modelling."),
80
+ 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)"),
81
+ datasets.BuilderConfig(name="classification-context", 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). Unlike 'classification' this dataset includes the document contexts, which eats memory but otherwise it is the same as 'classification'. This is useful for context-based modelling."),
82
+ 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."),
83
+ ]
84
+
85
+ #DEFAULT_CONFIG_NAME = "plain" # It's not mandatory to have a default configuration. Just use one if it make sense.
86
+
87
+ def _info(self):
88
+ # This method specifies the datasets.DatasetInfo object which contains informations and typings for the dataset
89
+ if self.config.name == "generation": # This is the name of the configuration selected in BUILDER_CONFIGS above
90
+ features = datasets.Features(
91
+ {
92
+ "id": datasets.Value("string"),
93
+ "gem_id": datasets.Value("string"),
94
+ "goeswith": datasets.Value("string"),
95
+ "fold": datasets.Value("int32"),
96
+ "input": datasets.Value("string"),
97
+ "output": datasets.Value("string"),
98
+ "label": datasets.Value("string"),
99
+ "binary_label": datasets.Value("string"),
100
+ "is_rewrite": datasets.Value("bool"),
101
+ }
102
+ )
103
+ elif self.config.name in ("classification","plain"):
104
+ features = datasets.Features(
105
+ {
106
+ "id": datasets.Value("string"),
107
+ "gem_id": datasets.Value("string"),
108
+ "goeswith": datasets.Value("string"),
109
+ "fold": datasets.Value("int32"),
110
+ "text1": datasets.Value("string"),
111
+ "text2": datasets.Value("string"),
112
+ "label": datasets.Value("string"),
113
+ "binary_label": datasets.Value("string"),
114
+ "is_rewrite": datasets.Value("bool"),
115
+ }
116
+ )
117
+ elif self.config.name in ("classification-context","plain-context"):# same format for classification/original
118
+ features = datasets.Features(
119
+ {
120
+ "id": datasets.Value("string"),
121
+ "gem_id": datasets.Value("string"),
122
+ "goeswith": datasets.Value("string"),
123
+ "fold": datasets.Value("int32"),
124
+ "text1": datasets.Value("string"),
125
+ "text2": datasets.Value("string"),
126
+ "label": datasets.Value("string"),
127
+ "binary_label": datasets.Value("string"),
128
+ "is_rewrite": datasets.Value("bool"),
129
+ "context1": {"doctext":datasets.Value("string"), "start":datasets.Value("int32"), "end":datasets.Value("int32")},
130
+ "context2": {"doctext":datasets.Value("string"), "start":datasets.Value("int32"), "end":datasets.Value("int32")}
131
+ }
132
+ )
133
+ return datasets.DatasetInfo(
134
+ description=_DESCRIPTION,
135
+ features=features,
136
+ # If there's a common (input, target) tuple from the features,
137
+ # specify them here. They'll be used if as_supervised=True in
138
+ # builder.as_dataset.
139
+ supervised_keys=None,
140
+ homepage=_HOMEPAGE,
141
+ license=_LICENSE,
142
+ citation=_CITATION,
143
+ )
144
+
145
+ def _split_generators(self, dl_manager):
146
+ """Returns SplitGenerators."""
147
+ # If several configurations are possible (listed in BUILDER_CONFIGS), the configuration selected by the user is in self.config.name
148
+
149
+ # dl_manager is a datasets.download.DownloadManager that can be used to download and extract URLs
150
+ # 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.
151
+ # By default the archives will be extracted and a path to a cached folder where they are extracted is returned instead of the archive
152
+
153
+ my_urls = _URLs
154
+ data_dir = dl_manager.download_and_extract(my_urls)
155
+ return [
156
+ datasets.SplitGenerator(name=datasets.Split.TRAIN, gen_kwargs={"filepath": data_dir["train"], "split": "train", "doctexts": data_dir["doctexts"]}),
157
+ datasets.SplitGenerator(name=datasets.Split.VALIDATION, gen_kwargs={"filepath": data_dir["validation"], "split": "validation", "doctexts": data_dir["doctexts"]}),
158
+ datasets.SplitGenerator(name=datasets.Split.TEST, gen_kwargs={"filepath": data_dir["test"], "split": "test", "doctexts": data_dir["doctexts"]})
159
+ ]
160
+
161
+ def _generate_examples(self, filepath, split, doctexts=None):
162
+ """ Yields examples as (key, example) tuples. """
163
+ # This method handles input defined in _split_generators to yield (key, example) tuples from the dataset.
164
+ # The `key` is here for legacy reason (tfds) and is not important in itself.
165
+
166
+ if doctexts and self.config.name in ("classification-context","plain-context"): #we dont want to read this in for configs which do not need the contexts
167
+ with open(doctexts, "rt", encoding="utf-8") as f:
168
+ doctexts_dict=json.load(f)
169
+ else:
170
+ doctexts_dict={}
171
+
172
+ with open(filepath, "rt", encoding="utf-8") as f:
173
+ data = json.load(f)
174
+ counter = 0
175
+ for example in data:
176
+ ctx=example.get("context") #this is either the context information (a dict), or an empty dict if absent
177
+ if ctx is None:
178
+ ctx={}
179
+ d1=ctx.get("doc1")
180
+ d2=ctx.get("doc2")
181
+ if self.config.name in ("classification-context","plain-context"): #these two configs take the context
182
+ example["context1"]={"doctext":doctexts_dict.get(d1,""),"start":ctx.get("beg1",0),"end":ctx.get("end1",0)}
183
+ example["context2"]={"doctext":doctexts_dict.get(d2,""),"start":ctx.get("beg2",0),"end":ctx.get("end2",0)}
184
+ if self.config.name == "generation":
185
+ examples = self._prepare_for_generation(example)
186
+ else:
187
+ examples = self._prepare_plain_and_classification(example)
188
+ for e in examples:
189
+ e["gem_id"] = f"gem-turku_paraphrase_corpus-{split}-{counter}" # fill in gem_id
190
+ e["id"]=f"turku_paraphrase_corpus-{split}-{counter}" # fill in gem_id
191
+ yield counter, e
192
+ counter += 1
193
+
194
+
195
+ #### HELPER FUNCTIONS ####
196
+
197
+ def _skip_in_generation(self, label):
198
+ """ define here which examples should be skipped when doing paraphrase generation """
199
+ skip_labels = ["2", "3", "i", "s"]
200
+ for l in skip_labels:
201
+ if l in label:
202
+ return True
203
+ return False
204
+
205
+ def _prepare_for_generation(self, orig_example):
206
+ """ turn examples into generation format """
207
+ processed = []
208
+ d = {
209
+ "gem_id": "placeholder", # fill in later
210
+ "goeswith": orig_example["goeswith"] if orig_example["goeswith"]!=None else "not available",
211
+ "fold": orig_example["fold"],
212
+ "input": orig_example["txt1"],
213
+ "output": orig_example["txt2"],
214
+ "label": orig_example["label"],
215
+ "binary_label": "positive" if orig_example["label"] != "2" else "negative",
216
+ "is_rewrite": False}
217
+
218
+ label = d["label"]
219
+ if self._skip_in_generation(label) == False:
220
+ if ">" in label:
221
+ processed.append(d)
222
+ elif "<" in label:
223
+ processed.append(self._flip_example(d, "input", "output"))
224
+ else:
225
+ processed.append(d)
226
+ processed.append(self._flip_example(d, "input", "output"))
227
+
228
+ for rew in orig_example["rewrites"]:
229
+ r = self._generate_rew(d, rew, "input", "output")
230
+ processed.append(r)
231
+ processed.append(self._flip_example(r, "input", "output"))
232
+ return processed
233
+
234
+ def _prepare_plain_and_classification(self, orig_example):
235
+ """ turn examples into classification format """
236
+ processed = []
237
+ d = {
238
+ "gem_id": "placeholder", # fill in later
239
+ "goeswith": orig_example["goeswith"] if orig_example["goeswith"]!=None else "not available",
240
+ "fold": orig_example["fold"],
241
+ "text1": orig_example["txt1"],
242
+ "text2": orig_example["txt2"],
243
+ "label": orig_example["label"],
244
+ "binary_label": "positive" if orig_example["label"] != "2" else "negative",
245
+ "is_rewrite": False,
246
+ }
247
+ if "context1" in orig_example and "context2" in orig_example:
248
+ d["context1"]=orig_example["context1"]
249
+ d["context2"]=orig_example["context2"]
250
+
251
+ processed.append(d)
252
+ if self.config.name in ("classification", "classification-context"):
253
+ processed.append(self._flip_example(d, "text1", "text2"))
254
+ for rew in orig_example["rewrites"]:
255
+ r = self._generate_rew(d, rew, "text1", "text2")
256
+ processed.append(r)
257
+ if self.config.name in ("classification","classification-context"):
258
+ processed.append(self._flip_example(d, "text1", "text2"))
259
+ return processed
260
+
261
+ def _generate_rew(self, orig, rew, field1, field2):
262
+ """ turn rewrite into individual example """
263
+ d = {
264
+ "gem_id": "placeholder", # fill in later
265
+ "goeswith": orig["goeswith"],
266
+ "fold": orig["fold"],
267
+ field1: rew[0],
268
+ field2: rew[1],
269
+ "label": "4",
270
+ "binary_label": "positive",
271
+ "is_rewrite": True,
272
+ }
273
+ if "context1" in orig and "context2" in orig:
274
+ d["context1"]={"doctext":"","start":0,"end":0}
275
+ d["context2"]={"doctext":"","start":0, "end":0}
276
+ return d
277
+
278
+ def _flip_example(self, example, field1, field2):
279
+ """ flip the example (text1, text2, label) --> (text2, text1, label) """
280
+ flipped = example.copy()
281
+ if "<" in example["label"]: # label needs to be flipped
282
+ flipped["label"] = example["label"].replace("<", ">")
283
+ if ">" in example["label"]:
284
+ flipped["label"] = example["label"].replace(">", "<")
285
+ flipped[field1] = example[field2]
286
+ flipped[field2] = example[field1]
287
+ if "context1" in example and "context2" in example:
288
+ flipped["context1"],flipped["context2"]=example["context2"],example["context1"]
289
+ return flipped
290
+