deepl.rb 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. # frozen_string_literal: true
  2. class TranslationService::DeepL < TranslationService
  3. include JsonLdHelper
  4. def initialize(plan, api_key)
  5. super()
  6. @plan = plan
  7. @api_key = api_key
  8. end
  9. def translate(text, source_language, target_language)
  10. request(text, source_language, target_language).perform do |res|
  11. case res.code
  12. when 429
  13. raise TooManyRequestsError
  14. when 456
  15. raise QuotaExceededError
  16. when 200...300
  17. transform_response(res.body_with_limit)
  18. else
  19. raise UnexpectedResponseError
  20. end
  21. end
  22. end
  23. private
  24. def request(text, source_language, target_language)
  25. req = Request.new(:post, endpoint_url, form: { text: text, source_lang: source_language&.upcase, target_lang: target_language, tag_handling: 'html' })
  26. req.add_headers('Authorization': "DeepL-Auth-Key #{@api_key}")
  27. req
  28. end
  29. def endpoint_url
  30. if @plan == 'free'
  31. 'https://api-free.deepl.com/v2/translate'
  32. else
  33. 'https://api.deepl.com/v2/translate'
  34. end
  35. end
  36. def transform_response(str)
  37. json = Oj.load(str, mode: :strict)
  38. raise UnexpectedResponseError unless json.is_a?(Hash)
  39. Translation.new(text: json.dig('translations', 0, 'text'), detected_source_language: json.dig('translations', 0, 'detected_source_language')&.downcase, provider: 'DeepL.com')
  40. rescue Oj::ParseError
  41. raise UnexpectedResponseError
  42. end
  43. end