搭配 Python 使用 Speech-to-Text API

1. 總覽

9e7124a578332fed.png

開發人員只要使用 Speech-to-Text API,就能透過簡單好用的 API,運用強大的類神經網路模型,將音訊轉換為文字,支援超過 125 種語言和方言。

在本教學課程中,您將著重於使用 Python 搭配 Speech-to-Text API。

課程內容

  • 如何設定環境
  • 如何轉錄英文音訊檔案
  • 如何轉錄音訊檔案並取得字詞時間戳記
  • 如何轉錄不同語言的音訊檔案

軟硬體需求

  • 具備 Google Cloud 專案
  • ChromeFirefox 瀏覽器
  • 熟悉 Python

問卷調查

您會如何使用本教學課程?

僅閱讀 閱讀並完成練習

你對 Python 的使用體驗如何?

新手 中級 熟練

你對 Google Cloud 服務的體驗滿意嗎?

新手 中級 熟練

2. 設定和需求條件

自修實驗室環境設定

  1. 登入 Google Cloud 控制台,然後建立新專案或重複使用現有專案。如果沒有 Gmail 或 Google Workspace 帳戶,請先建立帳戶

fbef9caa1602edd0.png

a99b7ace416376c4.png

5e3ff691252acf41.png

  • 專案名稱是這個專案參與者的顯示名稱。這是 Google API 未使用的字元字串。你隨時可以更新。
  • 專案 ID 在所有 Google Cloud 專案中都是不重複的,而且設定後即無法變更。Cloud 控制台會自動產生專屬字串,通常您不需要在意該字串為何。在大多數程式碼研究室中,您需要參照專案 ID (通常標示為 PROJECT_ID)。如果您不喜歡產生的 ID,可以產生另一個隨機 ID。你也可以嘗試使用自己的名稱,看看是否可用。完成這個步驟後就無法變更,且專案期間會維持不變。
  • 請注意,有些 API 會使用第三個值,也就是「專案編號」。如要進一步瞭解這三種值,請參閱說明文件
  1. 接著,您需要在 Cloud 控制台中啟用帳單,才能使用 Cloud 資源/API。完成這個程式碼研究室的費用不高,甚至可能完全免費。如要關閉資源,避免在本教學課程結束後繼續產生費用,請刪除您建立的資源或專案。Google Cloud 新使用者可參加價值$300 美元的免費試用計畫。

啟動 Cloud Shell

雖然您可以透過筆電遠端操作 Google Cloud,但在本程式碼研究室中,您將使用 Cloud Shell,這是 Cloud 中執行的指令列環境。

啟用 Cloud Shell

  1. 在 Cloud 控制台,點選「啟用 Cloud Shell」 圖示 853e55310c205094.png

3c1dabeca90e44e5.png

如果您是首次啟動 Cloud Shell,系統會顯示中繼畫面,說明這個指令列環境。如果出現中繼畫面,請按一下「繼續」

9c92662c6a846a5c.png

佈建並連至 Cloud Shell 預計只需要幾分鐘。

9f0e51b578fecce5.png

這部虛擬機器已載入所有必要的開發工具,並提供永久的 5 GB 主目錄,而且可在 Google Cloud 運作,大幅提升網路效能並強化驗證功能。本程式碼研究室幾乎所有工作都可在瀏覽器上完成。

連至 Cloud Shell 後,您應該會看到驗證已完成,專案也已設為獲派的專案 ID。

  1. 在 Cloud Shell 中執行下列指令,確認您已通過驗證:
gcloud auth list

指令輸出

 Credentialed Accounts
ACTIVE  ACCOUNT
*       <my_account>@<my_domain.com>

To set the active account, run:
    $ gcloud config set account `ACCOUNT`
  1. 在 Cloud Shell 中執行下列指令,確認 gcloud 指令知道您的專案:
gcloud config list project

指令輸出

[core]
project = <PROJECT_ID>

如未設定,請輸入下列指令手動設定專案:

gcloud config set project <PROJECT_ID>

指令輸出

Updated property [core/project].

3. 環境設定

如要開始使用 Speech-to-Text API,請先在 Cloud Shell 中執行下列指令來啟用 API:

gcloud services enable speech.googleapis.com

畫面應如下所示:

Operation "operations/..." finished successfully.

現在您可以使用 Speech-to-Text API 了!

前往主目錄:

cd ~

建立 Python 虛擬環境,隔離依附元件:

virtualenv venv-speech

啟動虛擬環境:

source venv-speech/bin/activate

安裝 IPython 和 Speech-to-Text API 用戶端程式庫:

pip install ipython google-cloud-speech

畫面應如下所示:

...
Installing collected packages: ..., ipython, google-cloud-speech
Successfully installed ... google-cloud-speech-2.25.1 ...

現在,您可以使用 Speech-to-Text API 用戶端程式庫了!

在接下來的步驟中,您會使用名為 IPython 的互動式 Python 解譯器,這個解譯器已在先前的步驟中安裝。在 Cloud Shell 中執行 ipython,啟動工作階段:

ipython

畫面應如下所示:

Python 3.9.2 (default, Feb 28 2021, 17:03:44)
Type 'copyright', 'credits' or 'license' for more information
IPython 8.18.1 -- An enhanced Interactive Python. Type '?' for help.

In [1]:

您已準備好提出第一個要求...

4. 轉錄音訊檔案

在本節中,您將轉錄英文音訊檔案。

將下列程式碼複製到 IPython 工作階段:

from google.cloud import speech


def speech_to_text(
    config: speech.RecognitionConfig,
    audio: speech.RecognitionAudio,
) -> speech.RecognizeResponse:
    client = speech.SpeechClient()

    # Synchronous speech recognition request
    response = client.recognize(config=config, audio=audio)

    return response


def print_response(response: speech.RecognizeResponse):
    for result in response.results:
        print_result(result)


def print_result(result: speech.SpeechRecognitionResult):
    best_alternative = result.alternatives[0]
    print("-" * 80)
    print(f"language_code: {result.language_code}")
    print(f"transcript:    {best_alternative.transcript}")
    print(f"confidence:    {best_alternative.confidence:.0%}")
    

請花點時間研究程式碼,瞭解如何使用 recognize 用戶端程式庫方法轉錄音訊檔案。config 參數會指出如何處理要求,audio 參數則會指定要辨識的音訊資料。

傳送要求:

config = speech.RecognitionConfig(
    language_code="en",
)
audio = speech.RecognitionAudio(
    uri="gs://cloud-samples-data/speech/brooklyn_bridge.flac",
)

response = speech_to_text(config, audio)
print_response(response)

您應該會看到以下的輸出內容:

--------------------------------------------------------------------------------
language_code: en-us
transcript:    how old is the Brooklyn Bridge
confidence:    98%

更新設定以啟用自動標點,然後傳送新要求:

config.enable_automatic_punctuation = True

response = speech_to_text(config, audio)
print_response(response)

您應該會看到以下的輸出內容:

--------------------------------------------------------------------------------
language_code: en-us
transcript:    How old is the Brooklyn Bridge?
confidence:    98%

摘要

在這個步驟中,您已使用不同參數轉錄英文音訊檔案,並列印結果。進一步瞭解如何轉錄音訊檔案

5. 取得字詞時間戳記

Speech-to-Text 可以偵測轉錄音訊的時間偏移值 (時間戳記)。時間偏移值會顯示在提供的音訊中,每個所說字詞的開始與結束時間。時間偏移值代表從音訊開始起算經過的時間量,以 100 毫秒為遞增量。

如要轉錄音訊檔案並取得字詞時間戳記,請複製下列程式碼到 IPython 工作階段,更新程式碼:

def print_result(result: speech.SpeechRecognitionResult):
    best_alternative = result.alternatives[0]
    print("-" * 80)
    print(f"language_code: {result.language_code}")
    print(f"transcript:    {best_alternative.transcript}")
    print(f"confidence:    {best_alternative.confidence:.0%}")
    print("-" * 80)
    for word in best_alternative.words:
        start_s = word.start_time.total_seconds()
        end_s = word.end_time.total_seconds()
        print(f"{start_s:>7.3f} | {end_s:>7.3f} | {word.word}")
        

請花點時間研究程式碼,瞭解如何轉錄音訊檔案並取得字詞時間戳記*。*enable_word_time_offsets 參數會指示 API 傳回每個字的時差 (詳情請參閱文件)。

傳送要求:

config = speech.RecognitionConfig(
    language_code="en",
    enable_automatic_punctuation=True,
    enable_word_time_offsets=True,
)
audio = speech.RecognitionAudio(
    uri="gs://cloud-samples-data/speech/brooklyn_bridge.flac",
)

response = speech_to_text(config, audio)
print_response(response)

您應該會看到以下的輸出內容:

--------------------------------------------------------------------------------
language_code: en-us
transcript:    How old is the Brooklyn Bridge?
confidence:    98%
--------------------------------------------------------------------------------
  0.000 |   0.300 | How
  0.300 |   0.600 | old
  0.600 |   0.800 | is
  0.800 |   0.900 | the
  0.900 |   1.100 | Brooklyn
  1.100 |   1.400 | Bridge?

摘要

在這個步驟中,您已能轉錄英文音訊檔案,並取得單字時間戳記和列印結果。進一步瞭解如何取得字詞時間戳記

6. 轉錄不同語言的內容

Speech-to-Text API 可辨識超過 125 種語言和方言!如要查看支援的語言清單,請按這裡

在本節中,您將轉錄法文音訊檔案。

如要轉錄法文音訊檔案,請將下列程式碼複製到 IPython 工作階段,更新程式碼:

config = speech.RecognitionConfig(
    language_code="fr-FR",
    enable_automatic_punctuation=True,
    enable_word_time_offsets=True,
)
audio = speech.RecognitionAudio(
    uri="gs://cloud-samples-data/speech/corbeau_renard.flac",
)

response = speech_to_text(config, audio)
print_response(response)

您應該會看到以下的輸出內容:

--------------------------------------------------------------------------------
language_code: fr-fr
transcript:    Maître corbeau sur un arbre perché Tenait dans son bec un fromage maître Renard par l'odeur alléché lui tint à peu près ce langage et bonjour monsieur du corbeau.
confidence:    94%
--------------------------------------------------------------------------------
  0.000 |   0.700 | Maître
  0.700 |   1.100 | corbeau
  1.100 |   1.300 | sur
  1.300 |   1.600 | un
  1.600 |   1.700 | arbre
  1.700 |   2.000 | perché
  2.000 |   3.000 | Tenait
  3.000 |   3.000 | dans
  3.000 |   3.200 | son
  3.200 |   3.500 | bec
  3.500 |   3.700 | un
  3.700 |   3.800 | fromage
...
 10.800 |  11.800 | monsieur
 11.800 |  11.900 | du
 11.900 |  12.100 | corbeau.

摘要

在這個步驟中,您已成功轉錄法文音訊檔案並列印結果。進一步瞭解支援的語言

7. 恭喜!

9e7124a578332fed.png

您已學會如何使用 Python 搭配 Speech-to-Text API,對音訊檔執行各種轉錄作業!

清除所用資源

如要清除開發環境,請在 Cloud Shell 中執行下列指令:

  • 如果仍在 IPython 工作階段中,請返回 Shell:exit
  • 停止使用 Python 虛擬環境:deactivate
  • 刪除虛擬環境資料夾:cd ~ ; rm -rf ./venv-speech

如要刪除 Google Cloud 專案,請在 Cloud Shell 中執行下列操作:

  • 擷取目前的專案 ID:PROJECT_ID=$(gcloud config get-value core/project)
  • 確認這是要刪除的專案:echo $PROJECT_ID
  • 刪除專案:gcloud projects delete $PROJECT_ID

瞭解詳情

授權

這項內容採用的授權為 Creative Commons 姓名標示 2.0 通用授權。