File size: 10,805 Bytes
256646e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# 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 QAMR (Question-Answer Meaning Representations) dataset (Michael et al., NAACL 2018)."""


import datasets
from pathlib import Path
import pandas as pd
from operator import itemgetter
from itertools import groupby

_CITATION = """\
@inproceedings{michael-etal-2018-crowdsourcing,
    title = "Crowdsourcing Question-Answer Meaning Representations",
    author = "Michael, Julian  and
      Stanovsky, Gabriel  and
      He, Luheng  and
      Dagan, Ido  and
      Zettlemoyer, Luke",
    booktitle = "Proceedings of the 2018 Conference of the North {A}merican Chapter of the Association for Computational Linguistics: Human Language Technologies, Volume 2 (Short Papers)",
    month = jun,
    year = "2018",
    address = "New Orleans, Louisiana",
    publisher = "Association for Computational Linguistics",
    url = "https://aclanthology.org/N18-2089",
    doi = "10.18653/v1/N18-2089",
    pages = "560--568",
    abstract = "We introduce Question-Answer Meaning Representations (QAMRs), which represent the predicate-argument structure of a sentence as a set of question-answer pairs. We develop a crowdsourcing scheme to show that QAMRs can be labeled with very little training, and gather a dataset with over 5,000 sentences and 100,000 questions. A qualitative analysis demonstrates that the crowd-generated question-answer pairs cover the vast majority of predicate-argument relationships in existing datasets (including PropBank, NomBank, and QA-SRL) along with many previously under-resourced ones, including implicit arguments and relations. We also report baseline models for question generation and answering, and summarize a recent approach for using QAMR labels to improve an Open IE system. These results suggest the freely available QAMR data and annotation scheme should support significant future work.",
}
"""


_DESCRIPTION = """\
Question-Answer Meaning Representations (QAMR) are a new paradigm for representing predicate-argument structure, which makes use of free-form questions and their answers in order to represent a wide range of semantic phenomena. 
The semantic expressivity of QAMR compares to (and in some cases exceeds) that of existing formalisms, while the representations can be annotated by non-experts (in particular, using crowdsourcing).
Formal Notes: 
* The `answer_ranges` feature here has a different meaning from that of the `qanom` and `qa_srl` datasets, although both are structured the same way; 
while in qasrl/qanom, each "answer range" (i.e. each span, represented as [begin-idx, end-idx]) stands for an independant answer which is read separately 
(e.g., "John Vincen", "head of marketing"), in this `qamr` dataset each question has a single answer who might be conposed of non-consecutive spans; 
 that is, all given spans should be read successively.
* Another difference is that the meaning of `predicate` in QAMR is different and softer than in QASRL/QANom - here, the predicate is not necessarily within the question, 
it can also be in the answer; it is generally what the annotator marked as the focus of the QA. 
"""

_HOMEPAGE = "https://github.com/uwnlp/qamr"

_LICENSE = """\
MIT License

Copyright (c) 2017 Julian Michael

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."""


_URLs = {
    "train": "https://github.com/uwnlp/qamr/raw/master/data/filtered/train.tsv",
    "dev": "https://github.com/uwnlp/qamr/raw/master/data/filtered/dev.tsv",
    "test": "https://github.com/uwnlp/qamr/raw/master/data/filtered/test.tsv",
    "ptb": "https://github.com/uwnlp/qamr/raw/master/data/filtered/ptb.tsv",
    "sentences": "https://github.com/uwnlp/qamr/raw/master/data/wiki-sentences.tsv",
}

TSV_COLUMNS = ["sentence_id", "target_words", "worker_id", "QA_id", "target_word_id", "question", "answer_indices", "validator_1_response", "validator_2_response"]

SpanFeatureType = datasets.Sequence(datasets.Value("int32"), length=2)

# helper func 
def consecutive_groups(iterable, ordering=lambda x: x):
    """ Adapted from the `more-itertools` package - 
    https://github.com/more-itertools/more-itertools/blob/ae32ef57502b9def6e2362cff43a453901fc1f4f/more_itertools/more.py#L2600
    """
    groups = []
    for k, g in groupby(
        enumerate(iterable), key=lambda x: x[0] - ordering(x[1])
    ):
        groups.append(list(map(itemgetter(1), g)))
    return groups


class Qamr(datasets.GeneratorBasedBuilder):
    """QAMR: Question-Answer Meaning Representations corpus"""

    VERSION = datasets.Version("1.0.0")

    BUILDER_CONFIGS = [
        datasets.BuilderConfig(
            name="plain_text", version=VERSION, description="This provides the filtered crowdsourced dataset for QAMR"
        ),
    ]

    DEFAULT_CONFIG_NAME = (
        "plain_text"  # It's not mandatory to have a default configuration. Just use one if it make sense.
    )

    def _info(self): #TODO
        features = datasets.Features(
            {
                "sentence": datasets.Value("string"),
                "sent_id": datasets.Value("string"),
                "predicate_idx": datasets.Value("int32"),
                "predicate": datasets.Value("string"),
                "question": datasets.Sequence(datasets.Value("string")),
                "answers": datasets.Sequence(datasets.Value("string")),
                "answer_ranges": datasets.Sequence(SpanFeatureType)
            }
        )
        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."""

        # iterate the tar file of the corpus
        
        # Older version of the corpus (has some format errors):
        # corpus_base_path = Path(dl_manager.download_and_extract(_URLs["qasrl_v2.0"]))
        # corpus_orig = corpus_base_path / "qasrl-v2" / "orig"        
        
        self.downloaded_files = {
            key: Path(dl_manager.download_and_extract(_URLs[key]))
            for key in _URLs
        } 
                
        return [
            datasets.SplitGenerator(
                name=datasets.Split.TRAIN,
                # These kwargs will be passed to _generate_examples
                gen_kwargs={
                    "filepath": self.downloaded_files["train"],
                },
            ),
            datasets.SplitGenerator(
                name=datasets.Split.VALIDATION,
                # These kwargs will be passed to _generate_examples
                gen_kwargs={
                    "filepath": self.downloaded_files["dev"],
                },
            ),
            datasets.SplitGenerator(
                name=datasets.Split.TEST,
                # These kwargs will be passed to _generate_examples
                gen_kwargs={
                    "filepath": self.downloaded_files["test"],
                },
            ),
        ]

    def _generate_examples(self, filepath):
        """ Yields QAMR examples (QAs) from a '.tsv' file ."""
        # merge sentence and create a map to raw-sentence from sentence-id 
        sent_df = pd.read_csv(self.downloaded_files["sentences"], sep='\t', names=["sentence_id", "sentence"])
        sent_id2sent = {r["sentence_id"]: r["sentence"] for _, r in sent_df.iterrows()}
        df = pd.read_csv(filepath, sep='\t', names=TSV_COLUMNS)
        for counter, row in df.iterrows():
            # Each record (row) in tsv is a QA 
            sentence = sent_id2sent[row.sentence_id]
            sent_tokens = sentence.split(" ")
            # TODO: split question to some slots? wh-question? question mark?
            question = [row.question]
            answer_tokens = [int(t) for t in row.answer_indices.split(" ")]
            answer_groups = consecutive_groups(answer_tokens) # list of lists-of-consecutive-indices
            answer_ranges = [[group[0], group[-1]+1] for group in answer_groups]    # make spans end-exclusive, to be inline with QASRL datasets
            answer = ' '.join(sent_tokens[tok_idx] for tok_idx in answer_tokens)
            
            yield counter, {
                "sentence": sentence,
                "sent_id": row.sentence_id,
                "predicate_idx": row.target_word_id,
                "predicate": sent_tokens[row.target_word_id],
                "question": question,
                "answers": [answer],
                "answer_ranges": answer_ranges
            }