File size: 12,884 Bytes
2fc81ec |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 |
import glob
import json
import os
from io import BytesIO
import ijson
import more_itertools
import pandas as pd
import datasets
from datasets import Dataset, DatasetDict, DatasetInfo, Features, Sequence, Value
logger = datasets.logging.get_logger(__name__)
# _URL = "https://www.cs.tau.ac.il/~ohadr/NatQuestions.zip"
# RERANKING_URLS = {
# "train": "https://dl.fbaipublicfiles.com/dpr/data/retriever/biencoder-nq-train.json.gz",
# "validation": "https://dl.fbaipublicfiles.com/dpr/data/retriever/biencoder-nq-dev.json.gz",
# # "test": "https://dl.fbaipublicfiles.com/dpr/data/retriever/nq-test.qa.csv",
# }
from tqdm.auto import tqdm
_CITATION = """ """
_DESCRIPTION = """ """
# def
# def read_glob(paths):
# paths = glob.glob(paths)
# data = []
# for path in paths:
# with open(path) as f:
# if path.endswith(".json"):
# data.extend(json.load(f))
# elif path.endswith(".jsonl"):
# for line in f:
# data.append(json.loads(line))
# return data
def to_dict_element(el, cols):
bucked_fields = more_itertools.bucket(cols, key=lambda x: x.split(".")[0])
final_dict = {}
for parent_name in list(bucked_fields):
fields = [y.split(".")[-1] for y in list(bucked_fields[parent_name])]
if len(fields) == 1 and fields[0] == parent_name:
final_dict[parent_name] = el[fields[0]]
else:
parent_list = []
zipped_fields = list(zip(*[el[f"{parent_name}.{child}"] for child in fields]))
for x in zipped_fields:
parent_list.append({k: v for k, v in zip(fields, x)})
final_dict[parent_name] = parent_list
return final_dict
def get_json_dataset(dataset):
flat_dataset = dataset.flatten()
json_dataset = dataset_to_json(flat_dataset)
return [to_dict_element(el, cols=flat_dataset.column_names) for el in json_dataset]
def dataset_to_json(dataset):
new_str = BytesIO()
dataset.to_json(new_str)
new_str.seek(0)
return [json.loads(line.decode()) for line in new_str]
# inference_features = datasets.Features(
# {
# "source": Value(dtype="string"),
# "meta": {
# "question": Value(dtype="string"),
# "text": Value(dtype="string"),
# "title": Value(dtype="string"),
# "qid": Value(dtype="string"),
# "id": Value(dtype="string"),
# },
# }
# )
class NatQuestionsConfig(datasets.BuilderConfig):
"""BuilderConfig for NatQuestionsDPR."""
def __init__(self, features, retriever, feature_format, url, **kwargs):
"""BuilderConfig for NatQuestions.
Args:
**kwargs: keyword arguments forwarded to super.
"""
super(NatQuestionsConfig, self).__init__(**kwargs)
self.features = features
self.retriever = retriever
self.feature_format = feature_format
self.url = url
RETBM25_RERANKING_URLS = {
split: f"https://dl.fbaipublicfiles.com/dpr/data/retriever/biencoder-nq-{split}.json.gz"
for split in ["train", "dev"]
}
RETDPR_RERANKING_URLS = {
split: f"https://dl.fbaipublicfiles.com/dpr/data/retriever/biencoder-nq-adv-hn-{split}.json.gz"
for split in ["train"]
}
RETDPR_INF_URLS = {
split: f"https://dl.fbaipublicfiles.com/dpr/data/retriever_results/single/nq-{split}.json.gz"
for split in ["train", "dev", "test"]
}
RETBM25_INF_URLS = {
split:f"https://www.cs.tau.ac.il/~ohadr/nq-{split}.json.gz" for split in ["dev","test"]
}
RETBM25_RERANKING_features = Features(
{
"dataset": Value(dtype="string"),
"qid": Value(dtype="string"),
"question": Value(dtype="string"),
"answers": Sequence(feature=Value(dtype="string")),
"positive_ctxs": Sequence(
feature={
"title": Value(dtype="string"),
"text": Value(dtype="string"),
"score": Value(dtype="float32"),
# 'title_score': Value(dtype='int32'),
"passage_id": Value(dtype="string"),
}
),
# 'negative_ctxs': Sequence(feature={'title': Value(dtype='string'),
# 'text': Value(dtype='string'),
# 'score': Value(dtype='float32'),
# # 'title_score': Value(dtype='int32'),
# 'passage_id': Value(dtype='string')}),
"hard_negative_ctxs": Sequence(
feature={
"title": Value(dtype="string"),
"text": Value(dtype="string"),
"score": Value(dtype="float32"),
# 'title_score': Value(dtype='int32'),
"passage_id": Value(dtype="string"),
}
),
}
)
RETDPR_RERANKING_features = Features(
{
"qid": Value(dtype="string"),
"question": Value(dtype="string"),
"answers": Sequence(feature=Value(dtype="string")),
# 'negative_ctxs': Sequence(feature=[]),
"hard_negative_ctxs": Sequence(
feature={
"passage_id": Value(dtype="string"),
"title": Value(dtype="string"),
"text": Value(dtype="string"),
"score": Value(dtype="string"),
# 'has_answer': Value(dtype='int32')
}
),
"positive_ctxs": Sequence(
feature={
"title": Value(dtype="string"),
"text": Value(dtype="string"),
"score": Value(dtype="float32"),
# 'title_score': Value(dtype='int32'),
# 'has_answer': Value(dtype='int32'),
"passage_id": Value(dtype="string"),
}
),
}
)
RETDPR_INF_features = Features(
{
"question": Value(dtype="string"),
"qid": Value(dtype="string"),
"answers": Sequence(feature=Value(dtype="string")),
"ctxs": Sequence(
feature={
"id": Value(dtype="string"),
"title": Value(dtype="string"),
"text": Value(dtype="string"),
"score": Value(dtype="float32"),
# "has_answer": Value(dtype="int32"),
}
),
}
)
URL_DICT = {"reranking_dprnq":RETDPR_RERANKING_URLS,
"reranking_bm25":RETBM25_RERANKING_URLS,
"inference_dprnq":RETDPR_INF_URLS}
class NatQuestions(datasets.GeneratorBasedBuilder):
BUILDER_CONFIGS = [
NatQuestionsConfig(
name="reranking_dprnq",
version=datasets.Version("1.0.1", ""),
description="NatQuestions dataset in DPR format with the dprnq retrieval results",
features=RETDPR_RERANKING_features,
retriever="dprnq",
feature_format="dpr",
url=URL_DICT,
),
NatQuestionsConfig(
name="reranking_bm25",
version=datasets.Version("1.0.1", ""),
description="NatQuestions dataset in DPR format with the bm25 retrieval results",
features=RETBM25_RERANKING_features,
retriever="bm25",
feature_format="dpr",
url=URL_DICT,
),
NatQuestionsConfig(
name="inference_dprnq",
version=datasets.Version("1.0.1", ""),
description="NatQuestions dataset in a format accepted by the inference model, performing reranking on the dprnq retrieval results",
features=RETDPR_INF_features,
retriever="dprnq",
feature_format="inference",
url=URL_DICT,
),
NatQuestionsConfig(
name="inference_bm25",
version=datasets.Version("1.0.1", ""),
description="NatQuestions dataset in a format accepted by the inference model, performing reranking on the bm25 retrieval results",
features=RETDPR_INF_features,
retriever="bm25",
feature_format="inference",
url=URL_DICT,
),
]
def _info(self):
self.features = self.config.features
self.retriever = self.config.retriever
self.feature_format = self.config.feature_format
self.url = self.config.url
return datasets.DatasetInfo(
description=_DESCRIPTION,
features=self.config.features,
supervised_keys=None,
homepage="",
citation=_CITATION,
)
def _split_generators(self, dl_manager):
print(self.url)
if len(self.url) > 0:
filepath = dl_manager.download_and_extract(self.url)
else:
filepath = ""
# filepath = "/home/joberant/home/ohadr/testbed/notebooks/NatQuestions_retrievers"
result = []
if "train" in filepath[self.info.config_name]:
result.append(
datasets.SplitGenerator(
name=datasets.Split.TRAIN,
gen_kwargs={"filepath": filepath, "split": "train"},
)
)
if "dev" in filepath[self.info.config_name] or self.info.config_name=="reranking_dprnq":
result.append(
datasets.SplitGenerator(
name=datasets.Split.VALIDATION,
gen_kwargs={"filepath": filepath, "split": "dev"},
)
)
if "test" in filepath[self.info.config_name] or self.info.config_name=="reranking_dprnq":
result.append(
datasets.SplitGenerator(
name=datasets.Split.TEST,
gen_kwargs={"filepath": filepath, "split": "test"},
)
)
return result
def _prepare_split(self, split_generator, **kwargs):
self.info.features = self.config.features
super()._prepare_split(split_generator, **kwargs)
def _generate_examples(self, filepath, split):
if self.info.config_name=="reranking_dprnq" and split in ["dev","test"]:
for i,dict_element in new_method(split, "inference_dprnq", f"{filepath['inference_dprnq'][split]}"):
dict_element['positive_ctxs'] = []
answers = dict_element['answers']
any_true = False
for x in dict_element['ctxs']:
x['passage_id'] = x.pop('id')
x['has_answer'] = False
for ans in answers:
if ans in x['title'] or ans in x['text']:
if 'id' in x:
x['passage_id'] = x.pop('id')
x['has_answer'] = True
dict_element['positive_ctxs'].append(x)
any_true = True
negative_candidates = [x for x in dict_element['ctxs'] if not x['has_answer']]
dict_element['hard_negative_ctxs'] = negative_candidates[:len(dict_element['positive_ctxs'])]
dict_element['ctxs'] = dict_element.pop("ctxs")
for name in ['positive_ctxs',"hard_negative_ctxs"]:
for x in dict_element[name]:
x.pop("has_answer",None)
if any_true:
dict_element.pop("ctxs")
yield i,dict_element
else:
yield from new_method(split, self.info.config_name, f"{filepath[self.info.config_name][split]}")
def new_method(split, config_name, object_path):
count = 0
with open(object_path) as f:
items = ijson.items(f, "item")
for element in items:
element.pop("negative_ctxs",None)
for name in ["positive_ctxs","hard_negative_ctxs","ctxs"]:
for x in element.get(name,[]):
x.pop("title_score",None)
x.pop("has_answer", None)
if "reranking" in config_name and "id" in x:
x["passage_id"] = x.pop("id")
element["qid"] = f"{count}_{split}"
yield count, element
count += 1
# def single_inference_format_example(ctx, question, qid):
# datum = {}
# datum["source"] = f"Title: {ctx['meta']['title']}\nText: {ctx['meta']['content']}\nQuestion: {question}\n"
# datum["meta"] = {}
# datum["meta"]["question"] = question
# datum["meta"]["qid"] = qid
# datum["meta"]["title"] = ctx["meta"]["title"]
# datum["meta"]["text"] = ctx["meta"]["content"]
# datum["meta"]["id"] = ctx["id"]
# return datum
# def inference_format_example(element):
# return [
# single_inference_format_example(ctx, element["proof"], element["pid"]) for ctx in element["query_res"]
# ]
# def inference_example(example):
|