Created
August 5, 2011 05:32
-
-
Save vraravam/1126964 to your computer and use it in GitHub Desktop.
Use Google translate to translate a yml file from one language to generate a new one for a different language
This file contains 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
#!/usr/bin/env ruby | |
if ARGV.size != 2 | |
puts "Usage: #{$0} <from_language> <to_language>" | |
exit -1 | |
end | |
require 'rubygems' | |
require 'ya2yaml' # this gem is needed for this to work! | |
require 'yaml' | |
require 'json' | |
require 'uri' | |
TRANSLATIONS_TABLE = {:"ja-JP" => :ja} | |
def translate(string) | |
command = <<-EOF | |
curl -s -A "Mozilla/5.0 (X11; Linux x86_64; rv:5.0) Gecko/20100101 Firefox/5.0" "http://translate.google.com/translate_a/t?client=t&text=#{URI.escape(string)}&hl=#{@from_language}&sl=auto&tl=#{@googles_to_language}&multires=1&prev=conf&psl=auto&ptl=#{@from_language}&otf=1&it=sel.7123%2Ctgtd.3099&ssel=0&tsel=4&uptl=#{@googles_to_language}&sc=1" | |
EOF | |
command.strip! | |
res = `#{command}`.gsub!(/,+/, ",") | |
JSON.parse(res).first.first.first.strip | |
end | |
def process(hash) | |
hash.inject({}) do |h, pair| | |
key, value = pair | |
h[key] = value.kind_of?(Hash) ? process(value) : translate(value) | |
h | |
end | |
end | |
@from_language = ARGV[0].to_sym | |
@users_to_language = ARGV[1].to_sym | |
@googles_to_language = TRANSLATIONS_TABLE[@users_to_language] || @users_to_language | |
directory = "config/locales/" | |
hash = YAML.load_file("#{directory}#{@from_language}.yml")[@from_language.to_s] | |
result = process(hash) | |
File.open("#{directory}#{@users_to_language}.yml", 'w') do |out| | |
out.write({@users_to_language.to_s => result}.ya2yaml) | |
end |
👍
Hello can any help me i was trying to run this code but got error 403, from url call, your client does not have permission
FYI: This gist no longer works. I was bummed about that, so I wrote this: https://github.com/midwire/tr4n5l4te
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
+1. The one change that you need to make is in line 22
return the string if res is nil (sometimes you'll get that based on what you're passing in)
This would be the new translate method
def translate(string)
command = <<-EOF
curl -s -A "Mozilla/5.0 (X11; Linux x86_64; rv:5.0) Gecko/20100101 Firefox/5.0" "http://translate.google.com/translate_a/t?client=t&text=#{URI.escape(string)}&hl=#{@from_language}&sl=auto&tl=#{@googles_to_language}&multires=1&prev=conf&psl=auto&ptl=#{@from_language}&otf=1&it=sel.7123%2Ctgtd.3099&ssel=0&tsel=4&uptl=#{@googles_to_language}&sc=1"
EOF
command.strip!
res =
#{command}
.gsub!(/,+/, ",")return string if res.nil?
JSON.parse(res).first.first.first.strip
end