音声文字変換リクエストを Cloud Speech-to-Text On-Prem に送信する

前提条件

  1. クイックスタート: 始める前にの手順をすべて完了します。
  2. API をデプロイします
  3. API に対してクエリを実行して、正常に動作していることを確認します。

依存関係のインストール

  1. python-speech のクローンを作成し、ディレクトリをサンプル ディレクトリに変更します。

    $ git clone https://github.com/googleapis/python-speech.git
    $ cd python-speech/samples/snippets
    
  2. pipvirtualenv をまだインストールしていない場合は、インストールします。詳細については、Google Cloud Platform の Python 開発環境設定ガイドをご覧ください。

  3. virtualenv を作成します。以下のサンプルは、Python 2.7 および 3.4 以降と互換性があります。

    $ virtualenv env
    $ source env/bin/activate
    
  4. サンプルの実行に必要な依存関係をインストールします。

    $ pip install -r requirements.txt
    

コードサンプル

次のコードサンプルでは、google-cloud-speech ライブラリを使用しています。GitHub を使用してソースを参照し、問題を報告できます。

音声ファイルの文字変換

次のコードサンプルを使用して、パブリック IP またはクラスタレベルの IP で音声ファイルを文字変換できます。IP タイプの詳細については、API のクエリ実行に関するドキュメントをご覧ください。

パブリック IP:

    # Using a Public IP
    $ python transcribe_onprem.py --file_path="../resources/two_channel_16k.wav" --api_endpoint=${PUBLIC_IP}:443

クラスタレベルの IP:

    # Using a cluster level IP
    $ kubectl port-forward -n $NAMESPACE $POD 10000:10000
    $ python transcribe_onprem.py --file_path="../resources/two_channel_16k.wav" --api_endpoint="0.0.0.0:10000"

Python

Speech-to-Text に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

def transcribe_onprem(
    local_file_path: str,
    api_endpoint: str,
) -> speech_v1p1beta1.RecognizeResponse:
    """
    Transcribe a short audio file using synchronous speech recognition on-prem

    Args:
      local_file_path: The path to local audio file, e.g. /path/audio.wav
      api_endpoint: Endpoint to call for speech recognition, e.g. 0.0.0.0:10000

    Returns:
      The speech recognition response
          {
    """
    # api_endpoint = '0.0.0.0:10000'
    # local_file_path = '../resources/two_channel_16k.raw'

    # Create a gRPC channel to your server
    channel = grpc.insecure_channel(target=api_endpoint)
    transport = speech_v1p1beta1.services.speech.transports.SpeechGrpcTransport(
        channel=channel
    )

    client = speech_v1p1beta1.SpeechClient(transport=transport)

    # The language of the supplied audio
    language_code = "en-US"

    # Sample rate in Hertz of the audio data sent
    sample_rate_hertz = 16000

    # Encoding of audio data sent. This sample sets this explicitly.
    # This field is optional for FLAC and WAV audio formats.
    encoding = speech_v1p1beta1.RecognitionConfig.AudioEncoding.LINEAR16
    config = {
        "encoding": encoding,
        "language_code": language_code,
        "sample_rate_hertz": sample_rate_hertz,
    }
    with io.open(local_file_path, "rb") as f:
        content = f.read()
    audio = {"content": content}

    response = client.recognize(request={"config": config, "audio": audio})
    for result in response.results:
        # First alternative is the most probable result
        alternative = result.alternatives[0]
        print(f"Transcript: {alternative.transcript}")

    return response