File size: 17,519 Bytes
5e2e206
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b9d1f15
5e2e206
250af51
5e2e206
b9d1f15
 
 
5e2e206
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b9d1f15
 
 
 
 
 
 
 
 
 
 
 
 
5e2e206
b9d1f15
5e2e206
 
 
 
250af51
 
b9d1f15
 
 
 
250af51
 
 
 
b9d1f15
 
5e2e206
 
 
 
 
 
80e6b8c
b9d1f15
 
5e2e206
 
b9d1f15
 
 
 
 
 
 
 
 
 
5e2e206
 
 
 
b9d1f15
5e2e206
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b9d1f15
250af51
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b9d1f15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
250af51
 
 
 
b9d1f15
 
 
 
 
 
250af51
 
 
 
b9d1f15
 
 
5e2e206
b9d1f15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5e2e206
b9d1f15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
250af51
 
 
 
 
b9d1f15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
250af51
b9d1f15
 
 
 
 
 
 
 
 
 
 
5e2e206
 
 
 
 
b9d1f15
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
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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
# 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 dataclasses import dataclass
from pathlib import Path
from typing import List, Tuple, Union, Set, Iterable
import pandas as pd
import json
import gzip
import itertools


_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 = {
    "csv": {
        "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",
        }, 
    },
    "jsonl": "https://qasrl.org/data/qasrl-gs.tar"       
}

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

SUPPOERTED_DOMAINS = {"wikinews", "wikipedia"}

@dataclass
class QASRL2020BuilderConfig(datasets.BuilderConfig):
    """ Allow the loader to re-distribute the original dev and test splits between train, dev and test. """
    load_from: str = "jsonl" # "csv" or "jsonl"
    
    domains: Union[str, Iterable[str]] = "all" # can provide also a subset of acceptable domains.
    # Acceptable domains are {"wikipedia", "wikinews"} for dev and test (qasrl-2020)
    # and {"wikipedia", "wikinews", "TQA"} for train (qasrl-2018)
 

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.2.0")
    
    BUILDER_CONFIG_CLASS = QASRL2020BuilderConfig

    BUILDER_CONFIGS = [
        QASRL2020BuilderConfig(
            name="default", version=VERSION, description="This provides the QASRL-2020 (QASRL-GS) dataset"
        ),
        QASRL2020BuilderConfig(
            name="csv", version=VERSION, description="This provides the QASRL-2020 (QASRL-GS) dataset",
            load_from="csv"
        ),
        QASRL2020BuilderConfig(
            name="jsonl", version=VERSION, description="This provides the QASRL-2020 (QASRL-GS) dataset",
            load_from="jsonl"
        ),
    ]

    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": 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."""            
        assert self.config.load_from in ("csv", "jsonl")
        
        # 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
        

        if self.config.load_from == "csv":
            # 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 
            URLs = _URLs["csv"]
            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"][f"{domain}.dev"] 
                                                    for domain in domains],
                        "sentences_paths": [corpora["sentences"][f"{domain}.dev"]
                                            for domain in domains],
                    },
                ),
                datasets.SplitGenerator(
                    name=datasets.Split.TEST,
                    # These kwargs will be passed to _generate_examples
                    gen_kwargs={
                        "qasrl_annotations_paths": [corpora["qasrl-annotations"][f"{domain}.test"] 
                                                    for domain in domains],
                        "sentences_paths": [corpora["sentences"][f"{domain}.test"]
                                            for domain in domains],
                    },
                ),
            ]
        
        elif self.config.load_from == "jsonl":
            self.corpus_base_path = Path(dl_manager.download_and_extract(_URLs["jsonl"]))        
            return [
                datasets.SplitGenerator(
                    name=datasets.Split.VALIDATION,
                    # These kwargs will be passed to _generate_examples
                    gen_kwargs={
                        "qasrl_annotations_paths": self.corpus_base_path / "qasrl-gs" / "dev.jsonl.gz",
                    },
                ),
                datasets.SplitGenerator(
                    name=datasets.Split.TEST,
                    # These kwargs will be passed to _generate_examples
                    gen_kwargs={
                        "qasrl_annotations_paths": self.corpus_base_path / "qasrl-gs" / "test.jsonl.gz",
                    },
                ),
            ]
   

    def _generate_examples(self, qasrl_annotations_paths: List[str], sentences_paths: List[str] = None):
        if self.config.load_from == "csv":
            return self._generate_examples_from_csv(qasrl_annotations_paths, sentences_paths)
        elif self.config.load_from == "jsonl": 
            return self._generate_examples_from_jsonl(qasrl_annotations_paths)

    def _generate_examples_from_jsonl(self, qasrl_annotations_path):
        """ Yields examples from a jsonl.gz file, in same format as qasrl-v2."""
        empty_to_underscore = lambda s: "_" if s=="" else s
        with gzip.open(qasrl_annotations_path, "rt") as f:
            qa_counter = 0
            for line in f:
                sent_obj = json.loads(line.strip())
                tokens = sent_obj['sentenceTokens']
                sentence = ' '.join(tokens)
                sent_id = sent_obj['sentenceId']
                # consider only selected domains
                sent_domain = sent_id.split(":")[1]
                if sent_domain not in self.config.domains:
                    continue
                for predicate_idx, verb_obj in sent_obj['verbEntries'].items():
                    verb_forms = verb_obj['verbInflectedForms']
                    predicate = tokens[int(predicate_idx)]
                    for question_obj in verb_obj['questionLabels'].values():
                        question_slots = question_obj['questionSlots']
                        verb_form = question_slots['verb'] 
                        verb_surface = verb_forms[verb_form.split(" ")[-1]] # if verb_form in verb_forms else verb_forms['stem']
                        question_slots_in_order = [
                            question_slots["wh"],
                            question_slots["aux"],
                            question_slots["subj"],                            
                            verb_surface,
                            question_slots["obj"],
                            empty_to_underscore(question_slots["prep"]), # fix bug in data
                            question_slots["obj2"],
                            '?'
                        ] 
                        # retrieve answers
                        answer_spans = []
                        for ans in question_obj['answerJudgments']:
                            if ans['isValid']: 
                                answer_spans.extend(ans['spans']) 
                        answer_spans = list(set(tuple(a) for a in answer_spans))
                        # answer_spans = list(set(answer_spans))
                        answer_strs = [' '.join([tokens[i] for i in range(*span)])
                                    for span in answer_spans]
                        
                        yield qa_counter, {
                            "sentence": sentence,
                            "sent_id": sent_id,
                            "predicate_idx": predicate_idx,
                            "predicate": predicate,
                            "is_verbal": True,
                            "verb_form": verb_forms['stem'],
                            "question": question_slots_in_order,
                            "answers": answer_strs,
                            "answer_ranges": answer_spans
                        }
                        qa_counter += 1
              
                
    @classmethod
    def span_from_str(cls, s:str):
        start, end = s.split(":")
        return [int(start), int(end)]
    
    def _generate_examples_from_csv(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
            }