-
Notifications
You must be signed in to change notification settings - Fork 0
/
data.py
292 lines (213 loc) · 10.2 KB
/
data.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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
# coding: utf-8
from __future__ import division, print_function
import random
import os
import sys
import operator
try:
import cPickle
except ImportError:
import _pickle as cPickle
try:
input = raw_input
except NameError:
pass
from io import open
import fnmatch
import shutil
DATA_PATH = "../data"
# path to text file in the format:
# word1 0.123 0.123 ... 0.123
# word2 0.123 0.123 ... 0.123 etc...
# e.g. glove.6B.50d.txt
PRETRAINED_EMBEDDINGS_PATH = None
END = "</S>"
UNK = "<UNK>"
NUM = "<NUM>"
SPACE = "_SPACE"
MAX_WORD_VOCABULARY_SIZE = 100000
MIN_WORD_COUNT_IN_VOCAB = 2
MAX_SEQUENCE_LEN = 50
TRAIN_FILE = os.path.join(DATA_PATH, "train")
DEV_FILE = os.path.join(DATA_PATH, "dev")
TEST_FILE = os.path.join(DATA_PATH, "test")
# Stage 2
TRAIN_FILE2 = os.path.join(DATA_PATH, "train2")
DEV_FILE2 = os.path.join(DATA_PATH, "dev2")
TEST_FILE2 = os.path.join(DATA_PATH, "test2")
WORD_VOCAB_FILE = os.path.join(DATA_PATH, "vocabulary")
PUNCTUATION_VOCABULARY = [SPACE, ",COMMA", ".PERIOD", "?QUESTIONMARK", "!EXCLAMATIONMARK", ":COLON", ";SEMICOLON", "-DASH"]
PUNCTUATION_MAPPING = {}
# Comma, period & question mark only:
# PUNCTUATION_VOCABULARY = {SPACE, ",COMMA", ".PERIOD", "?QUESTIONMARK"}
# PUNCTUATION_MAPPING = {"!EXCLAMATIONMARK": ".PERIOD", ":COLON": ",COMMA", ";SEMICOLON": ".PERIOD", "-DASH": ",COMMA"}
EOS_TOKENS = {".PERIOD", "?QUESTIONMARK", "!EXCLAMATIONMARK"}
CRAP_TOKENS = {"<doc>", "<doc.>"} # punctuations that are not included in vocabulary nor mapping, must be added to CRAP_TOKENS
PAUSE_PREFIX = "<sil="
# replacement for pickling that takes less RAM. Useful for large datasets.
def dump(d, path):
with open(path, 'w') as f:
for s in d:
f.write("%s\n" % repr(s))
def load(path):
d = []
with open(path, 'r') as f:
for l in f:
d.append(eval(l))
return d
def add_counts(word_counts, line):
for w in line.split():
if w in CRAP_TOKENS or w in PUNCTUATION_VOCABULARY or w in PUNCTUATION_MAPPING or w.startswith(PAUSE_PREFIX):
continue
word_counts[w] = word_counts.get(w, 0) + 1
def build_vocabulary(word_counts):
return [wc[0] for wc in reversed(sorted(word_counts.items(), key=operator.itemgetter(1))) if wc[1] >= MIN_WORD_COUNT_IN_VOCAB and wc[0] != UNK][:MAX_WORD_VOCABULARY_SIZE] # Unk will be appended to end
def write_vocabulary(vocabulary, file_name):
if END not in vocabulary:
vocabulary.append(END)
if UNK not in vocabulary:
vocabulary.append(UNK)
print("Vocabulary size: %d" % len(vocabulary))
with open(file_name, 'w', encoding='utf-8') as f:
f.write("\n".join(vocabulary))
def iterable_to_dict(arr):
return dict((x.strip(), i) for (i, x) in enumerate(arr))
def read_vocabulary(file_name):
with open(file_name, 'r', encoding='utf-8') as f:
return iterable_to_dict(f.readlines())
def write_processed_dataset(input_files, output_file):
"""
data will consist of two sets of aligned subsequences (words and punctuations) of MAX_SEQUENCE_LEN tokens (actually punctuation sequence will be 1 element shorter).
If a sentence is cut, then it will be added to next subsequence entirely (words before the cut belong to both sequences)
"""
data = []
word_vocabulary = read_vocabulary(WORD_VOCAB_FILE)
punctuation_vocabulary = iterable_to_dict(PUNCTUATION_VOCABULARY)
num_total = 0
num_unks = 0
current_words = []
current_punctuations = []
current_pauses = []
last_eos_idx = 0 # if it's still 0 when MAX_SEQUENCE_LEN is reached, then the sentence is too long and skipped.
last_token_was_punctuation = True # skipt first token if it's punctuation
last_pause = 0.0
skip_until_eos = False # if a sentence does not fit into subsequence, then we need to skip tokens until we find a new sentence
for input_file in input_files:
with open(input_file, 'r', encoding='utf-8') as text:
for line in text:
for token in line.split():
# First map oov punctuations to known punctuations
if token in PUNCTUATION_MAPPING:
token = PUNCTUATION_MAPPING[token]
if skip_until_eos:
if token in EOS_TOKENS:
skip_until_eos = False
continue
elif token in CRAP_TOKENS:
continue
elif token.startswith(PAUSE_PREFIX):
last_pause = float(token.replace(PAUSE_PREFIX,"").replace(">",""))
elif token in punctuation_vocabulary:
if last_token_was_punctuation: # if we encounter sequences like: "... !EXLAMATIONMARK .PERIOD ...", then we only use the first punctuation and skip the ones that follow
continue
if token in EOS_TOKENS:
last_eos_idx = len(current_punctuations) # no -1, because the token is not added yet
punctuation = punctuation_vocabulary[token]
current_punctuations.append(punctuation)
last_token_was_punctuation = True
else:
if not last_token_was_punctuation:
current_punctuations.append(punctuation_vocabulary[SPACE])
word = word_vocabulary.get(token, word_vocabulary[UNK])
current_words.append(word)
current_pauses.append(last_pause)
last_token_was_punctuation = False
num_total += 1
num_unks += int(word == word_vocabulary[UNK])
if len(current_words) == MAX_SEQUENCE_LEN: # this also means, that last token was a word
assert len(current_words) == len(current_punctuations) + 1, "#words: %d; #punctuations: %d" % (len(current_words), len(current_punctuations))
assert current_pauses == [] or len(current_words) == len(current_pauses), "#words: %d; #pauses: %d" % (len(current_words), len(current_pauses))
# Sentence did not fit into subsequence - skip it
if last_eos_idx == 0:
skip_until_eos = True
current_words = []
current_punctuations = []
current_pauses = []
last_token_was_punctuation = True # next sequence starts with a new sentence, so is preceded by eos which is punctuation
else:
subsequence = [
current_words[:-1] + [word_vocabulary[END]],
current_punctuations,
current_pauses[1:]
]
data.append(subsequence)
# Carry unfinished sentence to next subsequence
current_words = current_words[last_eos_idx+1:]
current_punctuations = current_punctuations[last_eos_idx+1:]
current_pauses = current_pauses[last_eos_idx+1:]
last_eos_idx = 0 # sequence always starts with a new sentence
print("%.2f%% UNK-s in %s" % (num_unks / num_total * 100, output_file))
dump(data, output_file)
def create_dev_test_train_split_and_vocabulary(root_path, create_vocabulary, train_output, dev_output, test_output, pretrained_embeddings_path=None):
train_txt_files = []
dev_txt_files = []
test_txt_files = []
if create_vocabulary and not pretrained_embeddings_path:
word_counts = dict()
for root, dirnames, filenames in os.walk(root_path):
for filename in fnmatch.filter(filenames, '*.txt'):
path = os.path.join(root, filename)
if filename.endswith(".test.txt"):
test_txt_files.append(path)
elif filename.endswith(".dev.txt"):
dev_txt_files.append(path)
else:
train_txt_files.append(path)
if create_vocabulary and not pretrained_embeddings_path:
with open(path, 'r', encoding='utf-8') as text:
for line in text:
add_counts(word_counts, line)
if create_vocabulary:
if pretrained_embeddings_path:
vocabulary = []
embeddings = []
with open(pretrained_embeddings_path, 'r', encoding='utf-8') as f:
for line in f:
line = line.split()
w = line[0]
e = [float(x) for x in line[1:]]
vocabulary.append(w)
embeddings.append(e)
with open("We.pcl", 'wb') as f:
cPickle.dump(embeddings, f)
else:
vocabulary = build_vocabulary(word_counts)
write_vocabulary(vocabulary, WORD_VOCAB_FILE)
write_processed_dataset(train_txt_files, train_output)
write_processed_dataset(dev_txt_files, dev_output)
write_processed_dataset(test_txt_files, test_output)
if __name__ == "__main__":
if len(sys.argv) > 1:
path = sys.argv[1]
else:
sys.exit("The path to stage1 source data directory with txt files is missing")
replace = False
if os.path.exists(DATA_PATH):
while True:
resp = input("Data path '%s' already exists. Do you want to:\n[r]eplace the files in existing data path?\n[e]xit?\n>" % DATA_PATH)
resp = resp.lower().strip()
if resp not in ('r', 'e'):
continue
if resp == 'e':
sys.exit()
elif resp == 'r':
replace = True
break
if replace and os.path.exists(DATA_PATH):
shutil.rmtree(DATA_PATH)
os.makedirs(DATA_PATH)
create_dev_test_train_split_and_vocabulary(path, True, TRAIN_FILE, DEV_FILE, TEST_FILE, PRETRAINED_EMBEDDINGS_PATH)
# Stage 2
if len(sys.argv) > 2:
path2 = sys.argv[2]
create_dev_test_train_split_and_vocabulary(path2, False, TRAIN_FILE2, DEV_FILE2, TEST_FILE2)