qa_srl2020 / qa_srl2020.py
kleinay's picture
First version of qa_srl2020 datasets script
5e2e206
raw history blame
No virus
11.3 kB
# 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
}