搭配 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 未使用的字元字串。你隨時可以更新。
  • 所有 Google Cloud 專案的專案 ID 均不得重複,而且設定後即無法變更。Cloud 控制台會自動產生一個不重複的字串。但通常是在乎它何在在大部分的程式碼研究室中,您必須參照專案 ID (通常為 PROJECT_ID)。如果您對產生的 ID 不滿意,可以隨機產生一個 ID。或者,您也可以自行嘗試,看看是否支援。在這個步驟後,這個名稱即無法變更,而且在專案期間內仍會保持有效。
  • 資訊中的第三個值是專案編號,部分 API 會使用這個編號。如要進一步瞭解這三個值,請參閱說明文件
  1. 接下來,您需要在 Cloud 控制台中啟用計費功能,才能使用 Cloud 資源/API。執行本程式碼研究室不會產生任何費用 (如果有的話)。如要關閉資源,以免產生本教學課程結束後產生的費用,您可以刪除自己建立的資源或刪除專案。新使用者符合 $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 工作階段,請返回殼層: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

瞭解詳情

授權

這項內容採用的是創用 CC 姓名標示 2.0 通用授權。