Microsoft Translator Added
This commit is contained in:
50
lib/translator/microsoft.ex
Normal file
50
lib/translator/microsoft.ex
Normal file
@@ -0,0 +1,50 @@
|
||||
defmodule Localizator.Translator.Microsoft 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
|
||||
|
||||
@impl true
|
||||
@spec detect(text) :: {:ok, locale} | {:error, message}
|
||||
def detect(text) when is_bitstring(text) do
|
||||
case MicrosoftTranslator.detect(text) do
|
||||
%{languageCode: locale} -> {:ok, locale}
|
||||
%{} -> {:error, "Couldn't detect language"}
|
||||
end
|
||||
end
|
||||
|
||||
@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 -> MicrosoftTranslator.translate(text, to)
|
||||
_ -> MicrosoftTranslator.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
|
||||
Reference in New Issue
Block a user