libre_translate.rb 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. # frozen_string_literal: true
  2. class TranslationService::LibreTranslate < TranslationService
  3. def initialize(base_url, api_key)
  4. super()
  5. @base_url = base_url
  6. @api_key = api_key
  7. end
  8. def translate(text, source_language, target_language)
  9. request(text, source_language, target_language).perform do |res|
  10. case res.code
  11. when 429
  12. raise TooManyRequestsError
  13. when 403
  14. raise QuotaExceededError
  15. when 200...300
  16. transform_response(res.body_with_limit, source_language)
  17. else
  18. raise UnexpectedResponseError
  19. end
  20. end
  21. end
  22. private
  23. def request(text, source_language, target_language)
  24. body = Oj.dump(q: text, source: source_language.presence || 'auto', target: target_language, format: 'html', api_key: @api_key)
  25. req = Request.new(:post, "#{@base_url}/translate", body: body, allow_local: true)
  26. req.add_headers('Content-Type': 'application/json')
  27. req
  28. end
  29. def transform_response(str, source_language)
  30. json = Oj.load(str, mode: :strict)
  31. raise UnexpectedResponseError unless json.is_a?(Hash)
  32. Translation.new(text: json['translatedText'], detected_source_language: source_language, provider: 'LibreTranslate')
  33. rescue Oj::ParseError
  34. raise UnexpectedResponseError
  35. end
  36. end