class Translatomatic::Provider::Google

Interface to the Google translation API @see cloud.google.com/translate/

Constants

BASE_URL
LANGUAGES_URL
LIMIT

cloud.google.com/translate/faq TODO: limit requested characters per second?

TRANSLATE_URL

Public Class Methods

new(options = {}) click to toggle source

Create a new Google provider instance

Calls superclass method Translatomatic::Provider::Base::new
# File lib/translatomatic/provider/google.rb, line 18
def initialize(options = {})
  super(options)
  @key = options[:google_api_key] || ENV['GOOGLE_API_KEY']
  raise t('provider.google.key_required') if @key.nil?
  @model = options[:google_model]
end
supports_no_translate_html?() click to toggle source

(see Base.supports_no_translate_html?)

# File lib/translatomatic/provider/google.rb, line 13
def self.supports_no_translate_html?
  true
end

Public Instance Methods

languages() click to toggle source

(see Base#languages)

# File lib/translatomatic/provider/google.rb, line 26
def languages
  @languages ||= fetch_languages
end

Private Instance Methods

fetch_languages() click to toggle source
# File lib/translatomatic/provider/google.rb, line 70
def fetch_languages
  response = http_client.get(LANGUAGES_URL, key: @key)
  body = JSON.parse(response.body)
  languages = try_hash(body, 'data', 'languages') || []
  languages.collect { |i| i['language'] }
end
perform_translate(strings, from, to) click to toggle source
# File lib/translatomatic/provider/google.rb, line 39
def perform_translate(strings, from, to)
  batcher(strings, max_count: LIMIT[0], max_length: LIMIT[1])
    .each_batch do |texts|
    perform_translate_texts(texts, from, to)
  end
end
perform_translate_texts(texts, from, to) click to toggle source
# File lib/translatomatic/provider/google.rb, line 46
def perform_translate_texts(texts, from, to)
  request_body = request_body(texts, from, to)
  response = http_client.post(TRANSLATE_URL, request_body)
  body = JSON.parse(response.body)
  data = body['data'] || {}
  translations = data['translations'] || []
  translations = translations.collect { |i| i['translatedText'] }
  texts.zip(translations).each do |original, translated|
    add_translations(original, translated)
  end
end
request_body(strings, from, to) click to toggle source
# File lib/translatomatic/provider/google.rb, line 58
def request_body(strings, from, to)
  body = {
    q: strings,
    source: from.language,
    target: to.language,
    format: 'html', # required for <span translate="no"></span>
    key: @key
  }
  body[:model] = @model if @model
  body
end