Translation Comparison App
Mix.install([
{:kino, "~> 0.14.2"},
{:deepl_ex, "~> 0.4.0"},
{:google_api_translate, "~> 0.21.0"}
])
Configuration
# Configure DeepL API key - using Livebook secrets
Application.put_env(:deepl_ex, :api_key, System.fetch_env!("LB_DEEPL_API_KEY"))
# Configure Google Translate API key - using Livebook secrets
System.fetch_env!("LB_GOOGLE_API_KEY")
Translation Logic
defmodule Translator do
def translate_with_deepl(text) do
case DeeplEx.translate(text, :EN, :PL) do
{:ok, translation} -> translation
{:error, reason} -> "Error with DeepL: #{inspect(reason)}"
end
end
def translate_with_google(text) do
conn = GoogleApi.Translate.V2.Connection.new()
case GoogleApi.Translate.V2.Api.Translations.language_translations_list(conn, text, "pl", [
{:source, "en"},
{:key, System.fetch_env!("LB_GOOGLE_API_KEY")}
]) do
{:ok, translation} -> hd(translation.translations).translatedText
{:error, reason} -> "Error with Google: #{inspect(reason)}"
end
end
end
User Interface
# Create input form for the English text
form = Kino.Control.form(
[
text: Kino.Input.text("Enter English text")
],
submit: "Translate"
)
# Create frame for displaying results
result_frame = Kino.Frame.new()
form
|> Kino.Control.stream()
|> Kino.listen(fn %{data: %{text: english_text}} ->
google_translation = Translator.translate_with_google(english_text)
deepl_translation = Translator.translate_with_deepl(english_text)
content =
Kino.Layout.grid(
[
Kino.Markdown.new("""
### Original Text
#{english_text}
"""),
Kino.Markdown.new("""
### Google Translate
#{google_translation}
"""),
Kino.Markdown.new("""
### DeepL
#{deepl_translation}
""")
],
columns: 3
)
Kino.Frame.render(result_frame, content)
end)
result_frame