Datasets:

Modalities:
Tabular
Text
Libraries:
Datasets
License:
qa_adj / qa_adj.py
kleinay's picture
qa_adj.py
34b2b51
raw
history blame
9.23 kB
# 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.
"""A Dataset loading script for the QA-Adj dataset."""
from dataclasses import dataclass
from typing import Optional, Tuple, Union, Iterable, Set
from pathlib import Path
import itertools
import pandas as pd
import datasets
_DESCRIPTION = """\
The dataset contains question-answer pairs to capture adjectival semantics.
This dataset was annotated by selected workers from Amazon Mechanical Turk.
"""
_LICENSE = """MIT License
Copyright (c) 2022 Ayal Klein (kleinay)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE."""
URL = "https://github.com/kleinay/QA-Adj-Dataset/raw/main/QAADJ_Dataset.zip"
SUPPOERTED_DOMAINS = {"wikinews", "wikipedia"}
@dataclass
class QAAdjBuilderConfig(datasets.BuilderConfig):
domains: Union[str, Iterable[str]] = "all" # can provide also a subset of acceptable domains.
full_dataset: bool = False
class QaAdj(datasets.GeneratorBasedBuilder):
"""QAAdj: Question-Answer based semantics for adjectives.
"""
VERSION = datasets.Version("1.0.0")
BUILDER_CONFIG_CLASS = QAAdjBuilderConfig
BUILDER_CONFIGS = [
QAAdjBuilderConfig(
name="default", version=VERSION, description="This provides the QAAdj dataset - train, dev and test"#, redistribute_dev=(0,1,0)
),
QAAdjBuilderConfig(
name="full", version=VERSION, full_dataset=True,
description="""This provides the QAAdj dataset including gold reference
(300 expert-annotated instances) and propbank comparison instances"""
),
]
DEFAULT_CONFIG_NAME = (
"default" # It's not mandatory to have a default configuration. Just use one if it make sense.
)
def _info(self):
features = datasets.Features(
{
"sentence": datasets.Value("string"),
"sent_id": datasets.Value("string"),
"predicate_idx": datasets.Value("int32"),
"predicate_idx_end": datasets.Value("int32"),
"predicate": datasets.Value("string"),
"object_question": datasets.Value("string"),
"object_answer": datasets.Sequence(datasets.Value("string")),
"domain_question": datasets.Value("string"),
"domain_answer": datasets.Sequence(datasets.Value("string")),
"reference_question": datasets.Value("string"),
"reference_answer": datasets.Sequence(datasets.Value("string")),
"extent_question": datasets.Value("string"),
"extent_answer": datasets.Sequence(datasets.Value("string")),
}
)
return datasets.DatasetInfo(
# This is the description that will appear on the datasets page.
description=_DESCRIPTION,
# This defines the different columns of the dataset and their types
features=features, # Here we define them above because they are different between the two configurations
# 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 of the dataset for documentation
# homepage=_HOMEPAGE,
# License for the dataset if available
license=_LICENSE,
# Citation for the dataset
# citation=_CITATION,
)
def _split_generators(self, dl_manager: datasets.utils.download_manager.DownloadManager):
"""Returns SplitGenerators."""
# Handle domain selection
domains: Set[str] = []
if self.config.domains == "all":
domains = SUPPOERTED_DOMAINS
elif isinstance(self.config.domains, str):
if self.config.domains in SUPPOERTED_DOMAINS:
domains = {self.config.domains}
else:
raise ValueError(f"Unrecognized domain '{self.config.domains}'; only {SUPPOERTED_DOMAINS} are supported")
else:
domains = set(self.config.domains) & SUPPOERTED_DOMAINS
if len(domains) == 0:
raise ValueError(f"Unrecognized domains '{self.config.domains}'; only {SUPPOERTED_DOMAINS} are supported")
self.config.domains = domains
self.corpus_base_path = Path(dl_manager.download_and_extract(URL))
splits = [
datasets.SplitGenerator(
name=datasets.Split.TRAIN,
# These kwargs will be passed to _generate_examples
gen_kwargs={
"csv_fn": self.corpus_base_path / "train.csv",
},
),
datasets.SplitGenerator(
name=datasets.Split.VALIDATION,
# These kwargs will be passed to _generate_examples
gen_kwargs={
"csv_fn": self.corpus_base_path / "dev.csv",
},
),
datasets.SplitGenerator(
name=datasets.Split.TEST,
# These kwargs will be passed to _generate_examples
gen_kwargs={
"csv_fn": self.corpus_base_path / "test.csv",
},
),
]
if self.config.full_dataset:
splits = splits + [
# ##TODO change "reference_data.csv" to be in same format and add it to zip file
# datasets.SplitGenerator(
# name="gold_reference",
# # These kwargs will be passed to _generate_examples
# gen_kwargs={
# "csv_fn": self.corpus_base_path / "reference_data.csv",
# },
# ),
datasets.SplitGenerator(
name="propbank",
# These kwargs will be passed to _generate_examples
gen_kwargs={
"csv_fn": self.corpus_base_path / "propbank_comparison_data.csv",
},
),
]
return splits
def _generate_examples(self, csv_fn):
df = pd.read_csv(csv_fn)
for counter, row in df.iterrows():
yield counter, {
"sentence": row['Input.sentence'],
"sent_id": row['Input.qasrl_id'],
"predicate_idx": row['Input.adj_index_start'],
"predicate_idx_end": row['Input.adj_index_end'],
"predicate": row['Input.target'],
"object_question": self._get_optional_question(row.object_q),
"object_answer": self._get_optional_answer(row["Answer.answer1"]),
"domain_question": self._get_optional_question(row.domain_q),
"domain_answer": self._get_optional_answer(row["Answer.answer3"]),
"reference_question": self._get_optional_question(row.comparison_q),
"reference_answer": self._get_optional_answer(row["Answer.answer2"]),
"extent_question": self._get_optional_question(row.degree_q),
"extent_answer": self._get_optional_answer(row["Answer.answer4"]),
}
def _get_optional_answer(self, val):
if pd.isnull(val): # no answer
return []
else:
return val.split("+")
def _get_optional_question(self, val):
if pd.isnull(val): # no question
return ""
else:
return val