rongzhangibm commited on
Commit
aa494fd
1 Parent(s): 44df3a3

added script nq.py

Browse files
Files changed (1) hide show
  1. nq.py +209 -0
nq.py ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2020 The TensorFlow Datasets Authors and the HuggingFace Datasets Authors.
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
+
16
+ # Lint as: python3
17
+ """Natural Questions: A Benchmark for Question Answering Research."""
18
+
19
+
20
+ import html
21
+ import json
22
+ import re
23
+
24
+ import apache_beam as beam
25
+
26
+ import datasets
27
+
28
+
29
+ _CITATION = """
30
+ @article{47761,
31
+ title = {Natural Questions: a Benchmark for Question Answering Research},
32
+ author = {Tom Kwiatkowski and Jennimaria Palomaki and Olivia Redfield and Michael Collins and Ankur Parikh and Chris Alberti and Danielle Epstein and Illia Polosukhin and Matthew Kelcey and Jacob Devlin and Kenton Lee and Kristina N. Toutanova and Llion Jones and Ming-Wei Chang and Andrew Dai and Jakob Uszkoreit and Quoc Le and Slav Petrov},
33
+ year = {2019},
34
+ journal = {Transactions of the Association of Computational Linguistics}
35
+ }
36
+ """
37
+
38
+ _DESCRIPTION = """
39
+ The NQ corpus contains questions from real users, and it requires QA systems to
40
+ read and comprehend an entire Wikipedia article that may or may not contain the
41
+ answer to the question. The inclusion of real user questions, and the
42
+ requirement that solutions should read an entire page to find the answer, cause
43
+ NQ to be a more realistic and challenging task than prior QA datasets.
44
+ """
45
+
46
+ _URL = "https://ai.google.com/research/NaturalQuestions/dataset"
47
+
48
+ _BASE_DOWNLOAD_URL = "https://storage.googleapis.com/natural_questions/v1.0"
49
+ _DOWNLOAD_URLS = {
50
+ "train": ["%s/train/nq-train-%02d.jsonl.gz" % (_BASE_DOWNLOAD_URL, i) for i in range(50)],
51
+ "validation": ["%s/dev/nq-dev-%02d.jsonl.gz" % (_BASE_DOWNLOAD_URL, i) for i in range(5)],
52
+ }
53
+
54
+ _VERSION = datasets.Version("0.0.4")
55
+
56
+
57
+
58
+ class NaturalQuestionsV2(datasets.BeamBasedBuilder):
59
+ """Natural Questions: A Benchmark for Question Answering Research."""
60
+
61
+ BUILDER_CONFIGS = [
62
+ datasets.BuilderConfig(name="default", version=_VERSION),
63
+ datasets.BuilderConfig(name="dev", version=_VERSION, description="Only dev split"),
64
+ ]
65
+ DEFAULT_CONFIG_NAME = "default"
66
+
67
+ def _info(self):
68
+ return datasets.DatasetInfo(
69
+ description=_DESCRIPTION,
70
+ features=datasets.Features(
71
+ {
72
+ "id": datasets.Value("string"),
73
+ "document": {
74
+ "title": datasets.Value("string"),
75
+ "url": datasets.Value("string"),
76
+ "html": datasets.Value("string"),
77
+ "tokens": datasets.features.Sequence(
78
+ {"token": datasets.Value("string"), "is_html": datasets.Value("bool"),
79
+ "start_byte": datasets.Value("int64"), "end_byte": datasets.Value("int64")}
80
+ ),
81
+ },
82
+ "question": {
83
+ "text": datasets.Value("string"),
84
+ "tokens": datasets.features.Sequence(datasets.Value("string")),
85
+ },
86
+ "long_answer_candidates": datasets.features.Sequence(
87
+ {
88
+ "start_token": datasets.Value("int64"),
89
+ "end_token": datasets.Value("int64"),
90
+ "start_byte": datasets.Value("int64"),
91
+ "end_byte": datasets.Value("int64"),
92
+ "top_level": datasets.Value("bool"),
93
+ }
94
+ ),
95
+ "annotations": datasets.features.Sequence(
96
+ {
97
+ "id": datasets.Value("string"),
98
+ "long_answer": {
99
+ "start_token": datasets.Value("int64"),
100
+ "end_token": datasets.Value("int64"),
101
+ "start_byte": datasets.Value("int64"),
102
+ "end_byte": datasets.Value("int64"),
103
+ "candidate_index": datasets.Value("int64")
104
+ },
105
+ "short_answers": datasets.features.Sequence(
106
+ {
107
+ "start_token": datasets.Value("int64"),
108
+ "end_token": datasets.Value("int64"),
109
+ "start_byte": datasets.Value("int64"),
110
+ "end_byte": datasets.Value("int64"),
111
+ "text": datasets.Value("string"),
112
+ }
113
+ ),
114
+ "yes_no_answer": datasets.features.ClassLabel(
115
+ names=["NO", "YES"]
116
+ ), # Can also be -1 for NONE.
117
+ }
118
+ ),
119
+ }
120
+ ),
121
+ supervised_keys=None,
122
+ homepage=_URL,
123
+ citation=_CITATION,
124
+ )
125
+
126
+ def _split_generators(self, dl_manager, pipeline):
127
+ """Returns SplitGenerators."""
128
+ urls = _DOWNLOAD_URLS
129
+ if self.config.name == "dev":
130
+ urls = {"validation": urls["validation"]}
131
+ files = dl_manager.download(urls)
132
+ if not pipeline.is_local():
133
+ files = dl_manager.ship_files_with_pipeline(files, pipeline)
134
+ return [
135
+ datasets.SplitGenerator(
136
+ name=split,
137
+ gen_kwargs={"filepaths": files[split]},
138
+ )
139
+ for split in [datasets.Split.TRAIN, datasets.Split.VALIDATION]
140
+ if split in files
141
+ ]
142
+
143
+ def _build_pcollection(self, pipeline, filepaths):
144
+ """Build PCollection of examples."""
145
+
146
+ def _parse_example(line):
147
+ """Parse a single json line and emit an example dict."""
148
+ ex_json = json.loads(line)
149
+ html_bytes = ex_json["document_html"].encode("utf-8")
150
+
151
+ def _parse_short_answer(short_ans):
152
+ """Extract text of short answer."""
153
+ ans_bytes = html_bytes[short_ans["start_byte"] : short_ans["end_byte"]]
154
+ # Remove non-breaking spaces.
155
+ ans_bytes = ans_bytes.replace(b"\xc2\xa0", b" ")
156
+ text = ans_bytes.decode("utf-8")
157
+ # Remove HTML markup.
158
+ text = re.sub("<([^>]*)>", "", html.unescape(text))
159
+ # Replace \xa0 characters with spaces.
160
+ return {
161
+ "start_token": short_ans["start_token"],
162
+ "end_token": short_ans["end_token"],
163
+ "start_byte": short_ans["start_byte"],
164
+ "end_byte": short_ans["end_byte"],
165
+ "text": text,
166
+ }
167
+
168
+ def _parse_annotation(an_json):
169
+ return {
170
+ # Convert to str since some IDs cannot be represented by datasets.Value('int64').
171
+ "id": str(an_json["annotation_id"]),
172
+ "long_answer": {
173
+ "start_token": an_json["long_answer"]["start_token"],
174
+ "end_token": an_json["long_answer"]["end_token"],
175
+ "start_byte": an_json["long_answer"]["start_byte"],
176
+ "end_byte": an_json["long_answer"]["end_byte"],
177
+ "candidate_index": an_json["long_answer"]["candidate_index"]
178
+ },
179
+ "short_answers": [_parse_short_answer(ans) for ans in an_json["short_answers"]],
180
+ "yes_no_answer": (-1 if an_json["yes_no_answer"] == "NONE" else an_json["yes_no_answer"]),
181
+ }
182
+
183
+ beam.metrics.Metrics.counter("nq", "examples").inc()
184
+ # Convert to str since some IDs cannot be represented by datasets.Value('int64').
185
+ id_ = str(ex_json["example_id"])
186
+ return (
187
+ id_,
188
+ {
189
+ "id": id_,
190
+ "document": {
191
+ "title": ex_json["document_title"],
192
+ "url": ex_json["document_url"],
193
+ "html": ex_json["document_html"],
194
+ "tokens": [
195
+ {"token": t["token"], "is_html": t["html_token"], "start_byte": t["start_byte"], "end_byte": t["end_byte"]} for t in ex_json["document_tokens"]
196
+ ],
197
+ },
198
+ "question": {"text": ex_json["question_text"], "tokens": ex_json["question_tokens"]},
199
+ "long_answer_candidates": [lac_json for lac_json in ex_json["long_answer_candidates"]],
200
+ "annotations": [_parse_annotation(an_json) for an_json in ex_json["annotations"]],
201
+ },
202
+ )
203
+
204
+ return (
205
+ pipeline
206
+ | beam.Create(filepaths)
207
+ | beam.io.ReadAllFromText(compression_type=beam.io.textio.CompressionTypes.GZIP)
208
+ | beam.Map(_parse_example)
209
+ )