Created
September 10, 2010 02:57
-
-
Save mdeering/572992 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
desc "Apply Google translate to auto translate all texts in locale ENV['FROM'] to locale ENV['TO']" | |
task :google => :environment do | |
raise "Please specify FROM and TO locales as environment variables" if ENV['FROM'].blank? || ENV['TO'].blank? | |
# Depends on httparty gem | |
# http://www.robbyonrails.com/articles/2009/03/16/httparty-goes-foreign | |
class GoogleApi | |
include HTTParty | |
base_uri 'ajax.googleapis.com' | |
def self.translate(string, to, from) | |
tries = 0 | |
begin | |
get("/ajax/services/language/translate", | |
:query => {:langpair => "#{from}|#{to}", :q => string, :v => 1.0}, | |
:format => :json) | |
rescue | |
tries += 1 | |
puts("SLEEPING - retrying in 5...") | |
sleep(5) | |
retry if tries < 10 | |
end | |
end | |
end | |
I18n.backend.send(:init_translations) | |
start_at = Time.now | |
translations = {} | |
Translate::Keys.new.i18n_keys(ENV['FROM']).each do |key| | |
from_text = I18n.backend.send(:lookup, ENV['FROM'], key).to_s | |
to_text = I18n.backend.send(:lookup, ENV['TO'], key) | |
if !from_text.blank? && to_text.blank? | |
print "#{key}: '#{from_text[0, 40]}' => " | |
if !translations[from_text] | |
response = GoogleApi.translate(from_text, ENV['TO'], ENV['FROM']) | |
translations[from_text] = response["responseData"] && response["responseData"]["translatedText"] | |
end | |
if !(translation = translations[from_text]).blank? | |
translation.gsub!(/\(\(([a-z_.]+)\)\)/i, '{{\1}}') | |
# Google translate sometimes replaces {{foobar}} with (()) foobar. We skip these | |
if translation !~ /\(\(\)\)/ | |
puts "'#{translation[0, 40]}'" | |
I18n.backend.store_translations(ENV['TO'].to_sym, Translate::Keys.to_deep_hash({key => translation})) | |
else | |
puts "SKIPPING since interpolations were messed up: '#{translation[0,40]}'" | |
end | |
else | |
puts "NO TRANSLATION - #{response.inspect}" | |
end | |
end | |
end | |
puts "\nTime elapsed: #{(((Time.now - start_at) / 60) * 10).to_i / 10.to_f} minutes" | |
Translate::Storage.new(ENV['TO'].to_sym).write_to_file | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment