Camille commited on
Commit
0ba900e
1 Parent(s): 17bfee8

first commit

Browse files
app.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ import logging
3
+ from typing import List
4
+
5
+ import streamlit as st
6
+ from transformers import BertTokenizer, TFAutoModelForMaskedLM
7
+
8
+ from rhyme_with_ai.utils import color_new_words, sanitize
9
+ from rhyme_with_ai.rhyme import query_rhyme_words
10
+ from rhyme_with_ai.rhyme_generator import RhymeGenerator
11
+
12
+
13
+ DEFAULT_QUERY = "Machines will take over the world soon"
14
+ N_RHYMES = 10
15
+
16
+
17
+ LANGUAGE = st.sidebar.radio("Language", ["english", "dutch"],0)
18
+ if LANGUAGE == "english":
19
+ MODEL_PATH = "bert-large-cased-whole-word-masking"
20
+ ITER_FACTOR = 5
21
+ elif LANGUAGE == "dutch":
22
+ MODEL_PATH = "GroNLP/bert-base-dutch-cased"
23
+ ITER_FACTOR = 10 # Faster model
24
+ else:
25
+ raise NotImplementedError(f"Unsupported language ({LANGUAGE}) expected 'english' or 'dutch'.")
26
+
27
+ def main():
28
+ st.markdown(
29
+ "<sup>Created with "
30
+ "[Datamuse](https://www.datamuse.com/api/), "
31
+ "[Mick's rijmwoordenboek](https://rijmwoordenboek.nl), "
32
+ "[Hugging Face](https://huggingface.co/), "
33
+ "[Streamlit](https://streamlit.io/) and "
34
+ "[App Engine](https://cloud.google.com/appengine/)."
35
+ " Read our [blog](https://blog.godatadriven.com/rhyme-with-ai) "
36
+ "or check the "
37
+ "[source](https://github.com/godatadriven/rhyme-with-ai).</sup>",
38
+ unsafe_allow_html=True,
39
+ )
40
+ st.title("Rhyme with AI")
41
+ query = get_query()
42
+ if not query:
43
+ query = DEFAULT_QUERY
44
+ rhyme_words_options = query_rhyme_words(query, n_rhymes=N_RHYMES,language=LANGUAGE)
45
+ if rhyme_words_options:
46
+ logging.getLogger(__name__).info("Got rhyme words: %s", rhyme_words_options)
47
+ start_rhyming(query, rhyme_words_options)
48
+ else:
49
+ st.write("No rhyme words found")
50
+
51
+
52
+ def get_query():
53
+ q = sanitize(
54
+ st.text_input("Write your first line and press ENTER to rhyme:", DEFAULT_QUERY)
55
+ )
56
+ if not q:
57
+ return DEFAULT_QUERY
58
+ return q
59
+
60
+
61
+ def start_rhyming(query, rhyme_words_options):
62
+ st.markdown("## My Suggestions:")
63
+
64
+ progress_bar = st.progress(0)
65
+ status_text = st.empty()
66
+ max_iter = len(query.split()) * ITER_FACTOR
67
+
68
+ rhyme_words = rhyme_words_options[:N_RHYMES]
69
+
70
+ model, tokenizer = load_model(MODEL_PATH)
71
+ sentence_generator = RhymeGenerator(model, tokenizer)
72
+ sentence_generator.start(query, rhyme_words)
73
+
74
+ current_sentences = [" " for _ in range(N_RHYMES)]
75
+ for i in range(max_iter):
76
+ previous_sentences = copy.deepcopy(current_sentences)
77
+ current_sentences = sentence_generator.mutate()
78
+ display_output(status_text, query, current_sentences, previous_sentences)
79
+ progress_bar.progress(i / (max_iter - 1))
80
+ st.balloons()
81
+
82
+
83
+ @st.cache(allow_output_mutation=True)
84
+ def load_model(model_path):
85
+ return (
86
+ TFAutoModelForMaskedLM.from_pretrained(model_path),
87
+ BertTokenizer.from_pretrained(model_path),
88
+ )
89
+
90
+
91
+ def display_output(status_text, query, current_sentences, previous_sentences):
92
+ print_sentences = []
93
+ for new, old in zip(current_sentences, previous_sentences):
94
+ formatted = color_new_words(new, old)
95
+ after_comma = "<li>" + formatted.split(",")[1][:-2] + "</li>"
96
+ print_sentences.append(after_comma)
97
+ status_text.markdown(
98
+ query + ",<br>" + "".join(print_sentences), unsafe_allow_html=True
99
+ )
100
+
101
+
102
+
103
+ if __name__ == "__main__":
104
+ logging.basicConfig(level=logging.INFO)
105
+ main()
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ gazpacho
2
+ numpy
3
+ requests
4
+ tensorflow
5
+ transformers
rhyme_with_ai/__init__.py ADDED
File without changes
rhyme_with_ai/rhyme.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import functools
2
+ import random
3
+ from typing import List, Optional
4
+
5
+ import requests
6
+ from gazpacho import Soup, get
7
+
8
+ from rhyme_with_ai.utils import find_last_word
9
+
10
+
11
+ def query_rhyme_words(sentence: str, n_rhymes: int, language:str="english") -> List[str]:
12
+ """Returns a list of rhyme words for a sentence.
13
+ Parameters
14
+ ----------
15
+ sentence : Sentence that may end with punctuation
16
+ n_rhymes : Maximum number of rhymes to return
17
+ Returns
18
+ -------
19
+ List[str] -- List of words that rhyme with the final word
20
+ """
21
+ last_word = find_last_word(sentence)
22
+ if language == "english":
23
+ return query_datamuse_api(last_word, n_rhymes)
24
+ elif language == "dutch":
25
+ return mick_rijmwoordenboek(last_word, n_rhymes)
26
+ else:
27
+ raise NotImplementedError(f"Unsupported language ({language}) expected 'english' or 'dutch'.")
28
+
29
+
30
+ def query_datamuse_api(word: str, n_rhymes: Optional[int] = None) -> List[str]:
31
+ """Query the DataMuse API.
32
+ Parameters
33
+ ----------
34
+ word : Word to rhyme with
35
+ n_rhymes : Max rhymes to return
36
+ Returns
37
+ -------
38
+ Rhyme words
39
+ """
40
+ out = requests.get(
41
+ "https://api.datamuse.com/words", params={"rel_rhy": word}
42
+ ).json()
43
+ words = [_["word"] for _ in out]
44
+ if n_rhymes is None:
45
+ return words
46
+ return words[:n_rhymes]
47
+
48
+
49
+ @functools.lru_cache(maxsize=128, typed=False)
50
+ def mick_rijmwoordenboek(word: str, n_words: int):
51
+ url = f"https://rijmwoordenboek.nl/rijm/{word}"
52
+ html = get(url)
53
+ soup = Soup(html)
54
+
55
+ results = soup.find("div", {"id": "rhymeResultsWords"}).html.split("<br>")
56
+
57
+ # clean up
58
+ results = [r.replace("\n", "").replace(" ", "") for r in results]
59
+
60
+ # filter html and empty strings
61
+ results = [r for r in results if ("<" not in r) and (len(r) > 0)]
62
+
63
+ return random.sample(results, min(len(results), n_words))
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)
rhyme_with_ai/token_weighter.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+
4
+ class TokenWeighter:
5
+ def __init__(self, tokenizer):
6
+ self.tokenizer_ = tokenizer
7
+ self.proba = self.get_token_proba()
8
+
9
+ def get_token_proba(self):
10
+ valid_token_mask = self._filter_short_partial(self.tokenizer_.vocab)
11
+ return valid_token_mask
12
+
13
+ def _filter_short_partial(self, vocab):
14
+ valid_token_ids = [v for k, v in vocab.items() if len(k) > 1 and "#" not in k]
15
+ is_valid = np.zeros(len(vocab.keys()))
16
+ is_valid[valid_token_ids] = 1
17
+ return is_valid
rhyme_with_ai/utils.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import itertools
2
+ import string
3
+
4
+
5
+ def color_new_words(new: str, old: str, color: str = "#eefa66") -> str:
6
+ """Color new words in strings with a span."""
7
+
8
+ def find_diff(new_, old_):
9
+ return [ii for ii, (n, o) in enumerate(zip(new_, old_)) if n != o]
10
+
11
+ new_words = new.split()
12
+ old_words = old.split()
13
+ forward = find_diff(new_words, old_words)
14
+ backward = find_diff(new_words[::-1], old_words[::-1])
15
+
16
+ if not forward or not backward:
17
+ # No difference
18
+ return new
19
+
20
+ start, end = forward[0], len(new_words) - backward[0]
21
+ return (
22
+ " ".join(new_words[:start])
23
+ + " "
24
+ + f'<span style="background-color: {color}">'
25
+ + " ".join(new_words[start:end])
26
+ + "</span>"
27
+ + " "
28
+ + " ".join(new_words[end:])
29
+ )
30
+
31
+
32
+ def find_last_word(s):
33
+ """Find the last word in a string."""
34
+ # Note: will break on \n, \r, etc.
35
+ alpha_only_sentence = "".join([c for c in s if (c.isalpha() or (c == " "))]).strip()
36
+ return alpha_only_sentence.split()[-1]
37
+
38
+
39
+ def pairwise(iterable):
40
+ """s -> (s0,s1), (s1,s2), (s2, s3), ..."""
41
+ # https://stackoverflow.com/questions/5434891/iterate-a-list-as-pair-current-next-in-python
42
+ a, b = itertools.tee(iterable)
43
+ next(b, None)
44
+ return zip(a, b)
45
+
46
+
47
+ def sanitize(s):
48
+ """Remove punctuation from a string."""
49
+ return s.translate(str.maketrans("", "", string.punctuation))