Class: Lit::CloudTranslation::Providers::Google

Inherits:
Base
  • Object
show all
Defined in:
lib/lit/cloud_translation/providers/google.rb

Overview

Google Cloud Translation API provider for Lit translation suggestions.

Configuration:

require 'lit/cloud_translation/providers/google'

Lit::CloudTranslation.provider = Lit::CloudTranslation::Providers::Google

# Service account configuration can be given via a file pointed to by
# ENV['GOOGLE_TRANSLATE_API_KEYFILE'] (see here:
# https://cloud.google.com/iam/docs/creating-managing-service-account-keys)
#
# Instead of providing the keyfile, credentials can be given using
# GOOGLE_TRANSLATE_API_<element> environment variables, where e.g.
# the GOOGLE_TRANSLATE_API_PROJECT_ID variable corresponds to the
# `project_id` element of your credentials. Typically, only the following
# variables are mandatory:
# * GOOGLE_TRANSLATE_API_PROJECT_ID
# * GOOGLE_TRANSLATE_API_PRIVATE_KEY_ID
# * GOOGLE_TRANSLATE_API_PRIVATE_KEY (be sure that it contains correct line breaks)
# * GOOGLE_TRANSLATE_API_CLIENT_EMAIL
# * GOOGLE_TRANSLATE_API_CLIENT_ID
#
# Alternatively, the contents of that file can be given as a Ruby hash
# and passed like the following (be careful to use secrets or something
# that prevents exposing private credentials):

Lit::CloudTranslation.configure do |config|
  config.keyfile_hash = {
    'type' => 'service_account',
    'project_id' => 'foo',
    'private_key_id' => 'keyid',
    ... # see link above for reference
  }
end

Instance Attribute Summary

Attributes inherited from Base

#config

Instance Method Summary collapse

Methods inherited from Base

configure, #initialize, translate

Constructor Details

This class inherits a constructor from Lit::CloudTranslation::Providers::Base

Instance Method Details

#translate(text:, from: nil, to:, **opts) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/lit/cloud_translation/providers/google.rb', line 47

def translate(text:, from: nil, to:, **opts)
  result = client.translate(sanitize_text(text), from: from, to: to, **opts)
  unsanitize_text(
    case result
    when translation_class then result.text
    when Array then result.map(&:text)
    end
  )
rescue Signet::AuthorizationError => e
  error_description =
    'Google credentials error: ' + # rubocop:disable Style/RescueModifier
    JSON.parse(e.response.body)['error_description'] rescue 'Unknown error'
  raise ::Lit::CloudTranslation::TranslationError, error_description,
        cause: e
rescue ::Google::Cloud::Error => e
  raise ::Lit::CloudTranslation::TranslationError, e.message, cause: e
end