Datasets:
lmqg
/

Languages:
English
Multilinguality:
monolingual
Size Categories:
10K<n<100K
Source Datasets:
subjqa
ArXiv:
Tags:
question-generation
License:
asahi417 commited on
Commit
3085290
1 Parent(s): 29cf22f
.gitignore ADDED
@@ -0,0 +1 @@
 
 
1
+ SubjQA
data/processed/books.dev.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
data/processed/books.test.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
data/processed/books.train.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
data/processed/electronics.dev.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
data/processed/electronics.test.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
data/processed/electronics.train.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
data/processed/grocery.dev.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
data/processed/grocery.test.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
data/processed/grocery.train.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
data/processed/movies.dev.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
data/processed/movies.test.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
data/processed/movies.train.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
data/processed/restaurants.dev.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
data/processed/restaurants.test.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
data/processed/restaurants.train.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
data/processed/tripadvisor.dev.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
data/processed/tripadvisor.test.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
data/processed/tripadvisor.train.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
process.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ Script to process raw SQuAD file for Question Generation format
2
+ You need to run `python -m spacy download en_core_web_sm`.
3
+ Split when uploading to dataset hub by
4
+ ```
5
+ gsplit -l 600 -d --additional-suffix=.jsonl test.jsonl test
6
+ gsplit -l 600 -d --additional-suffix=.jsonl train.jsonl train
7
+ gsplit -l 600 -d --additional-suffix=.jsonl valid.jsonl valid
8
+ ```
9
+ """
10
+ import json
11
+ import os
12
+ import re
13
+ from tqdm import tqdm
14
+ from itertools import chain
15
+
16
+ import pandas as pd
17
+ import spacy
18
+
19
+
20
+ SPLITTER = spacy.load('en_core_web_sm')
21
+ HIGHLIGHT_TOKEN = '<hl>'
22
+
23
+
24
+ def get_sentence(document: str):
25
+ return [str(s) for s in SPLITTER(document).sents]
26
+
27
+
28
+ def process_single_data(question, paragraph, answer):
29
+ """ Convert single raw json data into QG format """
30
+ example = {'question': question, 'paragraph': paragraph, 'answer': answer}
31
+ start = example['paragraph'].find(example['answer'])
32
+ end = start + len(answer)
33
+ assert paragraph[start:end] == answer
34
+ # get sentence
35
+ before_tmp = get_sentence(example['paragraph'][:start])
36
+ if len(before_tmp) == 0:
37
+ before = ''
38
+ before_sentence = ''
39
+ else:
40
+ if before_tmp[-1].endswith('.'):
41
+ before = ' '.join(before_tmp)
42
+ before_sentence = ''
43
+ else:
44
+ before = ' '.join(before_tmp[:-1])
45
+ before_sentence = before_tmp[-1]
46
+ before_sentence = before_sentence if before_sentence.endswith(' ') else '{} '.format(before_sentence)
47
+ after_tmp = get_sentence(example['paragraph'][start + len(example['answer']):])
48
+ if len(after_tmp) == 0:
49
+ after = ''
50
+ after_sentence = ''
51
+ else:
52
+ after = ' '.join(after_tmp[1:])
53
+ after_sentence = after_tmp[0]
54
+ after_sentence = after_sentence if after_sentence.startswith(' ') else ' {}'.format(after_sentence)
55
+ example['sentence'] = '{}{}{}'.format(before_sentence, example['answer'], after_sentence)
56
+
57
+ # get paragraph_sentence
58
+ before = '' if before == '' else '{} '.format(before)
59
+ after = '' if after == '' else ' {}'.format(after)
60
+ source_text = '{0}{1} {2} {1}{3}'.format(before, HIGHLIGHT_TOKEN, example['sentence'], after)
61
+ example['paragraph_sentence'] = re.sub(r'\s+', ' ', source_text)
62
+
63
+ # get paragraph_answer
64
+ source_text = '{0}{1} {2} {1}{3}'.format(
65
+ example['paragraph'][:start], HIGHLIGHT_TOKEN, example['answer'],
66
+ example['paragraph'][start + len(example['answer']):])
67
+ example['paragraph_answer'] = re.sub(r'\s+', ' ', source_text)
68
+
69
+ # get sentence_answer
70
+ if len(before_tmp) == 0 or before_tmp[-1].endswith('.'):
71
+ before = ''
72
+ else:
73
+ before = before_tmp[-1] if before_tmp[-1].endswith(' ') else '{} '.format(before_tmp[-1])
74
+ if len(after_tmp) == 0:
75
+ after = ''
76
+ else:
77
+ after = after_tmp[0] if after_tmp[0].startswith(' ') else ' {}'.format(after_tmp[0])
78
+ source_text = '{0}{1} {2} {1}{3}'.format(before, HIGHLIGHT_TOKEN, example['answer'], after)
79
+ example['sentence_answer'] = re.sub(r'\s+', ' ', source_text)
80
+
81
+ return example
82
+
83
+
84
+ if __name__ == '__main__':
85
+ os.makedirs('./data/processed', exist_ok=True)
86
+ for i in ["books", "electronics", "grocery", "movies", "restaurants", "tripadvisor"]:
87
+ for s in ["dev.csv", "test.csv", "train.csv"]:
88
+ df = pd.read_csv(f'SubjQA/SubjQA/{i}/splits/{s}')
89
+ df = df[[x != 'ANSWERNOTFOUND' for x in df['human_ans_spans']]]
90
+ df['review'] = [x.replace('ANSWERNOTFOUND', '') for x in df['review']]
91
+ output = []
92
+ for _, _g in df.groupby('q_review_id'):
93
+ if any(i == 'ANSWERNOTFOUND' for i in _g['human_ans_spans']):
94
+ continue
95
+ # if len(_g["human_ans_spans"].unique()) != 1:
96
+ # continue
97
+ # _df = _g.iloc[0]
98
+ _len = [len(i) for i in _g["human_ans_spans"]]
99
+ _df = _g.iloc[_len.index(max(_len))]
100
+ start, end = eval(_df['human_ans_indices'])
101
+ # if re.sub(r'[\s\W]', '', _df['review'][start:end]) != re.sub(r'[\s\W]', '', _df["human_ans_spans"]):
102
+ # input(f"{_df['review'][start:end]} != {_df['human_ans_spans']}")
103
+ # continue
104
+ out = process_single_data(question=re.sub(r'\s+\?', '?', _df['question']),
105
+ answer=_df['review'][start:end],
106
+ paragraph=_df['review'])
107
+ out['question_subj_level'] = int(_df['question_subj_level'])
108
+ out['answer_subj_level'] = int(_df['answer_subj_level'])
109
+ out['paragraph_id'] = _df['review_id']
110
+ output.append(out)
111
+ with open(f'./data/processed/{i}.{s.replace(".csv", ".jsonl")}', 'w') as f:
112
+ f.write('\n'.join([json.dumps(i) for i in output]))
113
+
114
+
qg_subjqa.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import datasets
3
+
4
+ logger = datasets.logging.get_logger(__name__)
5
+ _DESCRIPTION = """[SubjQA](https://github.com/megagonlabs/SubjQA) dataset for question generation (QG) task."""
6
+ _URL = 'https://huggingface.co/datasets/asahi417/qg_subjqa/raw/main/data/processed'
7
+ _DOMAINS = ["books", "electronics", "grocery", "movies", "restaurants", "tripadvisor"]
8
+
9
+
10
+ class QGSubjQAConfig(datasets.BuilderConfig):
11
+ """BuilderConfig for SquadQG"""
12
+
13
+ def __init__(self, **kwargs):
14
+ """BuilderConfig for SquadQG.
15
+ Args:
16
+ **kwargs: keyword arguments forwarded to super.
17
+ """
18
+ super(QGSubjQAConfig, self).__init__(**kwargs)
19
+
20
+
21
+ class QGSubjQA(datasets.GeneratorBasedBuilder):
22
+
23
+ BUILDER_CONFIGS = [QGSubjQAConfig(name=i, description="SubjQA from domain of `{}`.".format(i)) for i in _DOMAINS]
24
+
25
+ def _info(self):
26
+ return datasets.DatasetInfo(
27
+ description=_DESCRIPTION,
28
+ features=datasets.Features(
29
+ {
30
+ "answer": datasets.Value("string"),
31
+ "question": datasets.Value("string"),
32
+ "sentence": datasets.Value("string"),
33
+ "paragraph": datasets.Value("string"),
34
+ "sentence_answer": datasets.Value("string"),
35
+ "paragraph_answer": datasets.Value("string"),
36
+ "paragraph_sentence": datasets.Value("string"),
37
+ "paragraph_id": datasets.Value("string"),
38
+ "question_subj_level": datasets.Value("int32"),
39
+ "answer_subj_level": datasets.Value("int32")
40
+ }
41
+ ),
42
+ supervised_keys=None,
43
+ homepage="https://github.com/asahi417/lm-question-generation"
44
+ )
45
+
46
+ def _split_generators(self, dl_manager):
47
+ downloaded_file = dl_manager.download_and_extract({
48
+ 'train': f"{_URL}/{self.config.name}.train.jsonl",
49
+ 'dev': f"{_URL}/{self.config.name}.dev.jsonl",
50
+ 'test': f"{_URL}/{self.config.name}.test.jsonl"
51
+ })
52
+ return [
53
+ datasets.SplitGenerator(name=datasets.Split.TRAIN, gen_kwargs={"filepaths": downloaded_file["train"]}),
54
+ datasets.SplitGenerator(name=datasets.Split.VALIDATION, gen_kwargs={"filepaths": downloaded_file["dev"]}),
55
+ datasets.SplitGenerator(name=datasets.Split.TEST, gen_kwargs={"filepaths": downloaded_file["test"]}),
56
+ ]
57
+
58
+ def _generate_examples(self, filepaths):
59
+ _key = 0
60
+ for filepath in filepaths:
61
+ logger.info("generating examples from = %s", filepath)
62
+ with open(filepath, encoding="utf-8") as f:
63
+ _list = f.read().split('\n')
64
+ if _list[-1] == '':
65
+ _list = _list[:-1]
66
+ for i in _list:
67
+ data = json.loads(i)
68
+ yield _key, data
69
+ _key += 1