Generate Rhyming Word

parent:
poetry

Related:

# Introduction:

need to get end of word and rhyme. Might be better ways to get it but here's one way to skin this cat. Here's the initial setup; the code's also a gist at https://gist.github.com/brockmanmatt/ce9a2a83a55d9abefc5ca95aa2af8ee0. Load the key however you want.

``````import openai, json, pandas as pd
openai.api_key = "KEY GOES HERE"

#arguments to send the API
kwargs = {
"engine":"davinci",
"temperature":0,
"max_tokens":150,
"stop":"\n\n",
}```
```

# Get end of word

So actually getting the end part of a word seems to require quite a few examples; this may change but for now, 0 shot does not seem to work, nor just just a few examples.

Trying with just a few examples:

``````def getEndOfWord(someWord, verbose=False):
"""
Get the last part of a word that I'll need to rhyme
"""
prompt = ""
prompt += "full: turtle\n"
prompt += "ending: tle\n\n"

prompt += "full: apple\n"
prompt += "ending: ple\n\n"

prompt += "full: training\n"
prompt += "ending: ing\n\n"

prompt += "full: {}\n".format(someWord)
prompt += "ending:"

r = openai.Completion.create(prompt=prompt, **kwargs)["choices"]["text"].strip()
return r```
```

This fails easily;

``````>> getEndOfWord("hamper")
'per'
>> getEndOfWord("attica")
'cia'```
```

So if we add more examples it does better. It might be possible to optimize the context.

``````def getEndOfWord(someWord, verbose=False):
"""
Get the last part of a word that I'll need to rhyme
"""
prompt = ""
prompt += "full: turtle\n"
prompt += "ending: tle\n\n"

prompt += "full: apple\n"
prompt += "ending: ple\n\n"

prompt += "full: training\n"
prompt += "ending: ing\n\n"

prompt += "full: whopper\n"
prompt += "ending: per\n\n"

prompt += "full: balderdash\n"
prompt += "ending: ash\n\n"

prompt += "full: clause\n"
prompt += "ending: ause\n\n"

prompt += "full: higher\n"
prompt += "ending: er\n\n"

prompt += "full: small\n"
prompt += "ending: all\n\n"

prompt += "full: pernicious\n"
prompt += "ending: us\n\n"

prompt += "full: {}\n".format(someWord)
prompt += "ending:"

if verbose:
print(prompt)

r = openai.Completion.create(prompt=prompt, **kwargs)["choices"]["text"].strip()
return r```
```

And this seems to work better, e.g.
``````>> getEndOfWord("hamper")
'per'
>> getEndOfWord("attica")
'ica'```
```

# Getting a word that ends with an ending

So to help it out with getting the ending to a word, we can do some fill in the blak!

``````def fillInWord(letter, ending, temp=0, verbose=False):
"""
generate a word that ends with the ending and starts with a letter
"""
prompt = ""
prompt += "Guess: t__ial\n"

prompt += "Guess: c__ury\n"

prompt += "Guess: a__al\n"

prompt += "Guess: a__le\n"

prompt += "Guess: t__ble\n"

prompt += "Guess: {}__{}\n".format(letter, ending)

if verbose:
print(prompt)

myKwargs = kwargs.copy()
myKwargs["temperature"] = int(temp)
#print(kwargs)
#print(myKwargs)

r = openai.Completion.create(prompt=prompt, **myKwargs)["choices"]["text"].strip()
return r```
```

This often works

``````>> fillInWord("a", "ing", temp=1)
'aching'
>> fillInWord("f", "ing", temp=1)
'fighting'```
```

And we can nest the two functions above to get the end of a word + get a word that rhymes with it

``````>> fillInWord("a", getEndOfWord("hamper"))
'after'```
```

# Generating a word to match

So since can get the ending of a word and generate a word that ends with an ending with a given starting character, we can just try generating a rhyming word for each letter f the alphabet. (I guess for actual poetry we'd want to make sure that the context matters too but I leave that to someone else to figure out).

So here we can (try to) generate a rhyming word for each letter of the alphabet for a target word.

``````import string
def getPossibleWordChoices(ending, temp=0):
choices = []
for x in string.ascii_lowercase:
choices.append(fillInWord(x, ending, temp=temp))
return choices

>> getPossibleWordChoices("lousy")
['ally', 'barely', 'clearly', 'daily', 'easily', 'fly', 'gently', 'holy', 'illy', 'July', 'quickly', 'lovely', 'million', 'nicely', 'only', 'play', 'quickly', 'really', 'slyly', 'truly', 'ugly', 'valley', 'weekly', 'xylophone', 'yearly', 'zealously']```
```

And then we can use semantic similarity to a context to generate the best match to a target context. This is kind of what I do when I try to rhyme which is why I did this this way.

``````def generateRelevantWord(context, wordToRhyme, verbose=False):
"""
return semantic the possibleWord with highest semantic similarity to context
"""
possibleWords = getPossibleWordChoices(getEndOfWord(wordToRhyme))
if verbose:
print(possibleWords)
scores = openai.Engine("davinci").search(
documents=[x for x in possibleWords],
query=context
)

return max([(scores["data"][i]["score"], possibleWords[i]) for i in range(len(possibleWords))])

>> generateRelevantWord("I want to go to sleep but I'm not sure that's a good idea", "lousy")
'quickly'```
```
page revision: 6, last edited: 06 Aug 2020 16:34
{"ft_lang_label":"__label__en","ft_lang_prob":0.65032995,"math_prob":0.75898147,"size":4918,"snap":"2021-04-2021-17","text_gpt3_token_len":1389,"char_repetition_ratio":0.1982092,"word_repetition_ratio":0.16235632,"special_character_ratio":0.29869866,"punctuation_ratio":0.16720955,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.97895044,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2021-01-24T20:43:12Z\",\"WARC-Record-ID\":\"<urn:uuid:64adb259-d584-40ec-9191-3d45b12326de>\",\"Content-Length\":\"36031\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:34d958eb-2ca2-4bda-b6b6-b3c31cd43b1e>\",\"WARC-Concurrent-To\":\"<urn:uuid:29aeef96-95f8-4501-a55d-847ded11d7d2>\",\"WARC-IP-Address\":\"107.20.139.170\",\"WARC-Target-URI\":\"http://gptprompts.wikidot.com/poetry:generate-rhyming-word\",\"WARC-Payload-Digest\":\"sha1:PNBZTQSV7COAKS3E57QB3VPKTU4OVIUH\",\"WARC-Block-Digest\":\"sha1:KXYXRMXXS2TFD45AIOMTNARDVGYVJHMI\",\"WARC-Identified-Payload-Type\":\"application/xhtml+xml\",\"warc_filename\":\"/cc_download/warc_2021/CC-MAIN-2021-04/CC-MAIN-2021-04_segments_1610703557462.87_warc_CC-MAIN-20210124204052-20210124234052-00558.warc.gz\"}"}