|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
"""Natural Questions: A Benchmark for Question Answering Research.""" |
|
|
|
|
|
import html |
|
import json |
|
import re |
|
|
|
import datasets |
|
|
|
|
|
_CITATION = """ |
|
@article{47761, |
|
title = {Natural Questions: a Benchmark for Question Answering Research}, |
|
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}, |
|
year = {2019}, |
|
journal = {Transactions of the Association of Computational Linguistics} |
|
} |
|
""" |
|
|
|
_DESCRIPTION = """ |
|
The NQ corpus contains questions from real users, and it requires QA systems to |
|
read and comprehend an entire Wikipedia article that may or may not contain the |
|
answer to the question. The inclusion of real user questions, and the |
|
requirement that solutions should read an entire page to find the answer, cause |
|
NQ to be a more realistic and challenging task than prior QA datasets. |
|
""" |
|
|
|
_URL = "https://ai.google.com/research/NaturalQuestions/dataset" |
|
|
|
_BASE_DOWNLOAD_URL = "https://storage.googleapis.com/natural_questions/v1.0" |
|
_DOWNLOAD_URLS = { |
|
"train": ["%s/train/nq-train-%02d.jsonl.gz" % (_BASE_DOWNLOAD_URL, i) for i in range(50)], |
|
"validation": ["%s/dev/nq-dev-%02d.jsonl.gz" % (_BASE_DOWNLOAD_URL, i) for i in range(5)], |
|
} |
|
|
|
_VERSION = datasets.Version("0.0.4") |
|
|
|
def _clean_token(token: dict): |
|
"""Returns token in which blanks are replaced with underscores. |
|
Adapted from https://github.com/google-research-datasets/natural-questions/blob/master/text_utils.py |
|
Args: |
|
token: Dictionary representation of token in original NQ format. |
|
Returns: |
|
String token. |
|
""" |
|
return re.sub("<([^>]*)>", "", html.unescape(re.sub(" ", "_", token["token"]))) |
|
|
|
def _clean_text(raw_text: bytes): |
|
"""Strips text of HTML-specific characters. |
|
Args: |
|
raw_text: Byte string |
|
Returns: |
|
String text. |
|
""" |
|
text = raw_text.replace(b"\xc2\xa0", b" ").decode("utf-8") |
|
return re.sub("<([^>]*)>", "", html.unescape(text)) |
|
|
|
def create_raw_instance(sample): |
|
""" |
|
Given an example in dataset format, create the prompt and the list of |
|
correct references. |
|
""" |
|
|
|
document = " ".join([_clean_token(t) for t in sample["document"]["tokens"]]) |
|
html_bytes = sample["document"]["html"].encode("utf-8") |
|
title = sample["title"] |
|
question = sample["question"]["text"] |
|
|
|
short_answers, long_answers = [], [] |
|
for ans_json in sample["annotations"]: |
|
long_ans = ans_json["long_answer"] |
|
long_ans = _clean_text(html_bytes[long_ans["start_byte"] : long_ans["end_byte"]]) |
|
|
|
for ans in ans_json["short_answers"]: |
|
short_ans = html_bytes[ans["start_byte"] : ans["end_byte"]] |
|
short_ans = _clean_text(short_ans) |
|
|
|
short_answers.append(short_ans) |
|
long_answers.append(long_ans) |
|
|
|
return {"title": title, |
|
"document": document, |
|
"question": question, |
|
"long_answers": long_answers, |
|
"short_answers": short_answers, |
|
} |
|
|
|
class NaturalQuestions(datasets.BeamBasedBuilder): |
|
"""Natural Questions: A Benchmark for Question Answering Research.""" |
|
|
|
BUILDER_CONFIGS = [ |
|
datasets.BuilderConfig(name="default", version=_VERSION), |
|
] |
|
DEFAULT_CONFIG_NAME = "default" |
|
|
|
def _info(self): |
|
return datasets.DatasetInfo( |
|
description=_DESCRIPTION, |
|
features=datasets.Features( |
|
{ |
|
"id": datasets.Value("string"), |
|
"title": datasets.Value("string"), |
|
"document": datasets.Value("string"), |
|
"question": datasets.Value("string"), |
|
"long_answers": datasets.features.Sequence(datasets.Value("string")), |
|
"short_answers": datasets.features.Sequence(datasets.Value("string")), |
|
} |
|
), |
|
supervised_keys=None, |
|
homepage=_URL, |
|
citation=_CITATION, |
|
) |
|
|
|
def _split_generators(self, dl_manager, pipeline): |
|
"""Returns SplitGenerators.""" |
|
urls = _DOWNLOAD_URLS |
|
files = dl_manager.download(urls) |
|
if not pipeline.is_local(): |
|
files = dl_manager.ship_files_with_pipeline(files, pipeline) |
|
return [ |
|
datasets.SplitGenerator( |
|
name=split, |
|
gen_kwargs={"filepaths": files[split]}, |
|
) |
|
for split in [datasets.Split.TRAIN, datasets.Split.VALIDATION] |
|
if split in files |
|
] |
|
|
|
def _build_pcollection(self, pipeline, filepaths): |
|
"""Build PCollection of examples.""" |
|
try: |
|
import apache_beam as beam |
|
except ImportError as err: |
|
raise ImportError( |
|
"To be able to load natural_questions, you need to install apache_beam: 'pip install apache_beam'" |
|
) from err |
|
|
|
def _parse_example(line): |
|
"""Parse a single json line and emit an example dict.""" |
|
ex_json = json.loads(line) |
|
html_bytes = ex_json["document_html"].encode("utf-8") |
|
|
|
def _parse_short_answer(short_ans): |
|
"""Extract text of short answer.""" |
|
ans_bytes = html_bytes[short_ans["start_byte"] : short_ans["end_byte"]] |
|
|
|
ans_bytes = ans_bytes.replace(b"\xc2\xa0", b" ") |
|
text = ans_bytes.decode("utf-8") |
|
|
|
text = re.sub("<([^>]*)>", "", html.unescape(text)) |
|
|
|
return { |
|
"start_token": short_ans["start_token"], |
|
"end_token": short_ans["end_token"], |
|
"start_byte": short_ans["start_byte"], |
|
"end_byte": short_ans["end_byte"], |
|
"text": text, |
|
} |
|
|
|
def _parse_annotation(an_json): |
|
return { |
|
|
|
"id": str(an_json["annotation_id"]), |
|
"long_answer": { |
|
"start_token": an_json["long_answer"]["start_token"], |
|
"end_token": an_json["long_answer"]["end_token"], |
|
"start_byte": an_json["long_answer"]["start_byte"], |
|
"end_byte": an_json["long_answer"]["end_byte"], |
|
"candidate_index": an_json["long_answer"]["candidate_index"], |
|
}, |
|
"short_answers": [_parse_short_answer(ans) for ans in an_json["short_answers"]], |
|
"yes_no_answer": (-1 if an_json["yes_no_answer"] == "NONE" else an_json["yes_no_answer"]), |
|
} |
|
|
|
beam.metrics.Metrics.counter("nq", "examples").inc() |
|
|
|
id_ = str(ex_json["example_id"]) |
|
sample = { |
|
"id": id_, |
|
"document": { |
|
"title": ex_json["document_title"], |
|
"url": ex_json["document_url"], |
|
"html": ex_json["document_html"], |
|
"tokens": [ |
|
{ |
|
"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"] |
|
], |
|
}, |
|
"question": {"text": ex_json["question_text"], "tokens": ex_json["question_tokens"]}, |
|
"long_answer_candidates": [lac_json for lac_json in ex_json["long_answer_candidates"]], |
|
"annotations": [_parse_annotation(an_json) for an_json in ex_json["annotations"]], |
|
} |
|
return id_, create_raw_instance(sample) |
|
|
|
return ( |
|
pipeline |
|
| beam.Create(filepaths) |
|
| beam.io.ReadAllFromText(compression_type=beam.io.textio.CompressionTypes.GZIP) |
|
| beam.Map(_parse_example) |
|
) |
|
|