Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

port from google codes

  • Loading branch information...
commit 63c6430861a3f619b89899df024d7e641262d580 0 parents
Ye Dingding authored
3  .gitignore
@@ -0,0 +1,3 @@
+.svn
+**/.svn
+**/**/.svn
10 History.txt
@@ -0,0 +1,10 @@
+v1.0 Dec 16th, 2008
+* using the Google AJAX Language API instead of scrape
+* add the batch translation support
+* refactor the whole project
+
+v0.2 Nov 16, 2007
+* add a command line tool.
+
+v0.1 Nov 15, 2007
+* initial release
20 MIT-LICENSE
@@ -0,0 +1,20 @@
+Copyright (c) 2007 Dingding Ye
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
11 Manifest.txt
@@ -0,0 +1,11 @@
+History.txt
+MIT-LICENSE
+Manifest.txt
+README.txt
+Rakefile
+bin/rtranslate
+lib/rtranslate.rb
+lib/rtranslate/language.rb
+lib/rtranslate/rtranslate.rb
+rtranslate.gemspec
+tests/ts_translate.rb
25 README.txt
@@ -0,0 +1,25 @@
+= google-api-transalte-ruby
+A simple, unofficial, ruby client API for using Google Translate.
+
+== Install
+
+sudo gem install sishen-rtranslate
+
+== Usage
+1.
+{{{
+require "rtranslate"
+result = Translate.t("xxx", Language::English, Language::CHINESE_SIMPLIFIED)
+}}}
+
+2.
+{{{
+$rtranslate -f en -t zh-CN xxx
+}}}
+
+Check test for more examples
+
+== COPYRIGHT
+
+Copyright (c) 2007 Dingding Ye <yedingding@gmail.com>
+Distributed under MIT License
12 Rakefile
@@ -0,0 +1,12 @@
+require 'rubygems'
+require 'hoe'
+
+Hoe.new('rtranslate', '1.0') do |p|
+ p.rubyforge_name = 'rtranslate'
+ p.author = 'Ye Dingding'
+ p.email = 'yedingding@gmail.com'
+ p.url = 'http://sishen.lifegoo.com'
+ p.summary = 'Google translate ruby client api'
+ p.description = 'A simple, unofficial, ruby client API for using Google Translate.'
+ p.extra_deps = [['hpricot', '>= 0.4'], ['json', '>= 1.1.3']]
+end
37 bin/rtranslate
@@ -0,0 +1,37 @@
+#!/usr/bin/env ruby
+
+$:.unshift(File::join(File::dirname(File::dirname(__FILE__)), "lib"))
+
+require 'rtranslate'
+require 'optparse'
+
+options = {}
+opts = OptionParser.new do |opts|
+ opts.banner = <<-EOF
+ Usage:
+ rtranslate -f lang -t lang text
+ EOF
+
+ opts.on("-fLANG", "--from LANG", "From Language LANG") do |x|
+ options[:from] = x
+ end
+
+ opts.on("-tLANG", "--to LANG", "To Language LANG") do |x|
+ options[:to] = x
+ end
+
+ opts.on("-h", "--help", "Show this message") do
+ puts opts
+ exit
+ end
+end
+
+opts.parse!(ARGV)
+text = ARGV.shift
+
+if options[:from].nil? || options[:to].nil? || text.empty?
+ puts opts
+ exit
+end
+
+STDOUT.puts(Translate.t(text, options[:from], options[:to]))
23 lib/rtranslate.rb
@@ -0,0 +1,23 @@
+require File.join(File.dirname(__FILE__), 'rtranslate/language')
+require File.join(File.dirname(__FILE__), 'rtranslate/rtranslate')
+require 'uri'
+require 'open-uri'
+
+begin
+ require 'hpricot'
+rescue LoadError
+ require 'rubygems'
+ require 'hpricot'
+end
+
+$KCODE = 'u'
+
+include Translate
+def Translate.t(text, from, to)
+ begin
+ RTranslate.translate(text, from, to)
+ rescue
+ "Error: " + $!
+ end
+end
+
145 lib/rtranslate/language.rb
@@ -0,0 +1,145 @@
+module Google
+ module Language
+ Languages = {
+ 'af' => 'AFRIKAANS',
+ 'sq' => 'ALBANIAN',
+ 'am' => 'AMHARIC',
+ 'ar' => 'ARABIC',
+ 'hy' => 'ARMENIAN',
+ 'az' => 'AZERBAIJANI',
+
+ 'eu' => 'BASQUE',
+ 'be' => 'BELARUSIAN',
+ 'bn' => 'BENGALI',
+ 'bh' => 'BIHARI',
+ 'bg' => 'BULGARIAN',
+ 'my' => 'BURMESE',
+
+ 'ca' => 'CATALAN',
+ 'chr' => 'CHEROKEE',
+ 'zh' => 'CHINESE',
+ 'zh-CN' => 'CHINESE_SIMPLIFIED',
+ 'zh-TW' => 'CHINESE_TRADITIONAL',
+ 'hr' => 'CROATIAN',
+ 'cs' => 'CZECH',
+
+ 'da' => 'DANISH',
+ 'dv' => 'DHIVEHI',
+ 'nl' => 'DUTCH',
+
+ 'en' => 'ENGLISH',
+ 'eo' => 'ESPERANTO',
+ 'et' => 'ESTONIAN',
+
+ 'tl' => 'FILIPINO',
+ 'fi' => 'FINNISH',
+ 'fr' => 'FRENCH',
+
+ 'gl' => 'GALICIAN',
+ 'ka' => 'GEORGIAN',
+ 'de' => 'GERMAN',
+ 'el' => 'GREEK',
+ 'gn' => 'GUARANI',
+ 'gu' => 'GUJARATI',
+
+ 'iw' => 'HEBREW',
+ 'hi' => 'HINDI',
+ 'hu' => 'HUNGARIAN',
+
+ 'is' => 'ICELANDIC',
+ 'id' => 'INDONESIAN',
+ 'iu' => 'INUKTITUT',
+ 'it' => 'ITALIAN',
+
+ 'ja' => 'JAPANESE',
+
+ 'kn' => 'KANNADA',
+ 'kk' => 'KAZAKH',
+ 'km' => 'KHMER',
+ 'ko' => 'KOREAN',
+ 'ku' => 'KURDISH',
+ 'ky' => 'KYRGYZ',
+
+ 'lo' => 'LAOTHIAN',
+ 'lv' => 'LATVIAN',
+ 'lt' => 'LITHUANIAN',
+
+ 'mk' => 'MACEDONIAN',
+ 'ms' => 'MALAY',
+ 'ml' => 'MALAYALAM',
+ 'mt' => 'MALTESE',
+ 'mr' => 'MARATHI',
+ 'mn' => 'MONGOLIAN',
+
+ 'ne' => 'NEPALI',
+ 'no' => 'NORWEGIAN',
+
+ 'or' => 'ORIYA',
+
+ 'ps' => 'PASHTO',
+ 'fa' => 'PERSIAN',
+ 'pl' => 'POLISH',
+ 'pt-PT' => 'PORTUGUESE',
+ 'pa' => 'PUNJABI',
+
+ 'ro' => 'ROMANIAN',
+ 'ru' => 'RUSSIAN',
+
+ 'sa' => 'SANSKRIT',
+ 'sr' => 'SERBIAN',
+ 'sd' => 'SINDHI',
+ 'si' => 'SINHALESE',
+ 'sk' => 'SLOVAK',
+ 'sl' => 'SLOVENIAN',
+ 'es' => 'SPANISH',
+ 'sw' => 'SWAHILI',
+ 'sv' => 'SWEDISH',
+
+ 'tg' => 'TAJIK',
+ 'ta' => 'TAMIL',
+ 'tl' => 'TAGALOG',
+ 'te' => 'TELUGU',
+ 'th' => 'THAI',
+ 'bo' => 'TIBETAN',
+ 'tr' => 'TURKISH',
+
+ 'uk' => 'UKRAINIAN',
+ 'ur' => 'URDU',
+ 'uz' => 'UZBEK',
+ 'ug' => 'UIGHUR',
+
+ 'vi' => 'VIETNAMESE',
+
+ '' => 'UNKNOWN'
+ }
+
+ # judge whether the language is supported by google translate
+ def supported?(language)
+ if Languages.key?(language) || Languages.value?(language.upcase)
+ true
+ else
+ false
+ end
+ end
+ module_function :supported?
+
+ # get the abbrev of the language
+ def abbrev(language)
+ if supported?(language)
+ if Languages.key?(language)
+ language
+ else
+ language.upcase!
+ Languages.each do |k,v|
+ if v == language
+ return k
+ end
+ end
+ end
+ else
+ nil
+ end
+ end
+ module_function :abbrev
+ end
+end
137 lib/rtranslate/rtranslate.rb
@@ -0,0 +1,137 @@
+# The program is a simple, unofficial, ruby client API
+# for using Google Translate.
+#
+# Author:: Dingding Ye (mailto:yedingding@gmail.com)
+# Copyright:: Copyright (c) 2007 Dingding Ye
+# License:: Distributes under MIT License
+
+begin
+ require 'json'
+rescue LoadError
+ require 'rubygems'
+ require 'json'
+end
+
+module Translate
+ class UnsupportedLanguagePair < StandardError
+ end
+
+ class RTranslate
+ # Google AJAX Language REST Service URL
+ GOOGLE_TRANSLATE_URL = "http://ajax.googleapis.com/ajax/services/language/translate"
+
+ # Default version of Google AJAX Language API
+ DEFAULT_VERSION = "1.0"
+
+ attr_reader :version, :key
+ attr_reader :default_from, :default_to
+
+ class << self
+ def translate(text, from, to)
+ RTranslate.new.translate(text, { :from => from, :to => to })
+ end
+
+ def translate_strings(text_array, from, to)
+ RTranslate.new.translate_strings(text_array, {:from => from, :to => to})
+ end
+
+ def translate_string_to_languages(text, options)
+ RTranslate.new.translate_string_to_languages(text, options)
+ end
+
+ def batch_translate(translate_options)
+ RTranslate.new.batch_translate(translate_options)
+ end
+
+ alias_method :t, :translate
+ end
+
+ def initialize(version = DEFAULT_VERSION, key = nil, default_from = nil, default_to = nil)
+ @version = version
+ @key = key
+ @default_from = default_from
+ @default_to = default_to
+
+ if @default_from && !(Google::Lanauage.supported?(@default_from))
+ raise StandardError, "Unsupported source language '#{@default_from}'"
+ end
+
+ if @default_to && !(Google::Lanauage.supported?(@default_to))
+ raise StandardError, "Unsupported destination language '#{@default_to}'"
+ end
+ end
+
+ # translate the string from a source language to a target language.
+ #
+ # Configuration options:
+ # * <tt>:from</tt> - The source language
+ # * <tt>:to</tt> - The target language
+ def translate(text, options = { })
+ from = options[:from] || @default_from
+ to = options[:to] || @default_to
+ if Google::Language.supported?(from) && Google::Language.supported?(to)
+ from = Google::Language.abbrev(from)
+ to = Google::Language.abbrev(to)
+ langpair = "#{from}|#{to}"
+ url = "#{GOOGLE_TRANSLATE_URL}?q=#{text}&langpair=#{langpair}&v=#{@version}"
+ if @key
+ url << "&key=#{@key}"
+ end
+ do_translate(url)
+ else
+ raise UnsupportedLanguagePair, "Translation from '#{from}' to '#{to}' isn't supported yet!"
+ end
+ end
+
+ # translate several strings, all from the same source language to the same target language.
+ #
+ # Configuration options
+ # * <tt>:from</tt> - The source language
+ # * <tt>:to</tt> - The target language
+ def translate_strings(text_array, options = { })
+ text_array.collect do |text|
+ self.translate(text, options)
+ end
+ end
+
+ # Translate one string into several languages.
+ #
+ # Configuration options
+ # * <tt>:from</tt> - The source language
+ # * <tt>:to</tt> - The target language list
+ # Example:
+ #
+ # translate_string_to_languages("China", {:from => "en", :to => ["zh-CN", "zh-TW"]})
+ def translate_string_to_languages(text, option)
+ option[:to].collect do |to|
+ self.translate(text, { :from => option[:from], :to => to })
+ end
+ end
+
+ # Translate several strings, each into a different language.
+ #
+ # Examples:
+ #
+ # batch_translate([["China", {:from => "en", :to => "zh-CN"}], ["Chinese", {:from => "en", :to => "zh-CN"}]])
+ def batch_translate(translate_options)
+ translate_options.collect do |text, option|
+ self.translate(text, option)
+ end
+ end
+
+ private
+ def do_translate(url) #:nodoc:
+ begin
+ jsondoc = open(URI.escape(url)).read
+ response = JSON.parse(jsondoc)
+ if response["responseStatus"] == 200
+ response["responseData"]["translatedText"]
+ else
+ raise StandardError, response["responseDetails"]
+ end
+ rescue Exception => e
+ raise StandardError, e.message
+ end
+ end
+ end
+end
39 rtranslate.gemspec
@@ -0,0 +1,39 @@
+Gem::Specification.new do |s|
+ s.name = %q{rtranslate}
+ s.version = "1.0"
+
+ s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
+ s.authors = ["Ye Dingding"]
+ s.date = %q{2008-12-16}
+ s.description = %q{rtranslate is a simple, unofficial, ruby client API for using Google Translate.}
+ s.email = %q{yedingding@gmail.com}
+ s.extra_rdoc_files = ["History.txt", "Manifest.txt", "README.txt"]
+ s.files = ["History.txt", "MIT-LICENSE", "Manifest.txt", "README.txt", "Rakefile", "rtranslate.gemspec", "bin/rtranslate",
+ "lib/rtranslate.rb", "lib/rtranslate/language.rb", "lib/rtranslate/rtranslate.rb", "tests/ts_translate.rb",
+ "bin/rtranslate", "lib/rtranslate.rb", "lib/rtranslate/language.rb", "lib/rtranslate/rtranslate.rb"]
+ s.has_rdoc = true
+ s.homepage = %q{http://sishen.lifegoo.com}
+ s.rdoc_options = ["--main", "README.txt"]
+ s.require_paths = ["lib"]
+ s.rubygems_version = %q{1.2.0}
+ s.summary = %q{a simple, unofficial, ruby client API for using Google Translate}
+
+ if s.respond_to? :specification_version then
+ current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION
+ s.specification_version = 2
+
+ if current_version >= 3 then
+ s.add_development_dependency(%q<hoe>, [">= 1.7.0"])
+ s.add_development_dependency(%q<rspec>, [">= 1.1.4"])
+ s.add_development_dependency(%q<json>, [">= 1.1.3"])
+ else
+ s.add_dependency(%q<hoe>, [">= 1.7.0"])
+ s.add_dependency(%q<rspec>, [">= 1.1.4"])
+ s.add_dependency(%q<json>, [">= 1.1.3"])
+ end
+ else
+ s.add_dependency(%q<hoe>, [">= 1.7.0"])
+ s.add_dependency(%q<rspec>, [">= 1.1.4"])
+ s.add_dependency(%q<json>, [">= 1.1.3"])
+ end
+end
45 tests/ts_translate.rb
@@ -0,0 +1,45 @@
+# -*- coding: utf-8 -*-
+$:.unshift File.expand_path(File.dirname(__FILE__) + "/../lib")
+
+require 'test/unit'
+require 'rtranslate'
+
+class Translate::TranslateTest < Test::Unit::TestCase
+ include Google::Language
+ def test_english_translate
+ assert_equal("مرحبا العالم", Translate.t("Hello world", "ENGLISH", "ARABIC"));
+ assert_equal("世界您好", Translate.t("Hello world", "ENGLISH", "CHINESE_SIMPLIFIED"));
+ assert_equal("Bonjour le monde", Translate.t("Hello world", "ENGLISH", "FRENCH"));
+ assert_equal("Hallo Welt", Translate.t("Hello world", "ENGLISH", "GERMAN"));
+ assert_equal("Ciao mondo", Translate.t("Hello world", "ENGLISH", "ITALIAN"));
+ assert_equal("こんにちは世界", Translate.t("Hello world", "ENGLISH", "JAPANESE"));
+ assert_equal("여보세요 세계", Translate.t("Hello world", "ENGLISH", "KOREAN"));
+ assert_equal("Olá mundo", Translate.t("Hello world", "ENGLISH", "PORTUGUESE"));
+ assert_equal("Привет мир", Translate.t("Hello world", "ENGLISH", "RUSSIAN"));
+ assert_equal("Hola mundo", Translate.t("Hello world", "ENGLISH", "SPANISH"));
+ end
+
+ def test_chinese_translate
+ assert_equal("Hello World", Translate.t("你好世界", "CHINESE", "ENGLISH"))
+ assert_equal("Hello World", Translate.t("你好世界", 'zh', 'en'))
+ end
+
+ def test_unsupported_translate
+ assert_raise UnsupportedLanguagePair do
+ Translate::RTranslate.t("你好世界", 'zh', 'hz')
+ end
+ end
+
+ def test_translate_strings
+ assert_equal(["", "世界"], Translate::RTranslate.translate_strings(["Hello", "World"], "en", "zh-CN"))
+ end
+
+ def test_translate_string_to_languages
+ assert_equal(["世界您好", "ハローワールド"], Translate::RTranslate.translate_string_to_languages("Hello World", {:from => "en", :to => ["zh-CN", "ja"]}))
+ end
+
+ def test_batch_translate
+ assert_equal(["世界您好", "ハローワールド"],
+ Translate::RTranslate.batch_translate([["Hello World", {:from => "en", :to => "zh-CN"}], ["Hello World", {:from => "en", :to => "ja"}]]))
+ end
+end
Please sign in to comment.
Something went wrong with that request. Please try again.