DEV Community

loading...
Cover image for How to build an AI web app from scratch to translate languages & deploy it to Azure App services

How to build an AI web app from scratch to translate languages & deploy it to Azure App services

Amit Tomar
Freelance Tech Content Writer | Community Builder & Cloud Ambassador @AWS | Former GDSC Lead @Google | Student Ambassador @Microsoft | ZAmbassador @IBM
Updated on ・10 min read

Let me tell you a secret, "You do not need to be a highly experienced person in order to create an awesome AI app."

Yes! you heard it right. Microsoft Azure has made it easy to create intelligent apps with its awesome services. You just need an internet connection, Microsoft Azure account, laptop/pc and that's it. But how to get started?

Well, I have got you covered. In this tutorial, we will build a language translating app from scratch with the help of Azure Cognitive Services. We will use the Flask framework to design our app and Azure Translator as a backend. Then we will deploy it to Azure App services.

Objectives:
  • Creating a front end for our app with Flask.
  • Adding a backend with Azure Cognitive service.
  • Deploying the app on Azure App Services.
Prequiesties:
  • VS Code installed on the system or you can use any other code editor too.
  • Python 3.6 or later and Flask framework(We will install it throughout the process).
  • A Microsoft Azure Account.
And we will accomplish our work in two parts:

App development and App Deployment

And now...

1. App Development

In this phase, we will design our app from scratch. We will install all the dependencies and set up the environment. Then we will do some programming and also we'll add a backend in our app with the help of Azure Translator.

Setting up a development environment

So to get started with designing our Flask app we need to have some tools and a perfect development environment in order to make it easy for us but before setting up the environment you need to complete the following two steps:

  1. Install Visual Studio Code [Guide]

  2. Install Python [Guide]

Note: To check if you have already python on your system or not, you can execute the below-written command in your Command line/Bash.

python --version [Windows]

python3 --version [macOS or Linux]
Enter fullscreen mode Exit fullscreen mode

This will print the version of python installed on your system.

Now, Create the project directory or folder where we will store all of our files. You can create this anywhere in your system. After that start Git Bash in that folder. Now we will create a python environment for our application. You can use the following command in Bash:

python -m venv venv [Windows]

python3 -m venv venv [macOS or Linux]
Enter fullscreen mode Exit fullscreen mode

Now activate the environment with the following command:

.\\venv\\scripts\\activate [Windows]

source ./venv/bin/activate [macOS or Linux]
Enter fullscreen mode Exit fullscreen mode

Now, it's time to install the flask framework on our system and for that, we will create a requirement.txt file in our project directory which will contain all the libraries required for the application.

Open your VS code and navigate to your project directory. Create a new file in the same directory and name it "requirements.txt" and add the following text to it:

flask
python-dotenv
requests
Enter fullscreen mode Exit fullscreen mode

Save the file and return back to your command line/Bash. Run the following command:

pip install -r requirements.txt
Enter fullscreen mode Exit fullscreen mode

This command will install all the dependencies and libraries on your system. And, we have set up our development environment and it is...

Creating the front end for our app

Navigate in your VS code to your project directory and create a new file named "app.py". Add the following code to that file:

from flask import Flask, render_template
from flask import request
app = Flask(__name__)

@app.route('/', methods=['GET'])
def index():
return render_template('index.html')
Enter fullscreen mode Exit fullscreen mode

We need to fix a default root that will be used to run the application in case if the user hasn't given any specific name of server or domain. Thus we will use route - /.

Then we will use GET request here because when a GET request will come for /, Flask will call the declared function Index.html where we will write an HTML template as app front-end.

So let's design an HTML template for which we will use Bootstrap.

  1. Create a new folder in your project directory and name it as "templates".

  2. In that templates folder create two files and respectively name them "index.html" and "results.html".

  3. In Index.html add the following code:

<!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 by Amit Tomar</title>
</head>
<body>
    <div class="container">
        <h1>Translator by Amit Tomar</h1>
        <div>Enter the text below you want to translate, choose your preferred language, and click on Translate Now!</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 Now!</button>
                </div>
            </form>
        </div>
    </div>
</body>
</html>

Enter fullscreen mode Exit fullscreen mode

Here we have designed one part of our front-end but the app will not give us any results as we have not added our backend service yet. So to add Translator with our app navigate to your Azure Portal.

Adding Azure Translator in our app as backend

Now we will add Azure Translator in our app so it can translate one language into another. But before that let's understand what is Azure Translator?

Azure Translator is a part of Azure Cognitive services and it is a cloud-based language translation platform. Also, It is easy to integrate it with your apps and website.

So to add Azure Translator with our app. Open Azure portal if you have already an Account otherwise, you can create one for yourself. It offers a free tier too.

  • Click on create a resource.
    Alt Text

  • Search for "Translator" and open it.

  • Fill in the necessary information.

Subscription: Your subscription
Resource group: Choose an existing one or create new.
Resource group region: Select a region near to you
Resource region: Select same as resource group region
Name: A unique name of your app
Pricing tier: Free F0

Alt Text

  • Review and create your service. It will take a few seconds to deploy your resource successfully.

Alt Text

  • Once the resource is created, go to your resource. And, on the left side panel, click on Keys and Endpoint.

Alt Text

  • Copy Key 1 and make a note of the location and endpoint. Key 1 and Key 2 both are the same you can copy anyone.

Store the key and other backend values in our app

Now we need to connect our backend with our app. For that, we will create a new file named ".env" in our local project directory. And then enter the following code in that file:

KEY=your_key
ENDPOINT=your_endpoint
LOCATION=your_location

Enter fullscreen mode Exit fullscreen mode

Remember to replace your_key, your_endpoint, and your_location respectively with the details you copied from the Azure Translator dashboard. Save the file.

Calling the Azure Translator service in our app

Now let's add some more code to our app as we need to call the translator service in our app.

Navigate back to your VS code and open app.py. Add the following codes in your file respectively at the start and end:

import requests, os, uuid, json
from dotenv import load_dotenv
load_dotenv()

Enter fullscreen mode Exit fullscreen mode

In the above code, the first line is used to import all the necessary libraries which will be used to call the Azure Translator service. Later we are using load_dotenv to load the backend values from our .env file.

@app.route('/', methods=['POST'])
def index_post():

    original_text = request.form['text']
    target_language = request.form['language']

    key = os.environ['KEY']
    endpoint = os.environ['ENDPOINT']
    location = os.environ['LOCATION']

    path = '/translate?api-version=3.0'
    target_language_parameter = '&to=' + target_language
    constructed_url = endpoint + path + target_language_parameter

    headers = {
        'Ocp-Apim-Subscription-Key': key,
        'Ocp-Apim-Subscription-Region': location,
        'Content-type': 'application/json',
        'X-ClientTraceId': str(uuid.uuid4())
    }

    body = [{ 'text': original_text }]

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

    translator_response = translator_request.json()

    translated_text = translator_response[0]['translations'][0]['text']

    return render_template(
        'results.html',
        translated_text=translated_text,
        original_text=original_text,
        target_language=target_language
    )

Enter fullscreen mode Exit fullscreen mode

So now let's understand how does our above code working:

  1. First it reads the user-provided values: text and language selected.
  2. Then it takes the environment variable or values from our .env file.
  3. It detects the source language and creates a path to call the Azure Translator service.
  4. Creates the body for our text which we want to translate and calls the Translator service.
  5. Then it retrieves the translated text from the server as a JSON response.
  6. Gives the final output!

Everything looks good as we have designed the front end and also added the Translator as backend.

But when you will click on "Translate Now!" it will give you an error.

It is because we have not designed a result page for our app. So there is no end destination for our app and there is no clear way to navigate. To resolve this let's design a result page. So let's design a result page for our app.

Remember in your templates folder you added two HTML files: index.html and results.html. In the results.html, add the following code:

<!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 created by Amit Tomar</title>
</head>
<body>
    <div class="container">
        <h2>I have got you a result!</h2>
        <div>
            <strong>Original text was:</strong> {{ original_text }}
        </div>
        <div>
            <strong>Translated text is:</strong> {{ translated_text }}
        </div>
        <div>
            <strong>Target language code:</strong> {{ target_language }}
        </div>
        <div>
            <a href="{{ url_for('index') }}">Try another!</a>
        </div>
        <div>
        Thanks for using. Hope you loved it :)
        </div>

    </div>
</body>
</html>

Enter fullscreen mode Exit fullscreen mode

Now we are all good to go. And now we are going to test our final app!

Test the app locally

And now let's test our app locally. Open the terminal and run the following commands:

set FLASK_ENV=development [Windows]

export FLASK_ENV=development [Linux/macOS]
Enter fullscreen mode Exit fullscreen mode
flask run
Enter fullscreen mode Exit fullscreen mode

Open your browser and go to http://localhost:5000. You will see your app there. Now give some text to it for translation and choose your preferred language. Click on "Translate Now!" and boom :)

Alt Text

Alt Text

2. App Deployment

We have accomplished the first part of our app by successfully building it but it is only available locally. Sadly, others cannot access your localhost:5000. So you need to upload the whole app somewhere so it becomes available for everyone.

And to host our app on the internet we are using the Azure App service. So what is Azure App Service?

Azure App Service is an HTTP-based and fully managed "Platform as a Service" (PaaS) that is used for web application hosting, Mobile backend, and Rest APIs. With Azure App Service, you get security, autoscaling, load balancing features followed by DevOps capabilities.

Now Let's host our app on Azure App Services. For that, first, we will integrate the Azure App service with our VS code and then we will connect Azure App services with our Github repository where we will store all of our app data.

Add Azure app services in your VS Code:

  • Open your VS code and navigate to the extension tab.
  • Search for Azure App Services and install it.
  • After installation, it will require you to sign in to your Azure account. Simply signing with your credentials.

Once the Azure App services extension installed on your VS Code. You can access it from the left side panel and then click on "+".

Alt Text

Here you will name your app and provide other information related to that. In our case - translate-dev-in(Name) and Python version is 3.8.

After a moment on the right bottom, you will see your result. Just click on view output.
Alt Text

Now you can browse the website of our app but as we have not uploaded our code yet. so it will look like this.

Alt Text

Alt Text

Now click on the Deployment center option on our sample website. This will take you to the Azure portal. Now on the portal navigate to Deployment center[The latest one not Classic.]

Alt Text

So before we move forward here on our deployment part. Let's upload our app from the local system to our Github repository.

  • Create a new repo and name it as you like.

Alt Text

  • Upload your app in your repo as it is. You can upload it via Git bash.

Alt Text

Moving back to the deployment part. Select Github as our code source. and configure other details to navigate the app service for our app code.

Alt Text

And then save it. Wait for a while and navigate back to our VS code. And browse the website again.

Alt Text

You will see your app with a URL. You can share this URL with others and they will be able to access your app. The app will look like this:
Alt Text

Alt Text

And finally, you did it. Congratulations!

You can check my app here and Github repo here

If you have any doubts related to the app feel free to ask below or you can also connect with me on my social media handles: LinkedIn, Twitter, and Instagram

Bye-Bye!

Discussion (0)