Speech-to-Text API에서 언어 인식 사용 설정

컬렉션을 사용해 정리하기 내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요.

이 페이지에서는 Speech-to-Text로 전송되는 오디오 스크립트 작성 요청에 언어 인식을 사용 설정하는 방법을 설명합니다.

오디오 녹음에 어떤 언어가 포함되어 있는지 확실히 모르는 경우가 있습니다. 예를 들어 공식 언어가 여러 개인 국가에서 서비스, 앱 또는 제품을 게시하는 경우 다양한 언어로 된 사용자의 오디오 입력을 받을 수 있습니다. 이런 경우 텍스트 변환 요청에 단일 언어 코드를 지정하기가 상당히 어려울 수 있습니다.

여러 언어 인식

Speech-to-Text에서는 오디오 데이터에 포함되었을 수 있는 대체 언어 집합을 지정할 수 있습니다. Speech-to-Text로 오디오 텍스트 변환 요청을 보낼 때 오디오 데이터에 포함되었을 수 있는 추가 언어의 목록을 제공할 수 있습니다. 요청에 언어 목록을 포함하면 Speech-to-Text는 제공된 대체 언어 중에서 샘플에 가장 적합한 언어에 따라 오디오를 텍스트로 변환합니다. 그런 다음 Speech-to-Text는 텍스트 변환 결과에 예측한 언어 코드로 라벨을 표시합니다.

이 기능은 음성 명령이나 검색어와 같은 짧은 말을 텍스트로 변환해야 하는 앱에 적합합니다. 기본 언어 외에도 Speech-to-Text가 지원하는 언어 중 최대 3개의 대체 언어를 목록에 포함할 수 있습니다(총 4개 언어).

음성 텍스트 변환 요청에 대체 언어를 지정할 수 있는 경우라도 languageCode 필드에 기본 언어 코드를 제공해야 합니다. 또한, 요청하는 언어의 수를 최소로 제한해야 합니다. 요청하는 대체 언어 코드가 적을수록 Speech-to-Text가 정확한 언어를 선택할 확률이 높습니다. 단일 언어만 지정할 때 가장 좋은 결과를 얻을 수 있습니다.

오디오 텍스트 변환 요청에 언어 인식 사용 설정

오디오 텍스트 변환에 대체 언어를 지정하려면 요청에 대한 RecognitionConfig 매개변수에서 alternativeLanguageCodes 필드를 언어 코드 목록으로 설정해야 합니다. Speech-to-Text는 speech:recognize, speech:longrunningrecognize, 스트리밍 등 모든 음성 인식 메서드의 대체 언어 코드를 지원합니다.

를 확인하세요.

로컬 파일 사용

프로토콜

자세한 내용은 speech:recognize API 엔드포인트를 참조하세요.

동기 음성 인식을 수행하려면 POST 요청을 하고 적절한 요청 본문을 제공합니다. 다음은 curl을 사용한 POST 요청의 예시입니다. 이 예시에서는 Google Cloud Google Cloud CLI를 사용하여 프로젝트에 설정된 서비스 계정의 액세스 토큰을 사용합니다. gcloud CLI 설치, 서비스 계정으로 프로젝트 설정, 액세스 토큰 가져오기에 대한 자세한 내용은 빠른 시작을 참조하세요.

다음 예는 영어, 프랑스어, 독일어 음성을 포함할 수 있는 오디오 파일의 텍스트 변환을 요청하는 방법을 보여줍니다.

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": "LINEAR16",
        "languageCode": "en-US",
        "alternativeLanguageCodes": ["fr-FR", "de-DE"],
        "model": "command_and_search"
    },
    "audio": {
        "uri": "gs://cloud-samples-tests/speech/commercial_mono.wav"
    }
}' > multi-language.txt

요청이 성공하면 서버는 200 OK HTTP 상태 코드와 응답을 JSON 형식으로 반환하여 multi-language.txt라는 파일에 저장합니다.

{
  "results": [
    {
      "alternatives": [
        {
          "transcript": "hi I'd like to buy a Chromecast I'm ..."
          "confidence": 0.9466864
        }
      ],
      "languageCode": "en-us"
    },
    {
      "alternatives": [
        {
          "transcript": " let's go with the black one",
          "confidence": 0.9829583
        }
      ],
      "languageCode": "en-us"
    },
  ]
}

Java

/**
 * Transcribe a local audio file with multi-language recognition
 *
 * @param fileName the path to the audio file
 */
public static void transcribeMultiLanguage(String fileName) throws Exception {
  Path path = Paths.get(fileName);
  // Get the contents of the local audio file
  byte[] content = Files.readAllBytes(path);

  try (SpeechClient speechClient = SpeechClient.create()) {

    RecognitionAudio recognitionAudio =
        RecognitionAudio.newBuilder().setContent(ByteString.copyFrom(content)).build();
    ArrayList<String> languageList = new ArrayList<>();
    languageList.add("es-ES");
    languageList.add("en-US");

    // Configure request to enable multiple languages
    RecognitionConfig config =
        RecognitionConfig.newBuilder()
            .setEncoding(AudioEncoding.LINEAR16)
            .setSampleRateHertz(16000)
            .setLanguageCode("ja-JP")
            .addAllAlternativeLanguageCodes(languageList)
            .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\n", alternative.getTranscript());
    }
  }
}

Node.js

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: 'LINEAR16',
  sampleRateHertz: 44100,
  languageCode: 'en-US',
  alternativeLanguageCodes: ['es-ES', 'en-US'],
};

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');
console.log(`Transcription: ${transcription}`);

Python

from google.cloud import speech_v1p1beta1 as speech

client = speech.SpeechClient()

speech_file = "resources/multi.wav"
first_lang = "en-US"
second_lang = "es"

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=44100,
    audio_channel_count=2,
    language_code=first_lang,
    alternative_language_codes=[second_lang],
)

print("Waiting for operation to complete...")
response = client.recognize(config=config, audio=audio)

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

원격 파일 사용

Java

/**
 * Transcribe a remote audio file with multi-language recognition
 *
 * @param gcsUri the path to the remote audio file
 */
public static void transcribeMultiLanguageGcs(String gcsUri) throws Exception {
  try (SpeechClient speechClient = SpeechClient.create()) {

    ArrayList<String> languageList = new ArrayList<>();
    languageList.add("es-ES");
    languageList.add("en-US");

    // Configure request to enable multiple languages
    RecognitionConfig config =
        RecognitionConfig.newBuilder()
            .setEncoding(AudioEncoding.LINEAR16)
            .setSampleRateHertz(16000)
            .setLanguageCode("ja-JP")
            .addAllAlternativeLanguageCodes(languageList)
            .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);
    }

    for (SpeechRecognitionResult result : response.get().getResultsList()) {

      // 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\n", alternative.getTranscript());
    }
  }
}

Node.js

// 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: 'LINEAR16',
  sampleRateHertz: 44100,
  languageCode: 'en-US',
  alternativeLanguageCodes: ['es-ES', 'en-US'],
};

const audio = {
  uri: gcsUri,
};

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

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