language-translator 0.1.5 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 1dcf8eeb8ca7bdd51ece6cd887c96075f4b63f9456887b723af6f4540cf1881c
4
+ data.tar.gz: 8fff57087807702af24a22452024dd83aba24754fb0cd925b7cef3f79b671abb
5
+ SHA512:
6
+ metadata.gz: 8fbb593e9783625e2ca912db3fa66ca68c0ba927079b6efb35613dca9a9110f5df398bd3f5d1f90ec4710fbf7c98359b343e722342a9c2b959cc8552d001d347
7
+ data.tar.gz: 7c607fd9a3e7dc30085a33cc8ffbaca290f8adeaf15fae8bb7f14452204a270196571ce4ac7c6de75cffe75569cb42f2344e62bbc50cb63ef2b035a454d9fc18
data/README.rdoc CHANGED
@@ -1,23 +1,47 @@
1
- = Translator
1
+ = Translator
2
2
 
3
3
  == Description
4
- Ruby gem to translate a string from one language to another using google api.
4
+ Ruby gem to translate a string from one language to another using Google's public translate endpoint
5
+ (`https://translate.googleapis.com/translate_a/single`). The integration does **not** require an API key.
5
6
 
6
7
  == Installation
7
8
 
8
9
  gem install language-translator
9
10
 
10
- == Usage
11
+ == Usage
11
12
 
12
- require 'rubygems'
13
- require 'translator'
13
+ require 'rubygems'
14
+ require 'translator'
14
15
 
15
- #To translate 'Hello World' to Hindi
16
- tr = Translator.new()
17
- tr.translate( 'Hello, World', 'hi') #=> "नमस्ते, दुनिया"
16
+ tr = Translator.new
18
17
 
19
- #To translate "नमस्ते, दुनिया" to English
20
- tr.translate('नमस्ते, दुनिया', 'en','hi') #=> "Hello World"
18
+ # translate from English to Hindi
19
+ tr.translate('Hello, World', 'hi', 'en') #=> "नमस्ते, दुनिया"
21
20
 
22
- #From Unknown language to english, from 0.1.2
23
- tr.to_en('नमस्ते, दुनिया') #=> "Hello World"
21
+ # translate from Japanese to English
22
+ tr.translate('こんにちは世界', 'en', 'ja') #=> "Hello world"
23
+
24
+ # let Google auto-detect the source language (to English)
25
+ tr.to_en('¡Hola, mundo!') #=> "Hello world"
26
+
27
+ == Running tests
28
+
29
+ All HTTP calls are mocked via Mocha. You can run the suite without network access:
30
+
31
+ ruby -Itest test/translator_test.rb
32
+
33
+ == Trying it in IRB
34
+
35
+ To experiment interactively without installing the gem:
36
+
37
+ irb -I lib
38
+ irb(main):001:0> require 'translator'
39
+ => true
40
+ irb(main):002:0> Translator.new.translate('Hello world', 'es', 'en')
41
+ => "Hola Mundo"
42
+
43
+ == Supported languages
44
+
45
+ `Translator::SUPPORTED_LANG_CODES` tracks every language code currently available through Google Translate
46
+ (including legacy aliases like `iw` and `pt-PT`). Call `Translator::SUPPORTED_LANG_CODES.sort` if you need to
47
+ inspect or display the full list.
data/Rakefile CHANGED
@@ -2,7 +2,7 @@ require 'rubygems'
2
2
  require 'rake'
3
3
  require 'echoe'
4
4
 
5
- Echoe.new('language-translator', '0.1.2') do |p|
5
+ Echoe.new('language-translator', '0.1.5') do |p|
6
6
  p.description = "Ruby gem to translate a string from one language to another using google api."
7
7
  p.url = "http://github.com/anilyanduri/language-translator"
8
8
  p.author = "Anil Yanduri"
@@ -2,9 +2,10 @@
2
2
 
3
3
  Gem::Specification.new do |s|
4
4
  s.name = %q{language-translator}
5
- s.version = "0.1.5"
5
+ s.version = "1.0.0"
6
6
 
7
7
  s.required_rubygems_version = Gem::Requirement.new(">= 1.2") if s.respond_to? :required_rubygems_version=
8
+ s.required_ruby_version = Gem::Requirement.new(">= 2.6")
8
9
  s.authors = ["Anil Yanduri"]
9
10
  s.date = %q{2011-05-05}
10
11
  s.description = %q{Ruby gem to translate from one language to another using google api. }
@@ -14,8 +15,8 @@ Gem::Specification.new do |s|
14
15
  s.homepage = %q{http://github.com/anilyanduri/language-translator}
15
16
  s.rdoc_options = ["--line-numbers", "--inline-source", "--title", "Language-translator", "--main", "README.rdoc"]
16
17
  s.require_paths = ["lib"]
17
- s.rubyforge_project = %q{language-translator}
18
- s.rubygems_version = %q{1.3.5}
18
+ s.license = "MIT"
19
+ s.rubygems_version = %q{3.5.22}
19
20
  s.summary = %q{Ruby gem to translate from one language to another using google api.}
20
21
  s.test_files = ["test/translator_test.rb", "test/test_helper.rb"]
21
22
 
@@ -29,4 +30,3 @@ Gem::Specification.new do |s|
29
30
  else
30
31
  end
31
32
  end
32
-
data/lib/translator.rb CHANGED
@@ -1,5 +1,6 @@
1
1
  require 'net/http'
2
2
  require 'json'
3
+ require 'uri'
3
4
 
4
5
  class UnSupportedLanguage < RuntimeError
5
6
  attr :msg
@@ -10,44 +11,78 @@ end
10
11
 
11
12
  class Translator
12
13
 
13
- Site_Url = 'ajax.googleapis.com'
14
- Request_Uri = "/ajax/services/language/translate"
15
- SUPPORTED_LANG_CODES = ['sr','lt','lv','iw','cy','ga','id','de','zh-TW','es','sl','ko','it','eu','az','af','sk','pt-PT','no','gl','bg','ar','tr','fa','mk','el','da','yi','ur','uk','ro','ja','zh','sw','mt','ms','is','ka','en','hr','ca','th','ru','hy','vi','tl','sv','hu','hi','fi','sq','pl','fr','et','nl','cs','zh-CN','be']
14
+ Site_Url = 'translate.googleapis.com'
15
+ Request_Uri = "/translate_a/single"
16
+ SUPPORTED_LANG_CODES = [
17
+ 'af', 'sq', 'am', 'ar', 'hy', 'az', 'eu', 'be', 'bn', 'bs', 'bg', 'ca',
18
+ 'ceb', 'ny', 'zh-CN', 'zh-TW', 'co', 'hr', 'cs', 'da', 'nl', 'en', 'eo',
19
+ 'et', 'fil', 'fi', 'fr', 'fy', 'gl', 'ka', 'de', 'el', 'gu', 'ht', 'ha',
20
+ 'haw', 'iw', 'he', 'hi', 'hmn', 'hu', 'is', 'ig', 'id', 'ga', 'it', 'ja',
21
+ 'jw', 'kn', 'kk', 'km', 'rw', 'ko', 'ku', 'ky', 'lo', 'la', 'lv', 'lt',
22
+ 'lb', 'mk', 'mg', 'ms', 'ml', 'mt', 'mi', 'mr', 'mn', 'my', 'ne', 'no',
23
+ 'or', 'ps', 'fa', 'pl', 'pt', 'pt-PT', 'pa', 'ro', 'ru', 'sm', 'gd',
24
+ 'sr', 'st', 'sn', 'sd', 'si', 'sk', 'sl', 'so', 'es', 'su', 'sw', 'sv',
25
+ 'tg', 'ta', 'tt', 'te', 'th', 'tr', 'tk', 'uk', 'ur', 'ug', 'uz', 'vi',
26
+ 'cy', 'xh', 'yi', 'yo', 'zu'
27
+ ]
16
28
 
17
- # method to translate from one language to another
18
- def translate( text, to, from='en' )
19
-
29
+ # Public: Translate text using Google's HTTPS endpoint.
30
+ #
31
+ # text - String containing the source text.
32
+ # to - Language code for the target language (see SUPPORTED_LANG_CODES).
33
+ # from - Optional source language code. Provide an empty string to let Google auto-detect.
34
+ #
35
+ # Returns the translated String or nil if Google returns an empty result.
36
+ def translate(text, to, from='en')
20
37
  begin
21
38
  raise UnSupportedLanguage unless SUPPORTED_LANG_CODES.include?(to)
22
39
  raise UnSupportedLanguage unless SUPPORTED_LANG_CODES.include?(from) unless from.empty? # letting to translate from unknown language
23
-
24
- http = Net::HTTP.new(Site_Url, 80)
25
-
26
- request = Net::HTTP::Post.new(Request_Uri)
27
-
28
- request.set_form_data({'v'=>1.0, 'langpair'=>"#{from}|#{to}", 'q'=>"#{text}"})
29
-
30
- response = http.request(request)
31
-
32
- json_response_body = JSON.parse( response.body )
33
-
34
- if json_response_body['responseStatus'] == 200
35
- json_response_body['responseData']['translatedText']
36
- else
37
- puts json_response_body['responseDetails']
38
- raise StandardError, response['responseDetails']
39
- end
40
+
41
+ response = Net::HTTP.get_response(request_uri(text, to, from))
42
+ raise StandardError, "Translation API responded with #{response.code}" unless response.code.to_i == 200
43
+
44
+ parse_translation_response(response.body)
40
45
  rescue UnSupportedLanguage
41
46
  raise UnSupportedLanguage.new
42
47
  rescue => err_msg
43
48
  puts "#{err_msg}"
44
49
  end
45
-
46
50
  end
47
51
 
48
- # added in 0.1.2 to support from unknown to english
52
+ # Public: Convenience helper to translate from an unknown language to English.
53
+ #
54
+ # Equivalent to translate(text, "en", "") which triggers auto language detection.
49
55
  def to_en(text)
50
56
  translate( text, "en", "" )
51
57
  end
52
58
 
59
+ private
60
+
61
+ def request_uri(text, to, from)
62
+ query_params = {
63
+ 'client' => 'gtx',
64
+ 'dt' => 't',
65
+ 'sl' => from.to_s.empty? ? 'auto' : from,
66
+ 'tl' => to,
67
+ 'q' => text
68
+ }
69
+
70
+ URI::HTTPS.build(
71
+ host: Site_Url,
72
+ path: Request_Uri,
73
+ query: URI.encode_www_form(query_params)
74
+ )
75
+ end
76
+
77
+ def parse_translation_response(body)
78
+ json_response_body = JSON.parse(body)
79
+ translations = json_response_body[0]
80
+ raise StandardError, "Translation API returned unexpected payload" unless translations.is_a?(Array)
81
+
82
+ translated_text = translations.map { |segment| segment[0] }.join
83
+ translated_text.empty? ? nil : translated_text
84
+ rescue JSON::ParserError => e
85
+ raise StandardError, "Translation API returned invalid JSON: #{e.message}"
86
+ end
87
+
53
88
  end
data/test/test_helper.rb CHANGED
@@ -2,4 +2,4 @@ require 'test/unit'
2
2
  $:.unshift File.dirname(__FILE__) + '/../lib'
3
3
  require 'rubygems'
4
4
  require 'translator'
5
- require 'mocha'
5
+ require 'mocha/test_unit'
@@ -1,52 +1,61 @@
1
- require File.dirname(__FILE__) + '/test_helper'
1
+ require_relative 'test_helper'
2
2
  class TranslatorTest < Test::Unit::TestCase
3
-
4
- def test_translate_from_english_to_other
5
- tr = Translator.new()
6
- assert_equal("नमस्ते दुनिया", tr.translate("Hello world", "hi", "en"))
7
- assert_equal("Bonjour tout le monde", tr.translate("Hello world", "fr", "en"))
8
- assert_equal("Hallo Welt", tr.translate("Hello world", "de", "en"))
9
- assert_equal("Ciao a tutti", tr.translate("Hello world", "it", "en"))
10
- assert_equal("こんにちは、世界", tr.translate("Hello world", "ja", "en"))
11
- assert_equal("Dia duit domhan", tr.translate("Hello world", "ga", "en"))
12
- assert_equal("Olá mundo", tr.translate("Hello world", "pt-PT", "en"))
13
- assert_equal("Привет мир", tr.translate("Hello world", "ru", "en"))
14
- assert_equal("¡Hola, mundo", tr.translate("Hello world", "es", "en"))
15
- assert_equal("مرحبا العالم", tr.translate("Hello world", "ar", "en"))
16
- end
17
-
18
- def test_translate_from_other_to_english
19
- tr = Translator.new()
20
- assert_equal("Hello World", tr.translate("नमस्ते दुनिया", "en","hi") )
21
- assert_equal("Hello world", tr.translate("世界您好", "en", "zh-CN"))
22
- assert_equal("Hello world", tr.translate("Dia duit domhan", "en", "ga"))
23
- assert_equal("Hello world", tr.translate("こんにちは、世界", "en", "ja"))
24
- assert_equal("Hello world", tr.translate("안녕하세요 세상", "en", "ko"))
25
- assert_equal("Hello world", tr.translate("Olá mundo", "en", "pt-PT"))
26
- assert_equal("Hello world", tr.translate("Привет мир", "en", "ru"))
27
- assert_equal("Hello world", tr.translate("¡Hola, mundo", "en", "es"))
28
- assert_equal("Hello world", tr.translate("مرحبا العالم", "en", "ar"))
29
- end
30
-
3
+ def setup
4
+ @translator = Translator.new
5
+ end
6
+
7
+ def test_translate_from_english_to_other
8
+ expect_translation_request("Hello world", from: "en", to: "fr", translated_text: "Bonjour le monde")
9
+ assert_equal("Bonjour le monde", @translator.translate("Hello world", "fr", "en"))
10
+ end
11
+
31
12
  def test_translate_from_other_to_english
32
- tr = Translator.new()
33
- assert_equal("Hello World", tr.to_en("नमस्ते दुनिया"))
34
- assert_equal("Hello world", tr.to_en("世界您好"))
35
- assert_equal("Hello world", tr.to_en("Dia duit domhan"))
36
- assert_equal("Hello world", tr.to_en("こんにちは、世界"))
37
- assert_equal("Hello world", tr.to_en("안녕하세요 세상"))
38
- assert_equal("Hello world", tr.to_en("Olá mundo"))
39
- assert_equal("Hello world", tr.to_en("Привет мир"))
40
- assert_equal("Hello world", tr.to_en("¡Hola, mundo"))
41
- assert_equal("Hello world", tr.to_en("مرحبا العالم"))
42
- end
43
-
13
+ expect_translation_request("こんにちは世界", from: "ja", to: "en", translated_text: "Hello world")
14
+ assert_equal("Hello world", @translator.translate("こんにちは世界", "en", "ja"))
15
+ end
16
+
17
+ def test_translate_to_english_from_unknown_language
18
+ expect_translation_request("¡Hola, mundo!", from: "", to: "en", translated_text: "Hello world")
19
+ assert_equal("Hello world", @translator.to_en("¡Hola, mundo!"))
20
+ end
21
+
44
22
  def test_unsupported_translate
45
23
  assert_raise UnSupportedLanguage do
46
- tr = Translator.new()
47
- tr.translate("你好世界", 'zh', 'hz')
24
+ @translator.translate("你好世界", 'zh', 'hz')
48
25
  end
49
26
  end
50
-
51
- end
52
27
 
28
+ def test_api_failure_returns_nil
29
+ expect_failed_translation_request("Hello world", from: "en", to: "de")
30
+ assert_nil(@translator.translate("Hello world", "de", "en"))
31
+ end
32
+
33
+ private
34
+
35
+ def expect_translation_request(text, from:, to:, translated_text:)
36
+ response = stub(:code => '200', :body => build_google_response(text, translated_text))
37
+ Net::HTTP.expects(:get_response).with { |uri| uri_matches?(uri, text, from, to) }.returns(response)
38
+ end
39
+
40
+ def expect_failed_translation_request(text, from:, to:)
41
+ response = stub(:code => '500', :body => 'Internal Server Error')
42
+ Net::HTTP.expects(:get_response).with { |uri| uri_matches?(uri, text, from, to) }.returns(response)
43
+ end
44
+
45
+ def build_google_response(original_text, translated_text)
46
+ [[[translated_text, original_text, nil, nil, 1]]].to_json
47
+ end
48
+
49
+ def uri_matches?(uri, text, from, to)
50
+ params = URI.decode_www_form(uri.query).to_h
51
+ source_language = from.empty? ? 'auto' : from
52
+
53
+ uri.host == Translator::Site_Url &&
54
+ uri.path == Translator::Request_Uri &&
55
+ params['client'] == 'gtx' &&
56
+ params['dt'] == 't' &&
57
+ params['q'] == text &&
58
+ params['sl'] == source_language &&
59
+ params['tl'] == to
60
+ end
61
+ end
metadata CHANGED
@@ -1,34 +1,23 @@
1
- --- !ruby/object:Gem::Specification
1
+ --- !ruby/object:Gem::Specification
2
2
  name: language-translator
3
- version: !ruby/object:Gem::Version
4
- hash: 17
5
- prerelease: false
6
- segments:
7
- - 0
8
- - 1
9
- - 5
10
- version: 0.1.5
3
+ version: !ruby/object:Gem::Version
4
+ version: 1.0.0
11
5
  platform: ruby
12
- authors:
6
+ authors:
13
7
  - Anil Yanduri
14
8
  autorequire:
15
9
  bindir: bin
16
10
  cert_chain: []
17
-
18
- date: 2011-05-05 00:00:00 +05:30
19
- default_executable:
11
+ date: 2011-05-05 00:00:00.000000000 Z
20
12
  dependencies: []
21
-
22
- description: "Ruby gem to translate from one language to another using google api. "
13
+ description: 'Ruby gem to translate from one language to another using google api. '
23
14
  email: anilkumaryln@gmail.com
24
15
  executables: []
25
-
26
16
  extensions: []
27
-
28
- extra_rdoc_files:
17
+ extra_rdoc_files:
29
18
  - README.rdoc
30
19
  - lib/translator.rb
31
- files:
20
+ files:
32
21
  - MIT-LICENSE
33
22
  - Manifest
34
23
  - README.rdoc
@@ -37,46 +26,35 @@ files:
37
26
  - lib/translator.rb
38
27
  - test/test_helper.rb
39
28
  - test/translator_test.rb
40
- has_rdoc: true
41
29
  homepage: http://github.com/anilyanduri/language-translator
42
- licenses: []
43
-
30
+ licenses:
31
+ - MIT
32
+ metadata: {}
44
33
  post_install_message:
45
- rdoc_options:
46
- - --line-numbers
47
- - --inline-source
48
- - --title
34
+ rdoc_options:
35
+ - "--line-numbers"
36
+ - "--inline-source"
37
+ - "--title"
49
38
  - Language-translator
50
- - --main
39
+ - "--main"
51
40
  - README.rdoc
52
- require_paths:
41
+ require_paths:
53
42
  - lib
54
- required_ruby_version: !ruby/object:Gem::Requirement
55
- none: false
56
- requirements:
43
+ required_ruby_version: !ruby/object:Gem::Requirement
44
+ requirements:
57
45
  - - ">="
58
- - !ruby/object:Gem::Version
59
- hash: 3
60
- segments:
61
- - 0
62
- version: "0"
63
- required_rubygems_version: !ruby/object:Gem::Requirement
64
- none: false
65
- requirements:
46
+ - !ruby/object:Gem::Version
47
+ version: '2.6'
48
+ required_rubygems_version: !ruby/object:Gem::Requirement
49
+ requirements:
66
50
  - - ">="
67
- - !ruby/object:Gem::Version
68
- hash: 11
69
- segments:
70
- - 1
71
- - 2
72
- version: "1.2"
51
+ - !ruby/object:Gem::Version
52
+ version: '1.2'
73
53
  requirements: []
74
-
75
- rubyforge_project: language-translator
76
- rubygems_version: 1.3.7
54
+ rubygems_version: 3.5.22
77
55
  signing_key:
78
56
  specification_version: 3
79
57
  summary: Ruby gem to translate from one language to another using google api.
80
- test_files:
58
+ test_files:
81
59
  - test/translator_test.rb
82
60
  - test/test_helper.rb