|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
"""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" |
|
|
|
domains: Union[str, Iterable[str]] = "all" |
|
|
|
|
|
|
|
|
|
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" |
|
) |
|
|
|
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( |
|
|
|
description=_DESCRIPTION, |
|
|
|
features=features, |
|
|
|
|
|
|
|
supervised_keys=None, |
|
|
|
homepage=_HOMEPAGE, |
|
|
|
license=_LICENSE, |
|
|
|
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") |
|
|
|
|
|
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": |
|
|
|
self._prepare_wiktionary_verb_inflections(dl_manager) |
|
|
|
|
|
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, |
|
|
|
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, |
|
|
|
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, |
|
|
|
gen_kwargs={ |
|
"qasrl_annotations_paths": self.corpus_base_path / "qasrl-gs" / "dev.jsonl.gz", |
|
}, |
|
), |
|
datasets.SplitGenerator( |
|
name=datasets.Split.TEST, |
|
|
|
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'] |
|
|
|
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]] |
|
question_slots_in_order = [ |
|
question_slots["wh"], |
|
question_slots["aux"], |
|
question_slots["subj"], |
|
verb_surface, |
|
question_slots["obj"], |
|
empty_to_underscore(question_slots["prep"]), |
|
question_slots["obj2"], |
|
'?' |
|
] |
|
|
|
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_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.""" |
|
|
|
|
|
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()} |
|
|
|
df = pd.concat([pd.read_csv(fn) for fn in qasrl_annotations_paths]).reset_index() |
|
for counter, row in df.iterrows(): |
|
|
|
sentence = qasrl_id2sent[row.qasrl_id] |
|
|
|
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 |
|
])) + ['?'] |
|
|
|
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 |
|
} |
|
|