File size: 12,015 Bytes
4a9de96 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 |
# coding=utf-8
# Copyright 2020 The HuggingFace Datasets Authors and the current dataset script contributor.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Data Loader for Turku Paraphrase Corpus"""
import csv
import json
import os
import datasets
# Find for instance the citation on arxiv or on the dataset repo/website
_CITATION = """\
@inproceedings{kanerva-etal-2021-finnish,
title = {Finnish Paraphrase Corpus},
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},
booktitle = {Proceedings of the 23rd Nordic Conference on Computational Linguistics (NoDaLiDa'21)},
year = {2021},
publisher = {Linköping University Electronic Press, Sweden},
url = {https://aclanthology.org/2021.nodalida-main.29},
pages = {288--298}
}
"""
# You can copy an official description
_DESCRIPTION = """\
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.
"""
_HOMEPAGE = "https://turkunlp.org/paraphrase.html"
_LICENSE = "Creative Commons Attribution-ShareAlike 4.0 International (CC BY-SA 4.0)"
# The HuggingFace dataset library don't host the datasets but only point to the original files
# This can be an arbitrary nested dict/list of URLs (see below in `_split_generators` method)
_URLs = {
'train': 'https://raw.githubusercontent.com/TurkuNLP/Turku-paraphrase-corpus/main/data-fi/train.json',
'validation': 'https://raw.githubusercontent.com/TurkuNLP/Turku-paraphrase-corpus/main/data-fi/dev.json',
'test': 'https://raw.githubusercontent.com/TurkuNLP/Turku-paraphrase-corpus/main/data-fi/test.json'
}
class TurkuParaphraseCorpus(datasets.GeneratorBasedBuilder):
"""Turku Paraphrase Corpus is a dataset of 104,645 manually annotated Finnish paraphrases."""
VERSION = datasets.Version("1.1.0")
# This is an example of a dataset with multiple configurations.
# If you don't want/need to define several sub-sets in your dataset,
# just remove the BUILDER_CONFIG_CLASS and the BUILDER_CONFIGS attributes.
# If you need to make complex sub-parts in the datasets with configurable options
# You can create your own builder configuration class to store attribute, inheriting from datasets.BuilderConfig
# BUILDER_CONFIG_CLASS = MyBuilderConfig
# You will be able to load one or the other configurations in the following list with
# data = datasets.load_dataset('my_dataset', 'first_domain')
# data = datasets.load_dataset('my_dataset', 'second_domain')
BUILDER_CONFIGS = [
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)."),
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)"),
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."),
]
#DEFAULT_CONFIG_NAME = "plain" # It's not mandatory to have a default configuration. Just use one if it make sense.
def _info(self):
# This method specifies the datasets.DatasetInfo object which contains informations and typings for the dataset
if self.config.name == "generation": # This is the name of the configuration selected in BUILDER_CONFIGS above
features = datasets.Features(
{
"gem_id": datasets.Value("string"),
"goeswith": datasets.Value("string"),
"fold": datasets.Value("int32"),
"input": datasets.Value("string"),
"output": datasets.Value("string"),
"label": datasets.Value("string"),
"binary_label": datasets.Value("string"),
"is_rewrite": datasets.Value("bool"),
}
)
else: # same format for classification/original
features = datasets.Features(
{
"gem_id": datasets.Value("string"),
"goeswith": datasets.Value("string"),
"fold": datasets.Value("int32"),
"text1": datasets.Value("string"),
"text2": datasets.Value("string"),
"label": datasets.Value("string"),
"binary_label": datasets.Value("string"),
"is_rewrite": datasets.Value("bool"),
}
)
return datasets.DatasetInfo(
description=_DESCRIPTION,
features=features,
# If there's a common (input, target) tuple from the features,
# specify them here. They'll be used if as_supervised=True in
# builder.as_dataset.
supervised_keys=None,
homepage=_HOMEPAGE,
license=_LICENSE,
citation=_CITATION,
)
def _split_generators(self, dl_manager):
"""Returns SplitGenerators."""
# If several configurations are possible (listed in BUILDER_CONFIGS), the configuration selected by the user is in self.config.name
# dl_manager is a datasets.download.DownloadManager that can be used to download and extract URLs
# 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.
# By default the archives will be extracted and a path to a cached folder where they are extracted is returned instead of the archive
my_urls = _URLs
data_dir = dl_manager.download_and_extract(my_urls)
return [
datasets.SplitGenerator(name=datasets.Split.TRAIN, gen_kwargs={"filepath": data_dir["train"], "split": "train"}),
datasets.SplitGenerator(name=datasets.Split.VALIDATION, gen_kwargs={"filepath": data_dir["validation"], "split": "validation"}),
datasets.SplitGenerator(name=datasets.Split.TEST, gen_kwargs={"filepath": data_dir["test"], "split": "test"})
]
def _generate_examples(self, filepath, split):
""" Yields examples as (key, example) tuples. """
# This method handles input defined in _split_generators to yield (key, example) tuples from the dataset.
# The `key` is here for legacy reason (tfds) and is not important in itself.
with open(filepath, "rt", encoding="utf-8") as f:
data = json.load(f)
counter = 0
for example in data:
if self.config.name == "generation":
examples = self._prepare_for_generation(example)
else:
examples = self._prepare_plain_and_classification(example)
for e in examples:
e["gem_id"] = f"gem-turku_paraphrase_corpus-{split}-{counter}" # fill in gem_id
yield counter, e
counter += 1
#### HELPER FUNCTIONS ####
def _skip_in_generation(self, label):
""" define here which examples should be skipped when doing paraphrase generation """
skip_labels = ["2", "3", "i", "s"]
for l in skip_labels:
if l in label:
return True
return False
def _prepare_for_generation(self, orig_example):
""" turn examples into generation format """
processed = []
d = {
"gem_id": "placeholder", # fill in later
"goeswith": orig_example["goeswith"] if orig_example["goeswith"]!=None else "not available",
"fold": orig_example["fold"],
"input": orig_example["txt1"],
"output": orig_example["txt2"],
"label": orig_example["label"],
"binary_label": "positive" if orig_example["label"] != "2" else "negative",
"is_rewrite": False}
label = d["label"]
if self._skip_in_generation(label) == False:
if ">" in label:
processed.append(d)
elif "<" in label:
processed.append(self._flip_example(d, "input", "output"))
else:
processed.append(d)
processed.append(self._flip_example(d, "input", "output"))
for rew in orig_example["rewrites"]:
r = self._generate_rew(d, rew, "input", "output")
processed.append(r)
processed.append(self._flip_example(r, "input", "output"))
return processed
def _prepare_plain_and_classification(self, orig_example):
""" turn examples into classification format """
processed = []
d = {
"gem_id": "placeholder", # fill in later
"goeswith": orig_example["goeswith"] if orig_example["goeswith"]!=None else "not available",
"fold": orig_example["fold"],
"text1": orig_example["txt1"],
"text2": orig_example["txt2"],
"label": orig_example["label"],
"binary_label": "positive" if orig_example["label"] != "2" else "negative",
"is_rewrite": False}
processed.append(d)
if self.config.name == "classification":
processed.append(self._flip_example(d, "text1", "text2"))
for rew in orig_example["rewrites"]:
r = self._generate_rew(d, rew, "text1", "text2")
processed.append(r)
if self.config.name == "classification":
processed.append(self._flip_example(d, "text1", "text2"))
return processed
def _generate_rew(self, orig, rew, field1, field2):
""" turn rewrite into individual example """
d = {
"gem_id": "placeholder", # fill in later
"goeswith": orig["goeswith"],
"fold": orig["fold"],
field1: rew[0],
field2: rew[1],
"label": "4",
"binary_label": "positive",
"is_rewrite": True}
return d
def _flip_example(self, example, field1, field2):
""" flip the example (text1, text2, label) --> (text2, text1, label) """
flipped = example.copy()
if "<" in example["label"]: # label needs to be flipped
flipped["label"] = example["label"].replace("<", ">")
if ">" in example["label"]:
flipped["label"] = example["label"].replace(">", "<")
flipped[field1] = example[field2]
flipped[field2] = example[field1]
return flipped
|