Introduction to the

Creating Web applications using artificial intelligence (AI) does not involve a lot of code or create services from scratch. Suppose we want to create a website that can translate text for users.

For the front end, we need something that allows us to integrate services without a lot of hassle. Frameworks like Flask are a good choice. Flask’s creators describe it as a “microframework”, meaning that the framework provides the required core services (such as routing and templating), but otherwise allows you to use whatever back-end services your application needs. Flask is also a lightweight framework for quick setup and deployment. We don’t need a database or anything elaborate. All we need is a framework to create the UI and be able to call the back-end services.

For the back end, you can use a set of AI services (called Azure Cognition Services) instead of creating your own machine learning model. These services can be accessed through SDK or HTTP calls. We can use the translator service to meet the primary goal of translating text.

Flask and the Translator service will be discussed. We’ll learn how to create a Web application to translate text into various languages.

Setting up the Development Environment

To start writing Flask applications in Python, we need to set up the development environment, which will require several projects to be installed. Fortunately, the tools we use are relatively generic

Install Python

To complete this unit, you must have Python 3.6 or higher installed on your computer. You probably have Python installed, especially if you’ve already used it. You can verify that it is installed by executing one of the following commands:

# Windows:
python --version
​
#macOS or Linux
python3 --version
Copy the code

If Python is installed, the output will show the Python version number. If not, please go to the official website to install.

Create a project directory

Create a directory at the location of your choice. This directory will serve as your project directory and will contain all the code we will create. You can create a directory from a command or terminal window using one of the following commands:

# Windows
md contoso
cd contoso
​
## macOS or Linux
mkdir contoso
cd contoso
Copy the code

Create the Python virtual environment

The Python virtual environment is not necessarily as complex as it sounds. Instead of creating a virtual machine or container, a virtual environment is a folder containing all the libraries needed to run your application (including the Python runtime itself). With the virtual environment, we made the application modular so that we could keep the applications independent of each other and avoid versioning issues. As a best practice, you should always use a virtual environment when using Python.

To use the virtual environment, we will create and activate it. We used the venv module, which was installed in the previous Python installation instructions, to create the virtual environment. When the virtual environment is activated, we tell the system to use the folder we created for all of its Python requirements.

# Windows
# Create the environment
python -m venv venv
# Activate the environment
.\venv\scripts\activate
​
# macOS or Linux
# Create the environment
python3 -m venv venv
# Activate the environment
source ./venv/bin/activate
Copy the code

Install Flask and other libraries

With the virtual environment created and activated, we can now install Flask, the library required for the site. We will install Flask following the usual convention, which is to create a “requirements.txt” file. The “requirements. TXT” file itself is not special; It is a text file that lists the libraries required by the application. But this is a common convention used by developers to make it easier to manage applications that rely on a large number of libraries.

In later exercises, we will use several other libraries, including requests (for invoking the translator service) and Python-dotenv (for managing keys). Although we don’t need these libraries yet, installing them now will make the process a little easier.

  1. From a command or terminal window, run the following command to open the directory in Visual Studio Code:

       code .
    Copy the code
  2. In the Explorer window in Visual Studio Code, select New File

    If you don’t have Vscode installed, just do step 3 in the project directory

  3. Name the file requirements.txt and add the following text:

    flask
    python-dotenv
    requests
    Copy the code
  4. On the Mac, save the file by clicking Ctrl-s or CMD-s

  5. Return to the command or terminal window and run the following command using PIP to perform the installation:

    pip install -r requirements.txt
    Copy the code

This command downloads the required libraries and their dependencies.

If PIP is not the latest version, you may receive an error message. Follow the instructions in the error message to perform the upgrade. This module does not require an upgrade.

If all goes well, you have now set up your development environment!

Flask Basics

Flask is an open source Web “micro-framework”. When creators use the term “microframework,” they mean that the framework will perform the tasks required by a Web framework, but it does not contain advanced functionality or other specific requirements that applications must follow to function properly. This approach makes Flask very flexible and ideal for use as a front end to existing backends or apis such as cognitive services!

When creating Web applications using any framework, we need to understand a few core concepts: routing, methods, and templating. Before we write the code, let’s look at these concepts.

Respond to user requests using routing

With Web applications, users browse to different uniform resource locators (urls) to indicate what they are doing or looking for. The user can enter the address directly (such as https://adventure-works.com) or select a link or button containing the corresponding URL. On an e-commerce site, you might see the following URL:

  • Home page:https://adventure-works.com/
  • Panel details:https://adventure-works.com/products/widget
  • Completed purchase:https://adventure-works.com/cart/buy

As developers, we don’t really have to worry about the first part of the URL or the domain (” Adventworks.com “in this case). Our application will perform operations based on whatever follows the domain name, starting with /. The part after the domain name is called the route.

A route is the path of an operation. Similar to clicking a button in a mobile application, routing indicates what the user wants to do. We will register different routes in the Web application to respond to the various requests supported by the application.

In our application, we provide a function that indicates how to respond to a particular routing request. A route is a mapping to a function. This concept is relatively straightforward when we consider writing generic code. Functions are called when we want to perform a particular operation. Our users will do exactly the same thing! However, they will do so through an access route.

There are many ways to create Web applications, but the two most common (and the only ones we’ll focus on) are “GET” and “POST.” GET usually indicates that the user is requesting information, while POST indicates that the user needs to send us information and receive a response.

A common application flow using GET and POST revolves around using forms. Suppose we create an application where the user wants to sign up for a mailing list:

  1. The user accesses the registration form through GET
  2. The user completes the form and selects the submit button
  3. The information in the form is sent back to the server via POST
  4. Returns a success message to the user

Or, as you might expect, the user does not directly specify the predicates he or she wants to use; the predicates are controlled by the application. In general, GET is used to access the page if the user navigates directly to the URL by typing in the URL or selecting a link. When the user selects a button on the form, the information is usually sent via POST.

The template

Hypertext Markup Language (HTML) is the language used to construct the information displayed on the browser, while cascading style sheets (CSS) are used to manage style and layout. When you create an application, most HTML is static, which means the language doesn’t change. However, to make a page dynamic, we need to be able to programmatically put information into an HTML page. Almost every Web framework can meet this requirement through templates.

With templates, you can write core HTML (or templates) and indicate placeholders for dynamic information. Perhaps the most common syntax for placeholders is {{}}. Flask’s template engine, Jinja, uses this syntax.

HTML copy

<h1>Welcome, {{ name }}</h1>
Copy the code

In the previous example, we used H1 (header) HTML, which contains the text we want to display. {{name}} indicates that you want to display a variable named name after welcome. With this syntax, we can use existing skills to write HTML and inject dynamic information as needed.

Create an

We will build the application iteratively, focusing on specific concepts during the creation process. First, we’ll create a landing page for the application that displays the form the user wants to use.

Typically, the Flask application’s entry point is a file named “app.py”. We will follow this convention and create the core of the application. We will perform the following steps:

  1. Create the core application
  2. Add a route to the application
  3. Create HTML templates for your web site
  4. Test application

Create the core application

Create a new file to create a new file named “app.py”

  1. Add code to create the Flask application

    Python copy

    from flask import Flask, redirect, url_for, request, render_template, session
    
    app = Flask(__name__)
    Copy the code

Import statements contain references to Flask, which are at the heart of all Flask applications. When we want to return HTML, we’ll use render_template for a while.

App will be our core application. In the next step, we will use it to register the route.

Add the routing

The application will use a route – /. This route is sometimes called the “default” or “indexed” route because it is used when the user does not provide anything beyond the domain or server name.

Add the following code to the end of “app.py”

Python copy

@app.route('/', methods=['GET'])
def index():
    return render_template('index.html')
Copy the code

With @app.route, we can specify the route to be created. The path will be /, which is the default route. We indicate that this will be used for GET. Flask will automatically call the function declared directly below the decorator, which in our case is index, if/receives a GET request. In the body of index, we indicate that an HTML template named “index.html” will be returned to the user.

Create an HTML template for the form

Flask’s template engine, Jinja, is very HTML focused. Therefore, we can use all existing HTML skills and tools. We’ll use launches to lay out the page and make it look better. By launching, we’ll use different CSS classes on the HTML. If you’re not familiar with booting, you can ignore these classes and focus on HTML (which is the really important part).

Flask’s templates need to be created in a folder called “Templates”, which is appropriate. Let’s create folders, the necessary files, and add HTML.

  1. Create a new folder named Templates by selecting New Folder in Visual Studio Code’s Explorer tool

  2. Select the Templates folder you created, and then select New File to add the file to that folder

  3. Name the file “index.html”

  4. Add the following HTML

    HTML copy

    <! 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/[email protected]/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>Copy the code

The core components in the HTML above are the TextaREA of the text that the user wants translated, and the select list that the user will use to indicate the target language. If you want to add more languages, you can refer to the list of supported languages for additional options. Set the value attribute to the language code, for example, “pl” for Polish.

Test application

Once you’ve created your initial site, it’s time to test it! We’ll use integration terminals in Visual Studio Code to make this process a little easier.

  1. On Mac, select Ctrl- or Cmd- to open the integration terminal

  2. Run the following command to set the Flask runtime to development, which means that the server will automatically reload every time it changes

    Bash copy

    # Windows
    set FLASK_ENV=development
    
    # Linux/macOS
    export FLASK_ENV=development
    Copy the code
  3. Run the application!

    Bash copy

    flask run
    Copy the code
  4. Open the application in a browser by navigating to http://localhost:5000

You should see something like this

You should see the form displayed. Congratulations!

translation

While solutions using machine learning or artificial intelligence are becoming more common, creating them from scratch remains difficult. Fortunately, many solutions have been developed that we can access just like any application programming interface (API). This approach allows us to focus on code rather than complex modeling.

Azure offers a set of products/services called cognitive Services, which include computer vision, speech-to-text, text-to-speech, and text translation services. Any of these services can be accessed through a software Development kit (SDK) or invoked in the same way as other HTTP endpoints.

To use cognitive services, you need an Azure account. If you’re not familiar with Azure, you can sign up for free, which includes a $200 credit (for the first 30 days). If you’re a student, you can sign up for Azure for students, which includes a $100 (12-month) subscription and a host of other free services.

Translator service

The translator service (part of the cognitive service) will translate to and from dozens of languages. The service automatically detects the source language and can be translated into multiple target languages in a single invocation. The translator service is invoked in the same way as any other HTTP endpoint. With Python, this is usually done through the “request” library, which we will use when we return code.

Key management

To invoke the translator service (or any other cognitive service), we will need a key. This key will be used each time the service is accessed. A key is similar to a password. Anyone with access to the key can call this service, and if we used the paid version, there could be a big fee!

A good solution for securing keys while doing development work is to use a library called python-dotenv, often referred to as Dotenv. With Dotenv, we create a file called “.env “that contains key/value pairs that we don’t want to be part of the source code. When we push the code to GitHub, we make sure that the file is listed in the Gitignore file so that we don’t accidentally publish it publicly.

Create the translator service

Gets the key of the translator service. As mentioned earlier, we need an Azure account. We will use the Azure portal to create the key and store it in the application’s “. Env “file.

Gets the translator service key

  1. Browse to Azure Portal

  2. Select Create Resource

  3. In the Search box, type “Translator”

  4. Select “Translator”

Fill out the “Create Translator” form with the following values:

  • Subscription: your subscription

  • Resource group:

    • Select “New”
    • Name: flask-ai
  • Resource group area : select a nearby area

  • Resource area : select the same area as above

  • Name : a unique value, such as ai-yourname

  • Pricing Tier : Free F0

  1. Select View + Create
  2. Select Create
  3. The resource will be created in a few minutes
  4. Select “Go to Resources”
  5. Select Keys and Endpoints on the left under Resource Management

Next to Key 1, select Copy to Clipboard

Create the.env file to store the key

  1. Go back to Visual Studio Code and create a new file in the root directory of your application by selecting “New File” and naming it “.env”

  2. Paste the following text into “. Env”

    KEY=your_key
    ENDPOINT=your_endpoint
    LOCATION=your_location
    Copy the code
  3. Replace placeholders

    • Replace the placeholder your_key with the key copied above
    • Replace the placeholder your_endpoint with an endpoint in Azure
    • Replace the placeholder your_location with the location in Azure
  4. Your “. Env “file should look like this (using your values) :

    The text to copy

    KEY=00d09299d68548d646c097488f7d9be9
    ENDPOINT=https://api.cognitive.microsofttranslator.com/
    LOCATION=westus2
    Copy the code

    Invoke the translator service

With the back-end translator service we created on Azure and stored variables in place, we shifted our focus to adding the necessary logic and templates to the application to translate the text. We will perform the following steps:

  1. Add code to invoke the service
  2. Create a template to display the results
  3. Test application

Add code to invoke the service

App.py contains the logic of the application. We’ll add a few required imports for the library we’ll use, and then add a new route that responds to the user.

  1. At the very top of app.py, add the following line:

    import requests, os, uuid, json
    from dotenv import load_dotenv
    load_dotenv()
    Copy the code

The top line will import the library we will use later when calling the translator service. We also import load_dotenv from dotenv and execute the function that loads the value from.env.

  1. At the bottom of app.py, add the following line of code to create the route and logic to translate the text:

    @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 )Copy the code

Comments are added to the code explaining the steps being performed. Roughly speaking, our code will do the following:

  1. Reads the text entered by the user and the language selected by the user on the form
  2. Read the previously created environment variables from the. Env file
  3. Create the path required to invoke the translator service, which includes the target language (auto-detect source language)
  4. Create header information, including the key of the translator service, the location of the service, and any ID of the translation
  5. Create the body of the request, including the text to be translated
  6. inrequestsOn the callpostTo invoke the translator service
  7. Retrieves the JSON response from the server, including the translated text
  8. Retrieve the translated text (see notes below)
  9. callrender_templateTo display the response page

When a translator service is invoked, it is possible to translate multiple statements into multiple languages in a single invocation. Therefore, the JSON returned by the service contains a lot of information, of which we only need a small portion. Therefore, we need to subdivide down to get the translated text.

Specifically, we need to read the first result, then a collection of translations (the first translation), and then text. This is done with a call: translator_response[0][‘ Translations ‘][0][‘text’]

[{" detectedLanguage ": {" language" : "en", "score" : 1.0}, "translations" : [{" text ":" こ れ は テ ス ト で す ", "to" : "ja"}]}]Copy the code

Create a template to display the results

Let’s create an HTML template for the “results” page.

  1. In The Explorer tool in Visual Studio Code, select Template and create a new file in Template. I’m gonna go ahead and say New File

  2. Name the file results.html

  3. Add the following HTML to results.html

    HTML copy

    <! 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/[email protected]/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>Copy the code

You’ll notice that we accessed original_text, translated_text, and target_language, all of which were passed as named parameters in render_template using {{}}. This tells Flask to render the content as plain text. We also use url_for(‘index’) to create a link back to the default page. Although technically we can type the path to the original page, using URl_for tells Flask to read the path to the function using the name we provide (index in this case). If we rearrange the site, the URL generated for the link will always be valid.

The test page

Return to the integration terminal in Visual Studio Code (reopen it using Ctrl- or Cmd- on Mac). If the site is currently running, we need to stop and restart the site so that the application can read the environment variables.

  1. Stop the Flask application using Ctrl-C
  2. Execute the commandflask runTo restart the service
  3. Browse to http://localhost:5000 to test the application
  4. Enter text in the text area, select a language, and then select “Translate”