整合機器學習 API

整合機器學習 API

程式碼研究室簡介

subject上次更新時間:6月 30, 2021
account_circle作者:Torry Yang

1. 總覽

本程式碼研究室將為您快速介紹幾個機器學習 API。您將會使用:

  • Cloud Vision 可瞭解映像檔的內容
  • Cloud Speech-to-Text 將音訊轉錄為文字
  • Cloud Translation 可將任意字串翻譯成任何支援的語言
  • Cloud Natural Language 能從文字中擷取資訊

建構項目

您將會建構一個比較音訊影像的管道,並判斷兩者之間的關聯性。以下簡單介紹貴公司如何達成這個目標:

e6a57e5def315116.jpeg

課程內容

  • 如何使用 Vision、Speech-to-Text、Translation 和 Natural Language API
  • 哪裡可以找到程式碼範例

軟硬體需求

2. 設定和需求

自行調整環境設定

  1. 登入 Cloud Console,建立新專案或重複使用現有專案。如果您還沒有 Gmail 或 Google Workspace 帳戶,請先建立帳戶

96a9c957bc475304.png

b9a10ebdf5b5a448.png

a1e3c01a38fa61c2.png

提醒您,專案編號是所有 Google Cloud 專案的不重複名稱 (使用上述名稱後就無法使用,敬請見諒!)此程式碼研究室稍後將稱為 PROJECT_ID

  1. 接著,您必須在 Cloud Console 中啟用計費功能,才能使用 Google Cloud 資源。

透過這個程式碼研究室執行成本應該不會太高。請務必遵循「清除所用資源」一節中的操作說明,瞭解如何關閉資源,這樣就不會產生本教學課程以外的費用。Google Cloud 新用戶可享有 $300 美元的免費試用計畫。

啟用 API

您可以按一下這個連結來啟用所有必要的 API。完成上述操作後,請忽略設定驗證程序的操作說明;我們稍後就會完成設定。或者,您也可以個別啟用各項 API。方法是按一下畫面左上角的選單圖示。

2bfc27ef9ba2ec7d.png

從下拉式選單中選取 [API 與服務],然後按一下 [資訊主頁]

a9546a22581facd5.png

按一下 [啟用 API 和服務]

eae7ff043d13a35.png

然後在搜尋框中搜尋「visiont」。按一下 [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 等),並提供永久的 5GB 主目錄。我們會使用 Cloud Shell 建立對機器學習 API 的要求。

如要開始使用 Cloud Shell,請按一下標題列右上角的「啟用 Google Cloud Shell」圖示 Screen Shot 2015-06-08 at 5.30.32 PM.png

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

這是怎麼回事?

您已將 2 個引數傳送至 vision.py

  • 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」似乎是很好的入門起點,歡迎參考。複製 transbooke.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_rateRecognitionConfig()設定中的設定。當您在上車時,將語言代碼改成「tr-TR&#39」;因為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 用戶端

您必須有 Python 用戶端才能使用 Cloud Translation。如要安裝,請在 Cloud Shell 中輸入下列指令:

sudo pip install --upgrade google-cloud-translate

我們來試試

現在,請參考 Cloud Translation 的程式碼範例。本程式碼研究室的目的是將文字翻譯成英文。「snippets.py」的外觀符合你的需求。複製 snippetspy.content 並在 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 '你有沒有帶外套'

譯文應該是「你有外套系統嗎?」。

異動內容

您已將 3 個引數傳送至 translate.py

  • translate-text:選取要執行的 translate_text() 函式
  • en 會傳入 targettranslate_text() 並用於指定要翻譯的語言
  • “臺北市/外帶&&33; 是要翻譯的字串,並以文字的形式傳遞給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似乎含有可執行這項操作的代碼。複製 snippetspy.content 並在 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 應將「自行車」視為實體。實體可以是正確名詞 (公眾人物、地標等) 或通用名詞 (餐廳、體育場等)。

異動內容

您已將 2 個引數傳送至 natural_language.py

  • 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

匯入對帳單

取消註解,然後將匯入陳述式移到頂端。請注意,正在匯入 speech.typeslanguage.types。這會導致衝突,因此請直接移除它們,將 transcribe_gcs() 中的 typesentities_text() 分別變更為 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

找到的每個項目,程式碼都應輸出「“音訊和影像 」皆包含:「&tt;」。在上面的範例中,音訊和圖片都含有「“&tt;{/1}」。

額外好處:再試一次

請試試其他的音訊檔案和圖片檔案位置。

8. 恭喜!

您探索並整合了四個機器學習 API,以判斷語音樣本是否在討論所提供的圖片。這只是第一步,因為還有許多管道有待改善!

適用範圍

  • 向 Cloud Vision API 發出要求
  • 向 Cloud Speech-to-Text API 發出要求
  • 向 Cloud Translation API 發出要求
  • 向 Cloud Natural Language API 發出要求
  • 同時使用上述所有 API

後續步驟