Spaces:
Runtime error
Runtime error
Create new file
Browse files- rhyme-with-ai/rhyme_generator.py +175 -0
rhyme-with-ai/rhyme_generator.py
ADDED
@@ -0,0 +1,175 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import logging
|
2 |
+
from typing import List
|
3 |
+
|
4 |
+
import numpy as np
|
5 |
+
import tensorflow as tf
|
6 |
+
from transformers import BertTokenizer, TFAutoModelForMaskedLM
|
7 |
+
|
8 |
+
from rhyme_with_ai.token_weighter import TokenWeighter
|
9 |
+
from rhyme_with_ai.utils import pairwise
|
10 |
+
|
11 |
+
|
12 |
+
class RhymeGenerator:
|
13 |
+
def __init__(
|
14 |
+
self,
|
15 |
+
model: TFAutoModelForMaskedLM,
|
16 |
+
tokenizer: BertTokenizer,
|
17 |
+
token_weighter: TokenWeighter = None,
|
18 |
+
):
|
19 |
+
"""Generate rhymes.
|
20 |
+
Parameters
|
21 |
+
----------
|
22 |
+
model : Model for masked language modelling
|
23 |
+
tokenizer : Tokenizer for model
|
24 |
+
token_weighter : Class that weighs tokens
|
25 |
+
"""
|
26 |
+
|
27 |
+
self.model = model
|
28 |
+
self.tokenizer = tokenizer
|
29 |
+
if token_weighter is None:
|
30 |
+
token_weighter = TokenWeighter(tokenizer)
|
31 |
+
self.token_weighter = token_weighter
|
32 |
+
self._logger = logging.getLogger(__name__)
|
33 |
+
|
34 |
+
self.tokenized_rhymes_ = None
|
35 |
+
self.position_probas_ = None
|
36 |
+
|
37 |
+
# Easy access.
|
38 |
+
self.comma_token_id = self.tokenizer.encode(",", add_special_tokens=False)[0]
|
39 |
+
self.period_token_id = self.tokenizer.encode(".", add_special_tokens=False)[0]
|
40 |
+
self.mask_token_id = self.tokenizer.mask_token_id
|
41 |
+
|
42 |
+
def start(self, query: str, rhyme_words: List[str]) -> None:
|
43 |
+
"""Start the sentence generator.
|
44 |
+
Parameters
|
45 |
+
----------
|
46 |
+
query : Seed sentence
|
47 |
+
rhyme_words : Rhyme words for next sentence
|
48 |
+
"""
|
49 |
+
# TODO: What if no content?
|
50 |
+
self._logger.info("Got sentence %s", query)
|
51 |
+
tokenized_rhymes = [
|
52 |
+
self._initialize_rhymes(query, rhyme_word) for rhyme_word in rhyme_words
|
53 |
+
]
|
54 |
+
# Make same length.
|
55 |
+
self.tokenized_rhymes_ = tf.keras.preprocessing.sequence.pad_sequences(
|
56 |
+
tokenized_rhymes, padding="post", value=self.tokenizer.pad_token_id
|
57 |
+
)
|
58 |
+
p = self.tokenized_rhymes_ == self.tokenizer.mask_token_id
|
59 |
+
self.position_probas_ = p / p.sum(1).reshape(-1, 1)
|
60 |
+
|
61 |
+
def _initialize_rhymes(self, query: str, rhyme_word: str) -> List[int]:
|
62 |
+
"""Initialize the rhymes.
|
63 |
+
* Tokenize input
|
64 |
+
* Append a comma if the sentence does not end in it (might add better predictions as it
|
65 |
+
shows the two sentence parts are related)
|
66 |
+
* Make second line as long as the original
|
67 |
+
* Add a period
|
68 |
+
Parameters
|
69 |
+
----------
|
70 |
+
query : First line
|
71 |
+
rhyme_word : Last word for second line
|
72 |
+
Returns
|
73 |
+
-------
|
74 |
+
Tokenized rhyme lines
|
75 |
+
"""
|
76 |
+
|
77 |
+
query_token_ids = self.tokenizer.encode(query, add_special_tokens=False)
|
78 |
+
rhyme_word_token_ids = self.tokenizer.encode(
|
79 |
+
rhyme_word, add_special_tokens=False
|
80 |
+
)
|
81 |
+
|
82 |
+
if query_token_ids[-1] != self.comma_token_id:
|
83 |
+
query_token_ids.append(self.comma_token_id)
|
84 |
+
|
85 |
+
magic_correction = len(rhyme_word_token_ids) + 1 # 1 for comma
|
86 |
+
return (
|
87 |
+
query_token_ids
|
88 |
+
+ [self.tokenizer.mask_token_id] * (len(query_token_ids) - magic_correction)
|
89 |
+
+ rhyme_word_token_ids
|
90 |
+
+ [self.period_token_id]
|
91 |
+
)
|
92 |
+
|
93 |
+
def mutate(self):
|
94 |
+
"""Mutate the current rhymes.
|
95 |
+
Returns
|
96 |
+
-------
|
97 |
+
Mutated rhymes
|
98 |
+
"""
|
99 |
+
self.tokenized_rhymes_ = self._mutate(
|
100 |
+
self.tokenized_rhymes_, self.position_probas_, self.token_weighter.proba
|
101 |
+
)
|
102 |
+
|
103 |
+
rhymes = []
|
104 |
+
for i in range(len(self.tokenized_rhymes_)):
|
105 |
+
rhymes.append(
|
106 |
+
self.tokenizer.convert_tokens_to_string(
|
107 |
+
self.tokenizer.convert_ids_to_tokens(
|
108 |
+
self.tokenized_rhymes_[i], skip_special_tokens=True
|
109 |
+
)
|
110 |
+
)
|
111 |
+
)
|
112 |
+
return rhymes
|
113 |
+
|
114 |
+
def _mutate(
|
115 |
+
self,
|
116 |
+
tokenized_rhymes: np.ndarray,
|
117 |
+
position_probas: np.ndarray,
|
118 |
+
token_id_probas: np.ndarray,
|
119 |
+
) -> np.ndarray:
|
120 |
+
|
121 |
+
replacements = []
|
122 |
+
for i in range(tokenized_rhymes.shape[0]):
|
123 |
+
mask_idx, masked_token_ids = self._mask_token(
|
124 |
+
tokenized_rhymes[i], position_probas[i]
|
125 |
+
)
|
126 |
+
tokenized_rhymes[i] = masked_token_ids
|
127 |
+
replacements.append(mask_idx)
|
128 |
+
|
129 |
+
predictions = self._predict_masked_tokens(tokenized_rhymes)
|
130 |
+
|
131 |
+
for i, token_ids in enumerate(tokenized_rhymes):
|
132 |
+
replace_ix = replacements[i]
|
133 |
+
token_ids[replace_ix] = self._draw_replacement(
|
134 |
+
predictions[i], token_id_probas, replace_ix
|
135 |
+
)
|
136 |
+
tokenized_rhymes[i] = token_ids
|
137 |
+
|
138 |
+
return tokenized_rhymes
|
139 |
+
|
140 |
+
def _mask_token(self, token_ids, position_probas):
|
141 |
+
"""Mask line and return index to update."""
|
142 |
+
token_ids = self._mask_repeats(token_ids, position_probas)
|
143 |
+
ix = self._locate_mask(token_ids, position_probas)
|
144 |
+
token_ids[ix] = self.mask_token_id
|
145 |
+
return ix, token_ids
|
146 |
+
|
147 |
+
def _locate_mask(self, token_ids, position_probas):
|
148 |
+
"""Update masks or a random token."""
|
149 |
+
if self.mask_token_id in token_ids:
|
150 |
+
# Already masks present, just return the last.
|
151 |
+
# We used to return thee first but this returns worse predictions.
|
152 |
+
return np.where(token_ids == self.tokenizer.mask_token_id)[0][-1]
|
153 |
+
return np.random.choice(range(len(position_probas)), p=position_probas)
|
154 |
+
|
155 |
+
def _mask_repeats(self, token_ids, position_probas):
|
156 |
+
"""Repeated tokens are generally of less quality."""
|
157 |
+
repeats = [
|
158 |
+
ii for ii, ids in enumerate(pairwise(token_ids[:-2])) if ids[0] == ids[1]
|
159 |
+
]
|
160 |
+
for ii in repeats:
|
161 |
+
if position_probas[ii] > 0:
|
162 |
+
token_ids[ii] = self.mask_token_id
|
163 |
+
if position_probas[ii + 1] > 0:
|
164 |
+
token_ids[ii + 1] = self.mask_token_id
|
165 |
+
return token_ids
|
166 |
+
|
167 |
+
def _predict_masked_tokens(self, tokenized_rhymes):
|
168 |
+
return self.model(tf.constant(tokenized_rhymes))[0]
|
169 |
+
|
170 |
+
def _draw_replacement(self, predictions, token_probas, replace_ix):
|
171 |
+
"""Get probability, weigh and draw."""
|
172 |
+
# TODO (HG): Can't we softmax when calling the model?
|
173 |
+
probas = tf.nn.softmax(predictions[replace_ix]).numpy() * token_probas
|
174 |
+
probas /= probas.sum()
|
175 |
+
return np.random.choice(range(len(probas)), p=probas)
|