Class: BingTranslator
- Inherits:
-
Object
show all
- Defined in:
- lib/bing_translator.rb
Defined Under Namespace
Classes: ApiClient, ApiException, AuthenticationException, Exception, UnavailableException, UsageException
Instance Method Summary
collapse
Constructor Details
#initialize(subscription_key, options = {}) ⇒ BingTranslator
Returns a new instance of BingTranslator.
107
108
109
110
111
112
|
# File 'lib/bing_translator.rb', line 107
def initialize(subscription_key, options = {})
skip_ssl_verify = options.fetch(:skip_ssl_verify, false)
read_timeout = options.fetch(:read_timeout, 60)
open_timeout = options.fetch(:open_timeout, 60)
@api_client = ApiClient.new(subscription_key, skip_ssl_verify, read_timeout, open_timeout)
end
|
Instance Method Details
#detect(text) ⇒ Object
132
133
134
135
136
137
138
|
# File 'lib/bing_translator.rb', line 132
def detect(text)
data = [{ 'Text' => text }].to_json
response_json = api_client.post('/detect', data: data)
best_detection = response_json.sort_by { |detection| -detection['score'] }.first
best_detection['language'].to_sym
end
|
#language_names(codes, locale = 'en') ⇒ Object
151
152
153
154
155
156
157
158
159
160
|
# File 'lib/bing_translator.rb', line 151
def language_names(codes, locale = 'en')
response_json = api_client.get('/languages',
params: { scope: 'translation' },
headers: { 'Accept-Language' => locale },
authorization: false)
codes.map do |code|
response = response_json['translation'][code.to_s]
response['name'] unless response.nil?
end
end
|
#speak(text, params = {}) ⇒ Object
140
141
142
|
# File 'lib/bing_translator.rb', line 140
def speak(text, params = {})
raise UsageException.new('Not supported since 3.0.0')
end
|
#supported_language_codes ⇒ Object
144
145
146
147
148
149
|
# File 'lib/bing_translator.rb', line 144
def supported_language_codes
response_json = api_client.get('/languages',
params: { scope: 'translation' },
authorization: false)
response_json['translation'].keys
end
|
#translate(text, params) ⇒ Object
114
115
116
|
# File 'lib/bing_translator.rb', line 114
def translate(text, params)
translate_array([text], params).first
end
|
#translate_array(texts, params = {}) ⇒ Object
118
119
120
121
122
123
|
# File 'lib/bing_translator.rb', line 118
def translate_array(texts, params = {})
translations = translation_request(texts, params)
translations.map do |translation|
translation['text'] if translation.is_a?(Hash)
end
end
|
#translate_array2(texts, params = {}) ⇒ Object
125
126
127
128
129
130
|
# File 'lib/bing_translator.rb', line 125
def translate_array2(texts, params = {})
translations = translation_request(texts, params.merge('includeAlignment' => true))
translations.map do |translation|
[translation['text'], translation['alignment']['proj']] if translation.is_a?(Hash)
end
end
|