File size: 9,677 Bytes
c44ee05 8bea8b3 c44ee05 |
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 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 |
# coding=utf-8
# Copyright 2020 The TensorFlow Datasets Authors and the HuggingFace Datasets Authors.
#
# 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.
# Lint as: python3
"""LUDWIG, (Language Understanding With Implied meaninG). The conversational implicature dataset."""
from typing import Dict, Union
import numpy as np
import copy
import csv
import os
import datasets
logger = datasets.logging.get_logger(__name__)
_CITATION = """\
TBC
"""
_DESCRIPTION = """\
TODO
"""
_URL = "https://raw.githubusercontent.com/ucl-dark/ludwig/main/"
_URLS = {
"dev": _URL + "dev_conversational_implicatures.csv",
"test": _URL + "test_conversational_implicatures.csv"
}
class LudwigConfig(datasets.BuilderConfig):
"""BuilderConfig for LUDWIG."""
def __init__(self, k: int, seed: int, **kwargs):
"""BuilderConfig for LUDWIG.
Args:
**kwargs: keyword arguments forwarded to super.
"""
super(LudwigConfig, self).__init__(**kwargs)
self.k = k
self.seed = seed
self.rng = np.random.default_rng(seed)
def __eq__(self, other):
return self.k == other.k and self.seed == other.seed
def reset_rng(self):
self.rng = np.random.default_rng(self.seed)
class Ludwig(datasets.GeneratorBasedBuilder):
"""LUDWIG: Conversational implicatures dataset."""
BUILDER_CONFIGS = [
LudwigConfig(
name="0-shot",
version=datasets.Version("1.0.0", ""),
description="Plain text",
k=0,
seed=0,
),
LudwigConfig(
name="1-shot",
version=datasets.Version("1.0.0", ""),
description="Plain text",
k=1,
seed=0
),
LudwigConfig(
name="5-shot",
version=datasets.Version("1.0.0", ""),
description="Plain text",
k=5,
seed=0
),
LudwigConfig(
name="10-shot",
version=datasets.Version("1.0.0", ""),
description="Plain text",
k=10,
seed=0
),
LudwigConfig(
name="15-shot",
version=datasets.Version("1.0.0", ""),
description="Plain text",
k=15,
seed=0
),
LudwigConfig(
name="30-shot",
version=datasets.Version("1.0.0", ""),
description="Plain text",
k=30,
seed=0
)
]
def _info(self):
return datasets.DatasetInfo(
description=_DESCRIPTION,
features=datasets.Features(
{
"id": datasets.Value("string"),
"utterance": datasets.Value("string"),
"response": datasets.Value("string"),
"implicature": datasets.Value("string"),
"incoherent_implicature": datasets.Value("string"),
"prompts": datasets.features.Sequence(
{
"utterance": datasets.Value("string"),
"response": datasets.Value("string"),
"implicature": datasets.Value("string"),
"incoherent_implicature": datasets.Value("string"),
}
)
}
),
# No default supervised_keys (as we have to pass both question
# and context as input).
supervised_keys=None,
homepage="https://github.com/ucl-dark/ludwig",
citation=_CITATION
)
def _split_generators(self, dl_manager):
downloaded_files = dl_manager.download_and_extract(_URLS)
return [
datasets.SplitGenerator(name=datasets.Split.VALIDATION, gen_kwargs={"filepath": downloaded_files["dev"],
"dev_filepath": downloaded_files["dev"],
"k": self.config.k}),
datasets.SplitGenerator(name=datasets.Split.TEST, gen_kwargs={"filepath": downloaded_files["test"],
"dev_filepath": downloaded_files["dev"],
"k": self.config.k}),
]
@staticmethod
def _process_text(text):
return text.strip("\n")
def _filter_examples(
self, input_line: Dict[str, str],
) -> Union[None, Dict[str, str]]:
"""
Takes an input_line from the csv file and filters all examples
where the implicature is not a simple yes or no.
:param input_line: a line read from a csv file with data
:param source: the source of the example
:return:
"""
if not input_line:
return None
if "yes" in input_line["Implicature"].lower()[:5]:
implicature = "yes"
elif "no" in input_line["Implicature"].lower()[:4]:
implicature = "no"
else:
return None
response = self._process_text(input_line["Response utterance"])
example = {
"utterance": self._process_text(input_line["Context utterance"]),
"response": response,
"implicature": implicature,
}
return example
def get_negative_binary_example(self, example):
"""
Creates a false example for a binary implicature example.
:param example:
:return: the same dict as the input except for the implicature is negated (yes to no and vice-versa)
"""
if example["implicature"] == "yes":
false_implicature = "no"
elif example["implicature"] == "no":
false_implicature = "yes"
else:
raise ValueError("Unknown implicature %s" % example["implicature"])
false_example = copy.deepcopy(example)
false_example["implicature"] = false_implicature
return false_example
def read_data_csv(
self,
test_input_data_path: str,
dev_input_data_path: str,
):
assert os.path.exists(
test_input_data_path
), "No input data file found at: %s\n" "Current working direction: %s" % (
test_input_data_path,
os.getcwd(),
)
assert os.path.exists(
dev_input_data_path
), "No dev input data file found at: %s\n" "Current working direction: %s" % (
dev_input_data_path,
os.getcwd(),
)
with open(test_input_data_path, newline="") as csvfile:
with open(dev_input_data_path, newline="") as dev_csvfile:
reader = csv.DictReader(csvfile)
dev_reader = csv.DictReader(dev_csvfile)
all_data = {
"test_data": [],
"dev_data": [],
}
for row in reader:
example = self._filter_examples(row)
if example is not None:
negative_example = self.get_negative_binary_example(example)["implicature"]
example = {**example,
"incoherent_implicature": negative_example}
all_data["test_data"].append(example)
for row in dev_reader:
example = self._filter_examples(row)
if example is not None:
negative_example = self.get_negative_binary_example(example)["implicature"]
example = {**example,
"incoherent_implicature": negative_example}
all_data["dev_data"].append(example)
return all_data
def _get_prompt_examples(self, dev_data, k_shot=0):
"""
A function to parse the i-th example in self.data["data"]
:param dev_data: list of examples to sample from
:param k_shot: how many extra examples to parse from different indices than i
:return: a parsed example
"""
if k_shot > 0:
prompt_indices = self.config.rng.choice(
range(len(dev_data)), k_shot, replace=False
)
prompt_examples = [dev_data[j] for j in prompt_indices]
else:
prompt_examples = []
return prompt_examples
def _generate_examples(self, filepath, dev_filepath, k: int):
"""This function returns the examples in the raw (text) form."""
logger.info("generating examples from = %s", filepath)
logger.info("k-shot examples from = %s", dev_filepath)
all_data = self.read_data_csv(filepath, dev_filepath)
self.config.reset_rng()
for i, example in enumerate(all_data["test_data"]):
prompt_examples = self._get_prompt_examples(all_data["dev_data"], k)
yield i, {
**example,
"prompts": prompt_examples,
"id": i + 1,
}
|