File size: 11,308 Bytes
5e2e206
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# 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 QASRL-GS dataset (Roit et. al., ACL 2020)."""


import datasets
from pathlib import Path
from typing import List
import pandas as pd


_CITATION = """\
@inproceedings{roit2020controlled,
  title={Controlled Crowdsourcing for High-Quality QA-SRL Annotation},
  author={Roit, Paul and Klein, Ayal and Stepanov, Daniela and Mamou, Jonathan and Michael, Julian and Stanovsky, Gabriel and Zettlemoyer, Luke and Dagan, Ido},
  booktitle={Proceedings of the 58th Annual Meeting of the Association for Computational Linguistics},
  pages={7008--7013},
  year={2020}
}
"""


_DESCRIPTION = """\
The dataset contains question-answer pairs to model verbal predicate-argument structure. 
The questions start with wh-words (Who, What, Where, What, etc.) and contain a verb predicate in the sentence; the answers are phrases in the sentence.
This dataset, a.k.a "QASRL-GS" (Gold Standard) or "QASRL-2020", was constructed via controlled crowdsourcing.
See the paper for details: Controlled Crowdsourcing for High-Quality QA-SRL Annotation, Roit et. al., 2020 
"""

_HOMEPAGE = "https://github.com/plroit/qasrl-gs"

_LICENSE = """MIT License

Copyright (c) 2020 plroit

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 = {
    "sentences": {
        "wikinews.dev": "https://github.com/plroit/qasrl-gs/raw/master/data/sentences/wikinews.dev.full.csv",
        "wikinews.test": "https://github.com/plroit/qasrl-gs/raw/master/data/sentences/wikinews.test.full.csv",
        "wikipedia.dev": "https://github.com/plroit/qasrl-gs/raw/master/data/sentences/wikipedia.dev.full.csv",
        "wikipedia.test": "https://github.com/plroit/qasrl-gs/raw/master/data/sentences/wikipedia.test.full.csv",
    },
    "qasrl-annotations": {
        "wikinews.dev": "https://github.com/plroit/qasrl-gs/raw/master/data/gold/wikinews.dev.gold.csv",
        "wikinews.test": "https://github.com/plroit/qasrl-gs/raw/master/data/gold/wikinews.test.gold.csv",
        "wikipedia.dev": "https://github.com/plroit/qasrl-gs/raw/master/data/gold/wikipedia.dev.gold.csv",
        "wikipedia.test": "https://github.com/plroit/qasrl-gs/raw/master/data/gold/wikipedia.test.gold.csv",
    },        
}

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

# TODO: Name of the dataset usually match the script name with CamelCase instead of snake_case
class QaSrl2020(datasets.GeneratorBasedBuilder):
    """QA-SRL2020: Question-Answer driven SRL gold-standard dataset.
    Notice: This dataset genrally follows the format of `qa_srl` and `kleinay\qa_srl2018` datasets. 
    However, it extends Features to include "is_verbal" and "verb_form" fields, as in the `kleinay\qanom` dataset that accounts for nominalizations.
    Nevertheless these fields can be ignored, since for all data points in QASRL-2020, "is_verbal"==True and "verb_form" is equivalent to the "predicate" feature.  """

    VERSION = datasets.Version("1.0.0")

    BUILDER_CONFIGS = [
        datasets.BuilderConfig(
            name="plain_text", version=VERSION, description="This provides the QASRL-2020 (QASRL-GS) dataset"
        ),
    ]

    DEFAULT_CONFIG_NAME = (
        "plain_text"  # 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": datasets.Value("string"),
                "is_verbal": datasets.Value("bool"),
                "verb_form": 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 _prepare_wiktionary_verb_inflections(self, dl_manager):
        wiktionary_url = "https://raw.githubusercontent.com/nafitzgerald/nrl-qasrl/master/data/wiktionary/en_verb_inflections.txt"
        wiktionary_path = dl_manager.download(wiktionary_url)
        verb_map = {}
        with open(wiktionary_path, 'r', encoding="utf-8") as f:
            for l in f.readlines():
                inflections = l.strip().split('\t')
                stem, presentsingular3rd, presentparticiple, past, pastparticiple = inflections
                for inf in inflections:
                    verb_map[inf] = {"Stem" : stem, "PresentSingular3rd" : presentsingular3rd, "PresentParticiple":presentparticiple, "Past":past, "PastParticiple":pastparticiple}
        self.verb_inflections = verb_map 
                
    def _split_generators(self, dl_manager: datasets.utils.download_manager.DownloadManager):
        """Returns SplitGenerators."""            
        
        # prepare wiktionary for verb inflections inside 'self.verb_inflections'
        self._prepare_wiktionary_verb_inflections(dl_manager)
        
        # Download and prepare all files - keep same structure as _URLs 
        corpora = {data_type: {       
                section:  Path(dl_manager.download_and_extract(_URLs[data_type][section]))
                for section in _URLs[data_type] } 
            for data_type in _URLs
        }
        return [
            datasets.SplitGenerator(
                name=datasets.Split.VALIDATION,
                # These kwargs will be passed to _generate_examples
                gen_kwargs={
                    "qasrl_annotations_paths": [corpora["qasrl-annotations"]["wikinews.dev"], 
                                                corpora["qasrl-annotations"]["wikipedia.dev"]],
                    "sentences_paths": [corpora["sentences"]["wikinews.dev"],
                                        corpora["sentences"]["wikipedia.dev"]],
                },
            ),
            datasets.SplitGenerator(
                name=datasets.Split.TEST,
                # These kwargs will be passed to _generate_examples
                gen_kwargs={
                    "qasrl_annotations_paths": [corpora["qasrl-annotations"]["wikinews.test"], 
                                                corpora["qasrl-annotations"]["wikipedia.test"]],
                    "sentences_paths": [corpora["sentences"]["wikinews.test"],
                                        corpora["sentences"]["wikipedia.test"]],
                },
            ),
        ]

    @classmethod
    def span_from_str(cls, s:str):
        start, end = s.split(":")
        return [int(start), int(end)]
    
    def _generate_examples(self, qasrl_annotations_paths: List[str], sentences_paths: List[str]):

        """ Yields QASRL examples from a csv file in QASRL-2020/QANom format."""

        # merge sentence and create a map to raw-sentence from sentence-id 
        sent_df = pd.concat([pd.read_csv(fn) for fn in sentences_paths])
        qasrl_id2sent = {r["qasrl_id"]: r["sentence"] for _, r in sent_df.iterrows()}
        # merge annotations from sections 
        df = pd.concat([pd.read_csv(fn) for fn in qasrl_annotations_paths]).reset_index()
        for counter, row in df.iterrows():
            # Each record (row) in csv is a QA or is stating a predicate/non-predicate with no QAs
            sentence = qasrl_id2sent[row.qasrl_id]
            # Prepare question (slots)
            na_to_underscore = lambda s: "_" if pd.isna(s) else str(s)
            question = [] if pd.isna(row.question) else list(map(na_to_underscore, [
                    row.wh, row.aux, row.subj, row.verb_slot_inflection, row.obj, row.prep, row.obj2 
                ])) + ['?']
            # fix verb slot - replace with actual verb inflection, and prepend verb_prefix 
            if question:
                if row.verb in self.verb_inflections and not pd.isna(row.verb_slot_inflection):
                    verb_surface = self.verb_inflections[row.verb][row.verb_slot_inflection] 
                else:
                    verb_surface = row.verb
                if not pd.isna(row.verb_prefix):
                    verb_surface = row.verb_prefix + " " + verb_surface
                question[3] = verb_surface
            answers = [] if pd.isna(row.answer) else row.answer.split("~!~")
            answer_ranges = [] if pd.isna(row.answer_range) else [QaSrl2020.span_from_str(s) for s in row.answer_range.split("~!~")]
            
            yield counter, {
                "sentence": sentence,
                "sent_id": row.qasrl_id,
                "predicate_idx": row.verb_idx,
                "predicate": row.verb,
                "is_verbal": True,
                "verb_form": row.verb,
                "question": question,
                "answers": answers,
                "answer_ranges": answer_ranges
            }