単語レベルの信頼度を有効にする

Speech-to-Text では、音声文字変換を行う際にそれぞれの単語に対して信頼度レベル(正確さの値)を示すように指定できます。

単語レベルの信頼度

Speech-to-Text では、音声クリップの音声文字変換を行うときに、精度も測定してレスポンスします。Speech-to-Text から送信されるレスポンスでは、音声文字変換リクエスト全体の信頼度レベルが 0.0 から 1.0 の範囲の数値で示されます。次のコードサンプルは、Speech-to-Text から返される信頼度レベルの値を示しています。

{
  "results": [
    {
      "alternatives": [
        {
          "transcript": "how old is the Brooklyn Bridge",
          "confidence": 0.96748614
        }
      ]
    }
  ]
}

Speech-to-Text では、音声文字変換の全体の信頼度レベルに加えて、変換した個々の単語について信頼度レベルを示すこともできます。その場合、次の例に示すように、音声文字変換での WordInfo の詳細情報がレスポンスに含まれるようになり、個々の単語の信頼度レベルが示されます。

{
  "results": [
    {
      "alternatives": [
        {
          "transcript": "how old is the Brooklyn Bridge",
          "confidence": 0.98360395,
          "words": [
            {
              "startTime": "0s",
              "endTime": "0.300s",
              "word": "how",
              "confidence": SOME NUMBER
            },
            ...
          ]
        }
      ]
    }
  ]
}

リクエストで単語レベルの信頼度を有効にする

次のコード スニペットは、ローカル ファイルとリモート ファイルを使用して Speech-to-Text への音声文字変換リクエストの信頼性を有効にする方法を示しています。

ローカル ファイルを使用する

プロトコル

詳細については、speech:recognize API エンドポイントをご覧ください。

同期音声認識を実行するには、POST リクエストを作成し、適切なリクエスト本文を指定します。次は、curl を使用した POST リクエストの例です。この例では、Google Cloud CLI を使用してアクセス トークンを生成します。gcloud CLI のインストール手順については、クイックスタートをご覧ください。

次の例は、curl を使用して POST リクエストを送信する方法を示しています。ここでは、リクエストの本文で単語レベルの信頼度を有効にしています。

curl -s -H "Content-Type: application/json" \
    -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
    https://speech.googleapis.com/v1p1beta1/speech:recognize \
    --data '{
    "config": {
        "encoding": "FLAC",
        "sampleRateHertz": 16000,
        "languageCode": "en-US",
        "enableWordTimeOffsets": true,
        "enableWordConfidence": true
    },
    "audio": {
        "uri": "gs://cloud-samples-tests/speech/brooklyn.flac"
    }
}' > word-level-confidence.txt

リクエストが成功すると、サーバーは 200 OK HTTP ステータス コードと JSON 形式のレスポンス(word-level-confidence.txt というファイル名で保存される)を返します。

{
  "results": [
    {
      "alternatives": [
        {
          "transcript": "how old is the Brooklyn Bridge",
          "confidence": 0.98360395,
          "words": [
            {
              "startTime": "0s",
              "endTime": "0.300s",
              "word": "how",
              "confidence": 0.98762906
            },
            {
              "startTime": "0.300s",
              "endTime": "0.600s",
              "word": "old",
              "confidence": 0.96929157
            },
            {
              "startTime": "0.600s",
              "endTime": "0.800s",
              "word": "is",
              "confidence": 0.98271006
            },
            {
              "startTime": "0.800s",
              "endTime": "0.900s",
              "word": "the",
              "confidence": 0.98271006
            },
            {
              "startTime": "0.900s",
              "endTime": "1.100s",
              "word": "Brooklyn",
              "confidence": 0.98762906
            },
            {
              "startTime": "1.100s",
              "endTime": "1.500s",
              "word": "Bridge",
              "confidence": 0.98762906
            }
          ]
        }
      ],
      "languageCode": "en-us"
    }
  ]
}

Java

Speech-to-Text 用のクライアント ライブラリをインストールして使用する方法については、Speech-to-Text クライアント ライブラリをご覧ください。詳細については、Speech-to-Text の Java API リファレンス ドキュメントをご覧ください。

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

/**
 * Transcribe a local audio file with word level confidence
 *
 * @param fileName the path to the local audio file
 */
public static void transcribeWordLevelConfidence(String fileName) throws Exception {
  Path path = Paths.get(fileName);
  byte[] content = Files.readAllBytes(path);

  try (SpeechClient speechClient = SpeechClient.create()) {
    RecognitionAudio recognitionAudio =
        RecognitionAudio.newBuilder().setContent(ByteString.copyFrom(content)).build();
    // Configure request to enable word level confidence
    RecognitionConfig config =
        RecognitionConfig.newBuilder()
            .setEncoding(AudioEncoding.LINEAR16)
            .setSampleRateHertz(16000)
            .setLanguageCode("en-US")
            .setEnableWordConfidence(true)
            .build();
    // Perform the transcription request
    RecognizeResponse recognizeResponse = speechClient.recognize(config, recognitionAudio);

    // Print out the results
    for (SpeechRecognitionResult result : recognizeResponse.getResultsList()) {
      // There can be several alternative transcripts for a given chunk of speech. Just use the
      // first (most likely) one here.
      SpeechRecognitionAlternative alternative = result.getAlternatives(0);
      System.out.format("Transcript : %s\n", alternative.getTranscript());
      System.out.format(
          "First Word and Confidence : %s %s \n",
          alternative.getWords(0).getWord(), alternative.getWords(0).getConfidence());
    }
  }
}

Node.js

Speech-to-Text 用のクライアント ライブラリをインストールして使用する方法については、Speech-to-Text クライアント ライブラリをご覧ください。詳細については、Speech-to-Text の Node.js API リファレンス ドキュメントをご覧ください。

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

const fs = require('fs');

// Imports the Google Cloud client library
const speech = require('@google-cloud/speech').v1p1beta1;

// Creates a client
const client = new speech.SpeechClient();

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const fileName = 'Local path to audio file, e.g. /path/to/audio.raw';

const config = {
  encoding: 'FLAC',
  sampleRateHertz: 16000,
  languageCode: 'en-US',
  enableWordConfidence: true,
};

const audio = {
  content: fs.readFileSync(fileName).toString('base64'),
};

const request = {
  config: config,
  audio: audio,
};

const [response] = await client.recognize(request);
const transcription = response.results
  .map(result => result.alternatives[0].transcript)
  .join('\n');
const confidence = response.results
  .map(result => result.alternatives[0].confidence)
  .join('\n');
console.log(`Transcription: ${transcription} \n Confidence: ${confidence}`);

console.log('Word-Level-Confidence:');
const words = response.results.map(result => result.alternatives[0]);
words[0].words.forEach(a => {
  console.log(` word: ${a.word}, confidence: ${a.confidence}`);
});

Python

Speech-to-Text 用のクライアント ライブラリをインストールして使用する方法については、Speech-to-Text クライアント ライブラリをご覧ください。詳細については、Speech-to-Text の Python API リファレンス ドキュメントをご覧ください。

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

from google.cloud import speech_v1p1beta1 as speech

client = speech.SpeechClient()

speech_file = "resources/Google_Gnome.wav"

with open(speech_file, "rb") as audio_file:
    content = audio_file.read()

audio = speech.RecognitionAudio(content=content)

config = speech.RecognitionConfig(
    encoding=speech.RecognitionConfig.AudioEncoding.LINEAR16,
    sample_rate_hertz=16000,
    language_code="en-US",
    enable_word_confidence=True,
)

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

for i, result in enumerate(response.results):
    alternative = result.alternatives[0]
    print("-" * 20)
    print(f"First alternative of result {i}")
    print(f"Transcript: {alternative.transcript}")
    print(
        "First Word and Confidence: ({}, {})".format(
            alternative.words[0].word, alternative.words[0].confidence
        )
    )

return response.results

リモート ファイルを使用する

Java

Speech-to-Text 用のクライアント ライブラリをインストールして使用する方法については、Speech-to-Text クライアント ライブラリをご覧ください。詳細については、Speech-to-Text の Java API リファレンス ドキュメントをご覧ください。

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

/**
 * Transcribe a remote audio file with word level confidence
 *
 * @param gcsUri path to the remote audio file
 */
public static void transcribeWordLevelConfidenceGcs(String gcsUri) throws Exception {
  try (SpeechClient speechClient = SpeechClient.create()) {

    // Configure request to enable word level confidence
    RecognitionConfig config =
        RecognitionConfig.newBuilder()
            .setEncoding(AudioEncoding.FLAC)
            .setSampleRateHertz(44100)
            .setLanguageCode("en-US")
            .setEnableWordConfidence(true)
            .build();

    // Set the remote path for the audio file
    RecognitionAudio audio = RecognitionAudio.newBuilder().setUri(gcsUri).build();

    // Use non-blocking call for getting file transcription
    OperationFuture<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> response =
        speechClient.longRunningRecognizeAsync(config, audio);

    while (!response.isDone()) {
      System.out.println("Waiting for response...");
      Thread.sleep(10000);
    }
    // Just print the first result here.
    SpeechRecognitionResult result = response.get().getResultsList().get(0);

    // There can be several alternative transcripts for a given chunk of speech. Just use the
    // first (most likely) one here.
    SpeechRecognitionAlternative alternative = result.getAlternativesList().get(0);
    // Print out the result
    System.out.printf("Transcript : %s\n", alternative.getTranscript());
    System.out.format(
        "First Word and Confidence : %s %s \n",
        alternative.getWords(0).getWord(), alternative.getWords(0).getConfidence());
  }
}

Node.js

Speech-to-Text 用のクライアント ライブラリをインストールして使用する方法については、Speech-to-Text クライアント ライブラリをご覧ください。詳細については、Speech-to-Text の Node.js API リファレンス ドキュメントをご覧ください。

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

// Imports the Google Cloud client library
const speech = require('@google-cloud/speech').v1p1beta1;

// Creates a client
const client = new speech.SpeechClient();

/**
 * TODO(developer): Uncomment the following line before running the sample.
 */
// const uri = path to GCS audio file e.g. `gs:/bucket/audio.wav`;

const config = {
  encoding: 'FLAC',
  sampleRateHertz: 16000,
  languageCode: 'en-US',
  enableWordConfidence: true,
};

const audio = {
  uri: gcsUri,
};

const request = {
  config: config,
  audio: audio,
};

const [response] = await client.recognize(request);
const transcription = response.results
  .map(result => result.alternatives[0].transcript)
  .join('\n');
const confidence = response.results
  .map(result => result.alternatives[0].confidence)
  .join('\n');
console.log(`Transcription: ${transcription} \n Confidence: ${confidence}`);

console.log('Word-Level-Confidence:');
const words = response.results.map(result => result.alternatives[0]);
words[0].words.forEach(a => {
  console.log(` word: ${a.word}, confidence: ${a.confidence}`);
});

Python

Speech-to-Text 用のクライアント ライブラリをインストールして使用する方法については、Speech-to-Text クライアント ライブラリをご覧ください。詳細については、Speech-to-Text の Python API リファレンス ドキュメントをご覧ください。

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


from google.cloud import speech_v1p1beta1 as speech

def transcribe_file_with_word_level_confidence(gcs_uri: str) -> str:
    """Transcribe a remote audio file with word level confidence.

    Args:
        gcs_uri: The Google Cloud Storage path to an audio file.

    Returns:
        The generated transcript from the audio file provided.
    """

    client = speech.SpeechClient()

    # Configure request to enable word level confidence
    config = speech.RecognitionConfig(
        encoding=speech.RecognitionConfig.AudioEncoding.FLAC,
        sample_rate_hertz=44100,
        language_code="en-US",
        enable_word_confidence=True,
    )

    # Set the remote path for the audio file
    audio = speech.RecognitionAudio(uri=gcs_uri)

    # Use non-blocking call for getting file transcription
    response = client.long_running_recognize(config=config, audio=audio).result(
        timeout=300
    )

    transcript_builder = []
    for i, result in enumerate(response.results):
        alternative = result.alternatives[0]
        transcript_builder.append("-" * 20)
        transcript_builder.append(f"\nFirst alternative of result {i}")
        transcript_builder.append(f"\nTranscript: {alternative.transcript}")
        transcript_builder.append(
            "\nFirst Word and Confidence: ({}, {})".format(
                alternative.words[0].word, alternative.words[0].confidence
            )
        )

    transcript = "".join(transcript_builder)
    print(transcript)

    return transcript