단어 수준의 신뢰도 사용 설정

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