Datasets:
lmqg
/

Modalities:
Tabular
Text
Languages:
English
ArXiv:
Libraries:
Datasets
License:
qg_subjqa / process.py
asahi417's picture
update
aa8dd40
""" 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 1500 -d --additional-suffix=.jsonl default.train.jsonl default.train
```
"""
import json
import os
import re
import pandas as pd
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 process_single_data(question, paragraph, answer):
""" Convert single raw json data into QG format """
example = {'question': question, 'paragraph': paragraph, 'answer': answer}
start = example['paragraph'].find(example['answer'])
end = start + len(answer)
assert paragraph[start:end] == answer
# get sentence
before_tmp = get_sentence(example['paragraph'][:start])
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['paragraph'][start + 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 paragraph_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['paragraph_sentence'] = re.sub(r'\s+', ' ', source_text)
# get paragraph_answer
source_text = '{0}{1} {2} {1}{3}'.format(
example['paragraph'][:start], HIGHLIGHT_TOKEN, example['answer'],
example['paragraph'][start + len(example['answer']):])
example['paragraph_answer'] = re.sub(r'\s+', ' ', source_text)
# get sentence_answer
if len(before_tmp) == 0 or before_tmp[-1].endswith('.'):
before = ''
else:
before = before_tmp[-1] if before_tmp[-1].endswith(' ') else '{} '.format(before_tmp[-1])
if len(after_tmp) == 0:
after = ''
else:
after = after_tmp[0] if after_tmp[0].startswith(' ') else ' {}'.format(after_tmp[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__':
os.makedirs('./data/processed', exist_ok=True)
for i in ["books", "electronics", "grocery", "movies", "restaurants", "tripadvisor"]:
for s in ["dev.csv", "test.csv", "train.csv"]:
df = pd.read_csv(f'SubjQA/SubjQA/{i}/splits/{s}')
df = df[[x != 'ANSWERNOTFOUND' for x in df['human_ans_spans']]]
df['review'] = [x.replace('ANSWERNOTFOUND', '') for x in df['review']]
output = []
for _, _g in df.groupby('q_review_id'):
if any(i == 'ANSWERNOTFOUND' for i in _g['human_ans_spans']):
continue
_len = [len(i) for i in _g["human_ans_spans"]]
_df = _g.iloc[_len.index(max(_len))]
start, end = eval(_df['human_ans_indices'])
out = process_single_data(question=re.sub(r'\s+\?', '?', _df['question']),
answer=_df['review'][start:end],
paragraph=_df['review'])
out['question_subj_level'] = int(_df['question_subj_level'])
out['answer_subj_level'] = int(_df['answer_subj_level'])
out['paragraph_id'] = _df['review_id']
out['domain'] = _df['domain']
output.append(out)
with open(f'./data/processed/{i}.{s.replace(".csv", ".jsonl")}', 'w') as f:
f.write('\n'.join([json.dumps(i) for i in output]))