透過模型調整機制來改善語音轉錄結果

總覽

您可以使用模型調整功能,讓 Speech-to-Text 優先辨識特定字詞或詞組,而非其他可能建議的選項。舉例來說,假設您的音訊資料經常包含「weather」一詞。當 Speech-to-Text 遇到「weather」這個字詞時,您希望它將該字詞轉錄為「weather」的頻率高於「whether」。在這種情況下,您可以使用模型調整功能,讓 Speech-to-Text 傾向辨識「weather」。

模型調整功能在下列用途中特別實用:

  • 提高音訊資料中經常出現的字詞和詞組的準確度。舉例來說,您可以讓辨識模型留意使用者通常會說出的語音指令。

    • 擴充 Speech-to-Text 辨識的字詞。Speech-to-Text 包含大量詞彙。不過,如果音訊資料經常包含一般語言中不常使用的字詞 (例如專有名詞或特定領域的字詞),您可以使用模型調整功能新增這些字詞。

    • 在提供的音訊含有雜訊或不夠清晰時,提高語音轉錄的準確度。

您也可以使用模型調整提升功能,微調辨識模型的偏誤。

提升字詞和詞組辨識準確度

如要提高 Speech-to-Text 在轉錄音訊資料時辨識出「weather」一詞的機率,您可以在 SpeechAdaptation 資源的 PhraseSet 物件中傳遞「weather」這個單字。

如果您提供多字詞組,Speech-to-Text 較有可能依序辨識這些字詞。提供詞組也會提高辨識詞組部分內容 (包括個別字詞) 的機率。如要瞭解這些詞組的數量和大小限制,請參閱內容限制頁面。

使用類別提升辨識效果

類別代表自然語言中常見的概念,例如貨幣單位和日曆日期。類別可協助您提高對應至常見概念的大量字詞群組的轉錄準確度,但這些字詞群組不一定包含相同的字詞或詞組。

舉例來說,假設您的音訊資料包含使用者說出街道地址的錄音。假設您有一段錄音,內容是某人說「我家在 123 Main Street,左邊第四間房子」。在這種情況下,您會希望 Speech-to-Text 將第一組數字序列 (「123」) 辨識為地址,而不是序數 (「one-hundred twenty-third」)。不過,並非所有人都住在「123 Main Street」。在 PhraseSet 資源中列出所有可能的街道地址並不切實際。您可以改用類別,指出無論實際數字為何,都應辨識門牌號碼。在這個範例中,Speech-to-Text 就能更準確地轉錄「123 Main Street」和「987 Grand Boulevard」等詞組,因為這兩者都會被辨識為地址號碼。

類別符記

如要在模型調整中使用類別,請在 PhraseSet 資源的 phrases 欄位中加入類別權杖。請參閱支援的類別符記清單,瞭解您的語言支援哪些符記。舉例來說,如要提高來源音訊中地址號碼的轉錄品質,請在 PhraseSet. 的詞組中提供 $ADDRESSNUM 值

您可以將類別做為 phrases 陣列中的獨立項目,或在較長的多字詞詞組中嵌入一或多個類別符記。例如,您可以在字串中加入類別符記,在較長的詞組中指出地址號碼:["my address is $ADDRESSNUM"]。不過,如果音訊包含類似但不完全相同的詞組 (例如「I am at 123 Main Street」),這個詞組就無法發揮作用。為協助辨識類似詞組,請務必另外加入類別符記本身:["my address is $ADDRESSNUM", "$ADDRESSNUM"]。如果您使用無效或格式錯誤的類別權杖,Speech-to-Text 會忽略該權杖,不會觸發錯誤,但仍會使用詞組的其餘部分做為背景資訊。

自訂類別

您也可以建立自己的 CustomClass,這個類別由您的自訂清單組成,清單內含相關的項目或值。舉例來說,您想轉錄的音訊資料可能包含數百家區域餐廳中任一家的名稱。餐廳名稱在一般語音中相對罕見,因此辨識模型較不可能將其選為「正確」答案。您可以使用自訂類別,調整辨識模型,讓模型在音訊中出現這些名稱時,能正確辨識。

如要使用自訂類別,請建立 CustomClass 資源,並將每個餐廳名稱納入為 ClassItem。自訂類別的運作方式與預先建構的類別權杖相同。phrase 可以同時包含預先建構的類別權杖和自訂類別。

使用提升功能微調語音轉錄結果

根據預設,模型調整項的影響相對較小,尤其是對單字詞組。模型調整提升功能可讓您為某些詞組指派比其他詞組更高的權重,藉此提高辨識模型偏誤。如果符合下列所有條件,建議您導入提升功能:

  1. 您已導入模型調整功能。
  2. 您想進一步調整模型調整機制對語音轉錄結果的影響強度。如要查看您的語言是否支援強化功能,請參閱語言支援頁面。

chirp_3 模型會使用提示詞調整功能,並忽略 boost 值。詳情請參閱「透過模型調整功能提高準確度」。

舉例來說,您有許多錄音檔,內容是人們詢問「fare to get into the county fair」(進入郡博覽會的票價),其中「fair」一詞出現的頻率高於「fare」。在這種情況下,您可以使用模型調整功能,將這兩個字詞新增為 PhraseSet 資源中的 phrases,提高模型辨識出「fair」和「fare」的機率。這會指示 Speech-to-Text 優先辨識「fair」和「fare」,而非「hare」或「lair」。

不過,由於「fair」在音訊中出現的頻率較高,因此系統應更常辨識出「fair」,而非「fare」。您可能已使用 Speech-to-Text API 轉錄音訊,但發現辨識正確字詞 (「fair」) 的錯誤率很高。在這種情況下,您可以使用提升功能,為「fair」指派比「fare」更高的提升值。由於「fair」的加權值較高,Speech-to-Text API 會偏向更常選擇「fair」,而非「fare」。如果沒有提升值,辨識模型會以相同機率辨識「fair」和「fare」。

Boost 基本概念

使用提升功能時,您會為 PhraseSet 資源中的 phrase 項目指派加權值。Speech-to-Text 會參考這個加權值,為音訊資料中的字詞選取可能的轉錄稿。增強值越高,Speech-to-Text 從可能選項中選擇該字詞或詞組的機率便越高。

如果為多字詞組指派增強值,增強值會套用至整個詞組,且僅限於整個詞組。舉例來說,假設您想為「My favorite exhibit at the American Museum of Natural History is the blue whale」這個詞組指派提升值,如果將該詞組新增至 phrase 物件並指派提升值,辨識模型就更有可能逐字辨識出整個詞組。

如果提高多字詞詞組的權重後,仍未獲得預期結果,建議您將組成該詞組的所有雙詞組 (依序排列的 2 個字詞) 新增為額外的 phrase 項目,並為每個項目指派權重值。延續前一個例子,您可以考慮加入其他雙詞和結尾詞 (兩個以上的字詞),例如「我最喜歡」、「我最喜歡的展覽」、「最喜歡的展覽」、「我最喜歡的美國自然歷史博物館展覽」、「美國自然歷史博物館」和「藍鯨」。這樣一來,STT 辨識模型就更有可能辨識出音訊中與原始提升詞組相關,但並非完全相同的詞組。

設定提升值

提升值必須是大於 0 的浮點值。提高值的實際上限為 20。為獲得最佳結果,請嘗試調高或調低提升值,直到取得準確的轉錄結果。

提高提升值可減少偽陰性,也就是音訊中出現字詞或詞組,但 Speech-to-Text 未正確辨識的情況。不過,提高提升值也可能增加偽陽性的機率,也就是說,即使音訊中未出現該字詞或詞組,該字詞或詞組仍會出現在轉錄稿中。

使用模型調整功能的用途範例

以下範例逐步說明如何使用模型調整功能,轉錄某人說「The word is fare」的音訊錄音。在本例中,如果沒有語音調整功能,Speech-to-Text 會辨識出「fair」一詞。使用語音調整功能,Speech-to-Text 就能辨識出「fare」這個字。

事前準備

  1. 登入 Google Cloud 帳戶。如果您未曾使用過 Google Cloud,歡迎建立帳戶,親自體驗實際使用我們產品的成效。新客戶還能獲得價值 $300 美元的免費抵免額,用於執行、測試及部署工作負載。
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  3. Verify that billing is enabled for your Google Cloud project.

  4. Enable the Speech-to-Text APIs, if any are not already enabled.

    Roles required to enable APIs

    To enable APIs, you need the serviceusage.services.enable permission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.

    Enable the APIs

  5. Make sure that you have the following role or roles on the project: Cloud Speech Administrator

    Check for the roles

    1. In the Google Cloud console, go to the IAM page.

      Go to IAM
    2. Select the project.
    3. In the Principal column, find all rows that identify you or a group that you're included in. To learn which groups you're included in, contact your administrator.

    4. For all rows that specify or include you, check the Role column to see whether the list of roles includes the required roles.

    Grant the roles

    1. In the Google Cloud console, go to the IAM page.

      Go to IAM
    2. Select the project.
    3. Click Grant access.
    4. In the New principals field, enter your user identifier. This is typically the email address for a Google Account.

    5. Click Select a role, then search for the role.
    6. To grant additional roles, click Add another role and add each additional role.
    7. Click Save.
  6. Install the Google Cloud CLI.

  7. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  8. To initialize the gcloud CLI, run the following command:

    gcloud init
  9. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  10. Verify that billing is enabled for your Google Cloud project.

  11. Enable the Speech-to-Text APIs, if any are not already enabled.

    Roles required to enable APIs

    To enable APIs, you need the serviceusage.services.enable permission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.

    Enable the APIs

  12. Make sure that you have the following role or roles on the project: Cloud Speech Administrator

    Check for the roles

    1. In the Google Cloud console, go to the IAM page.

      Go to IAM
    2. Select the project.
    3. In the Principal column, find all rows that identify you or a group that you're included in. To learn which groups you're included in, contact your administrator.

    4. For all rows that specify or include you, check the Role column to see whether the list of roles includes the required roles.

    Grant the roles

    1. In the Google Cloud console, go to the IAM page.

      Go to IAM
    2. Select the project.
    3. Click Grant access.
    4. In the New principals field, enter your user identifier. This is typically the email address for a Google Account.

    5. Click Select a role, then search for the role.
    6. To grant additional roles, click Add another role and add each additional role.
    7. Click Save.
  13. Install the Google Cloud CLI.

  14. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  15. To initialize the gcloud CLI, run the following command:

    gcloud init
  16. 用戶端程式庫可以使用應用程式預設憑證,輕鬆向 Google API 進行驗證,並向這些 API 傳送要求。有了應用程式預設憑證,您可以在本機測試應用程式,並在不變更基礎程式碼的情況下部署應用程式。詳情請參閱「進行驗證以使用用戶端程式庫」一文。

  17. 如果您使用的是本機殼層,請為使用者帳戶建立本機驗證憑證:

    gcloud auth application-default login

    如果您使用的是 Cloud Shell,則不必執行這項操作。

    如果系統傳回驗證錯誤,且您使用的是外部識別資訊提供者 (IdP),請確認您已使用聯合身分登入 gcloud CLI。

此外,請確認您已安裝用戶端程式庫。

使用PhraseSet改善語音轉錄品質

  1. 以下範例會使用「fare」這個詞組建構 PhraseSet,並在辨識要求中將其新增為 inline_phrase_set:

Python

import os

from google.cloud.speech_v2 import SpeechClient
from google.cloud.speech_v2.types import cloud_speech

PROJECT_ID = os.getenv("GOOGLE_CLOUD_PROJECT")


def adaptation_v2_inline_phrase_set(audio_file: str) -> cloud_speech.RecognizeResponse:
    """Enhances speech recognition accuracy using an inline phrase set.
    The inline custom phrase set helps the recognizer produce more accurate transcriptions for specific terms.
    Phrases are given a boost to increase their chances of being recognized correctly.
    Args:
        audio_file (str): Path to the local audio file to be transcribed.
    Returns:
        cloud_speech.RecognizeResponse: The full response object which includes the transcription results.
    """

    # Instantiates a client
    client = SpeechClient()

    # Reads a file as bytes
    with open(audio_file, "rb") as f:
        audio_content = f.read()

    # Build inline phrase set to produce a more accurate transcript
    phrase_set = cloud_speech.PhraseSet(
        phrases=[{"value": "fare", "boost": 10}, {"value": "word", "boost": 20}]
    )
    adaptation = cloud_speech.SpeechAdaptation(
        phrase_sets=[
            cloud_speech.SpeechAdaptation.AdaptationPhraseSet(
                inline_phrase_set=phrase_set
            )
        ]
    )
    config = cloud_speech.RecognitionConfig(
        auto_decoding_config=cloud_speech.AutoDetectDecodingConfig(),
        adaptation=adaptation,
        language_codes=["en-US"],
        model="short",
    )

    # Prepare the request which includes specifying the recognizer, configuration, and the audio content
    request = cloud_speech.RecognizeRequest(
        recognizer=f"projects/{PROJECT_ID}/locations/global/recognizers/_",
        config=config,
        content=audio_content,
    )

    # Transcribes the audio into text
    response = client.recognize(request=request)

    for result in response.results:
        print(f"Transcript: {result.alternatives[0].transcript}")

    return response

  1. 這個範例會建立含有相同詞組的 PhraseSet 資源,然後在辨識要求中參照該資源:

Python

import os

from google.cloud.speech_v2 import SpeechClient
from google.cloud.speech_v2.types import cloud_speech

PROJECT_ID = os.getenv("GOOGLE_CLOUD_PROJECT")


def adaptation_v2_phrase_set_reference(
    audio_file: str,
    phrase_set_id: str,
) -> cloud_speech.RecognizeResponse:
    """Transcribe audio files using a PhraseSet.
    Args:
        audio_file (str): Path to the local audio file to be transcribed.
        phrase_set_id (str): The unique ID of the PhraseSet to use.
    Returns:
        cloud_speech.RecognizeResponse: The full response object which includes the transcription results.
    """

    # Instantiates a client
    client = SpeechClient()

    # Reads a file as bytes
    with open(audio_file, "rb") as f:
        audio_content = f.read()

    # Creating operation of creating the PhraseSet on the cloud.
    operation = client.create_phrase_set(
        parent=f"projects/{PROJECT_ID}/locations/global",
        phrase_set_id=phrase_set_id,
        phrase_set=cloud_speech.PhraseSet(phrases=[{"value": "fare", "boost": 10}]),
    )
    phrase_set = operation.result()

    # Add a reference of the PhraseSet into the recognition request
    adaptation = cloud_speech.SpeechAdaptation(
        phrase_sets=[
            cloud_speech.SpeechAdaptation.AdaptationPhraseSet(
                phrase_set=phrase_set.name
            )
        ]
    )

    # Automatically detect audio encoding. Use "short" model for short utterances.
    config = cloud_speech.RecognitionConfig(
        auto_decoding_config=cloud_speech.AutoDetectDecodingConfig(),
        adaptation=adaptation,
        language_codes=["en-US"],
        model="short",
    )
    #  Prepare the request which includes specifying the recognizer, configuration, and the audio content
    request = cloud_speech.RecognizeRequest(
        recognizer=f"projects/{PROJECT_ID}/locations/global/recognizers/_",
        config=config,
        content=audio_content,
    )
    # Transcribes the audio into text
    response = client.recognize(request=request)

    for result in response.results:
        print(f"Transcript: {result.alternatives[0].transcript}")

    return response

使用CustomClass改善語音轉錄結果

  1. 以下範例會建構 CustomClass,其中包含「fare」項目和「fare」名稱。然後在辨識要求中,於 inline_phrase_set 內參照 CustomClass:

Python

import os

from google.cloud.speech_v2 import SpeechClient
from google.cloud.speech_v2.types import cloud_speech

PROJECT_ID = os.getenv("GOOGLE_CLOUD_PROJECT")


def adaptation_v2_inline_custom_class(
    audio_file: str,
) -> cloud_speech.RecognizeResponse:
    """Transcribe audio file using inline custom class.
    The inline custom class helps the recognizer produce more accurate transcriptions for specific terms.
    Args:
        audio_file (str): Path to the local audio file to be transcribed.
    Returns:
        cloud_speech.RecognizeResponse: The response object which includes the transcription results.
    """
    # Instantiates a client
    client = SpeechClient()

    # Reads a file as bytes
    with open(audio_file, "rb") as f:
        audio_content = f.read()

    # Define an inline custom class to enhance recognition accuracy with specific items like "fare" etc.
    custom_class_name = "your-class-name"
    custom_class = cloud_speech.CustomClass(
        name=custom_class_name,
        items=[{"value": "fare"}],
    )

    # Build inline phrase set to produce a more accurate transcript
    phrase_set = cloud_speech.PhraseSet(
        phrases=[{"value": custom_class_name, "boost": 20}]
    )
    adaptation = cloud_speech.SpeechAdaptation(
        phrase_sets=[
            cloud_speech.SpeechAdaptation.AdaptationPhraseSet(
                inline_phrase_set=phrase_set
            )
        ],
        custom_classes=[custom_class],
    )
    config = cloud_speech.RecognitionConfig(
        auto_decoding_config=cloud_speech.AutoDetectDecodingConfig(),
        adaptation=adaptation,
        language_codes=["en-US"],
        model="short",
    )

    # Prepare the request which includes specifying the recognizer, configuration, and the audio content
    request = cloud_speech.RecognizeRequest(
        recognizer=f"projects/{PROJECT_ID}/locations/global/recognizers/_",
        config=config,
        content=audio_content,
    )

    # Transcribes the audio into text
    response = client.recognize(request=request)

    for result in response.results:
        print(f"Transcript: {result.alternatives[0].transcript}")

    return response

  1. 這個範例會建立含有相同項目的 CustomClass 資源。接著,系統會建立 PhraseSet 資源,並使用參照 CustomClass 資源名稱的詞組。然後在辨識要求中參照 PhraseSet 資源:

Python

import os

from google.cloud.speech_v2 import SpeechClient
from google.cloud.speech_v2.types import cloud_speech

PROJECT_ID = os.getenv("GOOGLE_CLOUD_PROJECT")


def adaptation_v2_custom_class_reference(
    audio_file: str, phrase_set_id: str, custom_class_id: str
) -> cloud_speech.RecognizeResponse:
    """Transcribe audio file using a custom class.
    Args:
        audio_file (str): Path to the local audio file to be transcribed.
        phrase_set_id (str): The unique ID of the phrase set to use.
        custom_class_id (str): The unique ID of the custom class to use.
    Returns:
        cloud_speech.RecognizeResponse: The full response object which includes the transcription results.
    """
    # Instantiates a speech client
    client = SpeechClient()

    # Reads a file as bytes
    with open(audio_file, "rb") as f:
        audio_content = f.read()

    # Create a custom class to improve recognition accuracy for specific terms
    custom_class = cloud_speech.CustomClass(items=[{"value": "fare"}])
    operation = client.create_custom_class(
        parent=f"projects/{PROJECT_ID}/locations/global",
        custom_class_id=custom_class_id,
        custom_class=custom_class,
    )
    custom_class = operation.result()

    # Create a persistent PhraseSet to reference in a recognition request
    created_phrase_set = cloud_speech.PhraseSet(
        phrases=[
            {
                "value": f"${{{custom_class.name}}}",
                "boost": 20,
            },  # Using custom class reference
        ]
    )
    operation = client.create_phrase_set(
        parent=f"projects/{PROJECT_ID}/locations/global",
        phrase_set_id=phrase_set_id,
        phrase_set=created_phrase_set,
    )
    phrase_set = operation.result()

    # Add a reference of the PhraseSet into the recognition request
    adaptation = cloud_speech.SpeechAdaptation(
        phrase_sets=[
            cloud_speech.SpeechAdaptation.AdaptationPhraseSet(
                phrase_set=phrase_set.name
            )
        ]
    )
    # Automatically detect the audio's encoding with short audio model
    config = cloud_speech.RecognitionConfig(
        auto_decoding_config=cloud_speech.AutoDetectDecodingConfig(),
        adaptation=adaptation,
        language_codes=["en-US"],
        model="short",
    )

    # Create a custom class to reference in a PhraseSet
    request = cloud_speech.RecognizeRequest(
        recognizer=f"projects/{PROJECT_ID}/locations/global/recognizers/_",
        config=config,
        content=audio_content,
    )

    # Transcribes the audio into text
    response = client.recognize(request=request)

    for result in response.results:
        print(f"Transcript: {result.alternatives[0].transcript}")

    return response

清除所用資源

如要避免系統向您的 Google Cloud 帳戶收取本頁所用資源的費用,請按照下列步驟操作。

  1. 選用:撤銷您建立的驗證憑證,並刪除本機憑證檔案。

    gcloud auth application-default revoke
  2. 選用:從 gcloud CLI 撤銷憑證。

    gcloud auth revoke

控制台

  • 前往 Google Cloud 控制台的「Manage resources」(管理資源) 頁面。

    前往「Manage resources」(管理資源)

  • 在專案清單中選取要刪除的專案,然後點選「Delete」(刪除)。
  • 在對話方塊中輸入專案 ID,然後按一下 [Shut down] (關閉) 以刪除專案。
  • gcloud

    刪除 Google Cloud 專案:

    gcloud projects delete PROJECT_ID

    後續步驟