current position:Home>Generating AI web applications using Python and flask

Generating AI web applications using Python and flask

2022-02-02 07:24:26 I just want a weekend off

brief introduction

Using artificial intelligence (AI) establish Web Applications don't need to involve a lot of code or create services from scratch . Suppose we want to create a website that can translate text for users .

For front-end , What we need should be able to integrate services without having to go through a lot of trouble . Flask Such a framework is a good choice . Flask The creator of describes it as “ Microframets ”, This means that the framework will provide the required core services ( For example, routing and templating ), But in other ways, it allows the use of any back-end services required by the application . Flask Or lightweight framework , It can be set up and deployed quickly . We don't need databases or any sophisticated content . We just need a framework to create UI, And can call back-end services .

For the back end , You can use a set of AI service ( be called Azure Cognitive services ), Instead of creating your own machine learning model . These services can be through SDK or HTTP Call access . We can use Translator service To meet the main goal of translating the text .

We'll talk about Flask And translator Services . We'll learn how to create a Web Application to translate text into various languages .

Set up the development environment

To start with Python To write Flask Applications , We need to set up the development environment , This will require several items to be installed . Fortunately, , The tools we want to use are relatively general

install Python

To complete this unit , You must install... On your computer Python 3.6 Or later . You may have installed Python, Especially if you've already used it . You can confirm that... Is installed by executing one of the following commands :

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

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

Create project directory

Create a directory in the location you choose . This directory will be your project directory , It will contain all the code we want to create . You can use one of the following commands to create a directory from a command or terminal window :

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

establish Python A virtual environment

Python Virtual environments are not necessarily as complex as they sound . Virtual environment is not creating virtual machines or containers , It's a folder that contains all the libraries needed to run the application ( Include Python The runtime itself ). Take advantage of the virtual environment , We modularize the application , In this way, we can make the applications independent of each other and avoid version problems . As a best practice , In the use of Python when , Virtual environments should always be used .

To use virtual environments , We will create and activate the virtual environment . We use venv Module to create a virtual environment , This module was used in the previous Python Installed in the installation instructions . When activating the virtual environment , We will tell the system to use the folder we created for all its Python demand .

# 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 code 

install Flask And other libraries

With the creation and activation of virtual environment , We can now install Flask, This is the library required by the website . We will follow common conventions to install Flask, Create a “requirements.txt” file . “requirements.txt” The file itself is not special ; It is a text file , It lists the libraries required by the application . But this is a convention that developers often use , Makes it easier to manage applications that rely on a large number of Libraries .

In later exercises , We will use several other libraries , Including the request ( Used to call the translator service ) and python-dotenv( Used to manage keys ). Although we don't need these libraries yet , But now the installation will make the process easier .

  1. In a command or terminal window , Run the following command to Visual Studio Code Open the directory in :

       code .
     Copy code 
  2. stay Visual Studio Code Medium “ Explorer ” Window , choice “ New file ”

     Show  Visual Studio Code  Medium “ New file ” Screenshot of the button .

    If not installed Vscode Then you just need to be in the project directory Just do the third step

  3. Name the file requirements.txt, Then add the following text :

    flask
    python-dotenv
    requests
     Copy code 
  4. stay Mac On , By clicking “Ctrl-S” or “Cmd-S” To save the file

  5. Return to the command or terminal window , Use pip Run the following command to perform the installation :

    pip install -r requirements.txt
     Copy code 

This command downloads the required libraries and their dependencies .

If pip 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 the development environment !

Flask Basic knowledge of

Flask It's open source Web“ Microframets ”. When the creator uses “ Microframets ” When this term is used , They mean that the framework will implement Web The tasks required by the framework , But it doesn't include advanced functions , Or other applications must follow specific requirements to work properly . This method makes Flask Very flexible , And very suitable for use as an existing back-end or API( Such as cognitive services ) The front end of the !

When using any framework to create Web When applied , We all need to understand several core concepts : route 、 Methods and templating . Before writing the code , Let's first understand these concepts .

Respond to user requests using routing

In the use of Web When applied , Users browse to different uniform resource locators ( namely URL) To indicate the operation you want to perform or the information you are looking for . The user can directly enter the address ( such as https://adventure-works.com), You can also select links or include corresponding URL The button . On the e-commerce website , You may see the following URL:

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

As a developer , We don't actually have to worry about URL The first part or domain of ( In this case “adventure-works.com”). Our application will operate according to anything behind the domain name , from / Start . The part behind the domain name is called “ route ”.

Routing is the path of operation . Similar to clicking a button in a mobile app , The route indicates what the user wants to do . We will be in Web Register different routes in the application , In response to various requests supported by the application .

In our application , We provide a function to indicate how to respond to a specific routing request . A route is a mapping to a function . When we consider writing general code , This concept is relatively intuitive . When we want to perform a specific operation , It calls the function . Our users will perform exactly the same operation ! However, they will do this by accessing the route .

establish Web When applied , There are many methods available , But the two most common methods ( It's also the only two we focus on ) yes “GET” and “POST”. GET It usually indicates that the user is requesting information , and POST It means that the user needs to send us a message and receive a response .

Use GET and POST Common application flows around using forms . Suppose we create an application , Where the user wants to register the mailing list :

  1. User pass GET Access the registration form
  2. The user completes the form , And select “ Submit ” Button
  3. The information in the form passes through POST Send back to the server
  4. Return to the user “ success ” news

Or as you might expect , The user does not directly indicate the predicate they want to use , Predicates are controlled by the application . Generally speaking , If the user types URL Or select a link to navigate directly to URL, Then use GET Visit the page . When the user selects the button of the form , Usually through POST Send a message .

Templates

Hypertext markup language (HTML) Is the language used to construct the information displayed on the browser , Cascading style sheets (CSS) Is used to manage styles and layouts . When creating an application , majority HTML It's all static , This means that the language will not change . However , To make the page dynamic , We need to be able to programmatically put information into HTML page . Almost every Web Frameworks can meet this need through templates .

With templates , You can write the core HTML( Or template ) And indicate placeholders for dynamic information . Perhaps the most common syntax for placeholders is {{ }}. Flask Template engine for Jinja Can use this syntax .

HTML Copy

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

In the previous example , We used h1( header ) Of HTML, It contains the text we want to display . {{ name }} I want to be in Beijing “ Welcome to use ” Then a message named name The variable of . Through this grammar , We can use our existing skills to write HTML, And inject dynamic information as needed .

Create an

We will create the application iteratively , Focus on specific concepts in the creation process . First , We will create a landing page for the application , This page will display the form that the user wants to use .

Usually ,Flask The entry point for the application is called “app.py” The file of . We will follow this Convention and create the core of the application . We will perform the following steps :

  1. Create core applications
  2. Add a route to the application
  3. Create... For your website HTML Templates
  4. Test the application

Create core applications

New file To create a file named “app.py” The new document of

  1. Add code to create Flask Applications

    Python Copy

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

The import statement contains a pair of  Flask  References to , This is all. Flask The core of the application . When we want to go back HTML when , We will use... For a period of time  render_template.

app  Will be our core application . In the next step , We will use it to register routes .

Add route

The application will use a route - /. This route is sometimes called “ Default ” or “ Indexes ” route , Because when the user does not provide anything other than the domain or server name , Will use this route .

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

Python Copy

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

adopt  @app.route, We can specify the route to be created . The path will be /, This is the default route . We point out that this will be used for GET. If / received GET request ,Flask The function directly declared under the decorator will be called automatically , Our example is  index. stay  index  In the body of , We said we would return a message named “index.html” Of HTML Templates .

Create... For the form HTML Templates

Flask Template engine for Jinja Very concerned HTML. therefore , We can use all the existing HTML Skills and tools . We will use start-up To arrange the page , Make it more beautiful . By starting , We will be in HTML Use different on CSS class . If you are not familiar with starting , You can ignore these classes and focus on HTML( This is the really important part ).

Flask Your template needs to be named “ Templates ” Create... In a folder , That's a good fit . Let's create a folder 、 Necessary files and add HTML.

  1. By means of Visual Studio Code Of “ Explorer ” Select from tools “ New folder ”, Create a file called “ Templates ” New folder for

  2. Choose to create “ Templates ” Folder , And then choose “ New file ” Add files to this 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 code 

above HTML The core component of is the text that users want to translate  textarea, And a drop-down list that the user will use to indicate the target language (select). If you want to add more languages , You can refer to List of supported languages , Get other options . take  value  Property to language code , for example ,“pl” Means polish .

Test the application

After creating the initial site , It's time to test it ! We will use Visual Studio Code Integrated terminal in , Make this process easier .

  1. stay Mac On , choice Ctrl- or Cmd- To open the integrated terminal

  2. Running the following command will Flask The runtime is set to development , This means that the server will automatically reload each time it changes

    Bash Copy

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

    Bash Copy

    flask run
     Copy code 
  4. Navigate to http://localhost:5000, Open the application in the browser

You should see such a web page

image.png

You should see the form displayed . Congratulations on !

translate

Although solutions using machine learning or artificial intelligence are becoming more and more common , But creating from scratch is still difficult . Fortunately, , Many solutions have been developed , We can access any application programming interface like (API) Access these solutions as well . This approach allows us to focus on the code , Instead of complex modeling .

Azure A set called Cognitive services Our products / service , This includes computer vision 、 Voice to text 、 Text to speech and text translation services . You can use the software development kit (SDK) Access any of these services , You can also call other HTTP The endpoint is called the same way .

To use cognitive services , You need one Azure account . If you're not familiar with Azure, Sure Free registration , It includes 200 The free amount of US dollars ( Before 30 God ). If you are a student , Sure Register for student oriented Azure, It includes 100 dollar ( For the period 12 Months ) Available limit , And a range of other free services .

Translator service

Translator service ( Part of cognitive services ) There will be translation between dozens of languages . The service can automatically detect the source language , And can be translated into multiple target languages in one call . The translator service is invoked in the same way as any other service HTTP Endpoints work the same way . Use Python when , Usually by “ request ” Library to do this , This is the library we will use when returning the code .

Key management

To call the translator service ( Or any other cognitive service ), We will need the key . This key will be used every time the service is accessed . A key is similar to a password . Anyone who has access to the key can call this service , If we use a paid version , There may be a lot of expenses !

During development work , A good solution can be used to protect the key , That's using the name  python-dotenv  The library of , Often referred to as dotenv. Use dotenv when , We will create a new one called “.env” The file of , It contains keys that we don't want to be part of the source code / It's worth it . When we push the code to  GitHub  when , Make sure the file is listed in  gitignore  In file , So it won't be accidentally released to the public .

  Create translator service

Get the key of the translator service . As mentioned earlier , We need a  Azure account . We will use Azure Portal creation key , And store it in the... Of the application “.env” In file .

Get the translator service key

  1. Browse to  Azure Gateway

  2. choice “ Create resources ”

     Show  Azure  In the portal “ Create resources ” Screenshot of options

  3. stay “ Search for ” In the box , Input “ translator ”

  4. choice “ 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. choice “ see + establish ”
  2. choice “ establish ”
  3. The resource will be created in a few minutes
  4. choice “ Go to resources ”
  5. choice “ Resource management ” Lower the left “ Keys and endpoints ”

stay “ secret key 1” side , choice “ Copy to clipboard ”

Create a for storing keys .env file

  1. Back to Visual Studio Code, By choice “ New file ” And named it “.env”, Create a new file in the root directory of the application

  2. Paste the following text into “.env” in

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

    • Replace the placeholder with the key copied above your_key
    • use Azure Replace placeholders with endpoints in your_endpoint
    • use Azure Replace placeholder with position in your_location
  4. Yours “.env” The file should look like ( Use your value ):

    text Copy

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

    Call the translator service

With us in Azure The back-end translator service created on and the stored variables are ready , Let's shift our focus to how to add the necessary logic and templates to the application to translate text . We will perform the following steps :

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

Add code to invoke the service

app.py Contains the logic of the application . We'll add several required imports to the library we're going to use , Then add a new route that responds to the user .

  1. stay app.py Top of , Add the following lines :

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

The top line imports the library we will use later when calling the translator service . We also  dotenv  Import  load_dotenv  And execute the function , This function will start from .env Load values .

  1. stay app.py The bottom of , Add the following lines , Create routes and logic for translating 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 code 

The code is annotated , Describe the steps being performed . Generally speaking , Our code will do the following :

  1. Read the text entered by the user , And the language selected by the user on the form
  2. from “.env” The environment variable created before the file is read
  3. Create the path required to call the translator service , The service includes the target language ( Automatically detect the source language )
  4. Create header information , Including the key of the translator service 、 The location of the service and any translation ID
  5. Create the body of the request , This includes the text to be translated
  6. stay  requests  On the call  post  The translator is called
  7. Retrieve... From the server JSON Respond to , Including the translated text
  8. Retrieve translated text ( Please refer to the following notes )
  9. call  render_template  To display the response page

When calling the translator service , You can translate multiple statements into multiple languages in one call . therefore , Service returned JSON It's a lot of information , We only need a small part of it . therefore , We need to subdivide down to get the translated text .

To be specific , We need to read the first result , And then it reads  translations  Set ( The first translation ), And then it reads  text. This is done by calling :translator_response[0]['translations'][0]['text']

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

Create a template to display the results

Let's make “ result ” Page creation HTML Templates .

  1. stay Visual Studio Code Medium “Explorer” Select from tools “ Templates ”, stay “ Templates ” Create a new file . And then choose “ New file ”

  2. Name the file results.html

  3. Add the following HTML Add to results.html in

    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 code 

You'll notice , We visited  original_texttranslated_text  and  target_language, These all use  {{ }}  stay  render_template  Passed as a named parameter in . This operation informs Flask Render content as plain text . We also need to use  url_for('index')  Create a link back to the default page . Although technically , We can type the path of the original page , But use  url_for  Will inform Flask Use the name we provided ( In this case  index) Read the path of the function . If we rearrange the site , Is generated for the link URL Will always be valid .

The test page

Back to Visual Studio Code Integrated terminal in ( stay Mac You can use Ctrl- or Cmd- Reopen it ). If the site is currently running , Then we need to stop and restart the site , So that the application can read the environment variables .

  1. Use Ctrl-C stop it Flask Applications
  2. Carry out orders  flask run  To restart the service
  3. Browse to http://localhost:5000 To test the application
  4. Enter text in the text area , Choose a language , And then choose “ translate ”

image.png

image.png

copyright notice
author[I just want a weekend off],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/02/202202020724178270.html

Random recommended