sishen-rtranslate 1.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,10 @@
1
+ v1.0 Dec 16th, 2008
2
+ * using the Google AJAX Language API instead of scrape
3
+ * add the batch translation support
4
+ * refactor the whole project
5
+
6
+ v0.2 Nov 16, 2007
7
+ * add a command line tool.
8
+
9
+ v0.1 Nov 15, 2007
10
+ * initial release
@@ -0,0 +1,20 @@
1
+ Copyright (c) 2007 Dingding Ye
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,11 @@
1
+ History.txt
2
+ MIT-LICENSE
3
+ Manifest.txt
4
+ README.txt
5
+ Rakefile
6
+ bin/rtranslate
7
+ lib/rtranslate.rb
8
+ lib/rtranslate/language.rb
9
+ lib/rtranslate/rtranslate.rb
10
+ rtranslate.gemspec
11
+ tests/ts_translate.rb
@@ -0,0 +1,25 @@
1
+ = google-api-transalte-ruby
2
+ A simple, unofficial, ruby client API for using Google Translate.
3
+
4
+ == Install
5
+
6
+ sudo gem install sishen-rtranslate
7
+
8
+ == Usage
9
+ 1.
10
+ {{{
11
+ require "rtranslate"
12
+ result = Translate.t("xxx", Language::English, Language::CHINESE_SIMPLIFIED)
13
+ }}}
14
+
15
+ 2.
16
+ {{{
17
+ $rtranslate -f en -t zh-CN xxx
18
+ }}}
19
+
20
+ Check test for more examples
21
+
22
+ == COPYRIGHT
23
+
24
+ Copyright (c) 2007 Dingding Ye <yedingding@gmail.com>
25
+ Distributed under MIT License
@@ -0,0 +1,12 @@
1
+ require 'rubygems'
2
+ require 'hoe'
3
+
4
+ Hoe.new('rtranslate', '1.0') do |p|
5
+ p.rubyforge_name = 'rtranslate'
6
+ p.author = 'Ye Dingding'
7
+ p.email = 'yedingding@gmail.com'
8
+ p.url = 'http://sishen.lifegoo.com'
9
+ p.summary = 'Google translate ruby client api'
10
+ p.description = 'A simple, unofficial, ruby client API for using Google Translate.'
11
+ p.extra_deps = [['hpricot', '>= 0.4'], ['json', '>= 1.1.3']]
12
+ end
@@ -0,0 +1,37 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ $:.unshift(File::join(File::dirname(File::dirname(__FILE__)), "lib"))
4
+
5
+ require 'rtranslate'
6
+ require 'optparse'
7
+
8
+ options = {}
9
+ opts = OptionParser.new do |opts|
10
+ opts.banner = <<-EOF
11
+ Usage:
12
+ rtranslate -f lang -t lang text
13
+ EOF
14
+
15
+ opts.on("-fLANG", "--from LANG", "From Language LANG") do |x|
16
+ options[:from] = x
17
+ end
18
+
19
+ opts.on("-tLANG", "--to LANG", "To Language LANG") do |x|
20
+ options[:to] = x
21
+ end
22
+
23
+ opts.on("-h", "--help", "Show this message") do
24
+ puts opts
25
+ exit
26
+ end
27
+ end
28
+
29
+ opts.parse!(ARGV)
30
+ text = ARGV.shift
31
+
32
+ if options[:from].nil? || options[:to].nil? || text.empty?
33
+ puts opts
34
+ exit
35
+ end
36
+
37
+ STDOUT.puts(Translate.t(text, options[:from], options[:to]))
@@ -0,0 +1,23 @@
1
+ require File.join(File.dirname(__FILE__), 'rtranslate/language')
2
+ require File.join(File.dirname(__FILE__), 'rtranslate/rtranslate')
3
+ require 'uri'
4
+ require 'open-uri'
5
+
6
+ begin
7
+ require 'hpricot'
8
+ rescue LoadError
9
+ require 'rubygems'
10
+ require 'hpricot'
11
+ end
12
+
13
+ $KCODE = 'u'
14
+
15
+ include Translate
16
+ def Translate.t(text, from, to)
17
+ begin
18
+ RTranslate.translate(text, from, to)
19
+ rescue
20
+ "Error: " + $!
21
+ end
22
+ end
23
+
@@ -0,0 +1,145 @@
1
+ module Google
2
+ module Language
3
+ Languages = {
4
+ 'af' => 'AFRIKAANS',
5
+ 'sq' => 'ALBANIAN',
6
+ 'am' => 'AMHARIC',
7
+ 'ar' => 'ARABIC',
8
+ 'hy' => 'ARMENIAN',
9
+ 'az' => 'AZERBAIJANI',
10
+
11
+ 'eu' => 'BASQUE',
12
+ 'be' => 'BELARUSIAN',
13
+ 'bn' => 'BENGALI',
14
+ 'bh' => 'BIHARI',
15
+ 'bg' => 'BULGARIAN',
16
+ 'my' => 'BURMESE',
17
+
18
+ 'ca' => 'CATALAN',
19
+ 'chr' => 'CHEROKEE',
20
+ 'zh' => 'CHINESE',
21
+ 'zh-CN' => 'CHINESE_SIMPLIFIED',
22
+ 'zh-TW' => 'CHINESE_TRADITIONAL',
23
+ 'hr' => 'CROATIAN',
24
+ 'cs' => 'CZECH',
25
+
26
+ 'da' => 'DANISH',
27
+ 'dv' => 'DHIVEHI',
28
+ 'nl' => 'DUTCH',
29
+
30
+ 'en' => 'ENGLISH',
31
+ 'eo' => 'ESPERANTO',
32
+ 'et' => 'ESTONIAN',
33
+
34
+ 'tl' => 'FILIPINO',
35
+ 'fi' => 'FINNISH',
36
+ 'fr' => 'FRENCH',
37
+
38
+ 'gl' => 'GALICIAN',
39
+ 'ka' => 'GEORGIAN',
40
+ 'de' => 'GERMAN',
41
+ 'el' => 'GREEK',
42
+ 'gn' => 'GUARANI',
43
+ 'gu' => 'GUJARATI',
44
+
45
+ 'iw' => 'HEBREW',
46
+ 'hi' => 'HINDI',
47
+ 'hu' => 'HUNGARIAN',
48
+
49
+ 'is' => 'ICELANDIC',
50
+ 'id' => 'INDONESIAN',
51
+ 'iu' => 'INUKTITUT',
52
+ 'it' => 'ITALIAN',
53
+
54
+ 'ja' => 'JAPANESE',
55
+
56
+ 'kn' => 'KANNADA',
57
+ 'kk' => 'KAZAKH',
58
+ 'km' => 'KHMER',
59
+ 'ko' => 'KOREAN',
60
+ 'ku' => 'KURDISH',
61
+ 'ky' => 'KYRGYZ',
62
+
63
+ 'lo' => 'LAOTHIAN',
64
+ 'lv' => 'LATVIAN',
65
+ 'lt' => 'LITHUANIAN',
66
+
67
+ 'mk' => 'MACEDONIAN',
68
+ 'ms' => 'MALAY',
69
+ 'ml' => 'MALAYALAM',
70
+ 'mt' => 'MALTESE',
71
+ 'mr' => 'MARATHI',
72
+ 'mn' => 'MONGOLIAN',
73
+
74
+ 'ne' => 'NEPALI',
75
+ 'no' => 'NORWEGIAN',
76
+
77
+ 'or' => 'ORIYA',
78
+
79
+ 'ps' => 'PASHTO',
80
+ 'fa' => 'PERSIAN',
81
+ 'pl' => 'POLISH',
82
+ 'pt-PT' => 'PORTUGUESE',
83
+ 'pa' => 'PUNJABI',
84
+
85
+ 'ro' => 'ROMANIAN',
86
+ 'ru' => 'RUSSIAN',
87
+
88
+ 'sa' => 'SANSKRIT',
89
+ 'sr' => 'SERBIAN',
90
+ 'sd' => 'SINDHI',
91
+ 'si' => 'SINHALESE',
92
+ 'sk' => 'SLOVAK',
93
+ 'sl' => 'SLOVENIAN',
94
+ 'es' => 'SPANISH',
95
+ 'sw' => 'SWAHILI',
96
+ 'sv' => 'SWEDISH',
97
+
98
+ 'tg' => 'TAJIK',
99
+ 'ta' => 'TAMIL',
100
+ 'tl' => 'TAGALOG',
101
+ 'te' => 'TELUGU',
102
+ 'th' => 'THAI',
103
+ 'bo' => 'TIBETAN',
104
+ 'tr' => 'TURKISH',
105
+
106
+ 'uk' => 'UKRAINIAN',
107
+ 'ur' => 'URDU',
108
+ 'uz' => 'UZBEK',
109
+ 'ug' => 'UIGHUR',
110
+
111
+ 'vi' => 'VIETNAMESE',
112
+
113
+ '' => 'UNKNOWN'
114
+ }
115
+
116
+ # judge whether the language is supported by google translate
117
+ def supported?(language)
118
+ if Languages.key?(language) || Languages.value?(language.upcase)
119
+ true
120
+ else
121
+ false
122
+ end
123
+ end
124
+ module_function :supported?
125
+
126
+ # get the abbrev of the language
127
+ def abbrev(language)
128
+ if supported?(language)
129
+ if Languages.key?(language)
130
+ language
131
+ else
132
+ language.upcase!
133
+ Languages.each do |k,v|
134
+ if v == language
135
+ return k
136
+ end
137
+ end
138
+ end
139
+ else
140
+ nil
141
+ end
142
+ end
143
+ module_function :abbrev
144
+ end
145
+ end
@@ -0,0 +1,137 @@
1
+ # The program is a simple, unofficial, ruby client API
2
+ # for using Google Translate.
3
+ #
4
+ # Author:: Dingding Ye (mailto:yedingding@gmail.com)
5
+ # Copyright:: Copyright (c) 2007 Dingding Ye
6
+ # License:: Distributes under MIT License
7
+
8
+ begin
9
+ require 'json'
10
+ rescue LoadError
11
+ require 'rubygems'
12
+ require 'json'
13
+ end
14
+
15
+ module Translate
16
+ class UnsupportedLanguagePair < StandardError
17
+ end
18
+
19
+ class RTranslate
20
+ # Google AJAX Language REST Service URL
21
+ GOOGLE_TRANSLATE_URL = "http://ajax.googleapis.com/ajax/services/language/translate"
22
+
23
+ # Default version of Google AJAX Language API
24
+ DEFAULT_VERSION = "1.0"
25
+
26
+ attr_reader :version, :key
27
+ attr_reader :default_from, :default_to
28
+
29
+ class << self
30
+ def translate(text, from, to)
31
+ RTranslate.new.translate(text, { :from => from, :to => to })
32
+ end
33
+
34
+ def translate_strings(text_array, from, to)
35
+ RTranslate.new.translate_strings(text_array, {:from => from, :to => to})
36
+ end
37
+
38
+ def translate_string_to_languages(text, options)
39
+ RTranslate.new.translate_string_to_languages(text, options)
40
+ end
41
+
42
+ def batch_translate(translate_options)
43
+ RTranslate.new.batch_translate(translate_options)
44
+ end
45
+
46
+ alias_method :t, :translate
47
+ end
48
+
49
+ def initialize(version = DEFAULT_VERSION, key = nil, default_from = nil, default_to = nil)
50
+ @version = version
51
+ @key = key
52
+ @default_from = default_from
53
+ @default_to = default_to
54
+
55
+ if @default_from && !(Google::Lanauage.supported?(@default_from))
56
+ raise StandardError, "Unsupported source language '#{@default_from}'"
57
+ end
58
+
59
+ if @default_to && !(Google::Lanauage.supported?(@default_to))
60
+ raise StandardError, "Unsupported destination language '#{@default_to}'"
61
+ end
62
+ end
63
+
64
+ # translate the string from a source language to a target language.
65
+ #
66
+ # Configuration options:
67
+ # * <tt>:from</tt> - The source language
68
+ # * <tt>:to</tt> - The target language
69
+ def translate(text, options = { })
70
+ from = options[:from] || @default_from
71
+ to = options[:to] || @default_to
72
+ if Google::Language.supported?(from) && Google::Language.supported?(to)
73
+ from = Google::Language.abbrev(from)
74
+ to = Google::Language.abbrev(to)
75
+ langpair = "#{from}|#{to}"
76
+ url = "#{GOOGLE_TRANSLATE_URL}?q=#{text}&langpair=#{langpair}&v=#{@version}"
77
+ if @key
78
+ url << "&key=#{@key}"
79
+ end
80
+ do_translate(url)
81
+ else
82
+ raise UnsupportedLanguagePair, "Translation from '#{from}' to '#{to}' isn't supported yet!"
83
+ end
84
+ end
85
+
86
+ # translate several strings, all from the same source language to the same target language.
87
+ #
88
+ # Configuration options
89
+ # * <tt>:from</tt> - The source language
90
+ # * <tt>:to</tt> - The target language
91
+ def translate_strings(text_array, options = { })
92
+ text_array.collect do |text|
93
+ self.translate(text, options)
94
+ end
95
+ end
96
+
97
+ # Translate one string into several languages.
98
+ #
99
+ # Configuration options
100
+ # * <tt>:from</tt> - The source language
101
+ # * <tt>:to</tt> - The target language list
102
+ # Example:
103
+ #
104
+ # translate_string_to_languages("China", {:from => "en", :to => ["zh-CN", "zh-TW"]})
105
+ def translate_string_to_languages(text, option)
106
+ option[:to].collect do |to|
107
+ self.translate(text, { :from => option[:from], :to => to })
108
+ end
109
+ end
110
+
111
+ # Translate several strings, each into a different language.
112
+ #
113
+ # Examples:
114
+ #
115
+ # batch_translate([["China", {:from => "en", :to => "zh-CN"}], ["Chinese", {:from => "en", :to => "zh-CN"}]])
116
+ def batch_translate(translate_options)
117
+ translate_options.collect do |text, option|
118
+ self.translate(text, option)
119
+ end
120
+ end
121
+
122
+ private
123
+ def do_translate(url) #:nodoc:
124
+ begin
125
+ jsondoc = open(URI.escape(url)).read
126
+ response = JSON.parse(jsondoc)
127
+ if response["responseStatus"] == 200
128
+ response["responseData"]["translatedText"]
129
+ else
130
+ raise StandardError, response["responseDetails"]
131
+ end
132
+ rescue Exception => e
133
+ raise StandardError, e.message
134
+ end
135
+ end
136
+ end
137
+ end
@@ -0,0 +1,39 @@
1
+ Gem::Specification.new do |s|
2
+ s.name = %q{rtranslate}
3
+ s.version = "1.0"
4
+
5
+ s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
6
+ s.authors = ["Ye Dingding"]
7
+ s.date = %q{2008-12-15}
8
+ s.description = %q{rtranslate is a simple, unofficial, ruby client API for using Google Translate.}
9
+ s.email = %q{yedingding@gmail.com}
10
+ s.extra_rdoc_files = ["History.txt", "Manifest.txt", "README.txt"]
11
+ s.files = ["History.txt", "MIT-LICENSE", "Manifest.txt", "README.txt", "Rakefile", "rtranslate.gemspec", "bin/rtranslate",
12
+ "lib/rtranslate.rb", "lib/rtranslate/language.rb", "lib/rtranslate/rtranslate.rb", "tests/ts_translate.rb",
13
+ "bin/rtranslate", "lib/rtranslate.rb", "lib/rtranslate/language.rb", "lib/rtranslate/rtranslate.rb"]
14
+ s.has_rdoc = true
15
+ s.homepage = %q{http://sishen.lifegoo.com}
16
+ s.rdoc_options = ["--main", "README.txt"]
17
+ s.require_paths = ["lib"]
18
+ s.rubygems_version = %q{1.2.0}
19
+ s.summary = %q{a simple, unofficial, ruby client API for using Google Translate}
20
+
21
+ if s.respond_to? :specification_version then
22
+ current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION
23
+ s.specification_version = 2
24
+
25
+ if current_version >= 3 then
26
+ s.add_development_dependency(%q<hoe>, [">= 1.7.0"])
27
+ s.add_development_dependency(%q<rspec>, [">= 1.1.4"])
28
+ s.add_development_dependency(%q<json>, [">= 1.1.3"])
29
+ else
30
+ s.add_dependency(%q<hoe>, [">= 1.7.0"])
31
+ s.add_dependency(%q<rspec>, [">= 1.1.4"])
32
+ s.add_dependency(%q<json>, [">= 1.1.3"])
33
+ end
34
+ else
35
+ s.add_dependency(%q<hoe>, [">= 1.7.0"])
36
+ s.add_dependency(%q<rspec>, [">= 1.1.4"])
37
+ s.add_dependency(%q<json>, [">= 1.1.3"])
38
+ end
39
+ end
@@ -0,0 +1,45 @@
1
+ # -*- coding: utf-8 -*-
2
+ $:.unshift File.expand_path(File.dirname(__FILE__) + "/../lib")
3
+
4
+ require 'test/unit'
5
+ require 'rtranslate'
6
+
7
+ class Translate::TranslateTest < Test::Unit::TestCase
8
+ include Google::Language
9
+ def test_english_translate
10
+ assert_equal("مرحبا العالم", Translate.t("Hello world", "ENGLISH", "ARABIC"));
11
+ assert_equal("世界您好", Translate.t("Hello world", "ENGLISH", "CHINESE_SIMPLIFIED"));
12
+ assert_equal("Bonjour le monde", Translate.t("Hello world", "ENGLISH", "FRENCH"));
13
+ assert_equal("Hallo Welt", Translate.t("Hello world", "ENGLISH", "GERMAN"));
14
+ assert_equal("Ciao mondo", Translate.t("Hello world", "ENGLISH", "ITALIAN"));
15
+ assert_equal("こんにちは世界", Translate.t("Hello world", "ENGLISH", "JAPANESE"));
16
+ assert_equal("여보세요 세계", Translate.t("Hello world", "ENGLISH", "KOREAN"));
17
+ assert_equal("Olá mundo", Translate.t("Hello world", "ENGLISH", "PORTUGUESE"));
18
+ assert_equal("Привет мир", Translate.t("Hello world", "ENGLISH", "RUSSIAN"));
19
+ assert_equal("Hola mundo", Translate.t("Hello world", "ENGLISH", "SPANISH"));
20
+ end
21
+
22
+ def test_chinese_translate
23
+ assert_equal("Hello World", Translate.t("你好世界", "CHINESE", "ENGLISH"))
24
+ assert_equal("Hello World", Translate.t("你好世界", 'zh', 'en'))
25
+ end
26
+
27
+ def test_unsupported_translate
28
+ assert_raise UnsupportedLanguagePair do
29
+ Translate::RTranslate.t("你好世界", 'zh', 'hz')
30
+ end
31
+ end
32
+
33
+ def test_translate_strings
34
+ assert_equal(["喂", "世界"], Translate::RTranslate.translate_strings(["Hello", "World"], "en", "zh-CN"))
35
+ end
36
+
37
+ def test_translate_string_to_languages
38
+ assert_equal(["世界您好", "ハローワールド"], Translate::RTranslate.translate_string_to_languages("Hello World", {:from => "en", :to => ["zh-CN", "ja"]}))
39
+ end
40
+
41
+ def test_batch_translate
42
+ assert_equal(["世界您好", "ハローワールド"],
43
+ Translate::RTranslate.batch_translate([["Hello World", {:from => "en", :to => "zh-CN"}], ["Hello World", {:from => "en", :to => "ja"}]]))
44
+ end
45
+ end
metadata ADDED
@@ -0,0 +1,92 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: sishen-rtranslate
3
+ version: !ruby/object:Gem::Version
4
+ version: "1.0"
5
+ platform: ruby
6
+ authors:
7
+ - Ye Dingding
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+
12
+ date: 2008-12-15 00:00:00 -08:00
13
+ default_executable:
14
+ dependencies:
15
+ - !ruby/object:Gem::Dependency
16
+ name: hoe
17
+ version_requirement:
18
+ version_requirements: !ruby/object:Gem::Requirement
19
+ requirements:
20
+ - - ">="
21
+ - !ruby/object:Gem::Version
22
+ version: 1.7.0
23
+ version:
24
+ - !ruby/object:Gem::Dependency
25
+ name: rspec
26
+ version_requirement:
27
+ version_requirements: !ruby/object:Gem::Requirement
28
+ requirements:
29
+ - - ">="
30
+ - !ruby/object:Gem::Version
31
+ version: 1.1.4
32
+ version:
33
+ - !ruby/object:Gem::Dependency
34
+ name: json
35
+ version_requirement:
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: 1.1.3
41
+ version:
42
+ description: rtranslate is a simple, unofficial, ruby client API for using Google Translate.
43
+ email: yedingding@gmail.com
44
+ executables: []
45
+
46
+ extensions: []
47
+
48
+ extra_rdoc_files:
49
+ - History.txt
50
+ - Manifest.txt
51
+ - README.txt
52
+ files:
53
+ - History.txt
54
+ - MIT-LICENSE
55
+ - Manifest.txt
56
+ - README.txt
57
+ - Rakefile
58
+ - rtranslate.gemspec
59
+ - bin/rtranslate
60
+ - lib/rtranslate.rb
61
+ - lib/rtranslate/language.rb
62
+ - lib/rtranslate/rtranslate.rb
63
+ - tests/ts_translate.rb
64
+ has_rdoc: true
65
+ homepage: http://sishen.lifegoo.com
66
+ post_install_message:
67
+ rdoc_options:
68
+ - --main
69
+ - README.txt
70
+ require_paths:
71
+ - lib
72
+ required_ruby_version: !ruby/object:Gem::Requirement
73
+ requirements:
74
+ - - ">="
75
+ - !ruby/object:Gem::Version
76
+ version: "0"
77
+ version:
78
+ required_rubygems_version: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - ">="
81
+ - !ruby/object:Gem::Version
82
+ version: "0"
83
+ version:
84
+ requirements: []
85
+
86
+ rubyforge_project:
87
+ rubygems_version: 1.2.0
88
+ signing_key:
89
+ specification_version: 2
90
+ summary: a simple, unofficial, ruby client API for using Google Translate
91
+ test_files: []
92
+