Simons2017
/
Towards-Implicit-Content-Introducing-for-Generative-Short-Text-Conversation-Systems
Public
forked from yaolili/Towards-Implicit-Content-Introducing-for-Generative-Short-Text-Conversation-Systems
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtranslate.py
174 lines (144 loc) · 5.66 KB
/
translate.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
'''
Translates a source file using a translation model.
'''
import argparse
import numpy
import cPickle as pkl
from nmt_all_twogate import (build_sampler, gen_sample, load_params,
init_params, init_tparams)
from multiprocessing import Process, Queue
def translate_model(queue, rqueue, pid, model, options, k, normalize):
from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams
from theano import shared
trng = RandomStreams(1234)
use_noise = shared(numpy.float32(0.))
# allocate model parameters
params = init_params(options)
# load model parameters and set theano shared variables
params = load_params(model, params)
tparams = init_tparams(params)
# word index
f_init, f_next = build_sampler(tparams, options, trng, use_noise)
def _translate(seq, topic):
# sample given an input sequence and obtain scores
sample, score = gen_sample(tparams, f_init, f_next,
numpy.array(seq).reshape([len(seq), 1]),
topic,
options, trng=trng, k=k, maxlen=50,
stochastic=False, argmax=False)
# Stochastic sample
# return sample
# Beam search
# normalize scores according to sequence lengths
if normalize:
lengths = numpy.array([len(s) for s in sample])
score = score / lengths
sidx = numpy.argmin(score)
return sample[sidx]
while True:
req = queue.get()
if req is None:
break
idx, x, kw = req[0], req[1], req[2]
print pid, '-', idx
seq = _translate(x, kw[0])
# generate one sentence
rqueue.put((idx, seq))
return
def main(model, dictionary, dictionary_target, source_file, topic_file, saveto, k=5,
normalize=False, n_process=5, chr_level=False):
# load model model_options
with open('%s.pkl' % model, 'rb') as f:
options = pkl.load(f)
# load source dictionary and invert
with open(dictionary, 'rb') as f:
word_dict = pkl.load(f)
word_idict = dict()
for kk, vv in word_dict.iteritems():
word_idict[vv] = kk
word_idict[0] = '<eos>'
word_idict[1] = 'UNK'
# load target dictionary and invert
with open(dictionary_target, 'rb') as f:
word_dict_trg = pkl.load(f)
word_idict_trg = dict()
for kk, vv in word_dict_trg.iteritems():
word_idict_trg[vv] = kk
word_idict_trg[0] = '<eos>'
word_idict_trg[1] = 'UNK'
# create input and output queues for processes
queue = Queue()
rqueue = Queue()
processes = [None] * n_process
for midx in xrange(n_process):
processes[midx] = Process(
target=translate_model,
args=(queue, rqueue, midx, model, options, k, normalize))
processes[midx].start()
# utility function
def _seqs2words(caps):
capsw = []
for cc in caps:
ww = []
for w in cc:
if w == 0:
break
if w not in word_idict_trg: ww.append('UNK')
else: ww.append(word_idict_trg[w])
capsw.append(' '.join(ww))
return capsw
def _send_jobs(q_file, kw_file):
with open(q_file, 'r') as f1, open(kw_file, "r") as f2:
for idx, (l1, l2) in enumerate(zip(f1, f2)):
if chr_level:
words = list(l1.decode('utf-8').strip())
kws = list(l2.decode('utf-8').strip())
else:
words = l1.strip().split()
kws = l2.strip().split()
x = map(lambda w: word_dict[w] if w in word_dict else 1, words)
x = map(lambda ii: ii if ii < options['n_words_src'] else 1, x)
x += [0]
kw = map(lambda w: word_dict_trg[w] if w in word_dict_trg else 1, kws)
kw = map(lambda ii: ii if ii < options['n_words'] else 1, kw)
# padding
kws = []
for i in range(0, len(kw)):
cur = [kw[i]] * (len(x) - 1) + [0]
kws.append(cur)
queue.put((idx, x, kws))
return idx+1
def _finish_processes():
for midx in xrange(n_process):
queue.put(None)
def _retrieve_jobs(n_samples):
trans = [None] * n_samples
for idx in xrange(n_samples):
resp = rqueue.get()
trans[resp[0]] = resp[1]
if numpy.mod(idx, 10) == 0:
print 'Sample ', (idx+1), '/', n_samples, ' Done'
return trans
print 'Translating ', source_file, '...'
n_samples = _send_jobs(source_file, topic_file)
trans = _seqs2words(_retrieve_jobs(n_samples))
_finish_processes()
with open(saveto, 'w') as f:
print >>f, '\n'.join(trans)
print 'Done'
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('-k', type=int, default=5)
parser.add_argument('-p', type=int, default=5)
parser.add_argument('-n', action="store_true", default=False)
parser.add_argument('-c', action="store_true", default=False)
parser.add_argument('model', type=str)
parser.add_argument('dictionary', type=str)
parser.add_argument('dictionary_target', type=str)
parser.add_argument('source', type=str)
parser.add_argument('topic', type=str)
parser.add_argument('saveto', type=str)
args = parser.parse_args()
main(args.model, args.dictionary, args.dictionary_target, args.source, args.topic,
args.saveto, k=args.k, normalize=args.n, n_process=args.p,
chr_level=args.c)