about summary refs log tree commit diff
path: root/app/lib/translation_service/libre_translate.rb
blob: 8bb194a9c2ba375c1a2626cd145a376d2066d226 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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
# frozen_string_literal: true

class TranslationService::LibreTranslate < TranslationService
  def initialize(base_url, api_key)
    super()

    @base_url = base_url
    @api_key  = api_key
  end

  def translate(text, source_language, target_language)
    body = Oj.dump(q: text, source: source_language.presence || 'auto', target: target_language, format: 'html', api_key: @api_key)
    request(:post, '/translate', body: body) do |res|
      transform_response(res.body_with_limit, source_language)
    end
  end

  def languages
    request(:get, '/languages') do |res|
      languages = Oj.load(res.body_with_limit).to_h do |language|
        [language['code'], language['targets'].without(language['code'])]
      end
      languages[nil] = languages.values.flatten.uniq.sort
      languages
    end
  end

  private

  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|
      case res.code
      when 429
        raise TooManyRequestsError
      when 403
        raise QuotaExceededError
      when 200...300
        yield res
      else
        raise UnexpectedResponseError
      end
    end
  end

  def transform_response(str, source_language)
    json = Oj.load(str, mode: :strict)

    raise UnexpectedResponseError unless json.is_a?(Hash)

    Translation.new(text: json['translatedText'], detected_source_language: source_language, provider: 'LibreTranslate')
  rescue Oj::ParseError
    raise UnexpectedResponseError
  end
end