集成机器学习 API

集成机器学习 API

关于此 Codelab

subject上次更新时间:6月 30, 2021
account_circleTorry Yang 编写

1. 概览

在此 Codelab 中,您可以快速了解一些机器学习 API。您将使用:

  • Cloud Vision:用于了解图片的内容
  • Cloud Speech-to-Text,用于将音频转录为文字
  • Cloud Translation,可将任意字符串翻译成受支持的任何语言
  • Cloud Natural Language,用于从文本中提取信息

构建内容

您将构建一个流水线,将录音图片进行比较,并确定它们彼此之间的相关性。您可以先了解一下实现这一目标的方法:

e6a57e5def315116.jpeg

学习内容

  • 如何使用 Vision API、Speech-to-Text API、Translation API 和 Natural Language API
  • 在哪里可以找到代码示例

您需要满足的条件

  • 一个浏览器,例如 ChromeFirefox
  • 具备 Python 基础知识

2. 设置和要求

自定进度的环境设置

  1. 登录 Cloud Console,然后创建一个新项目或重复使用现有项目。如果您还没有 Gmail 或 Google Workspace 帐号,则必须创建一个

96a9c957bc475304.png

b9a10ebdf5b5a448.png

a1e3c01a38fa61c2.png

请记住项目 ID,它在所有 Google Cloud 项目中都是唯一的名称(上述名称已被占用,您无法使用,抱歉!)。它稍后将在此 Codelab 中被称为 PROJECT_ID

  1. 接下来,您需要在 Cloud Console 中启用结算功能才能使用 Google Cloud 资源。

运行此 Codelab 应该不会产生太多的费用(如果有费用的话)。请务必按照“清理”部分中的说明操作,了解如何关闭资源,以免在本教程结束后继续产生费用。Google Cloud 的新用户有资格参与 $300 USD 免费试用计划。

启用 API

您可以点击此链接以启用所有必需的 API。完成上述操作后,请忽略有关设置身份验证的说明;我们很快就会完成。或者,您也可以单独启用每个 API。为此,请点击屏幕左上角的菜单图标。

2bfc27ef9ba2ec7d.png

从下拉菜单中选择 API 和服务,然后点击“信息中心”

a9546a22581facd5.png

点击启用 API 和服务

eae7ff043d13a35.png

然后,在搜索框中搜索“vision”。点击 Google Cloud Vision API

a47893f36372ae2f.png

点击启用以启用 Cloud Vision API:

a24fd082a22030ad.png

请稍等片刻,以将其启用。启用之后,您将看到以下内容:

633e58cbde1b74c6.png

重复上述过程,以启用 Cloud Speech API、Cloud Translation API 和 Cloud Natural Language API

Cloud Shell

Google Cloud Shell 是在云端运行的命令行环境。这是一款基于 Debian 的虚拟机,其中预装了您需要的所有开发工具(gcloudbqgit 等),并提供 5GB 的永久性主目录。我们将使用 Cloud Shell 创建对机器学习 API 的请求。

如需开始使用 Cloud Shell,请点击标题栏右上角的“激活 Google Cloud Shell”图标 2015 年 6 月 8 日下午 5.30.32 的屏幕截图

24ef50000ca737a4.png

一个 Cloud Shell 会话随即会在控制台底部的新框内打开,并显示命令行提示符。等待 user@project:~$ 提示出现。

可选:代码编辑器

根据您对命令行的习惯,您可能需要点击 Cloud Shell 栏右上角的“启动代码编辑器”图标 b885bf07bc1b02e5.png

de00be9278baf7b8.png

服务帐号

您需要使用服务帐号进行身份验证。要创建一个服务帐号,请将 [NAME] 替换为所需的服务帐号名称,并在 Cloud Shell 中运行以下命令:

gcloud iam service-accounts create [NAME]

现在,您需要生成密钥才能使用该服务帐号。将 [FILE_NAME] 替换为所需的密钥名称,将 [NAME] 替换为上面的服务帐号名称,并将 [PROJECT_ID] 替换为您的项目 ID。以下命令将创建密钥并以 [FILE_NAME].json 格式下载:

gcloud iam service-accounts keys create [FILE_NAME].json --iam-account [NAME]@[PROJECT_ID].iam.gserviceaccount.com

要使用服务帐号,您必须将变量 GOOGLE_APPLICATION_CREDENTIALS 设置为密钥的路径。为此,请在替换 [PATH_TO_FILE] 和 [FILE_NAME] 之后运行以下命令:

export GOOGLE_APPLICATION_CREDENTIALS=[PATH_TO_FILE]/[FILE_NAME].json

3. Cloud Vision

Python 客户端

您需要 Cloud Vision 的 Python 客户端。如需安装,请在 Cloud Shell 中输入以下内容:

pip install --upgrade google-cloud-vision --user

我们来试试看

我们来看一下 Cloud Vision API 的代码示例。我们想了解指定图片中的内容。detect.py 似乎很有用,所以我们来看一下。一种方法是复制 detect.py 的内容,在 Cloud Shell 中创建一个名为 vision.py 的新文件,并将所有代码粘贴到 vision.py 中。您可以在 Cloud Shell 代码编辑器中手动执行此操作,也可以在 Cloud Shell 中运行此 curl 命令:

curl https://raw.githubusercontent.com/GoogleCloudPlatform/python-docs-samples/master/vision/cloud-client/detect/detect.py -o vision.py

完成此操作后,通过在 Cloud Shell 中运行以下命令来使用该 API:

python vision.py labels-uri gs://cloud-samples-data/ml-api-codelab/birds.jpg

您应该会看到有关鸟类和鸵鸟的输出,因为对图片进行了分析:https://storage.googleapis.com/cloud-samples-data/ml-api-codelab/birds.jpg

这是怎么回事?

您向 vision.py 传递了 2 个参数:

  • labels-uri 选择要运行的 detect_labels_uri() 函数
  • gs://cloud-samples-data/ml-api-codelab/birds.jpg 是 Google Cloud Storage 中的图片位置,作为 uri 传递给 detect_labels_uri()

下面我们来详细了解一下 detect_labels_uri()。请注意已插入的其他注释。

def detect_labels_uri(uri):
   
"""Detects labels in the file located in Google Cloud Storage or on the
    Web."""

   
# relevant import from above
   
# from google.cloud import vision

   
# create ImageAnnotatorClient object
    client
= vision.ImageAnnotatorClient()

   
# create Image object
    image
= vision.types.Image()

   
# specify location of image
    image
.source.image_uri = uri

   
# get label_detection response by passing image to client
    response
= client.label_detection(image=image)

   
# get label_annotations portion of response
    labels
= response.label_annotations
   
print('Labels:')

   
for label in labels:
       
# print the label descriptions
       
print(label.description)

4. Cloud Speech-to-Text

Python 客户端

您需要 Cloud Speech-to-Text 的 Python 客户端。如需安装,请在 Cloud Shell 中输入以下内容:

sudo pip install --upgrade google-cloud-speech

我们来试试看

请查看 Cloud Speech-to-Text 代码示例。我们想要转录语音音频。transcribe.py 似乎是个不错的入手点,让我们开始使用吧。复制 trantran.py 的内容,在 Cloud Shell 中创建一个名为 speech2text.py 的新文件,并将所有代码粘贴到 speech2text.py 中。您可以在 Cloud Shell 代码编辑器中手动执行此操作,也可以在 Cloud Shell 中运行此 curl 命令:

curl https://raw.githubusercontent.com/GoogleCloudPlatform/python-docs-samples/master/speech/cloud-client/transcribe.py -o speech2text.py

完成此操作后,通过在 Cloud Shell 中运行以下命令来使用该 API:

python speech2text.py gs://cloud-samples-data/ml-api-codelab/tr-ostrich.wav

出现有关编码错误和采样率 赫兹率的错误。别担心,请转到代码中的 transcribe_gcs() 并从 RecognitionConfig() 中删除 encodingsampe_hertz_rate 设置。使用英语时,请将语言代码更改为“tr-TR'”,因为tr-ostrich.wav是土耳其语的语音录音。

config = types.RecognitionConfig(language_code='tr-TR')

现在,再次运行 speech2text.py。输出应该为一些土耳其语文本,因为这是音频分析:https://storage.googleapis.com/cloud-samples-data/ml-api-codelab/tr-ostrich.wav

发生了什么?

您已将 gs://cloud-samples-data/ml-api-codelab/tr-ostrich.wav(音频文件在 Google Cloud Storage 中的位置)传递给 speech2text.py,随后该文件以 gcs_uri 的形式传递到 transcribe_uri()

下面我们来详细了解一下修改后的 transcribe_uri()

def transcribe_gcs(gcs_uri):
   
"""Transcribes the audio file specified by the gcs_uri."""

   
from google.cloud import speech
   
# enums no longer used
   
# from google.cloud.speech import enums
   
from google.cloud.speech import types

   
# create ImageAnnotatorClient object
    client
= speech.SpeechClient()

   
# specify location of speech
    audio
= types.RecognitionAudio(uri=gcs_uri)

   
# set language to Turkish
   
# removed encoding and sample_rate_hertz
    config
= types.RecognitionConfig(language_code='tr-TR')

   
# get response by passing config and audio settings to client
    response
= client.recognize(config, audio)

   
# Each result is for a consecutive portion of the audio. Iterate through
   
# them to get the transcripts for the entire audio file.
   
for result in response.results:
       
# The first alternative is the most likely one for this portion.
       
# get the transcript of the first alternative
       
print(u'Transcript: {}'.format(result.alternatives[0].transcript))

5. Cloud Translation

Python 客户端

您需要安装适用于 Cloud Translation 的 Python 客户端。如需进行安装,请在 Cloud Shell 中输入以下内容:

sudo pip install --upgrade google-cloud-translate

我们来试试看

现在,请查看 Cloud Translation 代码示例。在此 Codelab 中,我们希望将文本翻译成英语。snippets.py 看起来与我们需要的一样。复制 snippets.py 的内容,在 Cloud Shell 中创建一个名为 translate.py 的新文件,并将所有代码粘贴到 translate.py 中。您可以在 Cloud Shell 代码编辑器中手动执行此操作,也可以在 Cloud Shell 中运行此 curl 命令:

curl https://raw.githubusercontent.com/GoogleCloudPlatform/python-docs-samples/master/translate/cloud-client/snippets.py -o translate.py

完成此操作后,通过在 Cloud Shell 中运行以下命令来使用该 API:

python translate.py translate-text en '你有沒有帶外套'

翻译应为“Do you have a jacket?"”。

发生了什么?

您向 translate.py 传递了 3 个参数:

  • translate-text 选择要运行的 translate_text() 函数
  • en 作为 target 传递到 translate_text() 中,用于指定要翻译为哪种语言
  • ‘您有但带外外' 是要翻译的字符串,并作为 text 传递到 translate_text()

下面我们来详细了解一下 translate_text()。请注意已添加的评论。

def translate_text(target, text):
   
"""Translates text into the target language.

    Target must be an ISO 639-1 language code.
    See https://g.co/cloud/translate/v2/translate-reference#supported_languages
    """

   
# relevant imports from above
   
# from google.cloud import translate
   
# import six

   
# create Client object
    translate_client
= translate.Client()

   
# decode text if it's a binary type
   
# six is a python 2 and 3 compatibility library
   
if isinstance(text, six.binary_type):
        text
= text.decode('utf-8')

   
# get translation result by passing text and target language to client
   
# Text can also be a sequence of strings, in which case this method
   
# will return a sequence of results for each text.
    result
= translate_client.translate(text, target_language=target)

   
# print original text, translated text and detected original language
   
print(u'Text: {}'.format(result['input']))
   
print(u'Translation: {}'.format(result['translatedText']))
   
print(u'Detected source language: {}'.format(
        result
['detectedSourceLanguage']))

6. Cloud Natural Language

Python 客户端

您需要安装适用于 Cloud Natural Language 的 Python 客户端。如需安装,请在 Cloud Shell 中输入以下内容:

sudo pip install --upgrade google-cloud-language

我们来试试看

最后,我们来看一下 Cloud Natural Language API 的代码示例。我们要检测文本中的实体。snippets.py 似乎包含执行此操作的代码。复制 snippets.py 的内容,在 Cloud Shell 中创建一个名为 natural_language.py 的新文件,并将所有代码粘贴到 natural_language.py 中。您可以在 Cloud Shell 代码编辑器中手动执行此操作,也可以在 Cloud Shell 中运行此 curl 命令:

curl https://raw.githubusercontent.com/GoogleCloudPlatform/python-docs-samples/master/language/cloud-client/v1/snippets.py -o natural_language.py

完成此操作后,通过在 Cloud Shell 中运行以下命令来使用该 API:

python natural_language.py entities-text 'where did you leave my bike'

该 API 应将“自行车”标识为一个实体。实体可能是专有名词(公众人物、地标等)或普通名词(餐厅、体育场等)。

发生了什么?

您向 natural_language.py 传递了 2 个参数:

  • entities-text 用于选择要运行的 entities_text() 函数
  • ‘某从何处离开了我的自行车’,这是要分析实体的字符串,会作为文本传递到 entities_text()

下面我们来详细了解一下 entities_text()。注意已插入的新评论。

def entities_text(text):
   
"""Detects entities in the text."""
   
# relevant imports from above
   
# from google.cloud import language
   
# from google.cloud.language import enums
   
# from google.cloud.language import types
   
# import six

   
# create LanguageServiceClient object
    client
= language.LanguageServiceClient()

   
# decode text if it's a binary type
   
# six is a python 2 and 3 compatibility library
   
if isinstance(text, six.binary_type):
        text
= text.decode('utf-8')

   
# Instantiates a plain text document.
    document
= types.Document(
        content
=text,
        type
=enums.Document.Type.PLAIN_TEXT)

   
# Detects entities in the document. You can also analyze HTML with:
   
#   document.type == enums.Document.Type.HTML
    entities
= client.analyze_entities(document).entities

   
# entity types from enums.Entity.Type
    entity_type
= ('UNKNOWN', 'PERSON', 'LOCATION', 'ORGANIZATION',
                   
'EVENT', 'WORK_OF_ART', 'CONSUMER_GOOD', 'OTHER')

   
# print information for each entity found
   
for entity in entities:
       
print('=' * 20)
       
print(u'{:<16}: {}'.format('name', entity.name))
       
print(u'{:<16}: {}'.format('type', entity_type[entity.type]))
       
print(u'{:<16}: {}'.format('metadata', entity.metadata))
       
print(u'{:<16}: {}'.format('salience', entity.salience))
       
print(u'{:<16}: {}'.format('wikipedia_url',
              entity
.metadata.get('wikipedia_url', '-')))

7. 让我们把它们集成起来

我们来提醒一下自己构建什么。

e6a57e5def315116.jpeg

现在,我们将所有内容融会贯通。创建一个 solution.py 文件;复制上一步中的 detect_labels_uri()transcribe_gcs()translate_text()entities_text() 并将其粘贴到 solution.py 中。

导入语句

取消注释并将 import 语句移至顶部。请注意,正在导入 speech.typeslanguage.types。这将导致冲突,因此让我们将其移除,并将 transcribe_gcs()entities_text() 中的每个 types 分别更改为 speech.typeslanguage.types。您应留下以下字段:

from google.cloud import vision
from google.cloud import speech
from google.cloud import translate
from google.cloud import language
from google.cloud.language import enums
import six

退货结果

让函数返回结果而不是输出。您应该会看到类似下图的内容:

# import statements

def detect_labels_uri(uri):
   
# code

   
# we only need the label descriptions
    label_descriptions
= []
   
for label in labels:
        label_descriptions
.append(label.description)

   
return label_descriptions

def transcribe_gcs(gcs_uri):
   
# code

   
# naive assumption that audio file is short
   
return response.results[0].alternatives[0].transcript

def translate_text(target, text):
   
# code

   
# only interested in translated text
   
return result['translatedText']

def entities_text(text):
   
# code

   
# we only need the entity names
    entity_names
= []
   
for entity in entities:
        entity_names
.append(entity.name)

   
return entity_names

使用函数

完成所有这些艰苦的工作后,您就可以调用这些函数了。开始吧!以下是一个示例:

def compare_audio_to_image(audio, image):
   
"""Checks whether a speech audio is relevant to an image."""

   
# speech audio -> text
    transcription
= transcribe_gcs(audio)

   
# text of any language -> english text
    translation
= translate_text('en', transcription)

   
# text -> entities
    entities
= entities_text(translation)

   
# image -> labels
    labels
= detect_labels_uri(image)

   
# naive check for whether entities intersect with labels
    has_match
= False
   
for entity in entities:
       
if entity in labels:
           
# print result for each match
           
print('The audio and image both contain: {}'.format(entity))
            has_match
= True

   
# print if there are no matches
   
if not has_match:
       
print('The audio and image do not appear to be related.')

支持多种语言

我们之前已将土耳其语硬编码为 transcribe_gcs()。让我们更改一下设置,在 compare_audio_to_image() 中指定语言。需要进行以下更改:

def transcribe_gcs(language, gcs_uri):
   
...
    config
= speech.types.RecognitionConfig(language_code=language)
def compare_audio_to_image(language, audio, image):
    transcription
= transcribe_gcs(language, audio)

试试看

最终代码可以在此 GitHub 代码库solution.py 中找到。以下是用于获取此 ID 的 curl 命令:

curl https://raw.githubusercontent.com/googlecodelabs/integrating-ml-apis/master/solution.py -O

GitHub 上的版本包含 argparse,后者支持从命令行执行以下操作:

python solution.py tr-TR gs://cloud-samples-data/ml-api-codelab/tr-ball.wav gs://cloud-samples-data/ml-api-codelab/football.jpg

对于找到的每项内容,代码都应输出“音频和图片均包含:"”。在上面的示例中,应为“音频和图片均包含:ball”。

奖励:试试看

这里列出了更多可供尝试的音频和图片文件。

8. 恭喜!

您已探索并集成了四个机器学习 API,以确定语音示例是否正在讨论提供的图片。这仅仅是开始,因为还有更多方法可以让此流水线实现改进!

所学内容

  • 向 Cloud Vision API 发出请求
  • 向 Cloud Speech-to-Text API 发出请求
  • 向 Cloud Translation API 发出请求
  • 向 Cloud Natural Language API 发出请求
  • 结合使用上述所有 API

后续步骤