Translate text and speech
Azure Translator in Foundry Tools is a service that enables you to translate text between languages. Similarly, Azure Speech in Foundry Tools provides translation services for speech. In this exercise, you'll use them to create translation apps that translates input in any supported language to the target language of your choice.
While this exercise is based on Python, you can develop text translation applications using multiple language-specific SDKs; including:
- Azure Translator client library for Python
- Azure Translator client library for .NET
- Azure Translator client library for JavaScript
- Azure AI Speech SDK for Python
- Azure AI Speech SDK for .NET
- Azure AI Speech SDK for JavaScript
This exercise takes approximately 30 minutes.
Prerequisites
Before starting this exercise, ensure you have:
- An active Azure subscription
- Visual Studio Code installed
- Python version 3.13 or higher installed
- Git installed and configured
Create a Microsoft Foundry project
Microsoft Foundry uses projects to organize models, resources, data, and other assets used to develop an AI solution.
-
In a web browser, open the Microsoft Foundry portal at
https://ai.azure.comand sign in using your Azure credentials. Close any tips or quick start panes that are opened the first time you sign in, and if necessary use the Foundry logo at the top left to navigate to the home page. -
If it is not already enabled, in the tool bar the top of the page, enable the New Foundry option. Then, if prompted, create a new project with a unique name; expanding the Advanced options area to specify the following settings for your project:
- Foundry resource: Use the default name for your resource (usually {project_name}-resource)
- Subscription: Your Azure subscription
- Resource group: Create or select a resource group
- Region: Select any of the AI Foundry recommended regions
Tip: Make a note of the region you selected. You'll need it later!
-
Select Create. Wait for your project to be created.
-
On the home page for your project, note the project endpoint, key, and OpenAI endpoint.
TIP: You're going to need the project key later!
Get the application files from GitHub
The initial application files you'll need to develop the translation application are provided in a GitHub repo.
-
Open Visual Studio Code.
-
Open the command palette (Ctrl+Shift+P) and use the
Git:clonecommand to clone thehttps://github.com/microsoftlearning/mslearn-ai-languagerepo to a local folder (it doesn't matter which one). Then open it.You may be prompted to confirm you trust the authors.
-
In Visual Studio Code, view the Extensions pane; and if it is not already installed, install the Python extension.
-
In the Command Palette, use the command
python:select interpreter. Then select an existing environment if you have one, or create a new Venv environment based on your Python 3.1x installation.Tip: If you are prompted to install dependencies, you can install the ones in the requirements.txt file in the /Labfiles/07-translation/Python/translators folder; but it's OK if you don't - we'll install them later!
Create a text translation application
Now you're ready to use Azure Translator to implement text translation.
- After the repo has been cloned, in the Explorer pane, navigate to the folder containing the application code files at /Labfiles/07-translation/Python/translators. The application files include:
- .env (the application configuration file)
- requirements.txt (the Python package dependencies that need to be installed)
- translate-text.py (the code file for text-application)
- translate-speech.py (the code file for speech-application)
Configure your text translation application
-
In the Explorer pane, in the translators folder, select the .env file to open it. Then update the configuration values to include the region and key for your Foundry project.
Important:Be sure to add the region for your resource, not the endpoint!
Save the modified configuration file.
-
In the Explorer pane, right-click the translators folder containing the application files, and select Open in integrated terminal (or open a terminal in the Terminal menu and navigate to the /Labfiles/07-translation/Python/translators folder.)
Note: Opening the terminal in Visual Studio Code will automatically activate the Python environment. You may need to enable running scripts on your system.
-
Ensure that the terminal is open in the translators folder with the prefix (.venv) to indicate that the Python environment you created is active.
-
Install the Azure Translator SDK package and other required packages by running the following command:
pip install -r requirements.txt azure-ai-translation-text==1.0.1
Add code to translate text
-
In the Explorer pane, in the translators folder, open the translate-text.py file.
-
Review the existing code. You will add code to work with Azure Translator.
Tip: As you add code to the code file, be sure to maintain the correct indentation.
-
At the top of the code file, under the existing namespace references, find the comment Import namespaces and add the following code to import the namespaces you will need to use the Translator SDK:
# import namespaces from azure.core.credentials import AzureKeyCredential from azure.ai.translation.text import * from azure.ai.translation.text.models import InputTextItem -
In the main function, note that the existing code reads the configuration settings.
-
Find the comment Create client using endpoint and key and add the following code:
# Create client using endpoint and key credential = AzureKeyCredential(translatorKey) client = TextTranslationClient(credential=credential, region=translatorRegion) -
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 languagesResponse = client.get_supported_languages(scope="translation") print("{} languages supported.".format(len(languagesResponse.translation))) print("(See https://learn.microsoft.com/azure/ai-services/translator/language-support#translation)") print("Enter a target language code for translation (for example, 'en'):") targetLanguage = "xx" supportedLanguage = False while supportedLanguage == False: targetLanguage = input() if targetLanguage in languagesResponse.translation.keys(): supportedLanguage = True else: print("{} is not a supported language.".format(targetLanguage)) -
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 inputText = "" while inputText.lower() != "quit": inputText = input("Enter text to translate ('quit' to exit):") if inputText != "quit": input_text_elements = [InputTextItem(text=inputText)] translationResponse = client.translate(body=input_text_elements, to_language=[targetLanguage]) translation = translationResponse[0] if translationResponse else None if translation: sourceLanguage = translation.detected_language for translated_text in translation.translations: print(f"'{inputText}' was translated from {sourceLanguage.language} to {translated_text.to} as '{translated_text.text}'.") -
Save your changes. Then, in the terminal pane, enter the following command to run the program:
python translate-text.py -
When prompted, enter a valid target language from the list displayed.
-
Enter a phrase to be translated (for example
This is a testorC'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.
Create a speech translation application
Now you're ready to use Azure Speech to implement text translation.
Configure your speech translation application
-
In the translators folder, verify that the .env file contains the region and key for your Foundry project (Azure Speech can use the same information as Azure Translator to connect to your Foundry resource).
-
Ensure that the terminal is open in the translators folder with the prefix (.venv) to indicate that the Python environment you created is active.
-
Install the Azure Speech SDK package and other required packages by running the following command:
pip install -r requirements.txt azure-cognitiveservices-speech==1.42.0
Add code to translate speech
-
In the Explorer pane, in the translators folder, open the translate-speech.py file.
-
Review the existing code. You will add code to work with Azure Speech.
Tip: As you add code to the code file, be sure to maintain the correct indentation.
-
At the top of the code file, under the existing namespace references, find the comment Import namespaces and add the following code to import the namespaces you will need to use the Speech SDK:
# Import namespaces from azure.core.credentials import AzureKeyCredential import azure.cognitiveservices.speech as speech_sdk -
In the main function, under the comment Get config settings, note that the code loads the key and region you defined in the configuration file.
-
Find the following code under the comment Configure translation, and add the following code to configure your connection to the Azure AI Services Speech endpoint:
# Configure translation translation_config = speech_sdk.translation.SpeechTranslationConfig(speech_key, speech_region) translation_config.speech_recognition_language = 'en-US' translation_config.add_target_language('fr') translation_config.add_target_language('es') translation_config.add_target_language('hi') print('Ready to translate from',translation_config.speech_recognition_language) -
You will use the SpeechTranslationConfig to translate speech into text, but you will also use a SpeechConfig to synthesize translations into speech. Add the following code under the comment Configure speech:
# Configure speech speech_config = speech_sdk.SpeechConfig(subscription=speech_key, region=speech_region) print('Ready to use speech service in:', speech_config.region) -
In the code file, note that the code uses the Translate function to translate spoken input. Then in the Translate function, under the comment Translate speech, add the following code to create a TranslationRecognizer client that can be used to recognize and translate speech from the default system microphone.
# Translate speech audio_config_in = speech_sdk.AudioConfig(use_default_microphone=True) translator = speech_sdk.translation.TranslationRecognizer(translation_config, audio_config = audio_config_in) print("Speak now...") result = translator.recognize_once_async().get() print('Translating "{}"'.format(result.text)) translation = result.translations[targetLanguage] print(translation) -
In the Translate function, find the comment Synthesize translation, and add the following code to use a SpeechSynthesizer client to synthesize the translation as speech and play it through the default system speaker:
# Synthesize translation voices = { "fr": "fr-FR-HenriNeural", "es": "es-ES-ElviraNeural", "hi": "hi-IN-MadhurNeural" } speech_config.speech_synthesis_voice_name = voices.get(targetLanguage) audio_config_out = speech_sdk.audio.AudioOutputConfig(use_default_speaker=True) speech_synthesizer = speech_sdk.SpeechSynthesizer(speech_config, audio_config_out) speak = speech_synthesizer.speak_text_async(translation).get() if speak.reason != speech_sdk.ResultReason.SynthesizingAudioCompleted: print(speak.reason) -
Save your changes. Then, in the terminal pane, enter the following command to run the program:
python translate-speech.py -
When prompted, enter a valid language code (fr, es, or hi). Then, when prompted to speak, say something aloud (for example, "Hello world!").
The program shouldtranslate it to the language you specified (French, Spanish, or Hindi), and synthesize the translation.
NOTE: The code in your application translates the input to all three languages in a single call. Only the translation for the specific language is displayed, but you could retrieve any of the translations by specifying the target language code in the translations collection of the result.
Repeat this process, trying each language supported by the application.
NOTE: The translation to Hindi may not always be displayed correctly in the terminal due to character encoding issues.
-
When you're finished, press ENTER to end the program.
Clean up resources
If you have finished exploring Microsoft Foundry, delete any resources that you no longer need. This avoids accruing any unnecessary costs.
- Open the Azure portal at https://portal.azure.com and select the resource group that contains the resources you created.
- Select Delete resource group and then enter the resource group name to confirm. The resource group is then deleted.