音声を文字に変換する

Google Distributed Cloud(GDC)エアギャップ上の Vertex AI の Speech-to-Text サービスは、音声ファイルから音声を認識します。 Speech-to-Text は、事前トレーニング済みの API を使用して、検出された音声をテキストに変換します。

このページでは、Distributed Cloud の Speech-to-Text API を使用して音声ファイルをテキストに変換する方法について説明します。

始める前に

Speech-to-Text API を使用するには、Speech-to-Text API が有効になっているプロジェクトと適切な認証情報が必要です。クライアント ライブラリをインストールして、API の呼び出しを行うこともできます。詳細については、音声認識プロジェクトを設定するをご覧ください。

デフォルト モデルで音声を文字変換する

Speech-to-Text は音声認識を行います。音声を認識する音声ファイルを API リクエストのコンテンツとして直接送信します。 システムは、文字変換されたテキストを API レスポンスで返します。

音声認識リクエストを行う場合は、RecognitionConfig 構成オブジェクトを指定する必要があります。このオブジェクトは、音声データの処理方法と必要な出力の種類を API に伝えます。この構成オブジェクトでモデルが明示的に指定されていない場合、Speech-to-Text はデフォルト モデルを選択します。

詳細については、Speech API のドキュメントをご覧ください

次の例では、デフォルトの Speech-to-Text モデルを使用して音声ファイルから音声を文字変換します。

Python

Python スクリプトから Speech-to-Text サービスを使用して音声ファイルから音声を文字変換するには、次の操作を行います。

  1. Speech-to-Text クライアント ライブラリの最新バージョンをインストールします

  2. Python スクリプトに必要な環境変数を設定します

  3. API リクエストを認証します

  4. 作成した Python スクリプトに次のコードを追加します。

    import base64
    
    from google.cloud import speech_v1p1beta1
    import google.auth
    from google.auth.transport import requests
    from google.api_core.client_options import ClientOptions
    
    audience="https://ENDPOINT:443"
    api_endpoint="ENDPOINT:443"
    
    def get_client(creds):
      opts = ClientOptions(api_endpoint=api_endpoint)
      return speech_v1p1beta1.SpeechClient(credentials=creds, client_options=opts)
    
    def main():
      creds = None
      try:
        creds, project_id = google.auth.default()
        creds = creds.with_gdch_audience(audience)
        req = requests.Request()
        creds.refresh(req)
        print("Got token: ")
        print(creds.token)
      except Exception as e:
        print("Caught exception" + str(e))
        raise e
      return creds
    
    def speech_func(creds):
      tc = get_client(creds)
    
      content="BASE64_ENCODED_AUDIO"
    
      audio = speech_v1p1beta1.RecognitionAudio()
      audio.content = base64.standard_b64decode(content)
      config = speech_v1p1beta1.RecognitionConfig()
      config.encoding= speech_v1p1beta1.RecognitionConfig.AudioEncoding.ENCODING
      config.sample_rate_hertz=RATE_HERTZ
      config.language_code="LANGUAGE_CODE"
      config.audio_channel_count=CHANNEL_COUNT
    
      metadata = [("x-goog-user-project", "projects/PROJECT_ID")]
      resp = tc.recognize(config=config, audio=audio, metadata=metadata)
      print(resp)
    
    if __name__=="__main__":
      creds = main()
      speech_func(creds)
    

    次のように置き換えます。

  5. Python スクリプトを保存します。

  6. Python スクリプトを実行して音声を文字変換します。

    python SCRIPT_NAME
    

    SCRIPT_NAME は、Python スクリプトに付けた名前に置き換えます(例: speech.py)。