將轉錄要求傳送至 Cloud Speech-to-Text On-Prem

必要條件

  1. 完成「開始使用」快速入門中的所有必要步驟。
  2. 部署 API
  3. 查詢 API,確認 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

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

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