]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - data/rbot/plugins/markov.rb
quiz: stop quizzes and timers on cleanup
[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 => 5,
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.clear
257     @learning_queue.push nil
258     @learning_thread.join
259     debug 'learning thread closed'
260     @chains.close
261     @rchains.close
262     super
263   end
264
265   # pick a word from the registry using the pair as key.
266   def pick_word(word1, word2=MARKER, chainz=@chains)
267     k = "#{word1} #{word2}"
268     return MARKER unless chainz.key? k
269     wordlist = chainz[k]
270     pick_word_from_list wordlist
271   end
272
273   # pick a word from weighted hash
274   def pick_word_from_list(wordlist)
275     total = wordlist.first
276     hash = wordlist.last
277     return MARKER if total == 0
278     return hash.keys.first if hash.length == 1
279     hit = rand(total)
280     ret = MARKER
281     hash.each do |k, w|
282       hit -= w
283       if hit < 0
284         ret = k
285         break
286       end
287     end
288     return ret
289   end
290
291   def generate_string(word1, word2)
292     # limit to max of markov.max_words words
293     if word2
294       output = [word1, word2]
295     else
296       output = word1
297       keys = []
298       @chains.each_key(output) do |key|
299         if key.downcase.include? output
300           keys << key
301         else
302           break
303         end
304       end
305       return nil if keys.empty?
306       output = keys[rand(keys.size)].split(/ /)
307     end
308     output = output.split(/ /) unless output.is_a? Array
309     input = [word1, word2]
310     while output.length < @bot.config['markov.max_words'] and (output.first != MARKER or output.last != MARKER) do
311       if output.last != MARKER
312         output << pick_word(output[-2], output[-1])
313       end
314       if output.first != MARKER
315         output.insert 0, pick_word(output[0], output[1], @rchains)
316       end
317     end
318     output.delete MARKER
319     if output == input
320       nil
321     else
322       output.join(" ")
323     end
324   end
325
326   def help(plugin, topic="")
327     topic, subtopic = topic.split
328
329     case topic
330     when "delay"
331       "markov delay <value> => Set message delay"
332     when "ignore"
333       case subtopic
334       when "add"
335         "markov ignore add <hostmask|channel> => ignore a hostmask or a channel"
336       when "list"
337         "markov ignore list => show ignored hostmasks and channels"
338       when "remove"
339         "markov ignore remove <hostmask|channel> => unignore a hostmask or channel"
340       else
341         "ignore hostmasks or channels -- topics: add, remove, list"
342       end
343     when "readonly"
344       case subtopic
345       when "add"
346         "markov readonly add <hostmask|channel> => read-only a hostmask or a channel"
347       when "list"
348         "markov readonly list => show read-only hostmasks and channels"
349       when "remove"
350         "markov readonly remove <hostmask|channel> => unreadonly a hostmask or channel"
351       else
352         "restrict hostmasks or channels to read only -- topics: add, remove, list"
353       end
354     when "status"
355       "markov status => show if markov is enabled, probability and amount of messages in queue for learning"
356     when "probability"
357       "markov probability [<percent>] => set the % chance of rbot responding to input, or display the current probability"
358     when "chat"
359       case subtopic
360       when "about"
361         "markov chat about <word> [<another word>] => talk about <word> or riff on a word pair (if possible)"
362       else
363         "markov chat => try to say something intelligent"
364       end
365     else
366       "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"
367     end
368   end
369
370   def clean_message(m)
371     str = m.plainmessage.dup
372     str =~ /^(\S+)([:,;])/
373     if $1 and m.target.is_a? Irc::Channel and m.target.user_nicks.include? $1.downcase
374       str.gsub!(/^(\S+)([:,;])\s+/, "")
375     end
376     str.gsub!(/\s{2,}/, ' ') # fix for two or more spaces
377     return str.strip
378   end
379
380   def probability?
381     return @bot.config['markov.probability']
382   end
383
384   def status(m,params)
385     if @bot.config['markov.enabled']
386       reply = _("markov is currently enabled, %{p}% chance of chipping in") % { :p => probability? }
387       l = @learning_queue.length
388       reply << (_(", %{l} messages in queue") % {:l => l}) if l > 0
389       l = @upgrade_queue.length
390       reply << (_(", %{l} chains to upgrade") % {:l => l}) if l > 0
391     else
392       reply = _("markov is currently disabled")
393     end
394     m.reply reply
395   end
396
397   def ignore?(m=nil)
398     return false unless m
399     return true if m.private?
400     return true if m.prefixed?
401     @bot.config['markov.ignore'].each do |mask|
402       return true if m.channel.downcase == mask.downcase
403       return true if m.source.matches?(mask)
404     end
405     return false
406   end
407
408   def readonly?(m=nil)
409     return false unless m
410     @bot.config['markov.readonly'].each do |mask|
411       return true if m.channel.downcase == mask.downcase
412       return true if m.source.matches?(mask)
413     end
414     return false
415   end
416
417   def ignore(m, params)
418     action = params[:action]
419     user = params[:option]
420     case action
421     when 'remove'
422       if @bot.config['markov.ignore'].include? user
423         s = @bot.config['markov.ignore']
424         s.delete user
425         @bot.config['ignore'] = s
426         m.reply _("%{u} removed") % { :u => user }
427       else
428         m.reply _("not found in list")
429       end
430     when 'add'
431       if user
432         if @bot.config['markov.ignore'].include?(user)
433           m.reply _("%{u} already in list") % { :u => user }
434         else
435           @bot.config['markov.ignore'] = @bot.config['markov.ignore'].push user
436           m.reply _("%{u} added to markov ignore list") % { :u => user }
437         end
438       else
439         m.reply _("give the name of a person or channel to ignore")
440       end
441     when 'list'
442       m.reply _("I'm ignoring %{ignored}") % { :ignored => @bot.config['markov.ignore'].join(", ") }
443     else
444       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")
445     end
446   end
447
448   def readonly(m, params)
449     action = params[:action]
450     user = params[:option]
451     case action
452     when 'remove'
453       if @bot.config['markov.readonly'].include? user
454         s = @bot.config['markov.readonly']
455         s.delete user
456         @bot.config['markov.readonly'] = s
457         m.reply _("%{u} removed") % { :u => user }
458       else
459         m.reply _("not found in list")
460       end
461     when 'add'
462       if user
463         if @bot.config['markov.readonly'].include?(user)
464           m.reply _("%{u} already in list") % { :u => user }
465         else
466           @bot.config['markov.readonly'] = @bot.config['markov.readonly'].push user
467           m.reply _("%{u} added to markov readonly list") % { :u => user }
468         end
469       else
470         m.reply _("give the name of a person or channel to read only")
471       end
472     when 'list'
473       m.reply _("I'm only reading %{readonly}") % { :readonly => @bot.config['markov.readonly'].join(", ") }
474     else
475       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")
476     end
477   end
478
479   def enable(m, params)
480     @bot.config['markov.enabled'] = true
481     m.okay
482   end
483
484   def probability(m, params)
485     if params[:probability]
486       @bot.config['markov.probability'] = params[:probability].to_i
487       m.okay
488     else
489       m.reply _("markov has a %{prob}% chance of chipping in") % { :prob => probability? }
490     end
491   end
492
493   def disable(m, params)
494     @bot.config['markov.enabled'] = false
495     m.okay
496   end
497
498   def should_talk(m)
499     return false unless @bot.config['markov.enabled']
500     prob = m.address? ? @bot.config['markov.answer_addressed'] : probability?
501     return true if prob > rand(100)
502     return false
503   end
504
505   # Generates all sequence pairs from array
506   # seq_pairs [1,2,3,4] == [ [1,2], [2,3], [3,4]]
507   def seq_pairs(arr)
508     res = []
509     0.upto(arr.size-2) do |i|
510       res << [arr[i], arr[i+1]]
511     end
512     res
513   end
514
515   def set_delay(m, params)
516     if params[:delay] == "off"
517       @bot.config["markov.delay"] = 0
518       m.okay
519     elsif !params[:delay]
520       m.reply _("Message delay is %{delay}" % { :delay => @bot.config["markov.delay"]})
521     else
522       @bot.config["markov.delay"] = params[:delay].to_i
523       m.okay
524     end
525   end
526
527   def reply_delay(m, line)
528     m.replied = true
529     if @bot.config['markov.delay'] > 0
530       @bot.timer.add_once(1 + rand(@bot.config['markov.delay'])) {
531         m.reply line, :nick => false, :to => :public
532       }
533     else
534       m.reply line, :nick => false, :to => :public
535     end
536   end
537
538   def random_markov(m, message)
539     return unless should_talk(m)
540
541     words = clean_message(m).split(/\s+/)
542     if words.length < 2
543       line = generate_string words.first, nil
544
545       if line and message.index(line) != 0
546         reply_delay m, line
547         return
548       end
549     else
550       pairs = seq_pairs(words).sort_by { rand }
551       pairs.each do |word1, word2|
552         line = generate_string(word1, word2)
553         if line and message.index(line) != 0
554           reply_delay m, line
555           return
556         end
557       end
558       words.sort_by { rand }.each do |word|
559         line = generate_string word.first, nil
560         if line and message.index(line) != 0
561           reply_delay m, line
562           return
563         end
564       end
565     end
566   end
567
568   def chat(m, params)
569     line = generate_string(params[:seed1], params[:seed2])
570     if line and line != [params[:seed1], params[:seed2]].compact.join(" ")
571       m.reply line
572     else
573       m.reply _("I can't :(")
574     end
575   end
576
577   def rand_chat(m, params)
578     # pick a random pair from the db and go from there
579     word1, word2 = MARKER, MARKER
580     output = Array.new
581     @bot.config['markov.max_words'].times do
582       word3 = pick_word(word1, word2)
583       break if word3 == MARKER
584       output << word3
585       word1, word2 = word2, word3
586     end
587     if output.length > 1
588       m.reply output.join(" ")
589     else
590       m.reply _("I can't :(")
591     end
592   end
593
594   def learn(*lines)
595     lines.each { |l| @learning_queue.push l }
596   end
597
598   def unreplied(m)
599     return if ignore? m
600
601     # in channel message, the kind we are interested in
602     message = m.plainmessage
603
604     if m.action?
605       message = "#{m.sourcenick} #{message}"
606     end
607
608     random_markov(m, message) unless readonly? m or m.replied?
609     learn clean_message(m)
610   end
611
612
613   def learn_triplet(word1, word2, word3)
614       k = "#{word1} #{word2}"
615       rk = "#{word2} #{word3}"
616       @chains_mutex.synchronize do
617         total = 0
618         hash = Hash.new(0)
619         if @chains.key? k
620           t2, h2 = @chains[k]
621           total += t2
622           hash.update h2
623         end
624         hash[word3] += 1
625         total += 1
626         @chains[k] = [total, hash]
627       end
628       @rchains_mutex.synchronize do
629         # Reverse
630         total = 0
631         hash = Hash.new(0)
632         if @rchains.key? rk
633           t2, h2 = @rchains[rk]
634           total += t2
635           hash.update h2
636         end
637         hash[word1] += 1
638         total += 1
639         @rchains[rk] = [total, hash]
640       end
641   end
642
643
644   def learn_line(message)
645     # debug "learning #{message.inspect}"
646     wordlist = message.strip.split(/\s+/).reject do |w|
647       @bot.config['markov.ignore_patterns'].map do |pat|
648         w =~ Regexp.new(pat.to_s)
649       end.select{|v| v}.size != 0
650     end
651     return unless wordlist.length >= 2
652     word1, word2 = MARKER, MARKER
653     wordlist << MARKER
654     wordlist.each do |word3|
655       learn_triplet(word1, word2, word3.to_sym)
656       word1, word2 = word2, word3
657     end
658   end
659
660   # TODO allow learning from URLs
661   def learn_from(m, params)
662     begin
663       path = params[:file]
664       file = File.open(path, "r")
665       pattern = params[:pattern].empty? ? nil : Regexp.new(params[:pattern].to_s)
666     rescue Errno::ENOENT
667       m.reply _("no such file")
668       return
669     end
670
671     if file.eof?
672       m.reply _("the file is empty!")
673       return
674     end
675
676     if params[:testing]
677       lines = []
678       range = case params[:lines]
679       when /^\d+\.\.\d+$/
680         Range.new(*params[:lines].split("..").map { |e| e.to_i })
681       when /^\d+$/
682         Range.new(1, params[:lines].to_i)
683       else
684         Range.new(1, [@bot.config['send.max_lines'], 3].max)
685       end
686
687       file.each do |line|
688         next unless file.lineno >= range.begin
689         lines << line.chomp
690         break if file.lineno == range.end
691       end
692
693       lines = lines.map do |l|
694         pattern ? l.scan(pattern).to_s : l
695       end.reject { |e| e.empty? }
696
697       if pattern
698         unless lines.empty?
699           m.reply _("example matches for that pattern at lines %{range} include: %{lines}") % {
700             :lines => lines.map { |e| Underline+e+Underline }.join(", "),
701             :range => range.to_s
702           }
703         else
704           m.reply _("the pattern doesn't match anything at lines %{range}") % {
705             :range => range.to_s
706           }
707         end
708       else
709         m.reply _("learning from the file without a pattern would learn, for example: ")
710         lines.each { |l| m.reply l }
711       end
712
713       return
714     end
715
716     if pattern
717       file.each { |l| learn(l.scan(pattern).to_s) }
718     else
719       file.each { |l| learn(l.chomp) }
720     end
721
722     m.okay
723   end
724
725   def stats(m, params)
726     m.reply "Markov status: chains: #{@chains.length} forward, #{@rchains.length} reverse, queued phrases: #{@learning_queue.size}"
727   end
728
729 end
730
731 plugin = MarkovPlugin.new
732 plugin.map 'markov delay :delay', :action => "set_delay"
733 plugin.map 'markov delay', :action => "set_delay"
734 plugin.map 'markov ignore :action :option', :action => "ignore"
735 plugin.map 'markov ignore :action', :action => "ignore"
736 plugin.map 'markov ignore', :action => "ignore"
737 plugin.map 'markov readonly :action :option', :action => "readonly"
738 plugin.map 'markov readonly :action', :action => "readonly"
739 plugin.map 'markov readonly', :action => "readonly"
740 plugin.map 'markov enable', :action => "enable"
741 plugin.map 'markov disable', :action => "disable"
742 plugin.map 'markov status', :action => "status"
743 plugin.map 'markov stats', :action => "stats"
744 plugin.map 'chat about :seed1 [:seed2]', :action => "chat"
745 plugin.map 'chat', :action => "rand_chat"
746 plugin.map 'markov probability [:probability]', :action => "probability",
747            :requirements => {:probability => /^\d+%?$/}
748 plugin.map 'markov learn from :file [:testing [:lines lines]] [using pattern *pattern]', :action => "learn_from", :thread => true,
749            :requirements => {
750              :testing => /^testing$/,
751              :lines   => /^(?:\d+\.\.\d+|\d+)$/ }
752
753 plugin.default_auth('ignore', false)
754 plugin.default_auth('probability', false)
755 plugin.default_auth('learn', false)
756