-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwrite_poem.py
211 lines (162 loc) · 6.19 KB
/
write_poem.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
import json
import os, sys,time
import logging
import math
import numpy as np
import tensorflow as tf
from char_rnn_model import CharRNNLM,SampleType
from config_poem import config_sample
from word2vec_helper import Word2Vec
from rhyme_helper import RhymeWords
class WritePoem():
def __init__(self,args):
self.args = args
logging.basicConfig(stream=sys.stdout,
format='%(asctime)s %(levelname)s:%(message)s',
level=logging.INFO, datefmt='%I:%M:%S')
with open(os.path.join(self.args.model_dir, 'result.json'), 'r') as f:
result = json.load(f)
params = result['params']
best_model = result['best_model']
best_valid_ppl = result['best_valid_ppl']
if 'encoding' in result:
self.args.encoding = result['encoding']
else:
self.args.encoding = 'utf-8'
base_path = args.data_dir
w2v_file = os.path.join(base_path, "vectors_poem.bin")
self.w2v = Word2Vec(w2v_file)
RhymeWords.read_rhyme_words(os.path.join(base_path,'rhyme_words.txt'))
if args.seed >= 0:
np.random.seed(args.seed)
logging.info('best_model: %s\n', best_model)
self.sess = tf.Session()
w2v_vocab_size = len(self.w2v.model.vocab)
with tf.name_scope('evaluation'):
self.model = CharRNNLM(is_training=False,w2v_model = self.w2v.model,vocab_size=w2v_vocab_size, infer=True, **params)
saver = tf.train.Saver(name='model_saver')
saver.restore(self.sess, best_model)
def free_verse(self):
'''
自由诗
Returns:
'''
sample = self.model.sample_seq(self.sess, 40, '[',sample_type= SampleType.weighted_sample)
if not sample:
return 'err occar!'
print('free_verse:',sample)
idx_end = sample.find(']')
parts = sample.split('。')
if len(parts) > 1:
two_sentence_len = len(parts[0]) + len(parts[1])
if idx_end < 0 or two_sentence_len < idx_end:
return sample[1:two_sentence_len + 2]
return sample[1:idx_end]
@staticmethod
def assemble(sample):
if sample:
parts = sample.split('。')
if len(parts) > 1:
return '{}。{}。'.format(parts[0][1:],parts[1][:len(parts[0])])
return ''
def rhyme_verse(self):
'''
押韵诗
Returns:
'''
gen_len = 20
sample = self.model.sample_seq(self.sess, gen_len, start_text='[',sample_type= SampleType.weighted_sample)
if not sample:
return 'err occar!'
print('rhyme_verse:',sample)
parts = sample.split('。')
if len(parts) > 0:
start = parts[0] + '。'
rhyme_ref_word = start[-2]
rhyme_seq = len(start) - 3
sample = self.model.sample_seq(self.sess, gen_len , start,
sample_type= SampleType.weighted_sample,rhyme_ref =rhyme_ref_word,rhyme_idx = rhyme_seq )
print(sample)
return WritePoem.assemble(sample)
return sample[1:]
def hide_words(self,given_text):
'''
藏字诗
Args:
given_text:
Returns:
'''
if(not given_text):
return self.rhyme_verse()
givens = ['','']
split_len = math.ceil(len(given_text)/2)
givens[0] = given_text[:split_len]
givens[1] = given_text[split_len:]
gen_len = 20
sample = self.model.sample_seq(self.sess, gen_len, start_text='[',sample_type= SampleType.select_given,given=givens[0])
if not sample:
return 'err occar!'
print('rhyme_verse:',sample)
parts = sample.split('。')
if len(parts) > 0:
start = parts[0] + '。'
rhyme_ref_word = start[-2]
rhyme_seq = len(start) - 3
# gen_len = len(start) - 1
sample = self.model.sample_seq(self.sess, gen_len , start,
sample_type= SampleType.select_given,given=givens[1],rhyme_ref =rhyme_ref_word,rhyme_idx = rhyme_seq )
print(sample)
return WritePoem.assemble(sample)
return sample[1:]
def cangtou(self,given_text):
'''
藏头诗
Returns:
'''
if(not given_text):
return self.rhyme_verse()
start = ''
rhyme_ref_word = ''
rhyme_seq = 0
# for i,word in enumerate(given_text):
for i in range(4):
word = ''
if i < len(given_text):
word = given_text[i]
if i == 0:
start = '[' + word
else:
start += word
before_idx = len(start)
if(i != 3):
sample = self.model.sample_seq(self.sess, self.args.length, start,
sample_type= SampleType.weighted_sample )
else:
if not word:
rhyme_seq += 1
sample = self.model.sample_seq(self.sess, self.args.length, start,
sample_type= SampleType.max_prob,rhyme_ref =rhyme_ref_word,rhyme_idx = rhyme_seq )
print('Sampled text is:\n\n%s' % sample)
sample = sample[before_idx:]
idx1 = sample.find(',')
idx2 = sample.find('。')
min_idx = min(idx1,idx2)
if min_idx == -1:
if idx1 > -1 :
min_idx = idx1
else: min_idx =idx2
if min_idx > 0:
# last_sample.append(sample[:min_idx + 1])
start ='{}{}'.format(start, sample[:min_idx + 1])
if i == 1:
rhyme_seq = min_idx - 1
rhyme_ref_word = sample[rhyme_seq]
print('last_sample text is:\n\n%s' % start)
return WritePoem.assemble(start)
def start_model():
now = int(time.time())
args = config_sample('--model_dir output_poem --length 16 --seed {}'.format(now))
writer = WritePoem(args)
return writer
if __name__ == '__main__':
writer = start_model()