Datasets:
lmqg
/

Modalities:
Text
Languages:
English
ArXiv:
Libraries:
Datasets
License:
qg_squad / process.py
asahi417's picture
init
030abe3
raw
history blame
3.86 kB
""" Script to process raw SQuAD file for Question Generation format
You need to run `python -m spacy download en_core_web_sm`.
Split when uploading to dataset hub by
```
gsplit -l 3300 -d --additional-suffix=.jsonl train.jsonl train
gsplit -l 3300 -d --additional-suffix=.jsonl test.jsonl test
gsplit -l 3300 -d --additional-suffix=.jsonl dev.jsonl dev
```
"""
import json
import os
import re
from glob import glob
from tqdm import tqdm
from typing import List, Dict
import spacy
SPLITTER = spacy.load('en_core_web_sm')
HIGHLIGHT_TOKEN = '<hl>'
def get_sentence(document: str):
return [str(s) for s in SPLITTER(document).sents]
def jsonline_reader(filename: str):
with open(filename, 'r') as f_reader:
examples = [json.loads(i) for i in f_reader.read().split('\n') if len(i) > 0]
return examples
def process_single_data(data: Dict):
""" Convert single raw json data into QG format """
example = {'question': data["question"], 'passage': data["context"], 'answer': data["answer"]}
# get sentence
position = example['passage'].find(example['answer'])
assert position != -1
before_tmp = get_sentence(example['passage'][:position])
if len(before_tmp) == 0:
before = ''
before_sentence = ''
else:
if before_tmp[-1].endswith('.'):
before = ' '.join(before_tmp)
before_sentence = ''
else:
before = ' '.join(before_tmp[:-1])
before_sentence = before_tmp[-1]
before_sentence = before_sentence if before_sentence.endswith(' ') else '{} '.format(before_sentence)
after_tmp = get_sentence(example['passage'][position + len(example['answer']):])
if len(after_tmp) == 0:
after = ''
after_sentence = ''
else:
after = ' '.join(after_tmp[1:])
after_sentence = after_tmp[0]
after_sentence = after_sentence if after_sentence.startswith(' ') else ' {}'.format(after_sentence)
example['sentence'] = '{}{}{}'.format(before_sentence, example['answer'], after_sentence)
# get passage_sentence
before = '' if before == '' else '{} '.format(before)
after = '' if after == '' else ' {}'.format(after)
source_text = '{0}{1} {2} {1}{3}'.format(before, HIGHLIGHT_TOKEN, example['sentence'], after)
example['passage_sentence'] = re.sub(r'\s+', ' ', source_text)
# get passage_answer
source_text = '{0}{1} {2} {1}{3}'.format(
example['passage'][:position], HIGHLIGHT_TOKEN, example['answer'],
example['passage'][position + len(example['answer']):])
example['passage_answer'] = re.sub(r'\s+', ' ', source_text)
# get sentence_answer
before = get_sentence(example['passage'][:position])
if len(before) == 0 or before[-1].endswith('.'):
before = ''
else:
before = before[-1] if before[-1].endswith(' ') else '{} '.format(before[-1])
after = get_sentence(example['passage'][position + len(example['answer']):])
if len(after) == 0:
after = ''
else:
after = after[0] if after[0].startswith(' ') else ' {}'.format(after[0])
source_text = '{0}{1} {2} {1}{3}'.format(before, HIGHLIGHT_TOKEN, example['answer'], after)
example['sentence_answer'] = re.sub(r'\s+', ' ', source_text)
return example
if __name__ == '__main__':
output = './data/processed'
os.makedirs(output, exist_ok=True)
path = {'train': 'data/raw/train*.jsonl', 'dev': 'data/raw/dev.jsonl', 'test': 'data/raw/test.jsonl'}
for k, v in path.items():
json_data = []
for _file in sorted(glob(v)):
json_data += jsonline_reader(_file)
with open('{}/{}.jsonl'.format(output, k), 'w') as f:
for single_data in tqdm(json_data):
single_data = process_single_data(single_data)
f.write(json.dumps(single_data) + '\n')