-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathdata.py
195 lines (155 loc) · 6.74 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
from config import *
flatten = lambda l: [item for sublist in l for item in sublist]
def prepare_sequence(seq, to_index):
idxs = list(map(lambda w: to_index[w] if to_index.get(w) is not None else to_index["<UNK>"], seq))
return Variable(LongTensor(idxs))
# Turn a Unicode string to plain ASCII, thanks to http://stackoverflow.com/a/518232/2809427
def unicode_to_ascii(s):
return ''.join(
c for c in unicodedata.normalize('NFD', s)
if unicodedata.category(c) != 'Mn'
)
# Lowercase, trim, and remove non-letter characters
def normalize_string(s):
s = unicode_to_ascii(s.lower().strip())
s = re.sub(r"([,.!?])", r" \1 ", s)
# s = re.sub(r"[^a-zA-Z,.!?]+", r" ", s)
s = re.sub(r"\s+", r" ", s).strip()
return s
class Train_Data(object):
def __init__(self):
self.MIN_LENGTH = 1
self.MAX_LENGTH = 16
self.corpus = self.load_corpus()
# print(len(self.corpus))
self.X_r, self.y_r = self.get_raw_pairs()
# print(len(self.X_r), len(self.y_r))
# print(self.X_r[0], self.y_r[0])
self.source_vocab = list(set(flatten(self.X_r)))
self.target_vocab = list(set(flatten(self.y_r)))
# print(len(self.source_vocab), len(self.target_vocab))
self.source2index = self.get_source2index()
self.index2source = self.get_index2source()
self.target2index = self.get_target2index()
self.index2target = self.get_index2target()
# print(len(self.source2index), len(self.target2index))
self.X_p, self.y_p = self.get_pro_pairs()
# print(len(self.X_p), len(self.y_p))
pass
def load_corpus(self):
corpus = open('./cn-jp.txt', 'r', encoding='utf-8').readlines()
# corpus = open('../fra-eng.txt', 'r', encoding='utf-8').readlines()
return corpus
def get_raw_pairs(self):
X_r, y_r = [],[]
for parallel in self.corpus:
if "\t" not in parallel:
continue
so,ta = parallel[:-1].split('\t')
if so.strip() == "" or ta.strip() == "":
continue
normalized_so = normalize_string(so).split()
normalized_ta = normalize_string(ta).split()
if len(normalized_so) >= self.MIN_LENGTH and len(normalized_so) <= self.MAX_LENGTH \
and len(normalized_ta) <= self.MAX_LENGTH:
# and len(normalized_ta) >= MIN_LENGTH
X_r.append(normalized_so)
y_r.append(normalized_ta)
return X_r, y_r
def get_source2index(self):
if os.path.exists('./source2index.pickle'):
print('loading source2index ...')
with open('./source2index.pickle', 'rb') as handle:
source2index = pickle.load(handle)
return source2index
# first init
print('making source2index')
source2index = {'<PAD>': 0, '<UNK>': 1, '<s>': 2, '</s>': 3}
for vo in self.source_vocab:
if source2index.get(vo) is None:
source2index[vo] = len(source2index)
# save as pickle
with open('./source2index.pickle', 'wb') as handle:
pickle.dump(source2index, handle, protocol=pickle.HIGHEST_PROTOCOL)
return source2index
def get_index2source(self):
index2source = {v:k for k, v in self.source2index.items()}
return index2source
pass
def get_target2index(self):
if os.path.exists('./target2index.pickle'):
print('loading target2index...')
with open('./target2index.pickle', 'rb') as handle:
target2index = pickle.load(handle)
return target2index
# first time init
print('making target2index...')
target2index = {'<PAD>': 0, '<UNK>': 1, '<s>': 2, '</s>': 3}
for vo in self.target_vocab:
if target2index.get(vo) is None:
target2index[vo] = len(target2index)
# save as pickle
with open('target2index.pickle', 'wb') as handle:
pickle.dump(target2index, handle, protocol=pickle.HIGHEST_PROTOCOL)
return target2index
def get_index2target(self):
index2target = {v:k for k, v in self.target2index.items()}
return index2target
pass
def get_pro_pairs(self):
X_p, y_p = [], []
for so, ta in zip(self.X_r, self.y_r):
X_p.append(prepare_sequence(so + ['</s>'], self.source2index).view(1, -1))
y_p.append(prepare_sequence(ta + ['</s>'], self.target2index).view(1, -1))
return X_p, y_p
def get_train_data(self):
train_data = list(zip(self.X_p, self.y_p))
return train_data
class Test_Data():
def __init__(self):
self.Train_Data = Train_Data()
self.MIN_LENGTH = self.Train_Data.MIN_LENGTH
self.MAX_LENGTH = self.Train_Data.MAX_LENGTH
self.corpus = self.load_corpus()
print(len(self.corpus))
self.X_r, self.y_r = self.get_raw_pairs()
print(len(self.X_r), len(self.y_r))
print(self.X_r[0], self.y_r[0])
self.source2index = self.Train_Data.source2index
self.target2index = self.Train_Data.target2index
print(len(self.source2index), len(self.target2index))
self.X_p, self.y_p = self.get_pro_pairs()
print(len(self.X_p), len(self.y_p))
pass
def load_corpus(self):
# corpus = open('../fra-eng.txt', 'r', encoding='utf-8').readlines()
corpus = open('../code-question-test.txt', 'r', encoding='utf-8').readlines()
return corpus
def get_raw_pairs(self):
X_r, y_r = [],[]
for parallel in self.corpus:
if "\t" not in parallel:
continue
so,ta = parallel[:-1].split('\t')
if so.strip() == "" or ta.strip() == "":
continue
normalized_so = normalize_string(so).split()
normalized_ta = normalize_string(ta).split()
if len(normalized_so) >= self.MIN_LENGTH and len(normalized_so) <= self.MAX_LENGTH \
and len(normalized_ta) <= self.MAX_LENGTH:
# and len(normalized_ta) >= MIN_LENGTH
X_r.append(normalized_so)
y_r.append(normalized_ta)
return X_r, y_r
def get_pro_pairs(self):
X_p, y_p = [], []
for so, ta in zip(self.X_r, self.y_r):
X_p.append(prepare_sequence(so + ['</s>'], self.source2index).view(1, -1))
y_p.append(prepare_sequence(ta + ['</s>'], self.target2index).view(1, -1))
return X_p, y_p
def get_test_data(self):
test_data = list(zip(self.X_p, self.y_p))
return test_data
# train = Train_Data()
# print('========================')
# test = Test_Data()