]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - data/rbot/plugins/markov.rb
markov: Intern only when it makes sense
[user/henk/code/ruby/rbot.git] / data / rbot / plugins / markov.rb
1 #-- vim:sw=2:et
2 #++
3 #
4 # :title: Markov plugin
5 #
6 # Author:: Tom Gilbert <tom@linuxbrit.co.uk>
7 # Copyright:: (C) 2005 Tom Gilbert
8 #
9 # Contribute to chat with random phrases built from word sequences learned
10 # by listening to chat
11
12 class MarkovPlugin < Plugin
13   Config.register Config::BooleanValue.new('markov.enabled',
14     :default => false,
15     :desc => "Enable and disable the plugin")
16   Config.register Config::IntegerValue.new('markov.probability',
17     :default => 25,
18     :validate => Proc.new { |v| (0..100).include? v },
19     :desc => "Percentage chance of markov plugin chipping in")
20   Config.register Config::ArrayValue.new('markov.ignore',
21     :default => [],
22     :desc => "Hostmasks and channel names markov should NOT learn from (e.g. idiot*!*@*, #privchan).")
23   Config.register Config::ArrayValue.new('markov.readonly',
24     :default => [],
25     :desc => "Hostmasks and channel names markov should NOT talk to (e.g. idiot*!*@*, #privchan).")
26   Config.register Config::IntegerValue.new('markov.max_words',
27     :default => 50,
28     :validate => Proc.new { |v| (0..100).include? v },
29     :desc => "Maximum number of words the bot should put in a sentence")
30   Config.register Config::FloatValue.new('markov.learn_delay',
31     :default => 0.5,
32     :validate => Proc.new { |v| v >= 0 },
33     :desc => "Time the learning thread spends sleeping after learning a line. If set to zero, learning from files can be very CPU intensive, but also faster.")
34    Config.register Config::IntegerValue.new('markov.delay',
35     :default => true,
36     :validate => Proc.new { |v| v >= 0 },
37     :desc => "Wait short time before contributing to conversation.")
38    Config.register Config::IntegerValue.new('markov.answer_addressed',
39     :default => 50,
40     :validate => Proc.new { |v| (0..100).include? v },
41     :desc => "Probability of answer when addressed by nick")
42    Config.register Config::ArrayValue.new('markov.ignore_patterns',
43     :default => [],
44     :desc => "Ignore these word patterns")
45
46   MARKER = :"\r\n"
47
48   # upgrade a registry entry from 0.9.14 and earlier, converting the Arrays
49   # into Hashes of weights
50   def upgrade_entry(k, logfile)
51     logfile.puts "\t#{k.inspect}"
52     logfile.flush
53     logfile.fsync
54
55     ar = @registry[k]
56
57     # wipe the current key
58     @registry.delete(k)
59
60     # discard empty keys
61     if ar.empty?
62       logfile.puts "\tEMPTY"
63       return
64     end
65
66     # otherwise, proceed
67     logfile.puts "\t#{ar.inspect}"
68
69     # re-encode key to UTF-8 and cleanup as needed
70     words = k.split.map do |w|
71       BasicUserMessage.strip_formatting(
72         @bot.socket.filter.in(w)
73       ).sub(/\001$/,'')
74     end
75
76     # old import that failed to split properly?
77     if words.length == 1 and words.first.include? '/'
78       # split at the last /
79       unsplit = words.first
80       at = unsplit.rindex('/')
81       words = [unsplit[0,at], unsplit[at+1..-1]]
82     end
83
84     # if any of the re-split/re-encoded words have spaces,
85     # or are empty, we would get a chain we can't convert,
86     # so drop it
87     if words.first.empty? or words.first.include?(' ') or
88       words.last.empty? or words.last.include?(' ')
89       logfile.puts "\tSKIPPED"
90       return
91     end
92
93     # former unclean CTCP, we can't convert this
94     if words.first[0] == 1
95       logfile.puts "\tSKIPPED"
96       return
97     end
98
99     # nonword CTCP => SKIP
100     # someword CTCP => nonword someword
101     if words.last[0] == 1
102       if words.first == "nonword"
103         logfile.puts "\tSKIPPED"
104         return
105       end
106       words.unshift MARKER
107       words.pop
108     end
109
110     # intern the old keys
111     words.map! do |w|
112       ['nonword', MARKER].include?(w) ? MARKER : w.chomp("\001")
113     end
114
115     newkey = words.join(' ')
116     logfile.puts "\t#{newkey.inspect}"
117
118     # the new key exists already, so we want to merge
119     if k != newkey and @registry.key? newkey
120       ar2 = @registry[newkey]
121       logfile.puts "\tMERGE"
122       logfile.puts "\t\t#{ar2.inspect}"
123       ar.push(*ar2)
124       # and get rid of the key
125       @registry.delete(newkey)
126     end
127
128     total = 0
129     hash = Hash.new(0)
130
131     @chains_mutex.synchronize do
132       if @chains.key? newkey
133         ar2 = @chains[newkey]
134         total += ar2.first
135         hash.update ar2.last
136       end
137
138       ar.each do |word|
139         case word
140         when :nonword
141           # former marker
142           sym = MARKER
143         else
144           # we convert old words into UTF-8, cleanup, resplit if needed,
145           # and only get the first word. we may lose some data for old
146           # missplits, but this is the best we can do
147           w = BasicUserMessage.strip_formatting(
148             @bot.socket.filter.in(word).split.first
149           )
150           case w
151           when /^\001\S+$/, "\001", ""
152             # former unclean CTCP or end of CTCP
153             next
154           else
155             # intern after clearing leftover end-of-actions if present
156             sym = w.chomp("\001")
157           end
158         end
159         hash[sym] += 1
160         total += 1
161       end
162       if hash.empty?
163         logfile.puts "\tSKIPPED"
164         return
165       end
166       logfile.puts "\t#{[total, hash].inspect}"
167       @chains[newkey] = [total, hash]
168     end
169   end
170
171   def upgrade_registry
172     # we load all the keys and then iterate over this array because
173     # running each() on the registry and updating it at the same time
174     # doesn't work
175     keys = @registry.keys
176     # no registry, nothing to do
177     return if keys.empty?
178
179     ki = 0
180     log "starting markov database conversion thread (v1 to v2, #{keys.length} keys)"
181
182     keys.each { |k| @upgrade_queue.push k }
183     @upgrade_queue.push nil
184
185     @upgrade_thread = Thread.new do
186       logfile = File.open(@bot.path('markov-conversion.log'), 'a')
187       logfile.puts "=== conversion thread started #{Time.now} ==="
188       while k = @upgrade_queue.pop
189         ki += 1
190         logfile.puts "Key #{ki} (#{@upgrade_queue.length} in queue):"
191         begin
192           upgrade_entry(k, logfile)
193         rescue Exception => e
194           logfile.puts "=== ERROR ==="
195           logfile.puts e.pretty_inspect
196           logfile.puts "=== EREND ==="
197         end
198         sleep @bot.config['markov.learn_delay'] unless @bot.config['markov.learn_delay'].zero?
199       end
200       logfile.puts "=== conversion thread stopped #{Time.now} ==="
201       logfile.close
202     end
203     @upgrade_thread.priority = -1
204   end
205
206   attr_accessor :chains
207
208   def initialize
209     super
210     @registry.set_default([])
211     if @registry.has_key?('enabled')
212       @bot.config['markov.enabled'] = @registry['enabled']
213       @registry.delete('enabled')
214     end
215     if @registry.has_key?('probability')
216       @bot.config['markov.probability'] = @registry['probability']
217       @registry.delete('probability')
218     end
219     if @bot.config['markov.ignore_users']
220       debug "moving markov.ignore_users to markov.ignore"
221       @bot.config['markov.ignore'] = @bot.config['markov.ignore_users'].dup
222       @bot.config.delete('markov.ignore_users'.to_sym)
223     end
224
225     @chains = @registry.sub_registry('v2')
226     @chains.set_default([])
227     @rchains = @registry.sub_registry('v2r')
228     @rchains.set_default([])
229     @chains_mutex = Mutex.new
230     @rchains_mutex = Mutex.new
231
232     @upgrade_queue = Queue.new
233     @upgrade_thread = nil
234     upgrade_registry
235
236     @learning_queue = Queue.new
237     @learning_thread = Thread.new do
238       while s = @learning_queue.pop
239         learn_line s
240         sleep @bot.config['markov.learn_delay'] unless @bot.config['markov.learn_delay'].zero?
241       end
242     end
243     @learning_thread.priority = -1
244   end
245
246   def cleanup
247     if @upgrade_thread and @upgrade_thread.alive?
248       debug 'closing conversion thread'
249       @upgrade_queue.clear
250       @upgrade_queue.push nil
251       @upgrade_thread.join
252       debug 'conversion thread closed'
253     end
254
255     debug 'closing learning thread'
256     @learning_queue.push nil
257     @learning_thread.join
258     debug 'learning thread closed'
259   end
260
261   # pick a word from the registry using the pair as key.
262   def pick_word(word1, word2=MARKER, chainz=@chains)
263     k = "#{word1} #{word2}"
264     return MARKER unless chainz.key? k
265     wordlist = chainz[k]
266     pick_word_from_list wordlist
267   end
268
269   # pick a word from weighted hash
270   def pick_word_from_list(wordlist)
271     total = wordlist.first
272     hash = wordlist.last
273     return MARKER if total == 0
274     return hash.keys.first if hash.length == 1
275     hit = rand(total)
276     ret = MARKER
277     hash.each do |k, w|
278       hit -= w
279       if hit < 0
280         ret = k
281         break
282       end
283     end
284     return ret
285   end
286
287   def generate_string(word1, word2)
288     # limit to max of markov.max_words words
289     if word2
290       output = [word1, word2]
291     else
292       output = word1
293       keys = []
294       @chains.each_key(output) do |key|
295         if key.downcase.include? output
296                 keys << key
297         else
298                 break
299         end
300       end
301       return nil if keys.empty?
302       output = keys[rand(keys.size)].split(/ /)
303      end
304     output = output.split(/ /) unless output.is_a? Array
305     input = [word1, word2]
306     while output.length < @bot.config['markov.max_words'] and (output.first != MARKER or output.last != MARKER) do
307       if output.last != MARKER
308         output << pick_word(output[-2], output[-1])
309       end
310       if output.first != MARKER
311         output.insert 0, pick_word(output[0], output[1], @rchains)
312       end
313     end
314     output.delete MARKER
315     if output == input
316       nil
317     else
318            output.join(" ")
319          end
320   end
321
322   def help(plugin, topic="")
323     topic, subtopic = topic.split
324
325     case topic
326     when "delay"
327       "markov delay <value> => Set message delay"
328     when "ignore"
329       case subtopic
330       when "add"
331         "markov ignore add <hostmask|channel> => ignore a hostmask or a channel"
332       when "list"
333         "markov ignore list => show ignored hostmasks and channels"
334       when "remove"
335         "markov ignore remove <hostmask|channel> => unignore a hostmask or channel"
336       else
337         "ignore hostmasks or channels -- topics: add, remove, list"
338       end
339     when "readonly"
340       case subtopic
341       when "add"
342         "markov readonly add <hostmask|channel> => read-only a hostmask or a channel"
343       when "list"
344         "markov readonly list => show read-only hostmasks and channels"
345       when "remove"
346         "markov readonly remove <hostmask|channel> => unreadonly a hostmask or channel"
347       else
348         "restrict hostmasks or channels to read only -- topics: add, remove, list"
349       end
350     when "status"
351       "markov status => show if markov is enabled, probability and amount of messages in queue for learning"
352     when "probability"
353       "markov probability [<percent>] => set the % chance of rbot responding to input, or display the current probability"
354     when "chat"
355       case subtopic
356       when "about"
357         "markov chat about <word> [<another word>] => talk about <word> or riff on a word pair (if possible)"
358       else
359         "markov chat => try to say something intelligent"
360       end
361     else
362       "markov plugin: listens to chat to build a markov chain, with which it can (perhaps) attempt to (inanely) contribute to 'discussion'. Sort of.. Will get a *lot* better after listening to a lot of chat. Usage: 'chat' to attempt to say something relevant to the last line of chat, if it can -- help topics: ignore, readonly, delay, status, probability, chat, chat about"
363     end
364   end
365
366   def clean_str(s)
367     str = s.dup
368     str.gsub!(/^\S+[:,;]/, "")
369     str.gsub!(/\s{2,}/, ' ') # fix for two or more spaces
370     return str.strip
371   end
372
373   def probability?
374     return @bot.config['markov.probability']
375   end
376
377   def status(m,params)
378     if @bot.config['markov.enabled']
379       reply = _("markov is currently enabled, %{p}% chance of chipping in") % { :p => probability? }
380       l = @learning_queue.length
381       reply << (_(", %{l} messages in queue") % {:l => l}) if l > 0
382       l = @upgrade_queue.length
383       reply << (_(", %{l} chains to upgrade") % {:l => l}) if l > 0
384     else
385       reply = _("markov is currently disabled")
386     end
387     m.reply reply
388   end
389
390   def ignore?(m=nil)
391     return false unless m
392     return true if m.private?
393     return true if m.prefixed?
394     @bot.config['markov.ignore'].each do |mask|
395       return true if m.channel.downcase == mask.downcase
396       return true if m.source.matches?(mask)
397     end
398     return false
399   end
400
401   def readonly?(m=nil)
402     return false unless m
403     @bot.config['markov.readonly'].each do |mask|
404       return true if m.channel.downcase == mask.downcase
405       return true if m.source.matches?(mask)
406     end
407     return false
408   end
409
410   def ignore(m, params)
411     action = params[:action]
412     user = params[:option]
413     case action
414     when 'remove'
415       if @bot.config['markov.ignore'].include? user
416         s = @bot.config['markov.ignore']
417         s.delete user
418         @bot.config['ignore'] = s
419         m.reply _("%{u} removed") % { :u => user }
420       else
421         m.reply _("not found in list")
422       end
423     when 'add'
424       if user
425         if @bot.config['markov.ignore'].include?(user)
426           m.reply _("%{u} already in list") % { :u => user }
427         else
428           @bot.config['markov.ignore'] = @bot.config['markov.ignore'].push user
429           m.reply _("%{u} added to markov ignore list") % { :u => user }
430         end
431       else
432         m.reply _("give the name of a person or channel to ignore")
433       end
434     when 'list'
435       m.reply _("I'm ignoring %{ignored}") % { :ignored => @bot.config['markov.ignore'].join(", ") }
436     else
437       m.reply _("have markov ignore the input from a hostmask or a channel. usage: markov ignore add <mask or channel>; markov ignore remove <mask or channel>; markov ignore list")
438     end
439   end
440
441   def readonly(m, params)
442     action = params[:action]
443     user = params[:option]
444     case action
445     when 'remove'
446       if @bot.config['markov.readonly'].include? user
447         s = @bot.config['markov.readonly']
448         s.delete user
449         @bot.config['markov.readonly'] = s
450         m.reply _("%{u} removed") % { :u => user }
451       else
452         m.reply _("not found in list")
453       end
454     when 'add'
455       if user
456         if @bot.config['markov.readonly'].include?(user)
457           m.reply _("%{u} already in list") % { :u => user }
458         else
459           @bot.config['markov.readonly'] = @bot.config['markov.readonly'].push user
460           m.reply _("%{u} added to markov readonly list") % { :u => user }
461         end
462       else
463         m.reply _("give the name of a person or channel to read only")
464       end
465     when 'list'
466       m.reply _("I'm only reading %{readonly}") % { :readonly => @bot.config['markov.readonly'].join(", ") }
467     else
468       m.reply _("have markov not answer to input from a hostmask or a channel. usage: markov readonly add <mask or channel>; markov readonly remove <mask or channel>; markov readonly list")
469     end
470   end
471
472   def enable(m, params)
473     @bot.config['markov.enabled'] = true
474     m.okay
475   end
476
477   def probability(m, params)
478     if params[:probability]
479       @bot.config['markov.probability'] = params[:probability].to_i
480       m.okay
481     else
482       m.reply _("markov has a %{prob}% chance of chipping in") % { :prob => probability? }
483     end
484   end
485
486   def disable(m, params)
487     @bot.config['markov.enabled'] = false
488     m.okay
489   end
490
491   def should_talk
492     return false unless @bot.config['markov.enabled']
493     prob = probability?
494     return true if prob > rand(100)
495     return false
496   end
497
498   # Generates all sequence pairs from array
499   # seq_pairs [1,2,3,4] == [ [1,2], [2,3], [3,4]]
500   def seq_pairs(arr)
501     res = []
502     0.upto(arr.size-2) do |i|
503       res << [arr[i], arr[i+1]]
504     end
505     res
506   end
507
508   def set_delay(m, params)
509     if params[:delay] == "off"
510       @bot.config["markov.delay"] = 0
511       m.okay
512     elsif !params[:delay]
513       m.reply _("Message delay is %{delay}" % { :delay => @bot.config["markov.delay"]})
514     else
515       @bot.config["markov.delay"] = params[:delay].to_i
516       m.okay
517     end
518   end
519
520   def reply_delay(m, line)
521     m.replied = true
522     if @bot.config['markov.delay'] > 0
523       @bot.timer.add_once(@bot.config['markov.delay']) {
524         m.reply line, :nick => false, :to => :public
525       }
526     else
527       m.reply line, :nick => false, :to => :public
528     end
529   end
530
531   def random_markov(m, message)
532     return unless (should_talk or (m.address? and  @bot.config['markov.answer_addressed'] > rand(100)))
533
534     words = clean_str(message).split(/\s+/)
535     if words.length < 2
536       line = generate_string words.first, nil
537
538       if line and message.index(line) != 0
539         reply_delay m, line
540         return
541       end
542     else
543       pairs = seq_pairs(words).sort_by { rand }
544       pairs.each do |word1, word2|
545         line = generate_string(word1, word2)
546         if line and message.index(line) != 0
547           reply_delay m, line
548           return
549         end
550       end
551       words.sort_by { rand }.each do |word|
552         line = generate_string word.first, nil
553         if line and message.index(line) != 0
554           reply_delay m, line
555           return
556         end
557       end
558     end
559   end
560
561   def chat(m, params)
562     line = generate_string(params[:seed1], params[:seed2])
563     if line and line != [params[:seed1], params[:seed2]].compact.join(" ")
564       m.reply line
565     else
566       m.reply _("I can't :(")
567     end
568   end
569
570   def rand_chat(m, params)
571     # pick a random pair from the db and go from there
572     word1, word2 = MARKER, MARKER
573     output = Array.new
574     @bot.config['markov.max_words'].times do
575       word3 = pick_word(word1, word2)
576       break if word3 == MARKER
577       output << word3
578       word1, word2 = word2, word3
579     end
580     if output.length > 1
581       m.reply output.join(" ")
582     else
583       m.reply _("I can't :(")
584     end
585   end
586
587   def learn(*lines)
588     lines.each { |l| @learning_queue.push l }
589   end
590
591   def unreplied(m)
592     return if ignore? m
593
594     # in channel message, the kind we are interested in
595     message = m.plainmessage
596
597     if m.action?
598       message = "#{m.sourcenick} #{message}"
599     end
600
601     random_markov(m, message) unless readonly? m or m.replied?
602     learn message
603   end
604
605
606   def learn_triplet(word1, word2, word3)
607       k = "#{word1} #{word2}"
608       rk = "#{word2} #{word3}"
609       @chains_mutex.synchronize do
610         total = 0
611         hash = Hash.new(0)
612         if @chains.key? k
613           t2, h2 = @chains[k]
614           total += t2
615           hash.update h2
616         end
617         hash[word3] += 1
618         total += 1
619         @chains[k] = [total, hash]
620       end
621       @rchains_mutex.synchronize do
622         # Reverse
623         total = 0
624         hash = Hash.new(0)
625         if @rchains.key? rk
626           t2, h2 = @rchains[rk]
627           total += t2
628           hash.update h2
629         end
630         hash[word1] += 1
631         total += 1
632         @rchains[rk] = [total, hash]
633       end
634   end
635
636
637   def learn_line(message)
638     # debug "learning #{message.inspect}"
639     wordlist = clean_str(message).split(/\s+/).reject do |w|
640       @bot.config['markov.ignore_patterns'].map do |pat|
641         w =~ Regexp.new(pat.to_s)
642       end.select{|v| v}.size != 0
643     end
644     return unless wordlist.length >= 2
645     word1, word2 = MARKER, MARKER
646     wordlist << MARKER
647     wordlist.each do |word3|
648       learn_triplet(word1, word2, word3.to_sym)
649       word1, word2 = word2, word3
650     end
651   end
652
653   # TODO allow learning from URLs
654   def learn_from(m, params)
655     begin
656       path = params[:file]
657       file = File.open(path, "r")
658       pattern = params[:pattern].empty? ? nil : Regexp.new(params[:pattern].to_s)
659     rescue Errno::ENOENT
660       m.reply _("no such file")
661       return
662     end
663
664     if file.eof?
665       m.reply _("the file is empty!")
666       return
667     end
668
669     if params[:testing]
670       lines = []
671       range = case params[:lines]
672       when /^\d+\.\.\d+$/
673         Range.new(*params[:lines].split("..").map { |e| e.to_i })
674       when /^\d+$/
675         Range.new(1, params[:lines].to_i)
676       else
677         Range.new(1, [@bot.config['send.max_lines'], 3].max)
678       end
679
680       file.each do |line|
681         next unless file.lineno >= range.begin
682         lines << line.chomp
683         break if file.lineno == range.end
684       end
685
686       lines = lines.map do |l|
687         pattern ? l.scan(pattern).to_s : l
688       end.reject { |e| e.empty? }
689
690       if pattern
691         unless lines.empty?
692           m.reply _("example matches for that pattern at lines %{range} include: %{lines}") % {
693             :lines => lines.map { |e| Underline+e+Underline }.join(", "),
694             :range => range.to_s
695           }
696         else
697           m.reply _("the pattern doesn't match anything at lines %{range}") % {
698             :range => range.to_s
699           }
700         end
701       else
702         m.reply _("learning from the file without a pattern would learn, for example: ")
703         lines.each { |l| m.reply l }
704       end
705
706       return
707     end
708
709     if pattern
710       file.each { |l| learn(l.scan(pattern).to_s) }
711     else
712       file.each { |l| learn(l.chomp) }
713     end
714
715     m.okay
716   end
717
718   def stats(m, params)
719     m.reply "Markov status: chains: #{@chains.length} forward, #{@rchains.length} reverse, queued phrases: #{@learning_queue.size}"
720   end
721
722 end
723
724 plugin = MarkovPlugin.new
725 plugin.map 'markov delay :delay', :action => "set_delay"
726 plugin.map 'markov delay', :action => "set_delay"
727 plugin.map 'markov ignore :action :option', :action => "ignore"
728 plugin.map 'markov ignore :action', :action => "ignore"
729 plugin.map 'markov ignore', :action => "ignore"
730 plugin.map 'markov readonly :action :option', :action => "readonly"
731 plugin.map 'markov readonly :action', :action => "readonly"
732 plugin.map 'markov readonly', :action => "readonly"
733 plugin.map 'markov enable', :action => "enable"
734 plugin.map 'markov disable', :action => "disable"
735 plugin.map 'markov status', :action => "status"
736 plugin.map 'markov stats', :action => "stats"
737 plugin.map 'chat about :seed1 [:seed2]', :action => "chat"
738 plugin.map 'chat', :action => "rand_chat"
739 plugin.map 'markov probability [:probability]', :action => "probability",
740            :requirements => {:probability => /^\d+%?$/}
741 plugin.map 'markov learn from :file [:testing [:lines lines]] [using pattern *pattern]', :action => "learn_from", :thread => true,
742            :requirements => {
743              :testing => /^testing$/,
744              :lines   => /^(?:\d+\.\.\d+|\d+)$/ }
745
746 plugin.default_auth('ignore', false)
747 plugin.default_auth('probability', false)
748 plugin.default_auth('learn', false)
749