61 lines
1.6 KiB
Elixir

defmodule Localizator.Translator.Yandex do
@type text :: String.t()
@type locale :: String.t()
@type from :: locale
@type optional_from :: from | nil
@type to :: locale
@type message :: String.t()
@behaviour Localizator.Translator.Base
alias Localizator.Commons
@impl true
@spec detect(nil) :: {:error, message}
def detect(nil), do: {:error, "Couldn't detect language"}
@impl true
@spec detect(text) :: {:ok, locale} | {:error, message}
def detect(text) when is_bitstring(text) do
case YandexTranslate.detect(text) do
%{languageCode: locale} -> {:ok, locale}
%{} -> {:error, "Couldn't detect language"}
end
end
@impl true
@spec detect(map) :: {:ok, locale} | {:error, message}
def detect(map) when is_map(map), do: detect(Commons.first_non_empty_longest_string(map))
@impl true
@spec translate(text, to, optional_from) :: {:ok, text} | {:error, message}
def translate(text, to, from \\ nil)
def translate(text, to, from) when is_bitstring(text) and is_bitstring(to) do
translator_response =
case from do
nil -> YandexTranslate.translate(text, to)
_ -> YandexTranslate.translate(text, to, from)
end
case translator_response do
%{translations: translations} ->
translations
|> List.first()
|> Map.fetch(:text)
%{message: message} ->
{:error, message}
end
end
@impl true
@spec translate(text, to, optional_from) :: text | nil
def translate!(text, to, from \\ nil) when is_bitstring(text) and is_bitstring(to) do
case translate(text, to, from) do
{:ok, result} -> result
_ -> nil
end
end
end