]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - data/rbot/plugins/translator.rb
translator.rb: use "help <translator>" instead of "help translator <translator>"...
[user/henk/code/ruby/rbot.git] / 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.name('translateForm').first
116   end
117
118   def do_translate(text, from, to)
119     @form.radiobuttons.name('langpair').value = "#{from},#{to}".upcase
120     @form.fields.name('sourceText').value = text
121
122     @form.submit(@form.buttons.name('translate')).
123           forms.name('translateForm').fields.name('translatedText').value
124   end
125 end
126
127
128 class ExciteTranslator < Translator
129   INFO = 'Excite.jp Translation <http://www.excite.co.jp/world/>'
130
131   def initialize(cache={})
132     require 'mechanize'
133     require 'iconv'
134
135     super(Translator::Direction.all_from_to(%w[ja en zh_CN zh_TW ko], %w[ja]), cache)
136
137     @forms = Hash.new do |h, k|
138       case k
139       when 'en'
140         h[k] = open_form('english')
141       when 'zh_CN', 'zh_TW'
142         # this way we don't need to fetch the same page twice
143         h['zh_CN'] = h['zh_TW'] = open_form('chinese')
144       when 'ko'
145         h[k] = open_form('korean')
146       end
147     end
148   end
149
150   def open_form(name)
151     WWW::Mechanize.new.get("http://www.excite.co.jp/world/#{name}").
152                    forms.name('world').first
153   end
154
155   def do_translate(text, from, to)
156     non_ja_language = from != 'ja' ? from : to
157     form = @forms[non_ja_language]
158
159     if non_ja_language =~ /zh_(CN|TW)/
160       form.fields.name('wb_lp').value = "#{from}#{to}".sub(/_(?:CN|TW)/, '').upcase
161       form.fields.name('big5').value = ($1 == 'TW' ? 'yes' : 'no')
162     else
163       # the en<->ja page is in Shift_JIS while other pages are UTF-8
164       text = Iconv.iconv('Shift_JIS', 'UTF-8', text) if non_ja_language == 'en'
165       form.fields.name('wb_lp').value = "#{from}#{to}".upcase
166     end
167     form.fields.name('before').value = text
168     result = form.submit.forms.name('world').fields.name('after').value
169     # the en<->ja page is in Shift_JIS while other pages are UTF-8
170     if non_ja_language == 'en'
171       Iconv.iconv('UTF-8', 'Shift_JIS', result)
172     else
173       result
174     end
175
176   end
177 end
178
179
180 class GoogleTranslator < Translator
181   INFO = 'Google Translate <http://www.google.com/translate_t>'
182
183   def initialize(cache={})
184     require 'mechanize'
185     load_form!
186     language_pairs = @lang_list.options.map do |o|
187       # these options have values like "en|zh-CN"; map to things like ['en', 'zh_CN'].
188       o.value.split('|').map {|l| l.sub('-', '_')}
189     end
190     super(Translator::Direction.pairs(language_pairs), cache)
191   end
192
193   def load_form!
194     agent = WWW::Mechanize.new
195     # without faking the user agent, Google Translate will serve non-UTF-8 text
196     agent.user_agent_alias = 'Linux Konqueror'
197     @form = agent.get('http://www.google.com/translate_t').
198             forms.action('/translate_t').first
199     @lang_list = @form.fields.name('langpair')
200   end
201
202   def do_translate(text, from, to)
203     load_form!
204
205     @lang_list.value = "#{from}|#{to}".sub('_', '-')
206     @form.fields.name('text').value = text
207     @form.submit.parser.search('div#result_box').inner_html
208   end
209 end
210
211
212 class BabelfishTranslator < Translator
213   INFO = 'AltaVista Babel Fish Translation <http://babelfish.altavista.com/babelfish/>'
214
215   def initialize(cache)
216     require 'mechanize'
217
218     @form = WWW::Mechanize.new.get('http://babelfish.altavista.com/babelfish/').
219             forms.name('frmTrText').first
220     @lang_list = @form.fields.name('lp')
221     language_pairs = @lang_list.options.map {|o| o.value.split('_')}.
222                                             reject {|p| p.empty?}
223     super(Translator::Direction.pairs(language_pairs), cache)
224   end
225
226   def do_translate(text, from, to)
227     if @form.fields.name('trtext').empty?
228       @form.add_field!('trtext', text)
229     else
230       @form.fields.name('trtext').value = text
231     end
232     @lang_list.value = "#{from}_#{to}"
233     @form.submit.parser.search("td.s/div[@style]").inner_html
234   end
235 end
236
237 class WorldlingoTranslator < Translator
238   INFO = 'WorldLingo Free Online Translator <http://www.worldlingo.com/en/products_services/worldlingo_translator.html>'
239
240   LANGUAGES = %w[en fr de it pt es ru nl el sv ar ja ko zh_CN zh_TW]
241   def initialize(cache)
242     require 'uri'
243     super(Translator::Direction.all_to_all(LANGUAGES), cache)
244   end
245
246   def translate(text, from, to)
247     response = Irc::Utils.bot.httputil.get_response(URI.escape(
248                "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}"))
249     # WorldLingo seems to respond an XML when error occurs
250     case response['Content-Type']
251     when %r'text/plain'
252       response.body
253     else
254       raise Translator::NoTranslationError
255     end
256   end
257 end
258
259 class TranslatorPlugin < Plugin
260   Config.register Config::IntegerValue.new('translator.timeout',
261     :default => 30, :validate => Proc.new{|v| v > 0},
262     :desc => _("Number of seconds to wait for the translation service before timeout"))
263
264   TRANSLATORS = {
265     'nifty' => NiftyTranslator,
266     'excite' => ExciteTranslator,
267     'google_translate' => GoogleTranslator,
268     'babelfish' => BabelfishTranslator,
269     'worldlingo' => WorldlingoTranslator,
270   }
271
272   def initialize
273     super
274
275     @translators = {}
276     TRANSLATORS.each_pair do |name, c|
277       begin
278         @translators[name] = c.new(@registry.sub_registry(name))
279         map "#{name} :from :to *phrase",
280           :action => :cmd_translate, :thread => true
281       rescue Exception
282         warning _("Translator %{name} cannot be used: %{reason}") %
283                {:name => name, :reason => $!}
284       end
285     end
286
287     Config.register Config::ArrayValue.new('translator.default_list',
288       :default => TRANSLATORS.keys,
289       :validate => Proc.new {|l| l.all? {|t| TRANSLATORS.has_key?(t)}},
290       :desc => _("List of translators to try in order when translator name not specified"),
291       :on_change => Proc.new {|bot, v| update_default})
292     update_default
293   end
294
295   def help(plugin, topic=nil)
296     if @translators.has_key?(plugin)
297       translator = @translators[plugin]
298       _('%{info}, supported directions of translation: %{directions}') % {
299         :info => translator.class::INFO,
300         :directions => translator.directions.map do |source, targets|
301                          _('%{source} -> %{targets}') %
302                          {:source => source, :targets => targets.to_a.join(', ')}
303                        end.join(' | ')
304       }
305     else
306       _('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') %
307         {:translators => @translators.keys.join(', ')}
308     end
309   end
310
311   def update_default
312     @default_translators = bot.config['translator.default_list'] & @translators.keys 
313   end
314
315   def cmd_translator(m, params)
316     from, to = params[:from], params[:to]
317     translator = @default_translators.find {|t| @translators[t].support?(from, to)}
318     if translator
319       cmd_translate m, params.merge({:translator => translator, :show_provider => true})
320     else
321       m.reply _('None of the default translators (translator.default_list) supports translating from %{source} to %{target}') % {:source => from, :target => to}
322     end
323   end
324
325   def cmd_translate(m, params)
326     # get the first word of the command
327     tname = params[:translator] || m.message[/\A(\w+)\s/, 1]
328     translator = @translators[tname]
329     from, to, phrase = params[:from], params[:to], params[:phrase].to_s
330     if translator
331       begin
332         translation = Timeout.timeout(@bot.config['translator.timeout']) do
333           translator.translate(phrase, from, to)
334         end
335         m.reply(if params[:show_provider]
336                   _('%{translation} (provided by %{translator})') %
337                     {:translation => translation, :translator => tname}
338                 else
339                   translation
340                 end)
341
342       rescue Translator::UnsupportedDirectionError
343         m.reply _("%{translator} doesn't support translating from %{source} to %{target}") %
344                 {:translator => tname, :source => from, :target => to}
345       rescue Translator::NoTranslationError
346         m.reply _('%{translator} failed to provide a translation') %
347                 {:translator => tname}
348       rescue Timeout::Error
349         m.reply _('The translator timed out')
350       end
351     else
352       m.reply _('No translator called %{name}') % {:name => tname}
353     end
354   end
355 end
356
357 plugin = TranslatorPlugin.new
358 plugin.map 'translator :from :to *phrase',
359            :action => :cmd_translator, :thread => true