Datasets:
lmqg
/

Modalities:
Tabular
Text
Languages:
English
ArXiv:
Libraries:
Datasets
License:
File size: 4,367 Bytes
3085290
 
 
 
5683f74
3085290
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22d4f68
3085290
 
 
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
""" 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]))