translator: fix random bug caused by undefined variables
[rbot] / data / rbot / plugins / translator.rb
1 #-- vim:sw=2:et
2 #++
3 #
4 # :title: Translator plugin for rbot
5 #
6 # Author:: Yaohan Chen <yaohan.chen@gmail.com>
7 # Copyright:: (C) 2007 Yaohan Chen
8 # License:: GPLv2
9 #
10 # This plugin allows using rbot to translate text on a few translation services
11 #
12 # TODO
13 #
14 # * Configuration for whether to show translation engine
15 # * Optionally sync default translators with karma.rb ranking
16
17 require 'set'
18 require 'timeout'
19
20 # base class for implementing a translation service
21 # = Attributes
22 # direction:: supported translation directions, a hash where each key is a source
23 #             language name, and each value is Set of target language names. The
24 #             methods in the Direction module are convenient for initializing this
25 #             attribute
26 class Translator
27   INFO = 'Some translation service'
28
29   class UnsupportedDirectionError < ArgumentError
30   end
31
32   class NoTranslationError < RuntimeError
33   end
34
35   attr_reader :directions, :cache
36
37   def initialize(directions, cache={})
38     @directions = directions
39     @cache = cache
40   end
41
42
43   # whether the translator supports this direction
44   def support?(from, to)
45     from != to && @directions[from].include?(to)
46   end
47
48   # this implements argument checking and caching. subclasses should define the
49   # do_translate method to implement actual translation
50   def translate(text, from, to)
51     raise UnsupportedDirectionError unless support?(from, to)
52     raise ArgumentError, _("Cannot translate empty string") if text.empty?
53     request = [text, from, to]
54     unless @cache.has_key? request
55       translation = do_translate(text, from, to)
56       raise NoTranslationError if translation.empty?
57       @cache[request] = translation
58     else
59       @cache[request]
60     end
61   end
62
63   module Direction
64     # given the set of supported languages, return a hash suitable for the directions
65     # attribute which includes any language to any other language
66     def self.all_to_all(languages)
67       directions = all_to_none(languages)
68       languages.each {|l| directions[l] = languages.to_set}
69       directions
70     end
71
72     # a hash suitable for the directions attribute which includes any language from/to
73     # the given set of languages (center_languages)
74     def self.all_from_to(languages, center_languages)
75       directions = all_to_none(languages)
76       center_languages.each {|l| directions[l] = languages - [l]}
77       (languages - center_languages).each {|l| directions[l] = center_languages.to_set}
78       directions
79     end
80
81     # get a hash from a list of pairs
82     def self.pairs(list_of_pairs)
83       languages = list_of_pairs.flatten.to_set
84       directions = all_to_none(languages)
85       list_of_pairs.each do |(from, to)|
86         directions[from] << to
87       end
88       directions
89     end
90
91     # an empty hash with empty sets as default values
92     def self.all_to_none(languages)
93       Hash.new do |h, k|
94         # always return empty set when the key is non-existent, but put empty set in the
95         # hash only if the key is one of the languages
96         if languages.include? k
97           h[k] = Set.new
98         else
99           Set.new
100         end
101       end
102     end
103   end
104 end
105
106
107 class NiftyTranslator < Translator
108   INFO = '@nifty Translation <http://nifty.amikai.com/amitext/indexUTF8.jsp>'
109
110   def initialize(cache={})
111    require 'mechanize'
112    super(Translator::Direction.all_from_to(%w[ja en zh_CN ko], %w[ja]), cache)
113     @form = WWW::Mechanize.new.
114             get('http://nifty.amikai.com/amitext/indexUTF8.jsp').
115             forms_with(:name => 'translateForm').last
116   end
117
118   def do_translate(text, from, to)
119     @radio = @form.radiobuttons_with(:name => 'langpair').first
120     @radio.value = "#{from},#{to}".upcase
121     @radio.check
122     @form.fields_with(:name => 'sourceText').last.value = text
123
124     @form.submit(@form.buttons_with(:name => 'translate').last).
125           forms_with(:name => 'translateForm').last.fields_with(:name => 'translatedText').last.value
126   end
127 end
128
129
130 class ExciteTranslator < Translator
131   INFO = 'Excite.jp Translation <http://www.excite.co.jp/world/>'
132
133   def initialize(cache={})
134     require 'mechanize'
135     require 'iconv'
136
137     super(Translator::Direction.all_from_to(%w[ja en zh_CN zh_TW ko], %w[ja]), cache)
138
139     @forms = Hash.new do |h, k|
140       case k
141       when 'en'
142         h[k] = open_form('english')
143       when 'zh_CN', 'zh_TW'
144         # this way we don't need to fetch the same page twice
145         h['zh_CN'] = h['zh_TW'] = open_form('chinese')
146       when 'ko'
147         h[k] = open_form('korean')
148       end
149     end
150   end
151
152   def open_form(name)
153     WWW::Mechanize.new.get("http://www.excite.co.jp/world/#{name}").
154                    forms_with(:name => 'world').first
155   end
156
157   def do_translate(text, from, to)
158     non_ja_language = from != 'ja' ? from : to
159     form = @forms[non_ja_language]
160
161     if non_ja_language =~ /zh_(CN|TW)/
162       form_with_fields(:name => 'wb_lp').first.value = "#{from}#{to}".sub(/_(?:CN|TW)/, '').upcase
163       form_with_fields(:name => 'big5').first.value = ($1 == 'TW' ? 'yes' : 'no')
164     else
165       # the en<->ja page is in Shift_JIS while other pages are UTF-8
166       text = Iconv.iconv('Shift_JIS', 'UTF-8', text) if non_ja_language == 'en'
167       form.fields_with(:name => 'wb_lp').first.value = "#{from}#{to}".upcase
168     end
169     form.fields_with(:name => 'before').first.value = text
170     result = form.submit.forms_with(:name => 'world').first.fields_with(:name => 'after').first.value
171     # the en<->ja page is in Shift_JIS while other pages are UTF-8
172     if non_ja_language == 'en'
173       Iconv.iconv('UTF-8', 'Shift_JIS', result)
174     else
175       result
176     end
177
178   end
179 end
180
181
182 class GoogleTranslator < Translator
183   INFO = 'Google Translate <http://www.google.com/translate_t>'
184
185   def initialize(cache={})
186     require 'mechanize'
187     load_form!
188
189     # we can probably safely assume that google translate is able to translate from
190     # any language in the source lang drop down list to any language in the target one
191     # so we create the language pairs based on that assumption
192     sl = @source_list.options.map { |o| o.value.sub('-', '_') }
193     tl = @target_list.options.map { |o| o.value.sub('-', '_') }
194     super(Translator::Direction.all_from_to(tl, sl), cache)
195   end
196
197   def load_form!
198     agent = WWW::Mechanize.new
199     # without faking the user agent, Google Translate will serve non-UTF-8 text
200     agent.user_agent_alias = 'Linux Konqueror'
201     @form = agent.get('http://www.google.com/translate_t').
202             forms_with(:action => '/translate_t').first
203     @source_list = @form.fields_with(:name => 'sl').last
204     @target_list = @form.fields_with(:name => 'tl').last
205   end
206
207   def do_translate(text, from, to)
208     load_form!
209
210     @source_list.value = from.sub('_', '-')
211     @target_list.value = to.sub('_', '-')
212     @form.fields_with(:name => 'text').last.value = text
213     @form.submit.parser.search('div#result_box').inner_html
214   end
215 end
216
217
218 class BabelfishTranslator < Translator
219   INFO = 'AltaVista Babel Fish Translation <http://babelfish.altavista.com/babelfish/>'
220
221   def initialize(cache)
222     require 'mechanize'
223
224     @form = WWW::Mechanize.new.get('http://babelfish.altavista.com/babelfish/').
225             forms_with(:name => 'frmTrText').first
226     @lang_list = @form.fields_with(:name => 'lp').first
227     language_pairs = @lang_list.options.map {|o| o.value.split('_')}.
228                                             reject {|p| p.empty?}
229     super(Translator::Direction.pairs(language_pairs), cache)
230   end
231
232   def do_translate(text, from, to)
233     if @form.fields_with(:name => 'trtext').empty?
234       @form.add_field!('trtext', text)
235     else
236       @form.fields_with(:name => 'trtext').first.value = text
237     end
238     @lang_list.value = "#{from}_#{to}"
239     @form.submit.parser.search("div[@id='result']/div[@style]").inner_html
240   end
241 end
242
243 class WorldlingoTranslator < Translator
244   INFO = 'WorldLingo Free Online Translator <http://www.worldlingo.com/en/products_services/worldlingo_translator.html>'
245
246   LANGUAGES = %w[en fr de it pt es ru nl el sv ar ja ko zh_CN zh_TW]
247   def initialize(cache)
248     require 'uri'
249     super(Translator::Direction.all_to_all(LANGUAGES), cache)
250   end
251
252   def translate(text, from, to)
253     response = Irc::Utils.bot.httputil.get_response(URI.escape(
254                "http://www.worldlingo.com/SEfpX0LV2xIxsIIELJ,2E5nOlz5RArCY,/texttranslate?wl_srcenc=utf-8&wl_trgenc=utf-8&wl_text=#{text}&wl_srclang=#{from.upcase}&wl_trglang=#{to.upcase}"))
255     # WorldLingo seems to respond an XML when error occurs
256     case response['Content-Type']
257     when %r'text/plain'
258       response.body
259     else
260       raise Translator::NoTranslationError
261     end
262   end
263 end
264
265 class TranslatorPlugin < Plugin
266   Config.register Config::IntegerValue.new('translator.timeout',
267     :default => 30, :validate => Proc.new{|v| v > 0},
268     :desc => _("Number of seconds to wait for the translation service before timeout"))
269   Config.register Config::StringValue.new('translator.destination',
270     :default => "en",
271     :desc => _("Default destination language to be used with translate command"))
272
273   TRANSLATORS = {
274     'nifty' => NiftyTranslator,
275     'excite' => ExciteTranslator,
276     'google_translate' => GoogleTranslator,
277     'babelfish' => BabelfishTranslator,
278     'worldlingo' => WorldlingoTranslator,
279   }
280
281   def initialize
282     super
283
284     @translators = {}
285     TRANSLATORS.each_pair do |name, c|
286       begin
287         @translators[name] = c.new(@registry.sub_registry(name))
288         map "#{name} :from :to *phrase",
289           :action => :cmd_translate, :thread => true
290       rescue Exception
291         warning _("Translator %{name} cannot be used: %{reason}") %
292                {:name => name, :reason => $!}
293       end
294     end
295
296     Config.register Config::ArrayValue.new('translator.default_list',
297       :default => TRANSLATORS.keys,
298       :validate => Proc.new {|l| l.all? {|t| TRANSLATORS.has_key?(t)}},
299       :desc => _("List of translators to try in order when translator name not specified"),
300       :on_change => Proc.new {|bot, v| update_default})
301     update_default
302   end
303
304   def help(plugin, topic=nil)
305     if @translators.has_key?(plugin)
306       translator = @translators[plugin]
307       _('%{translator} <from> <to> <phrase> => Look up phrase using %{info}, supported from -> to languages: %{directions}') % {
308         :translator => plugin,
309         :info => translator.class::INFO,
310         :directions => translator.directions.map do |source, targets|
311                          _('%{source} -> %{targets}') %
312                          {:source => source, :targets => targets.to_a.join(', ')}
313                        end.join(' | ')
314       }
315     else
316       _('Command: <translator> <from> <to> <phrase>, where <translator> is one of: %{translators}. If "translator" is used in place of the translator name, the first translator in translator.default_list which supports the specified direction will be picked automatically. Use "help <translator>" to look up supported from and to languages') %
317         {:translators => @translators.keys.join(', ')}
318     end
319   end
320
321   def languages
322     @languages ||= @translators.map { |t| t.last.directions.keys }.flatten.uniq
323   end
324
325   def update_default
326     @default_translators = bot.config['translator.default_list'] & @translators.keys
327   end
328
329   def cmd_translator(m, params)
330     params[:to] = @bot.config['translator.destination'] if params[:to].nil?
331
332     # Use google translate as translator if source language has not been given
333     # and auto-detect it
334     if params[:from].nil?
335       params[:from] = "auto"
336       translator = "google_translate"
337     else
338       translator = @default_translators.find {|t| @translators[t].support?(params[:from], params[:to])}
339     end
340
341     if translator
342       cmd_translate m, params.merge({:translator => translator, :show_provider => true})
343     else
344       m.reply _('None of the default translators (translator.default_list) supports translating from %{source} to %{target}') % {:source => params[:from], :target => params[:to]}
345     end
346   end
347
348   def cmd_translate(m, params)
349     # get the first word of the command
350     tname = params[:translator] || m.message[/\A(\w+)\s/, 1]
351     translator = @translators[tname]
352     from, to, phrase = params[:from], params[:to], params[:phrase].to_s
353     if translator
354       begin
355         translation = Timeout.timeout(@bot.config['translator.timeout']) do
356           translator.translate(phrase, from, to)
357         end
358         m.reply(if params[:show_provider]
359                   _('%{translation} (provided by %{translator})') %
360                     {:translation => translation, :translator => tname.gsub("_", " ")}
361                 else
362                   translation
363                 end)
364
365       rescue Translator::UnsupportedDirectionError
366         m.reply _("%{translator} doesn't support translating from %{source} to %{target}") %
367                 {:translator => tname, :source => from, :target => to}
368       rescue Translator::NoTranslationError
369         m.reply _('%{translator} failed to provide a translation') %
370                 {:translator => tname}
371       rescue Timeout::Error
372         m.reply _('The translator timed out')
373       end
374     else
375       m.reply _('No translator called %{name}') % {:name => tname}
376     end
377   end
378 end
379
380 plugin = TranslatorPlugin.new
381 req = Hash[*%w(from to).map { |e| [e.to_sym, /#{plugin.languages.join("|")}/] }.flatten]
382
383 plugin.map 'translate [:from] [:to] *phrase',
384            :action => :cmd_translator, :thread => true, :requirements => req
385 plugin.map 'translator [:from] [:to] *phrase',
386            :action => :cmd_translator, :thread => true, :requirements => req