-
Notifications
You must be signed in to change notification settings - Fork 0
/
text2poem_BERT.py
241 lines (205 loc) · 9.44 KB
/
text2poem_BERT.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
# Some parts of the code are taken from https://github.com/aparrish/plot-to-poem/
# The poetry corpus is taken from https://github.com/aparrish/gutenberg-poetry-corpus
import random
import sys
import plotutils
import poemutils
import pronouncing
import re
import string
import sklearn
from math import sqrt, acos, pi, inf
import numpy as np
from tqdm import tqdm
import os
from sentence_transformers import SentenceTransformer
import _pickle as pickle
model_name = sys.argv[1] # all-mpnet-base-v2
#model = SentenceTransformer('stsb-roberta-large', device='cuda')
model = SentenceTransformer(model_name, device='cuda')
def cos_sim(u, v):
dot = np.sum(u * v)
l2u = sqrt(np.sum(u * u))
l2v = sqrt(np.sum(v * v))
cs = dot/(l2u * l2v)
cs = cs if cs > -1 else -1
cs = cs if cs < 1 else 1
return cs
def angular_distance(u, v):
return acos(cos_sim(u, v)) / pi
from annoy import AnnoyIndex
import numpy as numpy
print("Loading plots....")
titles = plotutils.titleindex()
plots = plotutils.loadplots()
#def line_vector(line):
# return model.encode(line)
#print(line_vector('this is a test').shape)
#print(line_vector('this is a much larger test because it is needed, really really needed').shape)
all_lines = []
print("Loading poetry... ")
with open('poetry.txt', 'r', encoding='utf-8') as poetry_file:
for line in poetry_file:
all_lines.append(line.strip())
if not os.path.exists(model_name + '_poetry_bert_embeddings.pkl'):
print("Finding ", model_name, " embeddings for poetry")
poetry_embeddings = model.encode(all_lines, convert_to_numpy=True, show_progress_bar=True, batch_size=16)
with open(model_name + '_poetry_bert_embeddings.pkl', 'wb') as poebefile:
pickle.dump(poetry_embeddings, poebefile, protocol=4)
else:
print("Loading pre-calculated ", model_name, " embeddings for poetry")
with open(model_name + '_poetry_bert_embeddings.pkl', 'rb') as poebefile:
poetry_embeddings = pickle.load(poebefile)
if not os.path.exists(model_name + '_plot_bert_embeddings.pkl'):
print("Finding ", model_name, " embeddings for plots")
plots_embeddings = []
all_plot_sentences = []
all_plot_lengths = [0]
sum_len_plot_sen = 0
for i in tqdm(range(len(plots))):
plot_sentences = plots[i].split('\n')
plot_sentences = filter(None, plot_sentences)
plot_sentences = [sentence.strip() for sentence in plot_sentences if sentence.strip()]
all_plot_sentences += plot_sentences
sum_len_plot_sen += len(plot_sentences)
all_plot_lengths.append(sum_len_plot_sen)
print(len(all_plot_sentences))
print(all_plot_lengths[-1])
all_plot_line_embeddings = model.encode(all_plot_sentences, convert_to_numpy=True, show_progress_bar=True, batch_size=16)
for i in range(len(all_plot_lengths)-1):
plots_embeddings.append(all_plot_line_embeddings[all_plot_lengths[i]:all_plot_lengths[i+1]])
# plots_embeddings.append(plot_line_embeddings)
with open(model_name + '_plot_bert_embeddings.pkl', 'wb') as plobefile:
pickle.dump(plots_embeddings, plobefile, protocol=4)
else:
print("Loading pre-calculated ", model_name, " embeddings for plots")
with open(model_name + '_plot_bert_embeddings.pkl', 'rb') as plobefile:
plots_embeddings = pickle.load(plobefile)
if not os.path.exists(model_name + '_poetry_annoy_bert.ann'):
t = AnnoyIndex(poetry_embeddings[0].shape[0], metric='angular') #fast nearest neight lookup for poem lines
print('Building annoy for fast nearest neighbor search...')
for i in tqdm(range(len(poetry_embeddings))):
t.add_item(i, poetry_embeddings[i])
t.build(100) # build 100 trees. More trees gives higher precision when querying
t.save(model_name + '_poetry_annoy_bert.ann')
print('Saved Poetry annoy model based on ', model_name)
else:
print('Loading previously made annoy model for ', model_name)
t = AnnoyIndex(poetry_embeddings[0].shape[0], metric='angular')
t.load(model_name + '_poetry_annoy_bert.ann')
assert(t.get_n_items() == len(all_lines))
def getplot(idx):
plot_sentences = plots[idx].split('\n')
plot_sentences = filter(None, plot_sentences)
plot_sentences = [sentence.strip() for sentence in plot_sentences if sentence.strip()]
return idx, titles[idx], plot_sentences, plots_embeddings[idx]
def pickrandomplot():
idx = random.randrange(len(titles))
return getplot(idx)
def getplotfromtitle(title):
idx = title2idx[title]
return getplot(idx)
title2idx = dict([(t, i) for i, t in enumerate(titles)])
sentences = ''
with open('input.txt', 'r') as inputFile:
for line in inputFile:
sentences += line.strip() + '\n'
plot_sentences = sentences.split('\n')
plot_sentences = filter(None, plot_sentences)
plot_sentences = [sentence.strip() for sentence in plot_sentences if sentence.strip()]
plot_embeddings = model.encode(plot_sentences, convert_to_numpy=True, show_progress_bar=True)
print('##########################################################################')
# convert a plot to poetry without rhythmic constraint
with open(model_name + '_nonrhythm_output.txt', 'w') as outputFile:
for i in range(len(plot_sentences)):
sentence = plot_sentences[i]
sent_vec = plot_embeddings[i]
match_idx = t.get_nns_by_vector(sent_vec, n=1000)[0]
outputFile.write(all_lines[match_idx] + '\n')
print('##########################################################################')
# convert a plot to poetry with pairs of rhythmic sentences
def find_rhyming_lines(src_text):
src_text = src_text.strip()
exclude = list(string.punctuation)
src_text = ''.join([ch for ch in src_text if ch not in exclude])
src_words = filter(None, src_text.split(' '))
src_words = [word for word in src_words]
#print(src_words)
#print(src_words[-1].lower())
word_rhymes = pronouncing.rhymes(src_words[-1].lower())
#print(word_rhymes)
matched_lines = []
for i in range(len(all_lines)):
line = all_lines[i]
line = line.strip()
exclude = list(string.punctuation)
line = ''.join([ch for ch in line if ch not in exclude])
words = filter(None, line.split(' '))
words = [word for word in words]
if len(words) == 0:
continue
#print(words[-1].lower())
if words[-1].lower() in word_rhymes:
matched_lines.append([line, poetry_embeddings[i]])
return matched_lines
def find_closest(src_vec, linevectuples):
vec_lines = [linevectuple[1] for linevectuple in linevectuples]
index = 0
while (vec_lines[index] is None):
index += 1
best_dist = angular_distance(src_vec, vec_lines[index])
best_index = index
for i in range(index+1, len(vec_lines)):
if vec_lines[i] is not None:
dist = angular_distance(src_vec, vec_lines[i])
if dist < best_dist:
best_dist = dist
best_index = i
return linevectuples[best_index][0], best_dist
with open(model_name + '_rhythm_output.txt', 'w') as outputFile:
for i in range(1, len(plot_sentences) - 1, 2):
sentence1 = plot_sentences[i-1]
sentence2 = plot_sentences[i]
s1_vec = plot_embeddings[i-1]
s2_vec = plot_embeddings[i]
match_idx_s1 = t.get_nns_by_vector(s1_vec, n=1000)[0]
match_idx_s2 = t.get_nns_by_vector(s2_vec, n=1000)[0]
# Find closest poetry line to first line
m1_poetry_line_1 = all_lines[match_idx_s1]
poetry_match1_vec = poetry_embeddings[match_idx_s1] #line_vector(m1_poetry_line_1)
m1_dist1 = angular_distance(s1_vec, poetry_match1_vec)
# Get closest rhyming line according to first match
rhyming_lines_m1 = find_rhyming_lines(m1_poetry_line_1)
if len(rhyming_lines_m1) > 0:
m1_poetry_line_2, m1_dist2 = find_closest(s2_vec, rhyming_lines_m1)
else:
m1_poetry_line_2 = ""
m1_dist2 = inf
# Find closest poetry line to second line
m2_poetry_line_2 = all_lines[match_idx_s2]
poetry_match2_vec = poetry_embeddings[match_idx_s2]
m2_dist2 = angular_distance(s2_vec, poetry_match2_vec)
# Get closest rhyming line according to second match
rhyming_lines_m2 = find_rhyming_lines(m2_poetry_line_2)
if len(rhyming_lines_m2) > 0:
m2_poetry_line_1, m2_dist1 = find_closest(s1_vec, rhyming_lines_m2)
else:
if len(rhyming_lines_m1) == 0:
outputFile.write(all_lines[match_idx_s1] + '\n')
outputFile.write(all_lines[match_idx_s2] + '\n')
continue
else:
m2_poetry_line_1 = ""
m2_dist1 = inf
# Take the closest overall
if m1_dist1 + m1_dist2 <= m2_dist1 + m2_dist2:
outputFile.write(m1_poetry_line_1 + '\n')
outputFile.write(m1_poetry_line_2 + '\n')
else:
outputFile.write(m2_poetry_line_1 + '\n')
outputFile.write(m2_poetry_line_2 + '\n')
if not even:
last_sentence = plot_sentences[-1]
sent_vec = plot_embeddings[-1]
match_idx = t.get_nns_by_vector(sent_vec, n=1000)[0]
outputFile.write(all_lines[match_idx] + '\n')