This repository has been archived by the owner on Nov 3, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
agents.py
201 lines (171 loc) · 6.74 KB
/
agents.py
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""
Provides a dump of Wikipedia articles from 2/3/18.
One can either load full articles, using 'wikipedia:full',
or simply load the first paragraphs of the articles,
using 'wikipedia:summary'
To put the article in the labels and the title in the text, specify
':key-value' at the end (for a title/content key-value association)
"""
from parlai.core.teachers import DialogTeacher, ChunkTeacher, ChunkOutput
from parlai.utils.io import PathManager
from parlai.core.message import Message
from .build import build
import json
import os
from typing import List, Tuple
class FullTeacher(DialogTeacher):
"""
Reads Wikipedia pages one at a time.
"""
def __init__(self, opt, shared=None):
self.key_value = ':key-value' in opt['task']
opt['task'] = 'wikipedia:all'
build(opt)
self.opt = opt
opt['datafile'] = os.path.join(
opt['datapath'], 'wikipedia/full/wiki_full_extracted'
)
self.id = 'wikipedia'
super().__init__(opt, shared)
def setup_data(self, path):
print('loading: ' + path)
for subdir in os.listdir(path):
if subdir == 'README.md':
continue
subdir_path = os.path.join(path, subdir)
for wiki_file in os.listdir(subdir_path):
wiki_file_path = os.path.join(subdir_path, wiki_file)
with PathManager.open(wiki_file_path) as wf:
for article_json in wf:
article = json.loads(article_json)
title = article['title']
text = article['text']
if self.key_value:
yield (title, [text]), True
else:
yield (text, ['']), True
def get_extraction_instructions(self):
"""
If one wants to run extraction themselves on a raw wikipedia dump.
"""
dpath = os.path.join(self.opt['datapath'], 'wikipedia', 'full')
fname = 'enwiki-latest-pages-articles.xml.bz2'
instructions = (
"To complete the data extraction, please run the following:\n"
"mkdir -p {download} && "
"git clone https://github.com/attardi/wikiextractor "
"{download}/wikiextract && cd {download}/wikiextract && "
"python WikiExtractor.py {wikifile} --filter_disambig_pages "
"-o {output} --json"
).format(
download=self.opt['download_path'],
wikifile=dpath + '/' + fname,
output=dpath + '/' + 'wiki_extracted',
)
return instructions
class FullSplitTeacher(ChunkTeacher):
"""
Full Wikipedia teacher that splits the chunks into train/valid/test.
"""
def __init__(self, opt, shared=None):
self.TRAINSIZE = 5437097
self.VALIDSIZE = 71052
self.TESTSIZE = 39975
if shared is None:
# set map
self.opt = opt
self._set_chunk_idx_to_file()
else:
self.chunk_idx_to_file = shared['chunk_idx_to_file']
super().__init__(opt, shared)
def _get_data_folder(self):
return os.path.join(self.opt['datapath'], 'wikipedia/full/wiki_full_extracted')
def get_num_samples(self, opt) -> Tuple[int, int]:
"""
Return the number of samples given the datatype.
"""
datatype = opt['datatype']
if 'train' in datatype:
return self.TRAINSIZE, self.TRAINSIZE
elif 'valid' in datatype:
return self.VALIDSIZE, self.VALIDSIZE
else:
# test
return self.TESTSIZE, self.TESTSIZE
def _set_chunk_idx_to_file(self):
folder = self._get_data_folder()
all_subdirs = sorted([x for x in os.listdir(folder) if 'README' not in x])
self.chunk_idx_to_file = {i: x for i, x in enumerate(all_subdirs)}
def get_fold_chunks(self, opt) -> List[int]: # type: ignore
"""
Return a list of chunk IDs (integer).
Given the datatype (train/test/valid), return the list of chunk IDs that
correspond to that split.
"""
datatype = opt['datatype']
all_chunk_idxs = list(self.chunk_idx_to_file.keys())
if 'train' in datatype:
return all_chunk_idxs[:-2]
elif 'valid' in datatype:
return [all_chunk_idxs[-2]]
else:
return [all_chunk_idxs[-1]]
def load_from_chunk(self, chunk_idx: int):
"""
Given the chunk index, load examples from that chunk.
Return a list of tuples. The function `_create_message` will take these tuples
to form the Message object that is returned by the teacher.
"""
output = []
chunk_path = os.path.join(self.folder, self.chunk_idx_to_file[chunk_idx])
for wiki_file in os.listdir(chunk_path):
wiki_file_path = os.path.join(chunk_path, wiki_file)
with PathManager.open(wiki_file_path) as wf:
for article_json in wf:
article = json.loads(article_json)
title = article['title']
text = article['text']
output.append((title, text))
return output
def create_message(self, queue_output: ChunkOutput, entry_idx=0) -> 'Message':
"""
Given the tuple output of the queue, return an act.
"""
title, text = queue_output
return Message(
{'title': title, 'text': text, 'labels': [''], 'episode_done': True}
)
def share(self):
shared = super().share()
shared['chunk_idx_to_file'] = self.chunk_idx_to_file
return shared
class SummaryTeacher(DialogTeacher):
"""
Reads Wikipedia pages one at a time, only uses summaries.
"""
def __init__(self, opt, shared=None):
self.key_value = ':key-value' in opt['task']
opt['task'] = 'wikipedia:summary'
build(opt)
opt['datafile'] = os.path.join(
opt['datapath'], 'wikipedia/summary/summaries.json'
)
self.id = 'wikipedia'
super().__init__(opt, shared)
def setup_data(self, path):
print('loading: ' + path)
with PathManager.open(path) as wf:
for article_json in wf:
article = json.loads(article_json)
title = article['title']
text = article['text']
if self.key_value:
yield (title, [text]), True
else:
yield (title + '\n' + text, ['']), True
class DefaultTeacher(SummaryTeacher):
pass