0
class Boop < CampfireBot::Plugin
0
- # Markov chain implementation courtesy of http://
rubyquiz.com/quiz74.html0
+ # Markov chain implementation courtesy of http://
blog.segment7.net/articles/2006/02/25/markov-chain0
- on_message /.*/, :
build_chains0
+ on_message /.*/, :
listen0
on_command 'speak', :random_chatter
0
on_command 'prime_chains', :load_transcripts
0
on_command 'test', :debug
0
+ @phrases = Hash.new { |hash, key| hash[key] = [] } # phrase => next-word possibilities
0
- add_line(msg[:message])
0
+ add_words(msg[:message])
0
def random_chatter(msg)
0
@@ -29,75 +26,65 @@ class Boop < CampfireBot::Plugin
0
- # TODO strip tags, ignore images.
0
def load_transcripts(msg)
0
speak("Filling my brain with transcripts...")
0
bot.room.available_transcripts.each do |date|
0
transcript = bot.room.transcript(date)
0
transcript.each do |message|
0
filtered_text = strip_messages(message)
0
- add_
line(filtered_text.gsub(/([^\.])$/, '\1.')) unless filtered_text.blank?
0
+ add_
words(filtered_text.gsub(/([^\.])$/, '\1.')) unless filtered_text.blank?
0
puts filtered_text.gsub(/([^\.])$/, '\1.') unless filtered_text.blank?
0
- wordlist.each_with_index do |word, index|
0
- add_word(word, wordlist[index + 1]) if index <= wordlist.size - 2
0
+ words = line.scan(/\S+/))
0
+ @word_count += words.length
0
+ words.each_with_index do |word, index|
0
+ phrase = words[index, phrase_length] # current phrase
0
+ @phrases[phrase] << words[index + phrase_length] # next possibility
0
- def add_word(word, next_word)
0
- @words[word] = Hash.new(0) if !@words[word]
0
- @words[word][next_word] += 1
0
+ # phrase = words[0, phrase_length]
0
+ # grab all possibilities for our state
0
+ options = phrases[phrase]
0
+ # add the first word to our output and discard
0
+ output << phrase.shift
0
+ # select at random and add it to our phrase
0
+ phrase.push options[rand(options.length)]
0
+ # the last phrase of the input text will map to an empty array of
0
+ # possibilities so exit cleanly.
0
+ break if phrase.compact.empty? # all out of words
0
+ # print out our output
0
- # Fetching from the chains
0
+ @
phrases.keys.rand.first0
- return "" if !@words[word]
0
- followers = @words[word]
0
- sum = followers.inject(0) {|sum,kv| sum += kv[1]}
0
- next_word = followers.find do |word, count|
0
- def get_sentences(count = 1, start_word = nil)
0
- word = start_word || random_word
0
- puts "starting word is #{word}"
0
- until sentences.count('.') == count
0
- sentences << word << ' '
0
def strip_messages(msg)
0
str = msg[:message].to_s