dict: oxford fix from AndrewNTH
[rbot] / data / rbot / plugins / dict.rb
1 #-- vim:sw=2:et
2 #++
3 #
4 # :title: Dictionary lookup plugin for rbot
5 #
6 # Author:: Giuseppe "Oblomov" Bilotta <giuseppe.bilotta@gmail.com>
7 # Copyright:: (C) 2006-2007 Giuseppe Bilotta
8 # License:: GPL v2
9 #
10 # Provides a link to the definition of a word in one of the supported
11 # dictionaries. Currently available are
12 #   * the Oxford dictionary for (British) English
13 #   * the De Mauro/Paravia dictionary for Italian
14 #   * the Chambers dictionary for English (accepts both US and UK)
15 #   * the Littré dictionary for French
16 #
17 # Other plugins can use this one to check if a given word is valid in italian
18 # or english or french by using the is_italian?, is_british?, is_english?,
19 # is_french? methods
20 #
21 # TODO: cache results and reuse them if get_cached returns a cache copy
22
23 DEMAURO_LEMMA = /<anchor>(.*?)(?: - (.*?))<go href="lemma.php\?ID=(\d+)"\/><\/anchor>/
24 CHAMBERS_LEMMA = /<p><span class="hwd">(.*?)<\/span> <span class="psa">(.*?)<\/span>(.*?)<\/p>/
25
26 class DictPlugin < Plugin
27   Config.register Config::IntegerValue.new('dict.hits',
28     :default => 3,
29     :desc => "Number of hits to return from a dictionary lookup")
30   Config.register Config::IntegerValue.new('dict.first_par',
31     :default => 0,
32     :desc => "When set to n > 0, the bot will return the first paragraph from the first n dictionary hits")
33
34   def demauro_filter(s)
35     # check if it's a page we can handle
36     loc = Utils.check_location(s, @dmurlrx)
37     # the location might be not good, but we might still be able to handle the
38     # page
39     if !loc and s[:text] !~ /<!-- Il dizionario della lingua italiana Paravia: /
40       debug "not our business"
41       return
42     end
43     # we want to grab the content from the WAP page, since it's in a much
44     # cleaner HTML, so first try to get the word ID
45     if s[:text] !~ %r{<li><a href="(\d+)" title="vai al lemma precedente" accesskey="p">lemma precedente</a></li>}
46       return
47     end
48     id = $1.to_i + 1
49     title = s[:text].ircify_html_title
50     content = @bot.filter(:htmlinfo, URI.parse(@dmwaplemma % id))[:content]
51     return {:title => title, :content => content.sub(/^\S+\s+-\s+/,'')}
52   end
53
54   def initialize
55     super
56     @dmurl = "http://old.demauroparavia.it/"
57     @dmurlrx = %r{http://(?:www|old\.)?demauroparavia\.it/(\d+)}
58     @dmwapurl = "http://wap.demauroparavia.it/index.php?lemma=%s"
59     @dmwaplemma = "http://wap.demauroparavia.it/lemma.php?ID=%s"
60     @oxurl = "http://www.askoxford.com/concise_oed/%s"
61     @chambersurl = "http://www.chambersharrap.co.uk/chambers/features/chref/chref.py/main?query=%s&title=21st"
62     @littreurl = "http://francois.gannaz.free.fr/Littre/xmlittre.php?requete=%s"
63
64     @bot.register_filter(:demauro, :htmlinfo) { |s| demauro_filter(s) }
65   end
66
67
68   def help(plugin, topic="")
69     case topic
70     when "demauro"
71       return "demauro <word> => provides a link to the definition of <word> from the De Mauro/Paravia dictionary"
72     when "oxford"
73       return "oxford <word> => provides a link to the definition of <word> (it can also be an expression) from the Concise Oxford dictionary"
74     when "chambers"
75       return "chambers <word> => provides a link to the definition of <word> (it can also be an expression) from the Chambers 21st Century Dictionary"
76     when "littre"
77       return "littre <word> => provides a link to the definition of <word> (it can also be an expression) from the Littré online dictionary"
78     end
79     return "<dictionary> <word>: check for <word> on <dictionary> where <dictionary> can be one of: demauro, oxford, chambers, littre"
80   end
81
82   def demauro(m, params)
83     justcheck = params[:justcheck]
84
85     word = params[:word].downcase
86     url = @dmwapurl % CGI.escape(word)
87     xml = nil
88     info = @bot.httputil.get_response(url) rescue nil
89     xml = info.body if info
90     if xml.nil?
91       info = info ? " (#{info.code} - #{info.message})" : ""
92       return false if justcheck
93       m.reply "An error occurred while looking for #{word}#{info}"
94       return
95     end
96     if xml=~ /Non ho trovato occorrenze per/
97       return false if justcheck
98       m.reply "Nothing found for #{word}"
99       return
100     end
101     entries = xml.scan(DEMAURO_LEMMA)
102     text = word
103     urls = []
104     if not entries.transpose.first.grep(/\b#{word}\b/)
105       return false if justcheck
106       text += " not found. Similar words"
107     end
108     return true if justcheck
109     text += ": "
110     n = 0
111     hits = @bot.config['dict.hits']
112     text += entries[0...hits].map { |ar|
113       n += 1
114       urls << @dmwaplemma % ar[2]
115       key = ar[1].ircify_html
116       "#{n}. #{Bold}#{ar[0]}#{Bold} - #{key}: #{@dmurl}#{ar[2]}"
117     }.join(" | ")
118     m.reply text
119
120     first_pars = @bot.config['dict.first_par']
121
122     return unless first_pars > 0
123
124     Utils.get_first_pars urls, first_pars, :message => m,
125       :strip => /^.+?\s+-\s+/
126
127   end
128
129   def is_italian?(word)
130     return demauro(nil, :word => word, :justcheck => true)
131   end
132
133
134   def oxford(m, params)
135     justcheck = params[:justcheck]
136
137     word = params[:word].join
138     [word, word + "_1"].each { |check|
139       url = @oxurl % CGI.escape(check)
140       if params[:british]
141         url << "?view=uk"
142       end
143       h = @bot.httputil.get(url, :max_redir => 5)
144       if h
145         defs = h.split("<span class=\"definition\">")
146         defs = defs[1..-1].map {|d| d.split("</span>")[0]}
147         if defs.size == 0
148           return false if justcheck
149           m.reply "#{word} not found"
150           return false
151         end
152         m.reply("#{word}: #{url}") unless justcheck
153         defn = defs[0]
154         m.reply("#{Bold}%s#{Bold}: %s" % [word, defn.ircify_html(:nbsp => :space)], :overlong => :truncate)
155         return true
156       end
157     }
158   end
159
160   def is_british?(word)
161     return oxford(nil, :word => word, :justcheck => true, :british => true)
162   end
163
164
165   def chambers(m, params)
166     justcheck = params[:justcheck]
167
168     word = params[:word].to_s.downcase
169     url = @chambersurl % CGI.escape(word)
170     xml = nil
171     info = @bot.httputil.get_response(url) rescue nil
172     xml = info.body if info
173     case xml
174     when nil
175       info = info ? " (#{info.code} - #{info.message})" : ""
176       return false if justcheck
177       m.reply "An error occurred while looking for #{word}#{info}"
178       return
179     when /Sorry, no entries for <b>.*?<\/b> were found./
180       return false if justcheck
181       m.reply "Nothing found for #{word}"
182       return
183     when /No exact matches for <b>.*?<\/b>, but the following may be helpful./
184       return false if justcheck
185       m.reply "Nothing found for #{word}, but see #{url} for possible suggestions"
186       return
187     end
188     # Else, we have a hit
189     return true if justcheck
190     m.reply "#{word}: #{url}"
191     entries = xml.scan(CHAMBERS_LEMMA)
192     hits = @bot.config['dict.hits']
193     entries[0...hits].map { |ar|
194       m.reply(("#{Bold}%s#{Bold} #{Underline}%s#{Underline}%s" % ar).ircify_html, :overlong => :truncate)
195     }
196   end
197
198   def is_english?(word)
199     return chambers(nil, :word => word, :justcheck => true)
200   end
201
202   def littre(m, params)
203     justcheck = params[:justcheck]
204
205     word = params[:word].to_s.downcase
206     url = @littreurl % CGI.escape(word)
207     xml = nil
208     info = @bot.httputil.get_response(url) rescue nil
209     xml = info.body if info
210     head ||= xml.match(/<div class="entree">(.*?)<\/div>/)[1] rescue nil
211     case xml
212     when nil
213       info = info ? " (#{info.code} - #{info.message})" : ""
214       return false if justcheck
215       m.reply "An error occurred while looking for #{word}#{info}"
216       return
217     when /Erreur : le mot <STRONG>.*?<\/STRONG> n'a pas./
218       return false if justcheck
219       if head
220         m.reply "Nothing found for #{word}, I'll assume you meant #{head}"
221       else
222         m.reply "Nothing found for #{word}"
223         return
224       end
225     end
226     return true if justcheck
227     entete = xml.match(/<div class="entete">(.*?)<\/div>/m)[1] rescue nil
228     m.reply "#{head}: #{url} : #{entete.ircify_html rescue nil}"
229     entries = xml.scan(/<span class="variante">(.*?)<\!--variante-->/m)
230     hits = @bot.config['dict.hits']
231     n = 0
232     entries[0...hits].map { |ar|
233       n += 1
234       m.reply(("#{Bold}#{n}#{Bold} %s" % ar).ircify_html, :overlong => :truncate)
235     }
236   end
237
238   def is_french?(word)
239     return littre(nil, :word => word, :justcheck => true)
240   end
241
242 end
243
244 plugin = DictPlugin.new
245 plugin.map 'demauro :word', :action => 'demauro', :thread => true
246 plugin.map 'oxford *word', :action => 'oxford', :thread => true
247 plugin.map 'chambers *word', :action => 'chambers', :thread => true
248 plugin.map 'littre *word', :action => 'littre', :thread => true
249