2022-09-23 21:00:12 +00:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
class TranslationService::LibreTranslate < TranslationService
|
|
|
|
def initialize(base_url, api_key)
|
|
|
|
super()
|
|
|
|
|
|
|
|
@base_url = base_url
|
|
|
|
@api_key = api_key
|
|
|
|
end
|
|
|
|
|
2023-05-31 22:10:21 +00:00
|
|
|
def translate(texts, source_language, target_language)
|
|
|
|
body = Oj.dump(q: texts, source: source_language.presence || 'auto', target: target_language, format: 'html', api_key: @api_key)
|
2023-03-03 20:06:31 +00:00
|
|
|
request(:post, '/translate', body: body) do |res|
|
|
|
|
transform_response(res.body_with_limit, source_language)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def languages
|
2023-03-16 10:07:24 +00:00
|
|
|
request(:get, '/languages') do |res|
|
|
|
|
languages = Oj.load(res.body_with_limit).to_h do |language|
|
|
|
|
[language['code'], language['targets'].without(language['code'])]
|
2023-03-03 20:06:31 +00:00
|
|
|
end
|
2023-03-16 10:07:24 +00:00
|
|
|
languages[nil] = languages.values.flatten.uniq.sort
|
|
|
|
languages
|
2023-03-03 20:06:31 +00:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2023-03-16 10:07:24 +00:00
|
|
|
private
|
|
|
|
|
2023-03-03 20:06:31 +00:00
|
|
|
def request(verb, path, **options)
|
|
|
|
req = Request.new(verb, "#{@base_url}#{path}", allow_local: true, **options)
|
|
|
|
req.add_headers('Content-Type': 'application/json')
|
|
|
|
req.perform do |res|
|
2022-09-23 21:00:12 +00:00
|
|
|
case res.code
|
|
|
|
when 429
|
|
|
|
raise TooManyRequestsError
|
|
|
|
when 403
|
|
|
|
raise QuotaExceededError
|
|
|
|
when 200...300
|
2023-03-03 20:06:31 +00:00
|
|
|
yield res
|
2022-09-23 21:00:12 +00:00
|
|
|
else
|
|
|
|
raise UnexpectedResponseError
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2023-05-31 22:10:21 +00:00
|
|
|
def transform_response(json, source_language)
|
|
|
|
data = Oj.load(json, mode: :strict)
|
|
|
|
raise UnexpectedResponseError unless data.is_a?(Hash)
|
2022-09-23 21:00:12 +00:00
|
|
|
|
2023-05-31 22:10:21 +00:00
|
|
|
data['translatedText'].map.with_index do |text, index|
|
|
|
|
Translation.new(
|
|
|
|
text: text,
|
|
|
|
detected_source_language: data.dig('detectedLanguage', index, 'language') || source_language,
|
|
|
|
provider: 'LibreTranslate'
|
|
|
|
)
|
|
|
|
end
|
2022-09-23 21:00:12 +00:00
|
|
|
rescue Oj::ParseError
|
|
|
|
raise UnexpectedResponseError
|
|
|
|
end
|
|
|
|
end
|