File size: 9,227 Bytes
34b2b51
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# 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