Class: Translations::AwsTranslateService

Inherits:
Object
  • Object
show all
Includes:
AwsTranslationHelper, ElasticAPM::SpanHelpers
Defined in:
app/services/translations/aws_translate_service.rb

Overview

Service wrapper around AWS Translate for batch translating Restaurant fields. Uses conservative retry logic and instrumentation. Compatible with Ruby 2.7 / Rails 5.1.

Constant Summary collapse

BATCH_SIZE =

Keep small to respect AWS Translate limits

20
SUPPORTED_SOURCE =
'en'
AWS_LANGUAGE_CODES =

Map internal locale symbols to AWS Translate language codes

{
  en: 'en', th: 'th', cn: 'zh-TW', zh: 'zh', es: 'es', fr: 'fr', de: 'de', ru: 'ru', ms: 'ms', ko: 'ko', ja: 'ja', id: 'id', vi: 'vi'
}.freeze
RETRY_ERRORS =
[Aws::Translate::Errors::ThrottlingException,
Aws::Translate::Errors::ServiceUnavailableException,
Seahorse::Client::NetworkingError].freeze

Instance Method Summary collapse

Methods included from AwsTranslationHelper

#aws_translate_client

Instance Method Details

#translate_texts(texts, target_locale) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'app/services/translations/aws_translate_service.rb', line 23

def translate_texts(texts, target_locale)
  return {} if texts.blank?

  target_code = AWS_LANGUAGE_CODES[target_locale.to_sym]
  return {} if target_code.blank? || target_code == SUPPORTED_SOURCE

  client = aws_translate_client
  results = {}

  texts.each_slice(BATCH_SIZE) do |slice|
    slice.each do |key, value|
      next if value.blank?

      translated = with_retries { translate_one(client, value.to_s, target_code) }
      translated = value.to_s if translated.blank? # fallback to original to avoid empty cell
      results[key] = translated
    end
  end
  # Ensure every input key has at least original text (in case of global failure returning empty hash)
  if results.empty? || (results.keys.to_set != texts.keys.to_set)
    texts.each do |k, v|
      results[k] ||= v.to_s
    end
  end
  if defined?(BUSINESS_LOGGER)
    BUSINESS_LOGGER.info('aws_translate_batch_summary', {
                           target_locale: target_locale,
                           requested: texts.size,
                           returned: results.size,
                         })
  end
  results
rescue StandardError => e
  APMErrorHandler.report(e, context: { service: 'AwsTranslate', target_locale: target_locale })
  # Catastrophic failure: return original text map so export never blank
  texts.map { |k, v| [k, v.to_s] }.to_h
end