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.

Parveen Singh

8 Mins Read

June 17, 2024

Table of Content

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:

  1. 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.
  2. Python Installed: Ensure you have Python installed on your local machine. You can download the latest version from the official Python website.
  3. Basic Knowledge of Python: Familiarity with Python programming is essential as you will be writing scripts to interact with the Azure Translator API.
  4. 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

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

  2. Click on +Create to create a new Translator service:

    A form will appear where you configure the service.
  3. 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.

  4. On the Review + create tab, review the details and click Create to create the service:
  5. 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.
  6. 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.

  1. Launch Visual Studio Code on your machine.
  2. Press `Ctrl + “ (backtick) to open the integrated terminal within VS Code.
  3. Use the terminal to navigate to the directory where you want to create your project. For example:
    cd C:\\Development
    
  4. Install the Requests module by running the following command:
    pip install requests
    
  5. 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.

  6. 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=(',', ': ')))
    
  7. 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

  1. 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.

  2. 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.

  3. 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.

  1. 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
    
  2. 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.

  3. 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.
  4. 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']
    }
    
  5. 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.'}
    ]
    
  6. 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:

  1. Introduction to Azure Translator Service: Understanding its importance and features.
  2. Setting Up the Azure Translator Service: Creating a Translator resource on Azure and obtaining the necessary keys and endpoints.
  3. Setting Up Your Python Environment: Preparing your development environment and creating the translator.py file.
  4. Basic Text Translation: Writing and running a Python script to translate text using Azure Translator.
  5. 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


Discover more from Parveen Singh

Subscribe to get the latest posts sent to your email.

Recommended Readings

Discover more from Parveen Singh

Subscribe now to keep reading and get access to the full archive.

Continue reading