|
""" Script to prepare the SQuAD2.0 data to the GEM format |
|
|
|
@author: AbinayaM02 |
|
""" |
|
|
|
|
|
import json |
|
import pandas as pd |
|
from sklearn.model_selection import train_test_split |
|
|
|
|
|
def add_gem_id(data: dict, split: str) -> dict: |
|
""" |
|
Add gem id for each of the datapoint in the dataset. |
|
|
|
Parameters: |
|
----------- |
|
data: dict, |
|
data. |
|
split: str, |
|
split of data (train, test or validation). |
|
|
|
Returns: |
|
-------- |
|
dict |
|
dictionary with updated id |
|
""" |
|
gem_id = -1 |
|
generated_data = {"data": []} |
|
for example in data: |
|
temp_dict = {} |
|
title = example["title"] |
|
for paragraph in example["paragraphs"]: |
|
context = paragraph["context"] |
|
for qa in paragraph["qas"]: |
|
question = qa["question"] |
|
qa_id = qa["id"] |
|
answer_starts = [answer["answer_start"] for answer in qa["answers"]] |
|
answers = [answer["text"] for answer in qa["answers"]] |
|
|
|
|
|
gem_id += 1 |
|
temp_dict["id"] = qa_id |
|
temp_dict["gem_id"] = f"gem-squad_v2-{split}-{gem_id}" |
|
temp_dict["title"] = title |
|
temp_dict["context"] = context |
|
temp_dict["question"] = question |
|
temp_dict["answers"] = { |
|
"answer_start": answer_starts, |
|
"text": answers, |
|
} |
|
generated_data["data"].append(temp_dict) |
|
return generated_data |
|
|
|
|
|
|
|
def split_data(file_name: str, data_type: str) -> (dict, dict): |
|
""" |
|
Method to split the data specific to SQuAD2.0 |
|
|
|
Parameters: |
|
----------- |
|
file_name: str, |
|
name of the file. |
|
data_type: str, |
|
type of the data file. |
|
|
|
Returns: |
|
-------- |
|
(dict, dict) |
|
split of data |
|
""" |
|
|
|
if data_type == "json": |
|
with open(file_name, 'r') as json_file: |
|
data = json.load(json_file)["data"] |
|
json_file.close() |
|
|
|
|
|
train, test = train_test_split(data, train_size=0.7, random_state = 42) |
|
return(train, test) |
|
|
|
|
|
if __name__ == "__main__": |
|
|
|
train, test = split_data("squad_data/train-v2.0.json", "json") |
|
|
|
|
|
train = add_gem_id(train, "train") |
|
test = add_gem_id(test, "test") |
|
|
|
|
|
with open("train.json", "w") as train_file: |
|
json.dump(train, train_file, indent = 2) |
|
train_file.close() |
|
|
|
|
|
with open("test.json", "w") as test_file: |
|
json.dump(test, test_file, indent = 2) |
|
test_file.close() |
|
|
|
|
|
with open("squad_data/dev-v2.0.json", "r") as dev_file: |
|
validation = json.load(dev_file)["data"] |
|
dev_file.close() |
|
|
|
|
|
validation = add_gem_id(validation, "validation") |
|
with open("valid.json", "w") as val_file: |
|
json.dump(validation, val_file, indent = 2) |
|
val_file.close() |
|
|
|
|