Integrating Azure Translator Service in Python for Real-Time Text Translation

Learn how to integrate Azure Translator Service in Python for real-time text translation with this comprehensive guide.
parveensingh-headshot
Parveen
12 minutes read
June 17, 2024

Table of Content

Share this

Twitter
LinkedIn
Reddit

With the rapid advancements in artificial intelligence, Azure AI has emerged as a powerful suite of tools and services designed to infuse intelligent capabilities into applications. Azure AI encompasses a wide range of functionalities, including machine learning, cognitive services, and advanced analytics. Among these, the Translator service stands out as a robust tool for real-time language translation, breaking down communication barriers and enabling global reach.

 

In this blog, you’ll explore the Azure AI Translator service and how you can effortlessly integrate it within a Python script, empowering your applications with multilingual capabilities.

What is Azure AI Translator Service?

Azure AI Translator Service is a cloud-based machine translation service provided by Microsoft as part of its Azure AI Services. It enables developers to integrate real-time translation capabilities into their applications, websites, and workflows with ease. By leveraging advanced neural machine translation models, the service offers high-quality translations across numerous languages, making it an invaluable tool for breaking down language barriers in a globalized world.

 

Whether you need to translate text, detect languages, or even transliterate scripts, Azure Translator Service provides a robust and scalable solution. Its seamless integration with other Azure services and straightforward API make it an excellent choice for developers looking to enhance their applications with sophisticated language translation features.

Key Features of Azure Translator Service

Azure Translator Service offers a comprehensive set of features designed to meet various translation needs, making it a versatile tool for developers and businesses alike.

 

Text Translations

This feature allows for real-time translation between supported source and target languages. With the Translator API, developers can create dynamic dictionaries and control translations to ensure contextually accurate results. The service provides multiple integration options including a REST API, Text Translation SDK, and Translator container, enabling seamless incorporation into diverse applications.

 

Document Translation

Azure Translator also excels at translating entire documents. You can choose between two methods: asynchronous batch translation and synchronous single file translation. The asynchronous method is great for translating multiple or complex files at once, preserving the original format and structure. This process requires an Azure Blob storage account to manage your documents.

On the other hand, the synchronous method is perfect for translating a single document without any additional storage requirements. The translated document is returned directly to you, making the process quick and straightforward. Both methods can be accessed via the REST API and Translator container.

 

Custom Translator

For specialized translation needs, Azure Translator offers the Custom Translator feature. This allows you to build customized translation models tailored to specific industries or terminologies. Through the Custom Translator portal, you can create dictionaries for specific phrases or sentences to ensure that the translations are accurate and contextually appropriate. This feature is particularly useful for businesses that require precise translations reflecting industry-specific language and style.

 

These features collectively make Azure Translator Service a robust and flexible solution for a wide range of translation tasks, from simple text conversions to complex document translations and highly specialized custom models. Whether you are a developer looking to integrate translation capabilities into your app or a business needing precise and reliable translations, Azure Translator Service has you covered.

Exploring Text Translation Capabilities

In this blog post, you will explore the Text Translation capabilities of Azure Translator Service. We’ll guide you through the process of setting up the service, integrating it into your Python applications, and utilizing its powerful features to translate text in real-time. By the end of this tutorial, you will have a solid understanding of how to leverage Azure Translator’s Text Translations to enhance your applications with seamless translation functionality.

Prerequisites

Before you get started, make sure you have the following prerequisites in place:

  • Azure Subscription: You need an active Azure subscription to create and use Azure Translator Service. If you don’t have one, you can sign up for a free trial at Azure Free Account.
  • Python Installed: Ensure you have Python installed on your local machine. You can download the latest version from the official Python website.
  • Basic Knowledge of Python: Familiarity with Python programming is essential as you will be writing scripts to interact with the Azure Translator API.
  • Text Editor or IDE: A text editor or Integrated Development Environment (IDE) like Visual Studio Code, PyCharm, or any other of your choice to write and execute Python scripts.

Once you have these prerequisites in place, you’ll be ready to follow along with the steps to set up and use Azure Translator Service for text translation. Let’s get started!

Setting up the Azure Translator Service

  • Type translators in the Azure Portal search bar and select Translators from the search results:

  • Click on +Create to create a new Translator service:

    A form will appear where you configure the service.
  • On the Basics tab of Create Translator form, fill in the following details and click Review + create to proceed to the next step:
    • Subscription: Select your Azure subscription available from the list.
    • Resource group: Select a resource group or create a new one.
    • Region: Select Global.
    • Name: Enter a globally unique name for the service.
    • Pricing tier: Select Free F0 or a pricing tier of your choice.


You can only have one free tier per account. Consider using standard if the Free is already used in your subscription.

  • On the Review + create tab, review the details and click Create to create the service

  • Wait for the deployment to complete and click on Go to resource:

    The deployment will take about one minute to finish. You will be redirected to the Azure AI Translator service overview page.
  • In the sidebar, under Resource Management click on Keys and Endpoints:
    You’ve successfully set up the Azure Translator Service and navigated to the Keys and Endpoints page. Here, you can find your subscription key and endpoint URL, which you’ll need to authenticate and interact with the Translator API.

Now that you have the Azure Translator Service configured, let’s move on to setting up the Python environment.

Setting Up Your Python Environment

To get started, open the text editor or Integrated Development Environment (IDE) of your choice. For this tutorial, I will be using Visual Studio Code (VS Code). Check out my guide on VS Code Setup for Cloud Developers.

  • Launch Visual Studio Code on your machine.
  • Press Ctrl + ` (backtick) to open the integrated terminal within VS Code.
  • Use the terminal to navigate to the directory where you want to create your project. For example:
    cd C:\\Development
    
  • Install the Requests module by running the following command:
    pip install requests
    
  • In your project directory, create a new Python file named translator.py. You can do this by running the following command in the terminal:
    touch translator.py
    

    If you using Windows environment, create the file by right clicking on your file explorer instead.

  • Paste the following code in the translator.py file:
    import requests, uuid, json
    # Add your key and endpoint
    key = "<your-translator-key>"
    endpoint = "<https://api.cognitive.microsofttranslator.com>"
    # location, also known as region.
    # required if you're using a multi-service or regional (not global) resource. It can be found in the Azure portal on the Keys and Endpoint page.
    location = "<YOUR-RESOURCE-LOCATION>"
    
    path = '/translate'
    constructed_url = endpoint + path
    
    params = {
        'api-version': '3.0',
        'from': 'en',
        'to': ['fr', 'zu']
    }
    
    headers = {
        'Ocp-Apim-Subscription-Key': key,
        # location required if you're using a multi-service or regional (not global) resource.
        # 'Ocp-Apim-Subscription-Region': location,
        'Content-type': 'application/json',
        'X-ClientTraceId': str(uuid.uuid4())
    }
    
    # You can pass more than one object in body.
    body = [{
        'text': 'I would really like to drive your car around the block a few times!'
    }]
    
    request = requests.post(constructed_url, params=params, headers=headers, json=body)
    response = request.json()
    
    print(json.dumps(response, sort_keys=True, ensure_ascii=False, indent=4, separators=(',', ': ')))
    
  • Copy your API key and Text Translation URL for your Translator Service from the Azure Portal, and paste it replace key and endpoint in the code above respectively.

Code Explanation

  • Importing Libraries and Variables
    import requests, uuid, json
    
    # Add your key and endpoint
    key = "513afc836e5b4e928dd6ad948e1aff2b"
    endpoint = "<https://api.cognitive.microsofttranslator.com/>"
    
    # location, also known as region.
    # required if you're using a multi-service or regional (not global) resource. It can be found in the Azure portal on the Keys and Endpoint page.
    # location = "<YOUR-RESOURCE-LOCATION>"
    

    In this first chunk, you need to import the necessary Python libraries: requests for making HTTP requests, uuid for generating unique identifiers, and json for handling JSON data. You then set up the key and endpoint variables with the subscription key and endpoint URL for the Azure Translator Service. The location variable is commented out but is noted as necessary if using a regional or multi-service resource, which can be found on the Azure portal.

  • Constructing the URL and Setting Parameters
    path = '/translate'
    constructed_url = endpoint + path
    
    params = {
        'api-version': '3.0',
        'from': 'en',
        'to': ['fr', 'zu']
    }
    
    headers = {
        'Ocp-Apim-Subscription-Key': key,
        # location required if you're using a multi-service or regional (not global) resource.
        # 'Ocp-Apim-Subscription-Region': location,
        'Content-type': 'application/json',
        'X-ClientTraceId': str(uuid.uuid4())
    }
    # You can pass more than one object in body.
    body = [{
        'text': 'I would really like to drive your car around the block a few times!'
    }]
    

    You then define the path for the translation API endpoint and construct the full URL by concatenating the endpoint with the path. You then set up the params dictionary, which includes the API version, source language (from), and target languages (to). The headers dictionary includes the subscription key, content type, and a unique client trace ID generated using uuid. The location header is again commented out but noted as required for regional or multi-service resources. You define the body variable as a list containing a dictionary with the text to be translated.

  • Making the Request and Handling the Response
    request = requests.post(constructed_url, params=params, headers=headers, json=body)
    response = request.json()
    
    print(json.dumps(response, sort_keys=True, ensure_ascii=False, indent=4, separators=(',', ': ')))
    

    You then make a POST request to the constructed URL using the requests.post method, passing in the parameters, headers, and body as JSON. The response from the API is converted to a JSON object using request.json(). Finally, you print the formatted JSON response using json.dumps, making it easy to read and understand the translated text and other details.

Running Your Translation Script

Now that you have your translator.py file set up with the code to interact with the Azure Translator Service, it’s time to run the script and observe the output.

  • Ensure you are in the directory where your translator.py file is located. You can do this using the terminal or command prompt:
    cd path/to/your/project/directory
    
  • Execute the script using the following command:
       python3 translator.py
    

    If you’re using a different version of Python or a virtual environment, make sure to use the appropriate command, such as python translator.py or pipenv run python translator.py.

  • After running the script, you should see the JSON response printed in the terminal. This response will include the translated text in the specified target languages (French and Zulu in this example). The output should look something like this:You can also translate multiple blocks of text to an array to different languages at once.
  • In the params dictionary, you need to update the to key to include a list of target languages: French (fr), Spanish (es), German (de), and Simplified Chinese (zh-Hans).
    params = {
        'api-version': '3.0',
        'from': 'en',
        'to': ['fr', 'es', 'de', 'zh-Hans']
    }
    
  • The body variable now contains a list of dictionaries, each with a text key. This allows us to send multiple texts in a single request.
    # You can pass more than one object in body.
    body = [
        {'text': 'How are you today?'},
        {'text': 'The weather is great for a picnic.'}
    ]
    
  • After running the script, you should see a JSON response printed in the terminal. The response will include the translated texts in the specified target languages. The output should look something like this:

This output shows the original texts translated into French, Spanish, German, and Simplified Chinese, demonstrating the ability to handle multiple languages and multiple texts in a single request. Feel free to experiment further by adding more texts or different target languages to explore the full capabilities of the Azure Translator Service.

Conclusion

Throughout this tutorial, you’ve explored the powerful text translation capabilities of Azure Translator, learned how to handle multiple languages and texts, and gained hands-on experience with making API requests and handling responses.

By following these steps, you now have a solid foundation for adding real-time translation features to your applications. Whether you’re building a multilingual website, a global communication tool, or any other application that requires language translation, Azure Translator Service offers a robust and scalable solution.

Here’s a quick recap of what you’ve learned:

  • Introduction to Azure Translator Service: Understanding its importance and features.
  • Setting Up the Azure Translator Service: Creating a Translator resource on Azure and obtaining the necessary keys and endpoints.
  • Setting Up Your Python Environment: Preparing your development environment and creating the translator.py file.
  • Basic Text Translation: Writing and running a Python script to translate text using Azure Translator.
  • Advanced Translation Capabilities: Handling multiple languages and texts in a single request.

As you continue to explore Azure AI Services, you might want to learn about Azure SDK for Python, which offers even more control over your Azure Services using any programming language of your choice.

Further Reading and Resources

Stay wired with our newsletter!

Recommended Articles

Stay Up To Date with
Cloud News and Tutorials!

Subscribe to our weekly newsletter!

By entering your email address, you agree to our privacy policy.