您现在访问的是微软AZURE全球版技术文档网站,若需要访问由世纪互联运营的MICROSOFT AZURE中国区技术文档网站,请访问 https://docs.azure.cn.

教程:生成使用 Azure 认知服务的 Flask 应用Tutorial: Build a Flask app with Azure Cognitive Services

在本教程中,你将生成一个 Flask Web 应用,该应用使用 Azure 认知服务来翻译文本、分析情绪,并将翻译的文本合成为语音。In this tutorial, you'll build a Flask web app that uses Azure Cognitive Services to translate text, analyze sentiment, and synthesize translated text into speech. 本教程重点介绍用于实现该应用程序的 Python 代码和 Flask 路由,但是,也会介绍用于统合该应用的 HTML 和 Javascript 代码。Our focus is on the Python code and Flask routes that enable our application, however, we will help you out with the HTML and Javascript that pulls the app together. 如果遇到任何问题,请使用下面的反馈按钮告诉我们。If you run into any issues let us know using the feedback button below.

本教程的内容:Here's what this tutorial covers:

  • 获取 Azure 订阅密钥Get Azure subscription keys
  • 设置开发环境并安装依赖项Set up your development environment and install dependencies
  • 创建 Flask 应用Create a Flask app
  • 使用文本翻译 API 翻译文本Use the Translator Text API to translate text
  • 使用文本分析来分析输入文本和翻译内容中的积极/消极情绪Use Text Analytics to analyze positive/negative sentiment of input text and translations
  • 使用语音服务将翻译的文本转换为合成语音Use Speech Services to convert translated text into synthesized speech
  • 在本地运行 Flask 应用Run your Flask app locally

提示

如果想要跳过这些步骤并查看最终的整个代码,请参阅 GitHub 上的完整示例和生成说明。If you'd like to skip ahead and see all the code at once, the entire sample, along with build instructions are available on GitHub.

什么是 Flask?What is Flask?

Flask 是用于创建 Web 应用程序的微框架。Flask is a microframework for creating web applications. 也就是说,Flask 提供所需的工具、库和技术用于生成 Web 应用程序。This means Flask provides you with tools, libraries, and technologies that allow you to build a web application. 此 Web 应用程序可以是一些网页、一篇博客、Wiki,甚至可以是基于 Web 的日历应用程序或商业网站。This web application can be some web pages, a blog, a wiki or go as substantive as a web-based calendar application or a commercial website.

完成本教程后若要进行深入了解,请参考以下有用链接:For those of you who want to deep dive after this tutorial here are a few helpful links:

先决条件Prerequisites

下面是学习本教程所需的软件和订阅密钥。Let's review the software and subscription keys that you'll need for this tutorial.

创建帐户并订阅资源Create an account and subscribe to resources

如前所述,在本教程中需要三个订阅密钥。As previously mentioned, you're going to need three subscription keys for this tutorial. 这意味着,需要在 Azure 帐户中为以下服务创建资源:This means that you need to create a resource within your Azure account for:

  • 文本翻译Translator Text
  • 文本分析Text Analytics
  • 语音服务Speech Services

参考在 Azure 门户中创建认知服务帐户中的分步说明创建资源。Use Create a Cognitive Services Account in the Azure portal for step-by-step instructions to create resources.

重要

对于本教程,请在美国西部区域创建资源。For this tutorial, please create your resources in the West US region. 如果使用其他区域,需要在每个 Python 文件中调整基 URL。If using a different region, you'll need to adjust the base URL in each of your Python files.

设置开发环境Set up your dev environment

生成 Flask Web 应用之前,需要为项目创建一个工作目录,并安装几个 Python 包。Before you build your Flask web app, you'll need to create a working directory for your project and install a few Python packages.

创建工作目录Create a working directory

  1. 打开命令行 (Windows) 或终端 (macOS/Linux)。Open command line (Windows) or terminal (macOS/Linux). 然后,为项目创建工作目录和子目录:Then, create a working directory and sub directories for your project:

    mkdir -p flask-cog-services/static/scripts && mkdir flask-cog-services/templates
    
  2. 切换到项目的工作目录:Change to your project's working directory:

    cd flask-cog-services
    

使用 virtualenv 创建并激活虚拟环境Create and activate your virtual environment with virtualenv

让我们使用 virtualenv 创建 Flask 应用的虚拟环境。Let's create a virtual environment for our Flask app using virtualenv. 使用虚拟环境可确保在干净的环境中操作。Using a virtual environment ensures that you have a clean environment to work from.

  1. 在工作目录中,运行以下命令以创建虚拟环境:macOS/Linux:In your working directory, run this command to create a virtual environment: macOS/Linux:

    virtualenv venv --python=python3
    

    我们已显式声明,该虚拟环境应使用 Python 3。We've explicitly declared that the virtual environment should use Python 3. 这可以确保装有多个 Python 版本的用户使用正确的版本。This ensures that users with multiple Python installations are using the correct version.

    Windows CMD/Windows Bash:Windows CMD / Windows Bash:

    virtualenv venv
    

    为简单起见,我们将虚拟环境命名为 venv。To keep things simple, we're naming your virtual environment venv.

  2. 用于激活虚拟环境的命令根据平台/shell 而异:The commands to activate your virtual environment will vary depending on your platform/shell:

    平台Platform ShellShell 命令Command
    macOS/LinuxmacOS/Linux bash/zshbash/zsh source venv/bin/activate
    WindowsWindows bashbash source venv/Scripts/activate
    命令行Command Line venv\Scripts\activate.bat
    PowerShellPowerShell venv\Scripts\Activate.ps1

    运行此命令后,命令行或终端会话的前面应带有 venvAfter running this command, your command line or terminal session should be prefaced with venv.

  3. 随时可以通过在命令行或终端中键入以下命令,来停用该会话:deactivateYou can deactivate the session at any time by typing this into the command line or terminal: deactivate.

备注

Python 提供了大量的文档用于介绍如何创建和管理虚拟环境,具体请参阅 virtualenvPython has extensive documentation for creating and managing virtual environments, see virtualenv.

安装 RequestsInstall requests

Requests 是用于发送 HTTP 1.1 请求的常用模块。Requests is a popular module that is used to send HTTP 1.1 requests. 无需手动将查询字符串添加到 URL,或者对 POST 数据进行格式编码。There’s no need to manually add query strings to your URLs, or to form-encode your POST data.

  1. 若要安装 Requests,请运行:To install requests, run:

    pip install requests
    

备注

若要详细了解 Requests,请参阅 Requests:HTTP for HumansIf you'd like to learn more about requests, see Requests: HTTP for Humans.

安装并配置 FlaskInstall and configure Flask

接下来,需要安装 Flask。Next we need to install Flask. Flask 处理 Web 应用的路由,并使我们能够发出服务器到服务器的调用,以便向最终用户隐藏订阅密钥。Flask handles the routing for our web app, and allows us to make server-to-server calls that hide our subscription keys from the end user.

  1. 若要安装 Flask,请运行:To install Flask, run:

    pip install Flask
    

    确保已安装 Flask。Let's make sure Flask was installed. 运行:Run:

    flask --version
    

    终端中应会列显版本。The version should be printed to terminal. 如果列显其他任何信息,则表示出错。Anything else means something went wrong.

  2. 若要运行 Flask 应用,可以使用 flask 命令,或者结合 Flask 使用 Python 的 -m 开关。To run the Flask app, you can either use the flask command or Python’s -m switch with Flask. 在执行该操作之前,需要通过导出 FLASK_APP 环境变量,来告诉终端要使用哪个应用:Before you can do that you need to tell your terminal which app to work with by exporting the FLASK_APP environment variable:

    macOS/LinuxmacOS/Linux:

    export FLASK_APP=app.py
    

    Windows:Windows:

    set FLASK_APP=app.py
    

创建 Flask 应用Create your Flask app

在本部分,你将创建一个基本的 Flask 应用,以便在用户进入应用的根目录时返回一个 HTML 文件。In this section, you're going to create a barebones Flask app that returns an HTML file when users hit the root of your app. 请不会花费过多的时间来尝试分解代码,因为稍后我们会回来更新此文件。Don't spend too much time trying to pick apart the code, we'll come back to update this file later.

什么是 Flask 路由?What is a Flask route?

让我们花费片刻时间来了解“路由”。Let's take a minute to talk about "routes". 路由用于将 URL 绑定到特定的函数。Routing is used to bind a URL to a specific function. Flask 使用路由修饰器将函数注册到特定的 URL。Flask uses route decorators to register functions to specific URLs. 例如,当用户导航到 Web 应用的根目录 (/) 时,将会呈现 index.htmlFor example, when a user navigates to the root (/) of our web app, index.html is rendered.

@app.route('/')
def index():
    return render_template('index.html')

让我们通过一个额外的示例来彻底了解此过程。Let's take a look at one more example to hammer this home.

@app.route('/about')
def about():
    return render_template('about.html')

此代码确保当用户导航到 http://your-web-app.com/about 时,会呈现 about.html 文件。This code ensures that when a user navigates to http://your-web-app.com/about that the about.html file is rendered.

尽管这些示例演示的是如何向用户呈现 HTML 页面,但路由也可用于在按下某个按钮时调用 API,或者在不离开主页的情况下执行任意数量的操作。While these samples illustrate how to render html pages for a user, routes can also be used to call APIs when a button is pressed, or take any number of actions without having to navigate away from the homepage. 为翻译、情绪和语音合成创建路由时,将会看到此工作方式。You'll see this in action when you create routes for translation, sentiment, and speech synthesis.

入门Get started

  1. 在 IDE 中打开项目,然后在工作目录的根目录中创建名为 app.py 的文件。Open the project in your IDE, then create a file named app.py in the root of your working directory. 接下来,将以下代码复制到 app.py 并保存:Next, copy this code into app.py and save:

    from flask import Flask, render_template, url_for, jsonify, request
    
    app = Flask(__name__)
    app.config['JSON_AS_ASCII'] = False
    
    @app.route('/')
    def index():
        return render_template('index.html')
    

    此代码块告知应用,每当用户导航到 Web 应用的根目录 (/) 时,都要显示 index.htmlThis code block tells the app to display index.html whenever a user navigates to the root of your web app (/).

  2. 接下来,让我们创建 Web 应用的前端。Next, let's create the front-end for our web app. templates 目录中,创建名为 index.html 的文件。Create a file named index.html in the templates directory. 然后,将以下代码复制到 templates/index.html 中。Then copy this code into templates/index.html.

    <!doctype html>
    <html lang="en">
      <head>
        <!-- Required metadata tags -->
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <meta name="description" content="Translate and analyze text with Azure Cognitive Services.">
        <!-- Bootstrap CSS -->
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
        <title>Translate and analyze text with Azure Cognitive Services</title>
      </head>
      <body>
        <div class="container">
          <h1>Translate, synthesize, and analyze text with Azure</h1>
          <p>This simple web app uses Azure for text translation, text-to-speech conversion, and sentiment analysis of input text and translations. Learn more about <a href="https://docs.microsoft.com/azure/cognitive-services/">Azure Cognitive Services</a>.
         </p>
         <!-- HTML provided in the following sections goes here. -->
    
         <!-- End -->
        </div>
    
        <!-- Required Javascript for this tutorial -->
        <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
        <script type = "text/javascript" src ="static/scripts/main.js"></script>
      </body>
    </html>
    
  3. 让我们测试该 Flask 应用。Let's test the Flask app. 在终端中,运行:From the terminal, run:

    flask run
    
  4. 打开浏览器并导航到提供的 URL。Open a browser and navigate to the URL provided. 应会看到单页应用。You should see your single page app. Ctrl + C 终止该应用。Press Ctrl + c to kill the app.

翻译文本Translate text

大致了解简单 Flask 应用的工作方式后,让我们:Now that you have an idea of how a simple Flask app works, let's:

  • 编写一些 Python 代码来调用文本翻译 API 并返回响应Write some Python to call the Translator Text API and return a response
  • 创建一个 Flask 路由用于调用 Python 代码Create a Flask route to call your Python code
  • 使用文本输入和翻译区域、语言选择器和翻译按钮更新 HTMLUpdate the HTML with an area for text input and translation, a language selector, and translate button
  • 编写 Javascript 代码,使用户能够通过 HTML 来与 Flask 应用交互Write Javascript that allows users to interact with your Flask app from the HTML

调用文本翻译 APICall the Translator Text API

要做的第一件事是编写一个函数来调用文本翻译 API。The first thing you need to do is write a function to call the Translator Text API. 此函数采用两个参数:text_inputlanguage_outputThis function will take two arguments: text_input and language_output. 每当用户在该应用中按下翻译按钮时,就会调用此函数。This function is called whenever a user presses the translate button in your app. HTML 中的文本区域作为 text_input 发送,HTML 中的语言选择值作为 language_output 发送。The text area in the HTML is sent as the text_input, and the language selection value in the HTML is sent as language_output.

  1. 让我们先在工作目录的根目录中创建名为 translate.py 的文件。Let's start by creating a file called translate.py in the root of your working directory.
  2. 接下来,将以下代码添加到 translate.pyNext, add this code to translate.py. 此函数采用两个参数:text_inputlanguage_outputThis function takes two arguments: text_input and language_output.
    import os, requests, uuid, json
    
    # Don't forget to replace with your Cog Services subscription key!
    # If you prefer to use environment variables, see Extra Credit for more info.
    subscription_key = 'YOUR_TRANSLATOR_TEXT_SUBSCRIPTION_KEY'
    
    # Our Flask route will supply two arguments: text_input and language_output.
    # When the translate text button is pressed in our Flask app, the Ajax request
    # will grab these values from our web app, and use them in the request.
    # See main.js for Ajax calls.
    def get_translation(text_input, language_output):
        base_url = 'https://api.cognitive.microsofttranslator.com'
        path = '/translate?api-version=3.0'
        params = '&to=' + language_output
        constructed_url = base_url + path + params
    
        headers = {
            'Ocp-Apim-Subscription-Key': subscription_key,
            'Content-type': 'application/json',
            'X-ClientTraceId': str(uuid.uuid4())
        }
    
        # You can pass more than one object in body.
        body = [{
            'text' : text_input
        }]
        response = requests.post(constructed_url, headers=headers, json=body)
        return response.json()
    
  3. 添加文本翻译订阅密钥并保存。Add your Translator Text subscription key and save.

将路由添加到 app.pyAdd a route to app.py

接下来,需要在 Flask 应用中创建一个用于调用 translate.py 的路由。Next, you'll need to create a route in your Flask app that calls translate.py. 每当用户在该应用中按下翻译按钮时,就会调用此路由。This route will be called each time a user presses the translate button in your app.

对于此应用,路由将接受 POST 请求。For this app, your route is going to accept POST requests. 这是因为,该函数需要提供所要翻译的文本,以及翻译的输出语言。This is because the function expects the text to translate and an output language for the translation.

Flask 会提供帮助器函数来帮助分析和管理每个请求。Flask provides helper functions to help you parse and manage each request. 在提供的代码中,get_json()POST 请求返回 JSON 形式的数据。In the code provided, get_json() returns the data from the POST request as JSON. 然后,使用 data['text']data['to'] 将文本和输出语言值传递给 translate.py 中的 get_translation() 函数。Then using data['text'] and data['to'], the text and output language values are passed to get_translation() function available from translate.py. 最后一步是返回 JSON 形式的响应,因为需要在 Web 应用中显示此数据。The last step is to return the response as JSON, since you'll need to display this data in your web app.

在以下部分,为情绪分析和语音合成创建路由时需要重复此过程。In the following sections, you'll repeat this process as you create routes for sentiment analysis and speech synthesis.

  1. 打开 app.py,在 app.py 的顶部找到 import 语句,并添加以下行:Open app.py and locate the import statement at the top of app.py and add the following line:

    import translate
    

    现在,我们的 Flask 应用可以使用通过 translate.py 提供的方法。Now our Flask app can use the method available via translate.py.

  2. 将以下代码复制到 app.py 的末尾并保存:Copy this code to the end of app.py and save:

    @app.route('/translate-text', methods=['POST'])
    def translate_text():
        data = request.get_json()
        text_input = data['text']
        translation_output = data['to']
        response = translate.get_translation(text_input, translation_output)
        return jsonify(response)
    

更新 index.htmlUpdate index.html

创建用于翻译文本的函数,并在 Flask 应用中添加一个用于调用该函数的路由后,下一步是开始生成应用的 HTML。Now that you have a function to translate text, and a route in your Flask app to call it, the next step is to start building the HTML for your app. 以下 HTML 的作用是:The HTML below does a few things:

  • 提供一个文本区域,让用户输入要翻译的文本。Provides a text area where users can input text to translate.
  • 包含一个语言选择器。Includes a language selector.
  • 包含 HTML 元素用于呈现检测到的语言,以及翻译期间返回的置信度评分。Includes HTML elements to render the detected language and confidence scores returned during translation.
  • 提供一个只读的文本区域用于显示翻译输出。Provides a read-only text area where the translation output is displayed.
  • 包含稍后要在本教程中添加到此文件的情绪分析和语音合成代码的占位符。Includes placeholders for sentiment analysis and speech synthesis code that you'll add to this file later in the tutorial.

让我们更新 index.htmlLet's update index.html.

  1. 打开 index.html 并找到以下代码注释:Open index.html and locate these code comments:

    <!-- HTML provided in the following sections goes here. -->
    
    <!-- End -->
    
  2. 将代码注释替换为以下 HTML 块:Replace the code comments with this HTML block:

    <div class="row">
      <div class="col">
        <form>
          <!-- Enter text to translate. -->
          <div class="form-group">
            <label for="text-to-translate"><strong>Enter the text you'd like to translate:</strong></label>
            <textarea class="form-control" id="text-to-translate" rows="5"></textarea>
          </div>
          <!-- Select output language. -->
          <div class="form-group">
            <label for="select-language"><strong>Translate to:</strong></label>
            <select class="form-control" id="select-language">
              <option value="ar">Arabic</option>
              <option value="ca">Catalan</option>
              <option value="zh-Hans">Chinese (Simplified)</option>
              <option value="zh-Hant">Chinese (Traditional)</option>
              <option value="hr">Croatian</option>
              <option value="en">English</option>
              <option value="fr">French</option>
              <option value="de">German</option>
              <option value="el">Greek</option>
              <option value="he">Hebrew</option>
              <option value="hi">Hindi</option>
              <option value="it">Italian</option>
              <option value="ja">Japanese</option>
              <option value="ko">Korean</option>
              <option value="pt">Portuguese</option>
              <option value="ru">Russian</option>
              <option value="es">Spanish</option>
              <option value="th">Thai</option>
              <option value="tr">Turkish</option>
              <option value="vi">Vietnamese</option>
            </select>
          </div>
          <button type="submit" class="btn btn-primary mb-2" id="translate">Translate text</button></br>
          <div id="detected-language" style="display: none">
            <strong>Detected language:</strong> <span id="detected-language-result"></span><br />
            <strong>Detection confidence:</strong> <span id="confidence"></span><br /><br />
          </div>
    
          <!-- Start sentiment code-->
    
          <!-- End sentiment code -->
    
        </form>
      </div>
      <div class="col">
        <!-- Translated text returned by the Translate API is rendered here. -->
        <form>
          <div class="form-group" id="translator-text-response">
            <label for="translation-result"><strong>Translated text:</strong></label>
            <textarea readonly class="form-control" id="translation-result" rows="5"></textarea>
          </div>
    
          <!-- Start voice font selection code -->
    
          <!-- End voice font selection code -->
    
        </form>
    
        <!-- Add Speech Synthesis button and audio element -->
    
        <!-- End Speech Synthesis button -->
    
      </div>
    </div>
    

下一步是编写一些 Javascript 代码。The next step is to write some Javascript. 这是 HTML 与 Flask 路由之间的桥梁。This is the bridge between your HTML and Flask route.

创建 main.jsCreate main.js

main.js 文件是 HTML 与 Flask 路由之间的桥梁。The main.js file is the bridge between your HTML and Flask route. 应用将使用 jQuery、Ajax 和 XMLHttpRequest 的组合来呈现内容,并向 Flask 路由发出 POST 请求。Your app will use a combination of jQuery, Ajax, and XMLHttpRequest to render content, and make POST requests to your Flask routes.

在以下代码中,将使用 HTML 中的内容来构造对 Flask 路由发出的请求。In the code below, content from the HTML is used to construct a request to your Flask route. 具体而言,文本区域和语言选择器的内容将分配到变量,然后在请求中一起传递给 translate-textSpecifically, the contents of the text area and the language selector are assigned to variables, and then passed along in the request to translate-text.

然后,代码将循环访问响应,并使用翻译、检测到的语言和置信度评分更新 HTML。The code then iterates through the response, and updates the HTML with the translation, detected language, and confidence score.

  1. 在 IDE 中,在 static/scripts 目录中创建名为 main.js 的文件。From your IDE, create a file named main.js in the static/scripts directory.
  2. 将以下代码复制到 static/scripts/main.js 中:Copy this code into static/scripts/main.js:
    //Initiate jQuery on load.
    $(function() {
      //Translate text with flask route
      $("#translate").on("click", function(e) {
        e.preventDefault();
        var translateVal = document.getElementById("text-to-translate").value;
        var languageVal = document.getElementById("select-language").value;
        var translateRequest = { 'text': translateVal, 'to': languageVal }
    
        if (translateVal !== "") {
          $.ajax({
            url: '/translate-text',
            method: 'POST',
            headers: {
                'Content-Type':'application/json'
            },
            dataType: 'json',
            data: JSON.stringify(translateRequest),
            success: function(data) {
              for (var i = 0; i < data.length; i++) {
                document.getElementById("translation-result").textContent = data[i].translations[0].text;
                document.getElementById("detected-language-result").textContent = data[i].detectedLanguage.language;
                if (document.getElementById("detected-language-result").textContent !== ""){
                  document.getElementById("detected-language").style.display = "block";
                }
                document.getElementById("confidence").textContent = data[i].detectedLanguage.score;
              }
            }
          });
        };
      });
      // In the following sections, you'll add code for sentiment analysis and
      // speech synthesis here.
    })
    

测试翻译Test translation

让我们在应用中测试翻译。Let's test translation in the app.

flask run

导航到提供的服务器地址。Navigate to the provided server address. 在输入区域中键入文本,选择语言,然后按“翻译”。Type text into the input area, select a language, and press translate. 随后应会看到翻译结果。You should get a translation. 如果未看到翻译,请确保已添加订阅密钥。If it doesn't work, make sure that you've added your subscription key.

提示

如果所做的更改未显示,或者应用不按预期方式工作,请尝试清除缓存,或打开私密/隐匿窗口。If the changes you've made aren't showing up, or the app doesn't work the way you expect it to, try clearing your cache or opening a private/incognito window.

CTRL + C 终止应用,然后转到下一部分。Press CTRL + c to kill the app, then head to the next section.

分析情绪Analyze sentiment

文本分析 API 可用于执行情绪分析、从文本中提取关键短语,或检测源语言。The Text Analytics API can be used to perform sentiment analysis, extract key phrases from text, or detect the source language. 在此应用中,我们将使用情绪分析来确定提供的文本是积极的、中性的还是消极的。In this app, we're going to use sentiment analysis to determine if the provided text is positive, neutral, or negative. API 将返回介于 0 与 1 之间的数字评分。The API returns a numeric score between 0 and 1. 评分接近 1 代表积极的情绪,评分接近 0 代表消极的情绪。Scores close to 1 indicate positive sentiment, and scores close to 0 indicate negative sentiment.

在本部分,你将执行以下几项操作:In this section, you're going to do a few things:

  • 编写一些 Python 代码,以调用文本分析 API 来执行情绪分析并返回响应Write some Python to call the Text Analytics API to perform sentiment analysis and return a response
  • 创建一个 Flask 路由用于调用 Python 代码Create a Flask route to call your Python code
  • 使用情感评分区域和一个按钮更新 HTML,以执行分析Update the HTML with an area for sentiment scores, and a button to perform analysis
  • 编写 Javascript 代码,使用户能够通过 HTML 来与 Flask 应用交互Write Javascript that allows users to interact with your Flask app from the HTML

调用文本分析 APICall the Text Analytics API

让我们编写一个函数来调用文本分析 API。Let's write a function to call the Text Analytics API. 此函数采用四个参数:input_textinput_languageoutput_textoutput_languageThis function will take four arguments: input_text, input_language, output_text, and output_language. 每当用户在该应用中按下“运行情绪分析”按钮时,就会调用此函数。This function is called whenever a user presses the run sentiment analysis button in your app. 用户在文本区域和语言选择器中输入的数据,以及检测到的语言和翻译输出,将连同每个请求一起提供。Data provided by the user from the text area and language selector, as well as the detected language and translation output are provided with each request. 响应对象包含源文本和翻译结果的情绪评分。The response object includes sentiment scores for the source and translation. 在以下部分,你将编写一些 Javascript 代码来分析响应,并在应用中使用该响应。In the following sections, you're going to write some Javascript to parse the response and use it in your app. 现在,让我们重点了解如何调用文本分析 API。For now, let's focus on call the Text Analytics API.

  1. 在工作目录的根目录中创建名为 sentiment.py 的文件。Let's create a file called sentiment.py in the root of your working directory.
  2. 接下来,将以下代码添加到 sentiment.pyNext, add this code to sentiment.py.
    import os, requests, uuid, json
    
    # Don't forget to replace with your Cog Services subscription key!
    subscription_key = 'YOUR_TEXT_ANALYTICS_SUBSCRIPTION_KEY'
    
    # Our Flask route will supply four arguments: input_text, input_language,
    # output_text, output_language.
    # When the run sentiment analysis button is pressed in our Flask app,
    # the Ajax request will grab these values from our web app, and use them
    # in the request. See main.js for Ajax calls.
    
    def get_sentiment(input_text, input_language, output_text, output_language):
        base_url = 'https://westus.api.cognitive.microsoft.com/text/analytics'
        path = '/v2.0/sentiment'
        constructed_url = base_url + path
    
        headers = {
            'Ocp-Apim-Subscription-Key': subscription_key,
            'Content-type': 'application/json',
            'X-ClientTraceId': str(uuid.uuid4())
        }
    
        # You can pass more than one object in body.
        body = {
            'documents': [
                {
                    'language': input_language,
                    'id': '1',
                    'text': input_text
                },
                {
                    'language': output_language,
                    'id': '2',
                    'text': output_text
                }
            ]
        }
        response = requests.post(constructed_url, headers=headers, json=body)
        return response.json()
    
  3. 添加文本分析订阅密钥并保存。Add your Text Analytics subscription key and save.

将路由添加到 app.pyAdd a route to app.py

在 Flask 应用中创建一个用于调用 sentiment.py 的路由。Let's create a route in your Flask app that calls sentiment.py. 每当用户在该应用中按下“运行情绪分析”按钮时,就会调用此路由。This route will be called each time a user presses the run sentiment analysis button in your app. 与翻译路由一样,此路由将接受 POST 请求,因为该函数需要提供参数。Like the route for translation, this route is going to accept POST requests since the function expects arguments.

  1. 打开 app.py,在 app.py 的顶部找到 import 语句,并将其更新:Open app.py and locate the import statement at the top of app.py and update it:

    import translate, sentiment
    

    现在,我们的 Flask 应用可以使用通过 sentiment.py 提供的方法。Now our Flask app can use the method available via sentiment.py.

  2. 将以下代码复制到 app.py 的末尾并保存:Copy this code to the end of app.py and save:

    @app.route('/sentiment-analysis', methods=['POST'])
    def sentiment_analysis():
        data = request.get_json()
        input_text = data['inputText']
        input_lang = data['inputLanguage']
        output_text = data['outputText']
        output_lang =  data['outputLanguage']
        response = sentiment.get_sentiment(input_text, input_lang, output_text, output_lang)
        return jsonify(response)
    

更新 index.htmlUpdate index.html

创建用于运行情绪分析的函数,并在 Flask 应用中添加一个用于调用该函数的路由后,下一步是开始编写应用的 HTML。Now that you have a function to run sentiment analysis, and a route in your Flask app to call it, the next step is to start writing the HTML for your app. 以下 HTML 的作用是:The HTML below does a few things:

  • 将一个用于运行情绪分析的按钮添加到应用Adds a button to your app to run sentiment analysis
  • 添加一个用于解释情绪评分的元素Adds an element that explains sentiment scoring
  • 添加一个用于显示情绪评分的元素Adds an element to display the sentiment scores
  1. 打开 index.html 并找到以下代码注释:Open index.html and locate these code comments:

    <!-- Start sentiment code-->
    
    <!-- End sentiment code -->
    
  2. 将代码注释替换为以下 HTML 块:Replace the code comments with this HTML block:

    <button type="submit" class="btn btn-primary mb-2" id="sentiment-analysis">Run sentiment analysis</button></br>
    <div id="sentiment" style="display: none">
       <p>Sentiment scores are provided on a 1 point scale. The closer the sentiment score is to 1, indicates positive sentiment. The closer it is to 0, indicates negative sentiment.</p>
       <strong>Sentiment score for input:</strong> <span id="input-sentiment"></span><br />
       <strong>Sentiment score for translation:</strong> <span id="translation-sentiment"></span>
    </div>
    

更新 main.jsUpdate main.js

在以下代码中,将使用 HTML 中的内容来构造对 Flask 路由发出的请求。In the code below, content from the HTML is used to construct a request to your Flask route. 具体而言,文本区域和语言选择器的内容将分配到变量,然后在请求中一起传递给 sentiment-analysis 路由。Specifically, the contents of the text area and the language selector are assigned to variables, and then passed along in the request to the sentiment-analysis route.

然后,代码将循环访问响应,并使用情绪评分更新 HTML。The code then iterates through the response, and updates the HTML with the sentiment scores.

  1. 在 IDE 中,在 static 目录中创建名为 main.js 的文件。From your IDE, create a file named main.js in the static directory.

  2. 将以下代码复制到 static/scripts/main.js 中:Copy this code into static/scripts/main.js:

    //Run sentinment analysis on input and translation.
    $("#sentiment-analysis").on("click", function(e) {
      e.preventDefault();
      var inputText = document.getElementById("text-to-translate").value;
      var inputLanguage = document.getElementById("detected-language-result").innerHTML;
      var outputText = document.getElementById("translation-result").value;
      var outputLanguage = document.getElementById("select-language").value;
    
      var sentimentRequest = { "inputText": inputText, "inputLanguage": inputLanguage, "outputText": outputText,  "outputLanguage": outputLanguage };
    
      if (inputText !== "") {
        $.ajax({
          url: "/sentiment-analysis",
          method: "POST",
          headers: {
              "Content-Type":"application/json"
          },
          dataType: "json",
          data: JSON.stringify(sentimentRequest),
          success: function(data) {
            for (var i = 0; i < data.documents.length; i++) {
              if (typeof data.documents[i] !== "undefined"){
                if (data.documents[i].id === "1") {
                  document.getElementById("input-sentiment").textContent = data.documents[i].score;
                }
                if (data.documents[i].id === "2") {
                  document.getElementById("translation-sentiment").textContent = data.documents[i].score;
                }
              }
            }
            for (var i = 0; i < data.errors.length; i++) {
              if (typeof data.errors[i] !== "undefined"){
                if (data.errors[i].id === "1") {
                  document.getElementById("input-sentiment").textContent = data.errors[i].message;
                }
                if (data.errors[i].id === "2") {
                  document.getElementById("translation-sentiment").textContent = data.errors[i].message;
                }
              }
            }
            if (document.getElementById("input-sentiment").textContent !== '' && document.getElementById("translation-sentiment").textContent !== ""){
              document.getElementById("sentiment").style.display = "block";
            }
          }
        });
      }
    });
    // In the next section, you'll add code for speech synthesis here.
    

测试情绪分析Test sentiment analysis

让我们在应用中测试情绪分析。Let's test sentiment analysis in the app.

flask run

导航到提供的服务器地址。Navigate to the provided server address. 在输入区域中键入文本,选择语言,然后按“翻译”。Type text into the input area, select a language, and press translate. 随后应会看到翻译结果。You should get a translation. 接下来,按下“运行情绪分析”按钮。Next, press the run sentiment analysis button. 随后应会看到两个评分。You should see two scores. 如果未看到翻译,请确保已添加订阅密钥。If it doesn't work, make sure that you've added your subscription key.

提示

如果所做的更改未显示,或者应用不按预期方式工作,请尝试清除缓存,或打开私密/隐匿窗口。If the changes you've made aren't showing up, or the app doesn't work the way you expect it to, try clearing your cache or opening a private/incognito window.

CTRL + C 终止应用,然后转到下一部分。Press CTRL + c to kill the app, then head to the next section.

将文本转换到语音Convert text-to-speech

应用可以使用文本转语音 API 将文本转换为类似于人类的自然合成语音。The Text-to-speech API enables your app to convert text into natural human-like synthesized speech. 该服务支持标准语音、神经语音和自定义语音。The service supports standard, neural, and custom voices. 我们的示例应用使用了少量的可用声音,有关完整语音列表,请参阅支持的语言Our sample app uses a handful of the available voices, for a full list, see supported languages.

在本部分,你将执行以下几项操作:In this section, you're going to do a few things:

  • 编写一些 Python 代码,以使用文本转语音 API 将文本转换为语音Write some Python to convert text-to-speech with the Text-to-speech API
  • 创建一个 Flask 路由用于调用 Python 代码Create a Flask route to call your Python code
  • 使用一个用于将文本转换为语音的按钮,以及一个用于播放音频的元素来更新 HTMLUpdate the HTML with a button to convert text-to-speech, and an element for audio playback
  • 编写 Javascript 代码,使用户能够与 Flask 应用交互Write Javascript that allows users to interact with your Flask app

调用文本转语音 APICall the Text-to-Speech API

让我们编写一个函数用于将文本转换为语音。Let's write a function to convert text-to-speech. 此函数采用两个参数:input_textvoice_fontThis function will take two arguments: input_text and voice_font. 每当用户在该应用中按下“将文本转换为语音”按钮时,就会调用此函数。This function is called whenever a user presses the convert text-to-speech button in your app. input_text是调用“翻译文本”后返回的翻译输出,voice_font 是语音字体选择器中的 HTML 值。input_text is the translation output returned by the call to translate text, voice_font is the value from the voice font selector in the HTML.

  1. 在工作目录的根目录中创建名为 synthesize.py 的文件。Let's create a file called synthesize.py in the root of your working directory.

  2. 接下来,将以下代码添加到 synthesize.pyNext, add this code to synthesize.py.

    import os, requests, time
    from xml.etree import ElementTree
    
    class TextToSpeech(object):
        def __init__(self, input_text, voice_font):
            subscription_key = 'YOUR_SPEECH_SERVICES_SUBSCRIPTION_KEY'
            self.subscription_key = subscription_key
            self.input_text = input_text
            self.voice_font = voice_font
            self.timestr = time.strftime('%Y%m%d-%H%M')
            self.access_token = None
    
        # This function performs the token exchange.
        def get_token(self):
            fetch_token_url = 'https://westus.api.cognitive.microsoft.com/sts/v1.0/issueToken'
            headers = {
                'Ocp-Apim-Subscription-Key': self.subscription_key
            }
            response = requests.post(fetch_token_url, headers=headers)
            self.access_token = str(response.text)
    
        # This function calls the TTS endpoint with the access token.
        def save_audio(self):
            base_url = 'https://westus.tts.speech.microsoft.com/'
            path = 'cognitiveservices/v1'
            constructed_url = base_url + path
            headers = {
                'Authorization': 'Bearer ' + self.access_token,
                'Content-Type': 'application/ssml+xml',
                'X-Microsoft-OutputFormat': 'riff-24khz-16bit-mono-pcm',
                'User-Agent': 'YOUR_RESOURCE_NAME',
            }
            # Build the SSML request with ElementTree
            xml_body = ElementTree.Element('speak', version='1.0')
            xml_body.set('{http://www.w3.org/XML/1998/namespace}lang', 'en-us')
            voice = ElementTree.SubElement(xml_body, 'voice')
            voice.set('{http://www.w3.org/XML/1998/namespace}lang', 'en-US')
            voice.set('name', 'Microsoft Server Speech Text to Speech Voice {}'.format(self.voice_font))
            voice.text = self.input_text
            # The body must be encoded as UTF-8 to handle non-ascii characters.
            body = ElementTree.tostring(xml_body, encoding="utf-8")
    
            #Send the request
            response = requests.post(constructed_url, headers=headers, data=body)
    
            # Write the response as a wav file for playback. The file is located
            # in the same directory where this sample is run.
            return response.content
    
  3. 添加语音服务订阅密钥并保存。Add your Speech Services subscription key and save.

将路由添加到 app.pyAdd a route to app.py

在 Flask 应用中创建一个用于调用 synthesize.py 的路由。Let's create a route in your Flask app that calls synthesize.py. 每当用户在该应用中按下“将文本转换为语音”按钮时,就会调用此路由。This route will be called each time a user presses the convert text-to-speech button in your app. 与翻译和情绪分析的路由一样,此路由将接受 POST 请求,因为该函数需要两个参数:要合成的文本,以及要播放的语音字体。Like the routes for translation and sentiment analysis, this route is going to accept POST requests since the function expects two arguments: the text to synthesize, and the voice font for playback.

  1. 打开 app.py,在 app.py 的顶部找到 import 语句,并将其更新:Open app.py and locate the import statement at the top of app.py and update it:

    import translate, sentiment, synthesize
    

    现在,我们的 Flask 应用可以使用通过 synthesize.py 提供的方法。Now our Flask app can use the method available via synthesize.py.

  2. 将以下代码复制到 app.py 的末尾并保存:Copy this code to the end of app.py and save:

    @app.route('/text-to-speech', methods=['POST'])
    def text_to_speech():
        data = request.get_json()
        text_input = data['text']
        voice_font = data['voice']
        tts = synthesize.TextToSpeech(text_input, voice_font)
        tts.get_token()
        audio_response = tts.save_audio()
        return audio_response
    

更新 index.htmlUpdate index.html

创建用于将文本转换为语音的函数,并在 Flask 应用中添加一个用于调用该函数的路由后,下一步是开始编写应用的 HTML。Now that you have a function to convert text-to-speech, and a route in your Flask app to call it, the next step is to start writing the HTML for your app. 以下 HTML 的作用是:The HTML below does a few things:

  • 提供语音选择下拉列表Provides a voice selection drop-down
  • 添加一个用于将文本转换为语音的按钮Adds a button to convert text-to-speech
  • 添加一个用于播放合成语音的音频元素Adds an audio element, which is used to play back the synthesized speech
  1. 打开 index.html 并找到以下代码注释:Open index.html and locate these code comments:

    <!-- Start voice font selection code -->
    
    <!-- End voice font selection code -->
    
  2. 将代码注释替换为以下 HTML 块:Replace the code comments with this HTML block:

    <div class="form-group">
      <label for="select-voice"><strong>Select voice font:</strong></label>
      <select class="form-control" id="select-voice">
        <option value="(ar-SA, Naayf)">Arabic | Male | Naayf</option>
        <option value="(ca-ES, HerenaRUS)">Catalan | Female | HerenaRUS</option>
        <option value="(zh-CN, HuihuiRUS)">Chinese (Mainland) | Female | HuihuiRUS</option>
        <option value="(zh-CN, Kangkang, Apollo)">Chinese (Mainland) | Male | Kangkang, Apollo</option>
        <option value="(zh-HK, Tracy, Apollo)">Chinese (Hong Kong)| Female | Tracy, Apollo</option>
        <option value="(zh-HK, Danny, Apollo)">Chinese (Hong Kong) | Male | Danny, Apollo</option>
        <option value="(zh-TW, Yating, Apollo)">Chinese (Taiwan)| Female | Yaiting, Apollo</option>
        <option value="(zh-TW, Zhiwei, Apollo)">Chinese (Taiwan) | Male | Zhiwei, Apollo</option>
        <option value="(hr-HR, Matej)">Croatian | Male | Matej</option>
        <option value="(en-US, Jessa24kRUS)">English (US) | Female | Jessa24kRUS</option>
        <option value="(en-US, Guy24kRUS)">English (US) | Male | Guy24kRUS</option>
        <option value="(en-IE, Sean)">English (IE) | Male | Sean</option>
        <option value="(fr-FR, Julie, Apollo)">French | Female | Julie, Apollo</option>
        <option value="(fr-FR, HortenseRUS)">French | Female | Julie, HortenseRUS</option>
        <option value="(fr-FR, Paul, Apollo)">French | Male | Paul, Apollo</option>
        <option value="(de-DE, Hedda)">German | Female | Hedda</option>
        <option value="(de-DE, HeddaRUS)">German | Female | HeddaRUS</option>
        <option value="(de-DE, Stefan, Apollo)">German | Male | Apollo</option>
        <option value="(el-GR, Stefanos)">Greek | Male | Stefanos</option>
        <option value="(he-IL, Asaf)">Hebrew (Isreal) | Male | Asaf</option>
        <option value="(hi-IN, Kalpana, Apollo)">Hindi | Female | Kalpana, Apollo</option>
        <option value="(hi-IN, Hemant)">Hindi | Male | Hemant</option>
        <option value="(it-IT, LuciaRUS)">Italian | Female | LuciaRUS</option>
        <option value="(it-IT, Cosimo, Apollo)">Italian | Male | Cosimo, Apollo</option>
        <option value="(ja-JP, Ichiro, Apollo)">Japanese | Male | Ichiro</option>
        <option value="(ja-JP, HarukaRUS)">Japanese | Female | HarukaRUS</option>
        <option value="(ko-KR, HeamiRUS)">Korean | Female | Haemi</option>
        <option value="(pt-BR, HeloisaRUS)">Portuguese (Brazil) | Female | HeloisaRUS</option>
        <option value="(pt-BR, Daniel, Apollo)">Portuguese (Brazil) | Male | Daniel, Apollo</option>
        <option value="(pt-PT, HeliaRUS)">Portuguese (Portugal) | Female | HeliaRUS</option>
        <option value="(ru-RU, Irina, Apollo)">Russian | Female | Irina, Apollo</option>
        <option value="(ru-RU, Pavel, Apollo)">Russian | Male | Pavel, Apollo</option>
        <option value="(ru-RU, EkaterinaRUS)">Russian | Female | EkaterinaRUS</option>
        <option value="(es-ES, Laura, Apollo)">Spanish | Female | Laura, Apollo</option>
        <option value="(es-ES, HelenaRUS)">Spanish | Female | HelenaRUS</option>
        <option value="(es-ES, Pablo, Apollo)">Spanish | Male | Pablo, Apollo</option>
        <option value="(th-TH, Pattara)">Thai | Male | Pattara</option>
        <option value="(tr-TR, SedaRUS)">Turkish | Female | SedaRUS</option>
        <option value="(vi-VN, An)">Vietnamese | Male | An</option>
      </select>
    </div>
    
  3. 接下来,找到以下代码注释:Next, locate these code comments:

    <!-- Add Speech Synthesis button and audio element -->
    
    <!-- End Speech Synthesis button -->
    
  4. 将代码注释替换为以下 HTML 块:Replace the code comments with this HTML block:

<button type="submit" class="btn btn-primary mb-2" id="text-to-speech">Convert text-to-speech</button>
<div id="audio-playback">
  <audio id="audio" controls>
    <source id="audio-source" type="audio/mpeg" />
  </audio>
</div>
  1. 请务必保存已完成的工作。Make sure to save your work.

更新 main.jsUpdate main.js

在以下代码中,将使用 HTML 中的内容来构造对 Flask 路由发出的请求。In the code below, content from the HTML is used to construct a request to your Flask route. 具体而言,翻译和语音字体将分配到变量,然后在请求中一起传递给 text-to-speech 路由。Specifically, the translation and the voice font are assigned to variables, and then passed along in the request to the text-to-speech route.

然后,代码将循环访问响应,并使用情绪评分更新 HTML。The code then iterates through the response, and updates the HTML with the sentiment scores.

  1. 在 IDE 中,在 static 目录中创建名为 main.js 的文件。From your IDE, create a file named main.js in the static directory.
  2. 将以下代码复制到 static/scripts/main.js 中:Copy this code into static/scripts/main.js:
    // Convert text-to-speech
    $("#text-to-speech").on("click", function(e) {
      e.preventDefault();
      var ttsInput = document.getElementById("translation-result").value;
      var ttsVoice = document.getElementById("select-voice").value;
      var ttsRequest = { 'text': ttsInput, 'voice': ttsVoice }
    
      var xhr = new XMLHttpRequest();
      xhr.open("post", "/text-to-speech", true);
      xhr.setRequestHeader("Content-Type", "application/json");
      xhr.responseType = "blob";
      xhr.onload = function(evt){
        if (xhr.status === 200) {
          audioBlob = new Blob([xhr.response], {type: "audio/mpeg"});
          audioURL = URL.createObjectURL(audioBlob);
          if (audioURL.length > 5){
            var audio = document.getElementById("audio");
            var source = document.getElementById("audio-source");
            source.src = audioURL;
            audio.load();
            audio.play();
          }else{
            console.log("An error occurred getting and playing the audio.")
          }
        }
      }
      xhr.send(JSON.stringify(ttsRequest));
    });
    // Code for automatic language selection goes here.
    
  3. 即将完成。You're almost done. 要做的最后一件事是在 main.js 中添加一些代码,以根据选择的翻译语言自动选择语音字体。The last thing you're going to do is add some code to main.js to automatically select a voice font based on the language selected for translation. 将以下代码块添加到 main.jsAdd this code block to main.js:
    // Automatic voice font selection based on translation output.
    $('select[id="select-language"]').change(function(e) {
      if ($(this).val() == "ar"){
        document.getElementById("select-voice").value = "(ar-SA, Naayf)";
      }
      if ($(this).val() == "ca"){
        document.getElementById("select-voice").value = "(ca-ES, HerenaRUS)";
      }
      if ($(this).val() == "zh-Hans"){
        document.getElementById("select-voice").value = "(zh-HK, Tracy, Apollo)";
      }
      if ($(this).val() == "zh-Hant"){
        document.getElementById("select-voice").value = "(zh-HK, Tracy, Apollo)";
      }
      if ($(this).val() == "hr"){
        document.getElementById("select-voice").value = "(hr-HR, Matej)";
      }
      if ($(this).val() == "en"){
        document.getElementById("select-voice").value = "(en-US, Jessa24kRUS)";
      }
      if ($(this).val() == "fr"){
        document.getElementById("select-voice").value = "(fr-FR, HortenseRUS)";
      }
      if ($(this).val() == "de"){
        document.getElementById("select-voice").value = "(de-DE, HeddaRUS)";
      }
      if ($(this).val() == "el"){
        document.getElementById("select-voice").value = "(el-GR, Stefanos)";
      }
      if ($(this).val() == "he"){
        document.getElementById("select-voice").value = "(he-IL, Asaf)";
      }
      if ($(this).val() == "hi"){
        document.getElementById("select-voice").value = "(hi-IN, Kalpana, Apollo)";
      }
      if ($(this).val() == "it"){
        document.getElementById("select-voice").value = "(it-IT, LuciaRUS)";
      }
      if ($(this).val() == "ja"){
        document.getElementById("select-voice").value = "(ja-JP, HarukaRUS)";
      }
      if ($(this).val() == "ko"){
        document.getElementById("select-voice").value = "(ko-KR, HeamiRUS)";
      }
      if ($(this).val() == "pt"){
        document.getElementById("select-voice").value = "(pt-BR, HeloisaRUS)";
      }
      if ($(this).val() == "ru"){
        document.getElementById("select-voice").value = "(ru-RU, EkaterinaRUS)";
      }
      if ($(this).val() == "es"){
        document.getElementById("select-voice").value = "(es-ES, HelenaRUS)";
      }
      if ($(this).val() == "th"){
        document.getElementById("select-voice").value = "(th-TH, Pattara)";
      }
      if ($(this).val() == "tr"){
        document.getElementById("select-voice").value = "(tr-TR, SedaRUS)";
      }
      if ($(this).val() == "vi"){
        document.getElementById("select-voice").value = "(vi-VN, An)";
      }
    });
    

测试应用Test your app

让我们在应用中测试语音合成。Let's test speech synthesis in the app.

flask run

导航到提供的服务器地址。Navigate to the provided server address. 在输入区域中键入文本,选择语言,然后按“翻译”。Type text into the input area, select a language, and press translate. 随后应会看到翻译结果。You should get a translation. 接下来,选择一个语音,然后按下“将文本转换为语音”按钮。Next, select a voice, then press the convert text-to-speech button. 翻译结果应以合成语音的形式播放。the translation should be played back as synthesized speech. 如果未看到翻译,请确保已添加订阅密钥。If it doesn't work, make sure that you've added your subscription key.

提示

如果所做的更改未显示,或者应用不按预期方式工作,请尝试清除缓存,或打开私密/隐匿窗口。If the changes you've made aren't showing up, or the app doesn't work the way you expect it to, try clearing your cache or opening a private/incognito window.

好了,现已创建一个可以执行翻译、分析情绪和合成语音的正常运行的应用。That's it, you have a working app that performs translations, analyzes sentiment, and synthesized speech. 请按 CTRL + C 终止该应用。Press CTRL + c to kill the app. 请务必查看其他 Azure 认知服务Be sure to check out the other Azure Cognitive Services.

获取源代码Get the source code

此项目的源代码已在 GitHub 中提供。The source code for this project is available on GitHub.

后续步骤Next steps