DEV Community

Cover image for How I Built a Smart Translation App Using Azure AI (And You Can Too)
Olalekan Oladiran
Olalekan Oladiran

Posted on

How I Built a Smart Translation App Using Azure AI (And You Can Too)

Introduction

Azure AI Translator is a service that enables you to translate text between languages. In this exercise, you’ll use it to create a simple app that translates input in any supported language to the target language of your choice.

Provision an Azure AI Translator resource

  • Go to your Azure portal and click create a resource
  • In the search field at the top, search for Translators then select Translators in the results.
  • Create a resource with the following settings:
    • Subscription: Your Azure subscription
    • Resource group: Choose or create a resource group
    • Region: Choose any available region
    • Name: Enter a unique name
    • Pricing tier: Select F0 (free), or S (standard) if F is not available.
  • Select Review + create, then select Create to provision the resource.
  • Wait for deployment to complete, and then go to the deployed resource.
  • View the Keys and Endpoint page. You will need the information on this page later in the exercise.

Prepare to develop an app in Cloud Shell

  • Enter the following commands to clone the GitHub repo for this exercise: git clone https://github.com/microsoftlearning/mslearn-ai-language mslearn-ai-language

  • After the repo has been cloned, navigate to the folder containing the application code files: cd mslearn-ai-language/Labfiles/06-translator-sdk

Configure your application

Applications for both C# and Python have been provided, as well as a sample text file you’ll use to test the summarization. Both apps feature the same functionality. We will be using C# for this project. First, you’ll complete some key parts of the application to enable it to use your Azure AI Translator resource.

  • Run the command cd C-Sharp/translate-text or on your language preference. Each folder contains the language-specific code files for an app into which you’re you’re going to integrate Azure AI Translator functionality.
  • Install the Azure AI Translator SDK package by running the appropriate command for your language preference: dotnet add package Azure.AI.Translation.Text --version 1.0.0

  • Edit the appsettings.json by expanding translate-text.
  • Update the configuration values to include the region and a key from the Azure AI Translator resource you created (available on the Keys and Endpoint page for your Azure AI Translator resource in the Azure portal).
  • After you’ve replaced the placeholders, within the code editor, use the CTRL+S command or Right-click > Save to save your changes.

Add code to translate text

Now you’re ready to use Azure AI Translator to translate text.

  • Open Programs.cs file and at the top, under the existing namespace references, find the comment Import namespaces. Then, under this comment, add the following language-specific code to import the namespaces you will need to use the Text Analytics SDK:
 // import namespaces
 using Azure;
 using Azure.AI.Translation.Text;
Enter fullscreen mode Exit fullscreen mode

  • Find the comment Create client using endpoint and key and add the following code:
 // Create client using endpoint and key
 AzureKeyCredential credential = new(translatorKey);
 TextTranslationClient client = new(credential, translatorRegion);
Enter fullscreen mode Exit fullscreen mode

  • Find the comment Choose target language and add the following code, which uses the Text Translator service to return list of supported languages for translation, and prompts the user to select a language code for the target language.
 // Choose target language
 Response<GetSupportedLanguagesResult> languagesResponse = await client.GetSupportedLanguagesAsync(scope:"translation").ConfigureAwait(false);
 GetSupportedLanguagesResult languages = languagesResponse.Value;
 Console.WriteLine($"{languages.Translation.Count} languages available.\n(See https://learn.microsoft.com/azure/ai-services/translator/language-support#translation)");
 Console.WriteLine("Enter a target language code for translation (for example, 'en'):");
 string targetLanguage = "xx";
 bool languageSupported = false;
 while (!languageSupported)
 {
     targetLanguage = Console.ReadLine();
     if (languages.Translation.ContainsKey(targetLanguage))
     {
         languageSupported = true;
     }
     else
     {
         Console.WriteLine($"{targetLanguage} is not a supported language.");
     }

 }
Enter fullscreen mode Exit fullscreen mode

  • Find the comment Translate text and add the following code, which repeatedly prompts the user for text to be translated, uses the Azure AI Translator service to translate it to the target language (detecting the source language automatically), and displays the results until the user enters quit.
 // Translate text
 string inputText = "";
 while (inputText.ToLower() != "quit")
 {
     Console.WriteLine("Enter text to translate ('quit' to exit)");
     inputText = Console.ReadLine();
     if (inputText.ToLower() != "quit")
     {
         Response<IReadOnlyList<TranslatedTextItem>> translationResponse = await client.TranslateAsync(targetLanguage, inputText).ConfigureAwait(false);
         IReadOnlyList<TranslatedTextItem> translations = translationResponse.Value;
         TranslatedTextItem translation = translations[0];
         string sourceLanguage = translation?.DetectedLanguage?.Language;
         Console.WriteLine($"'{inputText}' translated from {sourceLanguage} to {translation?.Translations[0].TargetLanguage} as '{translation?.Translations?[0]?.Text}'.");
     }
 } 
Enter fullscreen mode Exit fullscreen mode

  • Save the changes to your code file and close the code editor.

Test your application

Now your application is ready to test.

  • Enter the following command to run the program (you maximize the console panel to see more text):

    dotnet run

  • When prompted, enter a valid target language from the list displayed e.g. en for English

  • Enter a phrase to be translated (for example This is a test or C'est un test) and view the results, which should detect the source language and translate the text to the target language.
    When you’re done, enter quit. You can run the application again and choose a different target language.

You've just unlocked the power of Azure AI Translator – transforming any text into multiple languages with just a few lines of code. Whether you're building multilingual apps, global customer support, or breaking down language barriers in your projects, this technology opens doors to truly borderless communication.

Thanks for staying till the end

Top comments (0)