Language Translator Using Azure Cognitive services and Flask

Aman Goyal
5 min readMar 19, 2021

Hey Guys , Today We will learn how to create a text translator Using Azure Cognitive services and Flask. This is an Intelligent Program that will automatically detect your input language and convert it in your required language type.

Some Prerequisites for this :-

  1. Latest Python version with its compiler (Prefer Visual Studio code).
  2. Active Azure Account
  3. Basic knowledge of Command line

Here I’m supposing that you have installed Visual Studio code and Python in it . So Now, First of all create a directory and environment where you will manage your all the code part. for this follow these commands

md contoso
cd contoso #in Windows to create directory

python -m venv venv #in Windows to Create the environment
.\\venv\\scripts\\activate #To Activate the environment

Now go to command line to start vs code .for that type

code .
```

now you are in vs code now open a new file name it requirements.txt. put following code in it so that program take it and install written requirements in it

flask
python-dotenv
requests

Now Return to the command or terminal window and perform the installation by using pip to run the following command

pip install -r requirements.txt

Now let’s start writing code for our requirement. We will create a main file of code in which We will put overview or main code . File name will be app.py as it is compulsory in Flask world. We will integrate this app.py code file with two other files using GET and POST method.

More over Supported files that would be our html ,CSS etc type of file would be in 1 folder separately Particularly named templates.

we will also create 1 .env file . As . (dot) represents , it would be a configuration file in it we will put our endpoint of translator function which we will create in azure cognitive services . here we will put key , endpoint and location .

First let see how we will create Translator function in Azure . For this login to Azure and now follow these steps.

Click on create resource
Search Translator here
click on create

Now provide all the details Asking here . (Recommended )Give same region in both the places .

Use Free Tier else it may charge you

Now review and create it . it will take few seconds to up . Now Go to resources and click on Key and Endpoint. From here copy key , endpoint url and location .
Now put these 3 details to .env file. It will look something like this

KEY=196acce68162dbbb4d8c097488f7d9be9 ENDPOINT=https://api.cognitive.microsofttranslator.com/ LOCATION=centralindia

Now let’s finalize it with code

app.py

from flask import Flask, render_template

import requests, os, uuid, json

from dotenv import load_dotenv

load_dotenv()

from flask import request

app = Flask(__name__)

@app.route(‘/’, methods=[‘GET’])

def index():

return render_template(‘index.html’)

@app.route(‘/’, methods=[‘POST’])

def index_post():

# Read the values from the form

original_text = request.form[‘text’]

target_language = request.form[‘language’]

# Load the values from .env

key = os.environ[‘KEY’]

endpoint = os.environ[‘ENDPOINT’]

location = os.environ[‘LOCATION’]

# Indicate that we want to translate and the API version (3.0) and the target language

path = ‘/translate?api-version=3.0’

# Add the target language parameter

target_language_parameter = ‘&to=’ + target_language

# Create the full URL

constructed_url = endpoint + path + target_language_parameter

# Set up the header information, which includes our subscription key

headers = {

‘Ocp-Apim-Subscription-Key’: key,

‘Ocp-Apim-Subscription-Region’: location,

‘Content-type’: ‘application/json’,

‘X-ClientTraceId’: str(uuid.uuid4())

}

# Create the body of the request with the text to be translated

body = [{ ‘text’: original_text }]

# Make the call using post

translator_request = requests.post(constructed_url, headers=headers, json=body)

# Retrieve the JSON response

translator_response = translator_request.json()

# Retrieve the translation

translated_text = translator_response[0][‘translations’][0][‘text’]

# Call render template, passing the translated text,

# original text, and target language to the template

return render_template(

‘results.html’,

translated_text=translated_text,

original_text=original_text,

target_language=target_language

)

results.html

<!DOCTYPE html>

<html lang=”en”>

<head>

<meta charset=”UTF-8">

<meta name=”viewport” content=”width=device-width, initial-scale=1.0">

<link rel=”stylesheet” href=”https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css"

integrity=”sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin=”anonymous”>

<title>Result</title>

</head>

<body>

<div class=”container”>

<h2>Results</h2>

<div>

<strong>Original text:</strong> {{ original_text }}

</div>

<div>

<strong>Translated text:</strong> {{ translated_text }}

</div>

<div>

<strong>Target language code:</strong> {{ target_language }}

</div>

<div>

<a href=”{{ url_for(‘index’) }}”>Try another one!</a>

</div>

</div>

</body>

</html>

index.html

<!DOCTYPE html>

<html lang=”en”>

<head>

<meta charset=”UTF-8">

<meta name=”viewport” content=”width=device-width, initial-scale=1.0">

<link rel=”stylesheet” href=”https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css"

integrity=”sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin=”anonymous”>

<title>Translator</title>

</head>

<body>

<div class=”container”>

<h1>Translation service</h1>

<div>Enter the text you wish to translate, choose the language, and click Translate!</div>

<div>

<form method=”POST”>

<div class=”form-group”>

<textarea name=”text” cols=”20" rows=”10" class=”form-control”></textarea>

</div>

<div class=”form-group”>

<label for=”language”>Language:</label>

<select name=”language” class=”form-control”>

<option value=”en”>English</option>

<option value=”it”>Italian</option>

<option value=”ja”>Japanese</option>

<option value=”ru”>Russian</option>

<option value=”de”>German</option>

</select>

</div>

<div>

<button type=”submit” class=”btn btn-success”>Translate!</button>

</div>

</form>

</div>

</div>

</body>

</html>

Here We are ready will complete code and setup . let’s run this. to run , in visual studio code open terminal and write

flask run

Congratulations You’ve now successfully created a website that uses Translator to implement translations!
To check your website , start browser and type

http://127.0.0.1:5000/

Converted to Russian

GitHub link for Complete code: https://github.com/AmanGoyal31/Translator-using-Azure-Flask

That’s all with this article. I hope you found the post Informative, if something was missing or you think some more things could have been added, feel free to provide suggestions in the comments section or on LinkedIn .

You can check out my LinkedIn profile.

Thanks for giving your precious time to this article✌ Hope you like it .

--

--