kleinay commited on
Commit
b0b4dd0
1 Parent(s): cfd2994

First version of qanom datasets script

Browse files
Files changed (1) hide show
  1. qanom.py +211 -0
qanom.py ADDED
@@ -0,0 +1,211 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2020 The HuggingFace Datasets Authors and the current dataset script contributor.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """A Dataset loading script for the QANom dataset (klein et. al., COLING 2000)."""
16
+
17
+
18
+ import datasets
19
+ from pathlib import Path
20
+ import pandas as pd
21
+
22
+
23
+ _CITATION = """\
24
+ @inproceedings{klein2020qanom,
25
+ title={QANom: Question-Answer driven SRL for Nominalizations},
26
+ author={Klein, Ayal and Mamou, Jonathan and Pyatkin, Valentina and Stepanov, Daniela and He, Hangfeng and Roth, Dan and Zettlemoyer, Luke and Dagan, Ido},
27
+ booktitle={Proceedings of the 28th International Conference on Computational Linguistics},
28
+ pages={3069--3083},
29
+ year={2020}
30
+ }
31
+ """
32
+
33
+
34
+ _DESCRIPTION = """\
35
+ The dataset contains question-answer pairs to model predicate-argument structure of deverbal nominalizations.
36
+ The questions start with wh-words (Who, What, Where, What, etc.) and contain a the verbal form of a nominalization from the sentence;
37
+ the answers are phrases in the sentence.
38
+ See the paper for details: QANom: Question-Answer driven SRL for Nominalizations (Klein et. al., COLING 2020)
39
+ For previewing the QANom data along with the verbal annotations of QASRL, check out "https://browse.qasrl.org/".
40
+ This dataset was annotated by selected workers from Amazon Mechanical Turk.
41
+ """
42
+
43
+ _HOMEPAGE = "https://github.com/kleinay/QANom"
44
+
45
+ _LICENSE = """MIT License
46
+
47
+ Copyright (c) 2020 Ayal Klein (kleinay)
48
+
49
+ Permission is hereby granted, free of charge, to any person obtaining a copy
50
+ of this software and associated documentation files (the "Software"), to deal
51
+ in the Software without restriction, including without limitation the rights
52
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
53
+ copies of the Software, and to permit persons to whom the Software is
54
+ furnished to do so, subject to the following conditions:
55
+
56
+ The above copyright notice and this permission notice shall be included in all
57
+ copies or substantial portions of the Software.
58
+
59
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
60
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
61
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
62
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
63
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
64
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
65
+ SOFTWARE."""
66
+
67
+
68
+ _URLs = {
69
+ "qanom_zip": "https://github.com/kleinay/QANom/raw/master/qanom_dataset.zip"
70
+ }
71
+
72
+ SpanFeatureType = datasets.Sequence(datasets.Value("int32"), length=2)
73
+
74
+ # TODO: Name of the dataset usually match the script name with CamelCase instead of snake_case
75
+ class Qanom(datasets.GeneratorBasedBuilder):
76
+ """QANom: Question-Answer driven SRL for Nominalizations corpus.
77
+ Notice: This datasets genrally follows the format of `qa_srl` and `kleinay\qa_srl2018` datasets.
78
+ However, it extends Features to include "is_verbal" and "verb_form" fields (required for nominalizations).
79
+ In addition, and most critically, unlike these verbal qasrl datasets, in the qanom datset some examples
80
+ are for canidate nominalization which are judged to be non-predicates ("is_verbal"==False) or predicates with no QAs.
81
+ In these cases, the qa fields (question, answers, answer_ranges) would be empty lists. """
82
+
83
+ VERSION = datasets.Version("1.0.0")
84
+
85
+ BUILDER_CONFIGS = [
86
+ datasets.BuilderConfig(
87
+ name="plain_text", version=VERSION, description="This provides the QANom dataset"
88
+ ),
89
+ ]
90
+
91
+ DEFAULT_CONFIG_NAME = (
92
+ "plain_text" # It's not mandatory to have a default configuration. Just use one if it make sense.
93
+ )
94
+
95
+ def _info(self):
96
+ features = datasets.Features(
97
+ {
98
+ "sentence": datasets.Value("string"),
99
+ "sent_id": datasets.Value("string"),
100
+ "predicate_idx": datasets.Value("int32"),
101
+ "predicate": datasets.Value("string"),
102
+ "is_verbal": datasets.Value("bool"),
103
+ "verb_form": datasets.Value("string"),
104
+ "question": datasets.Sequence(datasets.Value("string")),
105
+ "answers": datasets.Sequence(datasets.Value("string")),
106
+ "answer_ranges": datasets.Sequence(SpanFeatureType)
107
+ }
108
+ )
109
+ return datasets.DatasetInfo(
110
+ # This is the description that will appear on the datasets page.
111
+ description=_DESCRIPTION,
112
+ # This defines the different columns of the dataset and their types
113
+ features=features, # Here we define them above because they are different between the two configurations
114
+ # If there's a common (input, target) tuple from the features,
115
+ # specify them here. They'll be used if as_supervised=True in
116
+ # builder.as_dataset.
117
+ supervised_keys=None,
118
+ # Homepage of the dataset for documentation
119
+ homepage=_HOMEPAGE,
120
+ # License for the dataset if available
121
+ license=_LICENSE,
122
+ # Citation for the dataset
123
+ citation=_CITATION,
124
+ )
125
+
126
+ def _prepare_wiktionary_verb_inflections(self, dl_manager):
127
+ wiktionary_url = "https://raw.githubusercontent.com/nafitzgerald/nrl-qasrl/master/data/wiktionary/en_verb_inflections.txt"
128
+ wiktionary_path = dl_manager.download(wiktionary_url)
129
+ verb_map = {}
130
+ with open(wiktionary_path, 'r', encoding="utf-8") as f:
131
+ for l in f.readlines():
132
+ inflections = l.strip().split('\t')
133
+ stem, presentsingular3rd, presentparticiple, past, pastparticiple = inflections
134
+ for inf in inflections:
135
+ verb_map[inf] = {"Stem" : stem, "PresentSingular3rd" : presentsingular3rd, "PresentParticiple":presentparticiple, "Past":past, "PastParticiple":pastparticiple}
136
+ self.verb_inflections = verb_map
137
+
138
+ def _split_generators(self, dl_manager: datasets.utils.download_manager.DownloadManager):
139
+ """Returns SplitGenerators."""
140
+
141
+ # prepare wiktionary for verb inflections inside 'self.verb_inflections'
142
+ self._prepare_wiktionary_verb_inflections(dl_manager)
143
+
144
+ corpus_base_path = Path(dl_manager.download_and_extract(_URLs["qanom_zip"]))
145
+
146
+ return [
147
+ datasets.SplitGenerator(
148
+ name=datasets.Split.TRAIN,
149
+ # These kwargs will be passed to _generate_examples
150
+ gen_kwargs={
151
+ "filepath": corpus_base_path / "annot.train.csv",
152
+ },
153
+ ),
154
+ datasets.SplitGenerator(
155
+ name=datasets.Split.VALIDATION,
156
+ # These kwargs will be passed to _generate_examples
157
+ gen_kwargs={
158
+ "filepath": corpus_base_path / "annot.dev.csv",
159
+ },
160
+ ),
161
+ datasets.SplitGenerator(
162
+ name=datasets.Split.TEST,
163
+ # These kwargs will be passed to _generate_examples
164
+ gen_kwargs={
165
+ "filepath": corpus_base_path / "annot.test.csv",
166
+ },
167
+ ),
168
+ ]
169
+
170
+ @classmethod
171
+ def span_from_str(cls, s:str):
172
+ start, end = s.split(":")
173
+ return [int(start), int(end)]
174
+
175
+ def _generate_examples(self, filepath):
176
+
177
+ """ Yields examples from a 'annot.?.csv' file in QANom's format."""
178
+
179
+ df = pd.read_csv(filepath)
180
+ for counter, row in df.iterrows():
181
+ # Each record (row) in csv is a QA or is stating a predicate/non-predicate with no QAs
182
+
183
+ # Prepare question (slots)
184
+ na_to_underscore = lambda s: "_" if pd.isna(s) else str(s)
185
+ question = [] if pd.isna(row.question) else list(map(na_to_underscore, [
186
+ row.wh, row.aux, row.subj, row.verb_slot_inflection, row.obj, row.prep, row.obj2
187
+ ])) + ['?']
188
+ # fix verb slot - replace with actual verb inflection, and prepend verb_prefix
189
+ if question:
190
+ if row.verb_form in self.verb_inflections and not pd.isna(row.verb_slot_inflection):
191
+ verb_surface = self.verb_inflections[row.verb_form][row.verb_slot_inflection]
192
+ else:
193
+ verb_surface = row.verb_form
194
+ if not pd.isna(row.verb_prefix):
195
+ verb_surface = row.verb_prefix + " " + verb_surface
196
+ question[3] = verb_surface
197
+ answers = [] if pd.isna(row.answer) else row.answer.split("~!~")
198
+ answer_ranges = [] if pd.isna(row.answer_range) else [Qanom.span_from_str(s) for s in row.answer_range.split("~!~")]
199
+
200
+ yield counter, {
201
+ "sentence": row.sentence,
202
+ "sent_id": row.qasrl_id,
203
+ "predicate_idx": row.target_idx,
204
+ "predicate": row.noun,
205
+ "is_verbal": row.is_verbal,
206
+ "verb_form": row.verb_form,
207
+ "question": question,
208
+ "answers": answers,
209
+ "answer_ranges": answer_ranges
210
+ }
211
+