add limerick functionaliteit #5 #39

Merged
mark merged 3 commits from limericks into master 2026-10-24 23:14:55 +02:00
Showing only changes of commit 8517f544d5 - Show all commits
+325 -75
View File
@@ -12,7 +12,7 @@ import re
class Chatbot(commands.Cog): class Chatbot(commands.Cog):
"""Een heuse chatbot. Under construction...""" """Een heuse chatbot. Under construction..."""
def __init__(self, bot): def __init__(self, bot):
self.bot = bot self.bot = bot
self.voice_states = {} self.voice_states = {}
@@ -30,14 +30,19 @@ class Chatbot(commands.Cog):
np.save("markov_dict.npy", initFile) np.save("markov_dict.npy", initFile)
except: except:
print("ERROR! - Could not open or create Markov chat file") print("ERROR! - Could not open or create Markov chat file")
self.wordDict = np.load("markov_dict.npy", allow_pickle=True).item()
self.wordPairDict = self.wordDict["pairs"]
self.forward_dict = self.wordPairDict
self.reverse_dict = self.create_reverse_dict(self.forward_dict)
self.rijmwoordenboek = self.create_rijmwoordenboek(self.reverse_dict)
Review

Nu niets mee doen, maar de oude features hier doen alles op runtime: Functie aanroepen is dict inladen > parsen > doei.

Zo ook het leren van stroop.

Jij hebt (waarschijnlijk verstandiger) ervoor gekozen om dingen gewoon één keer in te laden en in memory te houden zodat het ready4use is wanneer je het nodig hebt. Dat is denk ik de goede keuze.

Out of scope: zo zou de rest van de chatbot eigenlijk ook moeten werken.

Nadeel is wel dat elke keer dat stroop leert je niet opnieuw je rijmpjes opbouwt. Workaround kan eventueel zijn om het inladen van het dict in een functie te proppen. initialize_rijm ofzo, weet ik veel. En die dan aan te roepen in de leer-functies aan het einde.

Hoef je niets mee te doen. Als je het zo laadt moet stroop een restart om het nieuwe woordenboek op te pakken, en dat is ook prima.

Nu niets mee doen, maar de oude features hier doen alles op runtime: Functie aanroepen is dict inladen > parsen > doei. Zo ook het leren van stroop. Jij hebt (waarschijnlijk verstandiger) ervoor gekozen om dingen gewoon één keer in te laden en in memory te houden zodat het ready4use is wanneer je het nodig hebt. Dat is denk ik de goede keuze. Out of scope: zo zou de rest van de chatbot eigenlijk ook moeten werken. Nadeel is wel dat elke keer dat stroop leert je niet opnieuw je rijmpjes opbouwt. Workaround kan eventueel zijn om het inladen van het dict in een functie te proppen. `initialize_rijm` ofzo, weet ik veel. En die dan aan te roepen in de leer-functies aan het einde. Hoef je niets mee te doen. Als je het zo laadt moet stroop een restart om het nieuwe woordenboek op te pakken, en dat is ook prima.
Review

Zat er al aan te denken om een functie te maken die dat periodiek doet of idd na een bepaalde aanroep. Nu update hij de woordjes elke keer als stroop restart en dat vond ik voor nu wel prima. Aangezien dit breder is dan mijn Limerick implementatie heb ik er een issue van gemaakt. zie #40

Zat er al aan te denken om een functie te maken die dat periodiek doet of idd na een bepaalde aanroep. Nu update hij de woordjes elke keer als stroop restart en dat vond ik voor nu wel prima. Aangezien dit breder is dan mijn Limerick implementatie heb ik er een issue van gemaakt. zie #40
#Do stuff when a message comes in: #Do stuff when a message comes in:
@self.bot.event @self.bot.event
async def on_message(message): async def on_message(message):
if message.author.bot: if message.author.bot:
return #ignore your own messages, Stroop return #ignore your own messages, Stroop
if message.content.strip() == "" or message.content.strip()[0] != '!': #don't respond to a command if message.content.strip() == "" or message.content.strip()[0] != '!': #don't respond to a command
if message.content.lower() == "nihao": if message.content.lower() == "nihao":
await message.channel.send("kankerlauw") await message.channel.send("kankerlauw")
@@ -53,7 +58,7 @@ class Chatbot(commands.Cog):
self.getResponseForMessageLocal("stroopwafel") self.getResponseForMessageLocal("stroopwafel")
] ]
try: try:
MENTIONED_RESPONSES.append("Wat mot je, " + random.choice(self.bot.get_cog("Shitpost").insult) + "?") MENTIONED_RESPONSES.append("Wat mot je, " + random.choice(self.bot.get_cog("Shitpost").insult) + "?")
except: except:
print("ERROR! - Could not import insults") print("ERROR! - Could not import insults")
await message.channel.send(random.choice(MENTIONED_RESPONSES)) await message.channel.send(random.choice(MENTIONED_RESPONSES))
@@ -75,16 +80,16 @@ class Chatbot(commands.Cog):
a = a / 20 # significantly increase the chance of responding if somebody talks about him. a = a / 20 # significantly increase the chance of responding if somebody talks about him.
if message.channel.id == os.getenv('STROOP_CHANNEL_SHITPOST') and a < 40: #shitpost channel if message.channel.id == os.getenv('STROOP_CHANNEL_SHITPOST') and a < 40: #shitpost channel
await self.respondToMessage(message) await self.respondToMessage(message)
elif a < 10: #all other channels elif a < 10: #all other channels
await self.respondToMessage(message) await self.respondToMessage(message)
#process commands: #process commands:
await self.bot.process_commands(message) await self.bot.process_commands(message)
def __check(self, ctx): def __check(self, ctx):
return True return True
#The "Guus filter" #The "Guus filter"
#Don't allow to learn from very large personal messages #Don't allow to learn from very large personal messages
#Only learn from 10 personal messages per hour at most #Only learn from 10 personal messages per hour at most
@@ -98,29 +103,29 @@ class Chatbot(commands.Cog):
if self.pmCount > 10: if self.pmCount > 10:
return False return False
return True return True
#Make word pairs: #Make word pairs:
def makePairs(self, corpus): def makePairs(self, corpus):
for i in range(len(corpus)-1): for i in range(len(corpus)-1):
yield (corpus[i], corpus[i+1]) yield (corpus[i], corpus[i+1])
#Make word trairs. Yes, I completely made up "trair" #Make word trairs. Yes, I completely made up "trair"
#It's like pairs, but with three, but not really, because there are two. OK? #It's like pairs, but with three, but not really, because there are two. OK?
#[1 0 1] #[1 0 1]
def makeTrairs(self, corpus): def makeTrairs(self, corpus):
for i in range(1, len(corpus)-1): for i in range(1, len(corpus)-1):
yield (corpus[i-1], corpus[i+1]) yield (corpus[i-1], corpus[i+1])
#Learn from a human message #Learn from a human message
#Returns an updated dict #Returns an updated dict
def learnFrom(self, wordDictPairs, wordDictTrairs, message: str): def learnFrom(self, wordDictPairs, wordDictTrairs, message: str):
newPairDict = wordDictPairs newPairDict = wordDictPairs
newTrairDict = wordDictTrairs newTrairDict = wordDictTrairs
#If the message is only a tag, don't learn from it. return #If the message is only a tag, don't learn from it. return
if message.count(' ') == 0 and message[0:2] == "<@": if message.count(' ') == 0 and message[0:2] == "<@":
return newPairDict, newTrairDict; return newPairDict, newTrairDict;
message = self.START_OF_MESSAGE + " " + message + " " + self.END_OF_MESSAGE message = self.START_OF_MESSAGE + " " + message + " " + self.END_OF_MESSAGE
corpus = message.split() corpus = message.split()
for n, word in enumerate(corpus): for n, word in enumerate(corpus):
@@ -137,7 +142,7 @@ class Chatbot(commands.Cog):
else: else:
newPairDict[word_1][word_2] = 1 newPairDict[word_1][word_2] = 1
else: else:
newPairDict[word_1] = {word_2 : 1} newPairDict[word_1] = {word_2 : 1}
#Add wordcounts to trair dict #Add wordcounts to trair dict
for word_1, word_3 in trairs: for word_1, word_3 in trairs:
if word_1 in newTrairDict.keys(): if word_1 in newTrairDict.keys():
@@ -147,18 +152,18 @@ class Chatbot(commands.Cog):
newTrairDict[word_1][word_3] = 1 newTrairDict[word_1][word_3] = 1
else: else:
newTrairDict[word_1] = {word_3 : 1} newTrairDict[word_1] = {word_3 : 1}
return newPairDict, newTrairDict; return newPairDict, newTrairDict;
#Learn to respond to messages #Learn to respond to messages
#Returns a new dict with response pairs #Returns a new dict with response pairs
def learnResponse(self, wordDictResp, message1: str, message2: str): def learnResponse(self, wordDictResp, message1: str, message2: str):
STOP_WORDS = ["aan", "achter", "al", "ben", "dan", "dat", "de", "die", "dit", "een", "en", "er", "gehad", "had", "heb", STOP_WORDS = ["aan", "achter", "al", "ben", "dan", "dat", "de", "die", "dit", "een", "en", "er", "gehad", "had", "heb",
"hen", "het", "hun", "in", "is", "kon", "met", "na", "of", "om", "ook", "op", "tot", "van", "was", "wat", "zo", "hen", "het", "hun", "in", "is", "kon", "met", "na", "of", "om", "ook", "op", "tot", "van", "was", "wat", "zo",
"a", "an", "the", "am", "was", "were", "be", "not", "at"] "a", "an", "the", "am", "was", "were", "be", "not", "at"]
newRespPairDict = wordDictResp newRespPairDict = wordDictResp
#Split messages into words and remove stopwords: #Split messages into words and remove stopwords:
message1List = [] message1List = []
message2List = [] message2List = []
@@ -168,7 +173,7 @@ class Chatbot(commands.Cog):
for word in message2.split(): for word in message2.split():
if word not in STOP_WORDS: if word not in STOP_WORDS:
message2List.append(word) message2List.append(word)
#link words of response to words of initial message #link words of response to words of initial message
for word_1 in message1List: for word_1 in message1List:
for word_2 in message2List: for word_2 in message2List:
@@ -178,11 +183,11 @@ class Chatbot(commands.Cog):
else: else:
newRespPairDict[word_1][word_2] = 1 newRespPairDict[word_1][word_2] = 1
else: else:
newRespPairDict[word_1] = {word_2 : 1} newRespPairDict[word_1] = {word_2 : 1}
return newRespPairDict return newRespPairDict
@commands.command(pass_context=True, hidden=True) @commands.command(pass_context=True, hidden=True)
async def trainmarkovchat(self, ctx, channelId=409751773595566081, nrOfMessages=50): async def trainmarkovchat(self, ctx, channelId=409751773595566081, nrOfMessages=50):
@@ -190,26 +195,26 @@ class Chatbot(commands.Cog):
param channelId: use this channel to train param channelId: use this channel to train
param nrOfMessages: use the x most recent messages param nrOfMessages: use the x most recent messages
""" """
channel=self.bot.get_channel(channelId) channel=self.bot.get_channel(channelId)
await self.learnFromMessagesInChannel(channel, nrOfMessages) await self.learnFromMessagesInChannel(channel, nrOfMessages)
await ctx.channel.send("Ik heb weer wat nieuwe woordjes geleerd. :slight_smile:") await ctx.channel.send("Ik heb weer wat nieuwe woordjes geleerd. :slight_smile:")
#Learns from an x number of messages from a certain channel #Learns from an x number of messages from a certain channel
async def learnFromMessagesInChannel(self, channel, nrOfMessages): async def learnFromMessagesInChannel(self, channel, nrOfMessages):
#Open current chain: #Open current chain:
wordDict = np.load('markov_dict.npy', allow_pickle=True).item() wordDict = np.load('markov_dict.npy', allow_pickle=True).item()
#Iterate through the last x messages from the channel: #Iterate through the last x messages from the channel:
messageIterator = channel.history(limit=nrOfMessages, before=None, after=None, oldest_first=False, around=None) messageIterator = channel.history(limit=nrOfMessages, before=None, after=None, oldest_first=False, around=None)
allMessages = [] allMessages = []
for i in range(nrOfMessages): for i in range(nrOfMessages):
msg = await anext(messageIterator) msg = await anext(messageIterator)
allMessages.append(msg) allMessages.append(msg)
i = 0 i = 0
nextMessageIndex = -10 nextMessageIndex = -10
#Note: the loop goes from new to old #Note: the loop goes from new to old
@@ -235,36 +240,36 @@ class Chatbot(commands.Cog):
else: else:
# Usable message! # Usable message!
wordDict['pairs'], wordDict['trairs'] = self.learnFrom(wordDict['pairs'], wordDict['trairs'], messageContent) wordDict['pairs'], wordDict['trairs'] = self.learnFrom(wordDict['pairs'], wordDict['trairs'], messageContent)
if (i-nextMessageIndex) == 1 and msg.author != nextMessage.author: #the previous usable messages was the one right after this one and was not from the same author if (i-nextMessageIndex) == 1 and msg.author != nextMessage.author: #the previous usable messages was the one right after this one and was not from the same author
timeDelta = nextMessage.created_at - msg.created_at timeDelta = nextMessage.created_at - msg.created_at
#TODO check for different author #TODO check for different author
if timeDelta.days == 0 and timeDelta.seconds < 3600: #less than an hour difference if timeDelta.days == 0 and timeDelta.seconds < 3600: #less than an hour difference
#this is counted as a response. learn from it #this is counted as a response. learn from it
wordDict['responsePairs'] = self.learnResponse(wordDict['responsePairs'], messageContent, nextMessageContent) wordDict['responsePairs'] = self.learnResponse(wordDict['responsePairs'], messageContent, nextMessageContent)
#save for next iteration: #save for next iteration:
nextMessage = msg nextMessage = msg
nextMessageContent = messageContent nextMessageContent = messageContent
nextMessageIndex = i nextMessageIndex = i
i += 1 i += 1
np.save("markov_dict.npy", wordDict) np.save("markov_dict.npy", wordDict)
@commands.command(pass_context=True, hidden=False) @commands.command(pass_context=True, hidden=False)
async def reageer(self, ctx): async def reageer(self, ctx):
"""Laat Stroop ergens op reageren. """Laat Stroop ergens op reageren.
Stroop leert van onze gesprekken. Hij kan zich nu voordoen als een van ons. Soort van. Stroop leert van onze gesprekken. Hij kan zich nu voordoen als een van ons. Soort van.
""" """
#Get previous message to respond to #Get previous message to respond to
messageIterator = ctx.channel.history(limit=3, before=None, after=None, oldest_first=False, around=None) messageIterator = ctx.channel.history(limit=3, before=None, after=None, oldest_first=False, around=None)
messageToRespondTo = await anext(messageIterator) #this will be the !reageer command. skip messageToRespondTo = await anext(messageIterator) #this will be the !reageer command. skip
messageToRespondTo = await anext(messageIterator) messageToRespondTo = await anext(messageIterator)
if messageToRespondTo.content.strip()[0] == '!' or messageToRespondTo.author.bot: #another chance if messageToRespondTo.content.strip()[0] == '!' or messageToRespondTo.author.bot: #another chance
messageToRespondTo = await anext(messageIterator) #but it's not a huge problem if he responds to himself messageToRespondTo = await anext(messageIterator) #but it's not a huge problem if he responds to himself
if messageToRespondTo.content.strip()[0] == '!': if messageToRespondTo.content.strip()[0] == '!':
wordsToRespondTo = [] wordsToRespondTo = []
else: else:
wordsToRespondTo = messageToRespondTo.content.strip().split() wordsToRespondTo = messageToRespondTo.content.strip().split()
@@ -275,26 +280,26 @@ class Chatbot(commands.Cog):
await ctx.message.delete() await ctx.message.delete()
except: except:
pass pass
response = await self.getResponseForMessage(wordsToRespondTo) response = await self.getResponseForMessage(wordsToRespondTo)
await ctx.channel.send(response) await ctx.channel.send(response)
# Calculate probabilities and pick a next word from a word pair dict: # Calculate probabilities and pick a next word from a word pair dict:
# https://stackoverflow.com/questions/835092/python-dictionary-are-keys-and-values-always-the-same-order # https://stackoverflow.com/questions/835092/python-dictionary-are-keys-and-values-always-the-same-order
def pickNextWord(self, pairPossibilities): def pickNextWord(self, pairPossibilities):
possible_words = list(pairPossibilities.keys()) possible_words = list(pairPossibilities.keys())
weights = np.array(list(pairPossibilities.values())) weights = np.array(list(pairPossibilities.values()))
probs = weights / weights.sum() probs = weights / weights.sum()
return np.random.choice(possible_words, p=probs) return np.random.choice(possible_words, p=probs)
#Respond to a message. #Respond to a message.
#Assumes the message isn't a command #Assumes the message isn't a command
async def respondToMessage(self, message): async def respondToMessage(self, message):
wordsToRespondTo = message.content.strip().split() wordsToRespondTo = message.content.strip().split()
response = await self.getResponseForMessage(wordsToRespondTo) response = await self.getResponseForMessage(wordsToRespondTo)
await message.channel.send(response) await message.channel.send(response)
#Gets a response #Gets a response
async def getResponseForMessage(self, wordsToRespondTo, gptChance=0.1): async def getResponseForMessage(self, wordsToRespondTo, gptChance=0.1):
if random.random() < 1-gptChance: if random.random() < 1-gptChance:
@@ -324,28 +329,28 @@ class Chatbot(commands.Cog):
return self.translateTo("nl", respons) return self.translateTo("nl", respons)
def getResponseForMessageLocal(self, wordsToRespondTo): def getResponseForMessageLocal(self, wordsToRespondTo):
MAX_N_WORDS = 100 #Don't use more words than this MAX_N_WORDS = 100 #Don't use more words than this
#Get dictionary/Markov chain #Get dictionary/Markov chain
wordDict = np.load('markov_dict.npy', allow_pickle=True).item() wordDict = np.load('markov_dict.npy', allow_pickle=True).item()
wordPairDict = wordDict['pairs'] wordPairDict = wordDict['pairs']
wordTrairDict = wordDict['trairs'] wordTrairDict = wordDict['trairs']
responsePairDict = wordDict['responsePairs'] responsePairDict = wordDict['responsePairs']
#TODO store in global variable to minimise IO? #TODO store in global variable to minimise IO?
#Start with <SOM> #Start with <SOM>
chain = [self.START_OF_MESSAGE] chain = [self.START_OF_MESSAGE]
#Go through the chain: #Go through the chain:
for i in range(1, MAX_N_WORDS): for i in range(1, MAX_N_WORDS):
if chain[-1] == self.END_OF_MESSAGE: if chain[-1] == self.END_OF_MESSAGE:
break break
#Find the possibilities: #Find the possibilities:
pairPossibilities = wordPairDict[chain[-1]].copy() pairPossibilities = wordPairDict[chain[-1]].copy()
#Increase score if it would be a good response: #Increase score if it would be a good response:
for userWord in wordsToRespondTo: for userWord in wordsToRespondTo:
if userWord in responsePairDict: if userWord in responsePairDict:
@@ -363,75 +368,75 @@ class Chatbot(commands.Cog):
for word2 in pairPossibilities.keys(): for word2 in pairPossibilities.keys():
if word2 in trairPossibilities.keys(): if word2 in trairPossibilities.keys():
pairPossibilities[word2] += trairPossibilities[word2] pairPossibilities[word2] += trairPossibilities[word2]
#Pick a next word: #Pick a next word:
chain.append(self.pickNextWord(pairPossibilities)) chain.append(self.pickNextWord(pairPossibilities))
if chain[0] == self.START_OF_MESSAGE: if chain[0] == self.START_OF_MESSAGE:
chain = chain[1:-1] #remove <SOM> and <EOM> chain = chain[1:-1] #remove <SOM> and <EOM>
else: else:
chain = chain[:-1] #remove <EOM> chain = chain[:-1] #remove <EOM>
#remove 90% of tags: #remove 90% of tags:
for n, word in enumerate(chain): for n, word in enumerate(chain):
if word[0:2] == "<@": if word[0:2] == "<@":
a = random.randint(1,10) a = random.randint(1,10)
if a != 1: if a != 1:
chain[n] = "@jemoeder" chain[n] = "@jemoeder"
#print(' '.join(chain)) #print(' '.join(chain))
#await ctx.channel.send(' '.join(chain)) #await ctx.channel.send(' '.join(chain))
return ' '.join(chain) return ' '.join(chain)
#Try to count the number of syllables in a word #Try to count the number of syllables in a word
#Used to make Haikus #Used to make Haikus
def countSyllables(self, word: str): def countSyllables(self, word: str):
KNOWN_ACRONYMS = ["aub", "svp", "ivm", "nr", "zsm", "mbt", "tmi", "fyi", "afk", "omg", "idk", "coc"] KNOWN_ACRONYMS = ["aub", "svp", "ivm", "nr", "zsm", "mbt", "tmi", "fyi", "afk", "omg", "idk", "coc"]
word = word.lower().strip() word = word.lower().strip()
#for acryonyms, just count the letters: #for acryonyms, just count the letters:
if word in KNOWN_ACRONYMS or re.match("^([a-z]{1}[.]{1}){2,}$", word) or re.match("^([bcdfghjklmnpqrstvwxz]){2,}$", word): if word in KNOWN_ACRONYMS or re.match("^([a-z]{1}[.]{1}){2,}$", word) or re.match("^([bcdfghjklmnpqrstvwxz]){2,}$", word):
return len(word.replace(".", "")) return len(word.replace(".", ""))
#count vowels surrounded by consonants #count vowels surrounded by consonants
count = len(re.findall("[bcdfghjklmnpqrstvwxyz]{1}[aeiouyëäïöüéèáà]{1,2}[bcdfghjklmnpqrstvwxz]{0,1}|[aeiouyëäïöüéèáà]{1,2}[bcdfghjklmnpqrstvwxz]{1}", word)) count = len(re.findall("[bcdfghjklmnpqrstvwxyz]{1}[aeiouyëäïöüéèáà]{1,2}[bcdfghjklmnpqrstvwxz]{0,1}|[aeiouyëäïöüéèáà]{1,2}[bcdfghjklmnpqrstvwxz]{1}", word))
count += len(re.findall("[ëäï]", word)) #ideeën etc count += len(re.findall("[ëäï]", word)) #ideeën etc
return max(1, count) return max(1, count)
#Append a message change with a numer of syllables #Append a message change with a numer of syllables
#If it returns False, it couldn't find anything #If it returns False, it couldn't find anything
#It's recursive, yo #It's recursive, yo
def appendMessageWithNrOfSyllables(self, nrOfSyl: int, chain, wordPairDict): def appendMessageWithNrOfSyllables(self, nrOfSyl: int, chain, wordPairDict):
#Find the possibilities: #Find the possibilities:
if chain[-1] == "\n": if chain[-1] == "\n":
pairPossibilities = wordPairDict[chain[-2]].copy() pairPossibilities = wordPairDict[chain[-2]].copy()
else: else:
pairPossibilities = wordPairDict[chain[-1]].copy() pairPossibilities = wordPairDict[chain[-1]].copy()
for poss in list(pairPossibilities.keys()): for poss in list(pairPossibilities.keys()):
if self.countSyllables(poss) > nrOfSyl or poss == self.END_OF_MESSAGE: #TODO change to constant if self.countSyllables(poss) > nrOfSyl or poss == self.END_OF_MESSAGE: #TODO change to constant
del pairPossibilities[poss] del pairPossibilities[poss]
if len(pairPossibilities) == 0: if len(pairPossibilities) == 0:
return False return False
#Pick a next word: #Pick a next word:
chain.append(self.pickNextWord(pairPossibilities)) chain.append(self.pickNextWord(pairPossibilities))
if self.countSyllables(chain[-1]) == nrOfSyl: if self.countSyllables(chain[-1]) == nrOfSyl:
return chain return chain
#RECURSION! #RECURSION!
return self.appendMessageWithNrOfSyllables( (nrOfSyl-self.countSyllables(chain[-1])) , chain, wordPairDict) return self.appendMessageWithNrOfSyllables( (nrOfSyl-self.countSyllables(chain[-1])) , chain, wordPairDict)
#Make a nice Haiku #Make a nice Haiku
def getHaiku(self): def getHaiku(self):
MAX_N_TRIES = 50 MAX_N_TRIES = 50
#Get dictionary/Markov chain #Get dictionary/Markov chain
wordDict = np.load('markov_dict.npy', allow_pickle=True).item() wordDict = np.load('markov_dict.npy', allow_pickle=True).item()
wordPairDict = wordDict['pairs'] wordPairDict = wordDict['pairs']
@@ -439,7 +444,7 @@ class Chatbot(commands.Cog):
#try: #try:
for i in range(1, MAX_N_TRIES): for i in range(1, MAX_N_TRIES):
chain = [self.START_OF_MESSAGE] chain = [self.START_OF_MESSAGE]
chain = self.appendMessageWithNrOfSyllables(5, chain, wordPairDict) chain = self.appendMessageWithNrOfSyllables(5, chain, wordPairDict)
if chain is not False: if chain is not False:
chain.append("\n") chain.append("\n")
@@ -449,15 +454,15 @@ class Chatbot(commands.Cog):
chain = self.appendMessageWithNrOfSyllables(5, chain, wordPairDict) chain = self.appendMessageWithNrOfSyllables(5, chain, wordPairDict)
if chain is not False: if chain is not False:
break break
chain = chain[1:] #remove <SOM> chain = chain[1:] #remove <SOM>
return ' '.join(chain) return ' '.join(chain)
@commands.command(pass_context=True, hidden=False) @commands.command(pass_context=True, hidden=False)
async def haiku(self, ctx): async def haiku(self, ctx):
"""Stroop is een poëet. Laat hem een Haiku maken. """Stroop is een poëet. Laat hem een Haiku maken.
""" """
response = self.getHaiku() response = self.getHaiku()
await ctx.channel.send(response) await ctx.channel.send(response)
@@ -483,10 +488,255 @@ class Chatbot(commands.Cog):
except: except:
pass pass
# Geeft eindrijm suffix voor gegeven woord
guus marked this conversation as resolved
Review

whitespace

whitespace
def get_eindrijm(self, word):
# handig bij rijmen en dichten zonder de broek op te hoeven lichten
word = self.normalize(word)
if not word: #niks rijmt op empty strings.
return ""
V = "(?:ij|[aeiouyëäïöüéèáà])" #klinkers + ij
C = "[bcdfghjklmnpqrstvwxz]" #medeklinkers
rijmelarij = [
rf"{V}+{C}*(?:lijk|ig)+(?:e|en)?$", #uitzonderingen (WIP): heerlijk, eerlijk, buitensporig, saamhorig
rf"{V}+{C}+e[nrls]?s?$", #slepend rijm op C: lopen, kopen, roepen, poepen
rf"{V}+{C}+{V}+$", #slepend rijm op V: koffie, kloffie,
rf"{V}+{C}+$", #staand rijm op C: loop, koop, hond, mond
rf"{V}+$", #staand rijm op V: moe, koe
]
ending = ""
for pattern in rijmelarij:
for match in re.finditer(pattern, word):
Review

for-loop is hier niet nodig omdat het pattern $ bevat. Je krijgt per definitie dus altijd maar één hit, dus dan kun je net zo makkelijk re.search gebruiken

for-loop is hier niet nodig omdat het pattern $ bevat. Je krijgt per definitie dus altijd maar één hit, dus dan kun je net zo makkelijk `re.search` gebruiken
ending = word[match.start():match.end()]
if ending:
break
return ending or word[-1] #niks rijmt op: brrr, zzz, pssjt. indexeren op laatste letter.
# Genereert een rijmwoordenboek zodat je niet hoeft te hopen dat je loopje eindelijk
# de juiste combinatie van aantal lettergrepen + rijmuitgang genereert na 200 tries.
def create_rijmwoordenboek(self, raw_dict):
# {rhyme_suffix: [list of words]}
# {"ak": ["brak", "kak"]},
# {"elling": ["helling", "terschelling", "versnelling"]},
rijmwoordenboek = {}
for word in raw_dict:
rhyme_suffix = self.get_eindrijm(word)
if rhyme_suffix not in rijmwoordenboek:
rijmwoordenboek[rhyme_suffix] = []
rijmwoordenboek[rhyme_suffix].append(word)
return rijmwoordenboek
# Draait de wordPairDict om. Dat rijmt wat makkelijker.
def create_reverse_dict(self, forward_dict):
# forward_dict: {word: {follow_word: count}} (wordPairDict)
# "de": {"kat": 3, "hond": 2},
# "een": {"kat": 4, "beer": 1},
# reverse_dict: {follow_word: {word: count}} (DictPairword) (:
# "kat": {"de": 3, "een": 4},
# "hond": {"de": 2},
# "beer": {"een" : 1},
words_filter = ["<SOM>", "<EOM>"] #TODO misschien op andere manier filteren ten behoeve van modulariteit
Review

eom en som zijn al gedefinieerd op de class

eom en som zijn al gedefinieerd op de class
Review

Ja, het is meer dat ik er niks mee doe. De kans dat een woord naar SOM of EOM gaat is vrij groot dus heb je meer fails als je een zin met een vast aantal lettergrepen wilt genereren.

Heb het nu hier gezet, maar zou in de functie verwerkt kunnen worden die ook forward_dict bijwerkt. JP's oude code maakt hier nog wel gebruik van, maar die kan de ruwe WordDict gebruiken ervoor.

Ik zet het bij #40

Ja, het is meer dat ik er niks mee doe. De kans dat een woord naar SOM of EOM gaat is vrij groot dus heb je meer fails als je een zin met een vast aantal lettergrepen wilt genereren. Heb het nu hier gezet, maar zou in de functie verwerkt kunnen worden die ook forward_dict bijwerkt. JP's oude code maakt hier nog wel gebruik van, maar die kan de ruwe WordDict gebruiken ervoor. Ik zet het bij #40
reverse_dict = {}
for word, follow_words in forward_dict.items():
for follow_word, count in follow_words.items():
if follow_word not in reverse_dict:
reverse_dict[follow_word] = {}
if word not in words_filter:
Review

zo filter je alleen vooruit, niet achteruit. (Of ja, vooruit in een reverse dict is dus eigenlijk achteruit). Er rijmt gelukkig niets op <EOM> dus het is niet écht een probleem.

zo filter je alleen vooruit, niet achteruit. (Of ja, vooruit in een reverse dict is dus eigenlijk achteruit). Er rijmt gelukkig niets op `<EOM>` dus het is niet écht een probleem.
Review

Known issue. pakken we op in #40

Known issue. pakken we op in #40
reverse_dict[follow_word][word] = count
return reverse_dict
# random woord uit het vocabulaire van stroop op basis van lettergrepen
def get_random_word_by_sylls(self, syls: int):
words_with_n_sylls = []
Review

deze kun je ook bij init één keer berekenen. of elke keer dat het rijmwoordenboek wordt opgebouwd. dict-of-lists dan. #efficiency

deze kun je ook bij init één keer berekenen. of elke keer dat het rijmwoordenboek wordt opgebouwd. dict-of-lists dan. #efficiency
Review

Goed punt. de persoon die #40 oppakt gaat het druk krijgen.

Goed punt. de persoon die #40 oppakt gaat het druk krijgen.
for word in self.wordPairDict:
if self.countSyllables(word) == syls and word not in ("<SOM>", "<EOM>"):
Review

idem, al op de class gedefinieerd.

Als je dan een list maakt (in plaats van een pair), kun je [self.END_OF_MESSAGE, self.START_OF_MESSAGE] ook gewon direct op de class definieren en dan heb je meteen een ready-to-filter lijstje klaar voor alles.

idem, al op de class gedefinieerd. Als je dan een list maakt (in plaats van een pair), kun je `[self.END_OF_MESSAGE, self.START_OF_MESSAGE]` ook gewon direct op de class definieren en dan heb je meteen een ready-to-filter lijstje klaar voor alles.
Review

Had hier niet bewust een tuple van gemaakt. Maar kan idd vanuit de class.

Had hier niet bewust een tuple van gemaakt. Maar kan idd vanuit de class.
words_with_n_sylls.append(word)
result = random.choice(words_with_n_sylls)
return result
# een wrapper voor appendMessageWithNrOfSyllables voor gebruik zonder chain manipulatie
# gebruikt om regels af te maken vanuit een gegeven lijst woorden die de "stam" vormen
def try_append_syl_msg(self, msg_stem, syllables, wordPairDict):
if not msg_stem or syllables < 1:
return None
result = self.appendMessageWithNrOfSyllables(syllables, list(msg_stem), wordPairDict)
return result or None
# normaliseer zelfde woorden voor rijm checks
def normalize(self, word):
return re.sub(r"^[^\w]+|[^\w]+$", "", word).lower()
# checkt of een rijmwoord al gebruikt is, ook als dit om samengestelde woorden gaat (kerstliedjes X liedjes)
def is_word_used(self, candidate, used_words):
c = self.normalize(candidate)
for u in used_words:
if u.endswith(c) or c.endswith(u):
return True
return False
# opvolgend in markov chain ? True : False
def check_words_connect(self, word_1, word_2, wordPairDict):
return word_2 in wordPairDict.get(word_1, {})
# returns specificaties per dichtregel voor de limerick generator
def get_line_specs(self, line_number):
guus marked this conversation as resolved
Review

Dit hoeft denk ik geen gettertje te zijn, mag gewoon een class attribute worden.

Dit hoeft denk ik geen gettertje te zijn, mag gewoon een class attribute worden.
line_specs_dict = {
1: {
"syllables" : 9,
"rhyme_type" : "A",
"line_start" : ["Er was eens", "Een", "Er was eens een", "Er was ooit"],
"min_end_syls" : 2,
"max_end_syls" : 4,
"new_rhyme" : True,
},
2: {
"syllables" : 9,
"rhyme_type" : "A",
"line_start" : ["Die", "Die ging", "Die", "Die deed", "Die", "Die had"],
"min_end_syls" : 1,
"max_end_syls" : 3,
"new_rhyme" : False,
},
3: {
"syllables" : 5,
"rhyme_type" : "B",
"line_start" : ["Maar", "Toen", "Maar oh", "Ze", "Hij", "Op", "Voor", "Bij", "Met"],
"min_end_syls" : 1,
"max_end_syls" : 3,
"new_rhyme" : True,
},
4: {
"syllables" : 5,
"rhyme_type" : "B",
"line_start" : ["Zijn", "Haar", "Een", "Geen", "En"],
"min_end_syls" : 1,
"max_end_syls" : 2,
"new_rhyme" : False,
},
5: {
"syllables" : 9,
"rhyme_type" : "A",
"line_start" : ["Toen", "Dus", "Want", "Nu", "Met", "Dan"],
"min_end_syls" : 2,
"max_end_syls" : 4,
"new_rhyme" : False,
}
}
return line_specs_dict[line_number]
# genereert een limerick regel op basis van line_specs_dict
def get_line(self, line_number, used_rhymes, forward_dict, reverse_dict, rijmwoordenboek):
MAX_CANDIDATES = 20
line_spec = self.get_line_specs(line_number) #dict definities per limerickregel
line_start = random.choice(line_spec["line_start"]) #"Er was eens..."
start = line_start.split() # Start sectie, later bijplakken
end_of_line = ["\n"]
syls_remaining = line_spec["syllables"] - self.countSyllables(line_start)
# voor A1 en B1 verzinnen we een nieuw rijmwoord
if line_spec["new_rhyme"]:
word = self.get_random_word_by_sylls(random.randint(line_spec["min_end_syls"], line_spec["max_end_syls"]))
end_of_line.append(word)
else: # A2,A3 rijmt op A1; B2 rijmt op B1
rhyme_group = used_rhymes[line_spec["rhyme_type"]] #gebruikt voor type; {"ing": ["koning", "ring"]}
suffix = next(iter(rhyme_group)) #rijmuitgang is eerste (en enige) key; "ing"
used_words = rhyme_group[suffix] #woorden met deze uitgang zijn al gebruikt; ["koning", "ring"]
for _ in range(50):
# kies een woord dat rijmt op de rijmuitgang voor de betreffende A of B regel
candidate = random.choice(rijmwoordenboek[suffix])
# maar niet als deze al gebruikt is (of als het woord te lang is)
if self.is_word_used(candidate, used_words) or self.countSyllables(candidate) > line_spec["max_end_syls"]:
continue
end_of_line.append(candidate)
break
else:
return None
syls_remaining -= self.countSyllables(" ".join(end_of_line)) #opnieuw berekenen op basis van EoL
if syls_remaining < 0:
return None
if syls_remaining == 0: #als max syls bereikt, kijk of start aansluit op EoL
if self.check_words_connect(start[-1].lower(), end_of_line[-1].lower(), forward_dict):
return start + end_of_line[::-1]
else:
return None
# meet in the middle
# hak restant syls in 2 en check aansluiting
# start -> forwards <-> backwards <- end_of_line
forw_syls = syls_remaining // 2
backw_syls = syls_remaining - forw_syls
forwards = [] #kandidaten
backwards = []
if syls_remaining == 1: # 1 kun je niet meer splitsen; sluit aan op start
forwards = [start]
backw_syls = syls_remaining
else:
for _ in range(MAX_CANDIDATES): #voorwaarts vanaf start
candidate = self.try_append_syl_msg(start, forw_syls, forward_dict)
if candidate:
forwards.append(candidate)
for _ in range(MAX_CANDIDATES): #achterstevoren vanaf eind
candidate = self.try_append_syl_msg(end_of_line, backw_syls, reverse_dict)
if candidate:
backwards.append(candidate)
matches = []
for f in forwards:
for b in backwards:
#als laatste van forw aansluit op eerste backw slaan we de match op
if self.check_words_connect(f[-1].lower(), b[-1].lower(), forward_dict):
matches.append(f + b[::-1])
if matches:
return random.choice(matches) #en kiezen we een willekeurige om order bias te voorkomen
return None
# Make a nice Limerick
def get_limerick(self):
MAX_ATTEMPTS = 15
MAX_LINE_TRIES = 5
for _ in range(MAX_ATTEMPTS):
limerick = []
used_rhymes = {}
for line_number in range(1, 6):
line_success = False
for t in range(MAX_LINE_TRIES):
result = self.get_line(line_number, used_rhymes, self.forward_dict, self.reverse_dict, self.rijmwoordenboek)
if result: # voeg regel toe aan limerick en houd bij welke rijm en rijmwoorden gebruikt zijn
limerick.extend(result)
# "A": {"-elling": ["helling", "terschelling"]}
# "B": {"-ak": ["brak", "kak"]}
rhyme_type = self.get_line_specs(line_number)["rhyme_type"]
rhyme_suffix = self.get_eindrijm(result[-2])
if rhyme_type not in used_rhymes:
used_rhymes[rhyme_type] = {}
if rhyme_suffix not in used_rhymes[rhyme_type]:
used_rhymes[rhyme_type][rhyme_suffix] = []
used_rhymes[rhyme_type][rhyme_suffix].append(self.normalize(result[-2]))
line_success = True
break
if not line_success:
break
else:
return " ".join(limerick)
return None
@commands.command()
async def limerick(self, ctx):
"""Stroop is een schunnige rijmkoning. Laat hem een limerick maken."""
response = await asyncio.to_thread(self.get_limerick)
if response:
await ctx.channel.send(response)
else:
await ctx.channel.send("Sorry, geen inspiratie vandaag.")
@commands.command(pass_context=True) @commands.command(pass_context=True)
async def nos(self, ctx, categorie=None): async def nos(self, ctx, categorie=None):
"""Een leuk NOS artikel. Hoef je het zelf niet meer op te zoeken. """Een leuk NOS artikel. Hoef je het zelf niet meer op te zoeken.
Mag optioneel een categorie aangeven: Mag optioneel een categorie aangeven:
algemeen binnenland buitenland politiek economie opmerkelijk koningshuis cultuurenmedia tech """ algemeen binnenland buitenland politiek economie opmerkelijk koningshuis cultuurenmedia tech """
try: try:
await ctx.message.delete() await ctx.message.delete()