Machine Learning API の統合

機械学習 API の統合

この Codelab について

subject最終更新: 6月 30, 2021
account_circle作成者: Torry 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 を忘れないようにしてください。プロジェクト ID はすべての Google Cloud プロジェクトを通じて一意の名前にする必要があります(上記の名前はすでに使用されているので使用できません)。以降、このコードラボでは PROJECT_ID と呼びます。

  1. 次に、Google Cloud リソースを使用するために、Cloud Console で課金を有効にする必要があります。

このコードラボを実行しても、費用はほとんどかからないはずです。このチュートリアル以外で請求が発生しないように、リソースのシャットダウン方法を説明する「クリーンアップ」セクションの手順に従うようにしてください。Google Cloud の新規ユーザーは、300 米ドルの無料トライアル プログラムをご利用いただけます。

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、Cloud Translation、Cloud Natural Language API を有効にします

Cloud Shell

Google Cloud Shell は、Cloud 内で動作するコマンドライン環境です。この Debian ベースの仮想マシンには、必要な開発ツール(gcloudbqgit など)がすべて揃っており、永続的な 5 GB のホーム ディレクトリが用意されています。Cloud Shell を使用して、機械学習 API に対するリクエストを作成します。

Cloud Shell の使用を開始するには、ヘッダーバーの右上の「Google Cloud Shell をアクティブにする」スクリーンショット 2015-06-08 5.30.32 PM.pngアイコンをクリックします。

24ef50000ca737a4.png

コンソールの下部の新しいフレーム内で Cloud Shell セッションが開き、コマンドライン プロンプトが表示されます。user@project:~$ プロンプトが表示されるまで待ちます。

省略可: コードエディタ

コマンドラインでの都合に合わせて、Cloud Shell バーの右上にある [b885bf07bc1b02e5.pngCode Editor を起動] アイコンをクリックします。

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 には役に立つため、入手しましょう。1 つの方法は、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 はおすすめです。ぜひご利用ください。trantrane.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() に移動し、encodingsampe_hertz_rate の設定を RecognitionConfig() から削除します。tr-ostrich.wav はトルコ語の音声録音であるため、言語設定を「tr-TR&#39」に変更します。

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

ここで、speech2text.py を再度実行します。音声が分析されるため、出力はトルコ語テキストになります。https://storage.googleapis.com/cloud-samples-data/ml-api-codelab/tr-ostrich.wav

どうなっているのですか?

Google Cloud Storage 上の音声ファイルの場所である gs://cloud-samples-data/ml-api-codelab/tr-ostrich.wavspeech2text.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 は望ましい構造です。snippet.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 '你有沒有帶外套'

訳文は「ジャケットを着ていますか?」です。

どうなっているのですか?

translate.py に 3 つの引数を渡しました。

  • translate-text は実行する translate_text() 関数を選択する
  • entarget として translate_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 には、これを行うコードが含まれているようです。snippet.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 ステートメント

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 にあります。次の 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

検出された各項目に対して、コードには「&」と「&」の両方が含まれます。この例では、「&」は「ボール」です。

参考: もっと試してみる

オーディオ ファイルと画像ファイルのその他の場所は次のとおりです。

8. お疲れさまでした

音声サンプルが、指定された画像について話しているかどうかを判断するために、4 つの機械学習 API を調べて統合しました。このパイプラインには他にも多くの改善の余地があるため、これはほんの始まりにすぎません。

学習した内容

  • Cloud Vision API にリクエストを送信する
  • Cloud Speech-to-Text API にリクエストを送信する
  • Cloud Translation API にリクエストを送信する
  • Cloud Natural Language API にリクエストを送信する
  • 上記のすべての API を併用する

次のステップ