啟用不雅用語篩選器

本頁面說明如何使用語音轉文字功能,自動偵測音訊資料中的不雅字詞,並在轉錄稿中加以審查。

如要啟用不雅用語篩選器,請在 RecognitionFeatures 中將 profanityFilter 設為 true。啟用後,語音轉文字會嘗試偵測不雅字詞,並在轉錄稿中只傳回第一個字母,其餘字元則以星號表示 (例如 f***)。如果將這個欄位設為 false 或未設定,Speech-to-Text 就不會嘗試過濾不雅用語。

下列範例示範如何啟用不雅用語篩選器,辨識儲存在 Cloud Storage 值區中的音訊。

Python

如要瞭解如何安裝及使用 Speech-to-Text 的用戶端程式庫,請參閱這篇文章。 詳情請參閱 Speech-to-Text Python API 參考說明文件

如要向語音轉文字服務進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

from google.cloud import speech
from google.cloud.speech import RecognizeResponse


def sync_recognize_with_profanity_filter_gcs(audio_uri: str) -> RecognizeResponse:
    """Recognizes speech from an audio file in Cloud Storage and filters out profane language.
    Args:
        audio_uri (str): The Cloud Storage URI of the input audio, e.g., gs://[BUCKET]/[FILE]
    Returns:
        cloud_speech.RecognizeResponse: The full response object which includes the transcription results.
    """
    # Define the audio source
    audio = {"uri": audio_uri}

    client = speech.SpeechClient()
    config = speech.RecognitionConfig(
        encoding=speech.RecognitionConfig.AudioEncoding.FLAC,  # Audio format
        sample_rate_hertz=16000,
        language_code="en-US",
        # Enable profanity filter
        profanity_filter=True,
    )

    response = client.recognize(config=config, audio=audio)

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

    return response.results