클라이언트 라이브러리를 사용하여 음성을 텍스트로 변환하기

이 페이지에서는 Google Cloud 클라이언트 라이브러리를 사용하여 선호하는 프로그래밍 언어로 Speech-to-Text에 음성 인식 요청을 보내는 방법을 설명합니다.

Speech-to-Text를 사용하면 Google 음성 인식 기술을 개발자 애플리케이션에 간편하게 통합할 수 있습니다. 오디오 데이터를 Speech-to-Text API로 보내면 Speech-to-Text API가 해당 오디오 파일의 텍스트 스크립트를 반환합니다. 이 서비스에 대한 자세한 내용은 Speech-to-Text 기본사항을 참조하세요.

시작하기 전에

  1. Google Cloud 계정에 로그인합니다. Google Cloud를 처음 사용하는 경우 계정을 만들고 Google 제품의 실제 성능을 평가해 보세요. 신규 고객에게는 워크로드를 실행, 테스트, 배포하는 데 사용할 수 있는 $300의 무료 크레딧이 제공됩니다.
  2. Google Cloud Console의 프로젝트 선택기 페이지에서 Google Cloud 프로젝트를 선택하거나 만듭니다.

    프로젝트 선택기로 이동

  3. Google Cloud 프로젝트에 결제가 사용 설정되어 있는지 확인합니다.

  4. API Speech-to-Text 사용 설정

    API 사용 설정

  5. 프로젝트에 다음 역할이 있는지 확인합니다. Cloud Speech Administrator

    역할 확인

    1. Google Cloud 콘솔에서 IAM 페이지로 이동합니다.

      IAM으로 이동
    2. 프로젝트를 선택합니다.
    3. 주 구성원 열에서 이메일 주소가 있는 행을 찾습니다.

      이메일 주소가 열에 없으면 역할이 없는 것입니다.

    4. 이메일 주소가 있는 행에 대해 역할 열에서 역할 목록에 필요한 역할이 있는지 확인합니다.

    역할 부여

    1. Google Cloud 콘솔에서 IAM 페이지로 이동합니다.

      IAM으로 이동
    2. 프로젝트를 선택합니다.
    3. 액세스 권한 부여를 클릭합니다.
    4. 새 주 구성원 필드에 이메일 주소를 입력합니다.
    5. 역할 선택 목록에서 역할을 선택합니다.
    6. 역할을 추가로 부여하려면 다른 역할 추가를 클릭하고 각 역할을 추가합니다.
    7. 저장을 클릭합니다.
  6. Google Cloud CLI를 설치합니다.
  7. gcloud CLI를 초기화하려면 다음 명령어를 실행합니다.

    gcloud init
  8. Google Cloud Console의 프로젝트 선택기 페이지에서 Google Cloud 프로젝트를 선택하거나 만듭니다.

    프로젝트 선택기로 이동

  9. Google Cloud 프로젝트에 결제가 사용 설정되어 있는지 확인합니다.

  10. API Speech-to-Text 사용 설정

    API 사용 설정

  11. 프로젝트에 다음 역할이 있는지 확인합니다. Cloud Speech Administrator

    역할 확인

    1. Google Cloud 콘솔에서 IAM 페이지로 이동합니다.

      IAM으로 이동
    2. 프로젝트를 선택합니다.
    3. 주 구성원 열에서 이메일 주소가 있는 행을 찾습니다.

      이메일 주소가 열에 없으면 역할이 없는 것입니다.

    4. 이메일 주소가 있는 행에 대해 역할 열에서 역할 목록에 필요한 역할이 있는지 확인합니다.

    역할 부여

    1. Google Cloud 콘솔에서 IAM 페이지로 이동합니다.

      IAM으로 이동
    2. 프로젝트를 선택합니다.
    3. 액세스 권한 부여를 클릭합니다.
    4. 새 주 구성원 필드에 이메일 주소를 입력합니다.
    5. 역할 선택 목록에서 역할을 선택합니다.
    6. 역할을 추가로 부여하려면 다른 역할 추가를 클릭하고 각 역할을 추가합니다.
    7. 저장을 클릭합니다.
  12. Google Cloud CLI를 설치합니다.
  13. gcloud CLI를 초기화하려면 다음 명령어를 실행합니다.

    gcloud init
  14. 클라이언트 라이브러리는 애플리케이션 기본 사용자 인증 정보를 사용하여 간편하게 Google API를 인증하고 API에 요청을 보낼 수 있습니다. 애플리케이션 기본 사용자 인증 정보를 사용하면 애플리케이션을 로컬에서 테스트하고 기본 코드를 변경하지 않은 상태로 배포할 수 있습니다. 자세한 내용은 <atrack-type="commonincludes" l10n-attrs-original-order="href,track-type,track-name" l10n-encrypted-href="WDE63JFVMK0YqIWBqG8nCycgwkRfOeEqRvzYs1N+2tJUEhcZvE5VtDH5LoWw0lj/" track-name="referenceLink">클라이언트 라이브러리 사용 인증</atrack-type="commonincludes">을 참조하세요.

  15. Google 계정의 로컬 인증 사용자 인증 정보를 만듭니다.

    gcloud auth application-default login

또한 클라이언트 라이브러리를 설치했는지 확인합니다.

오디오 텍스트 변환 요청하기

Speech-to-Text API에 Recognize 요청을 보내려면 다음 코드를 사용하세요.

Java

// Imports the Google Cloud client library
import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.speech.v2.AutoDetectDecodingConfig;
import com.google.cloud.speech.v2.CreateRecognizerRequest;
import com.google.cloud.speech.v2.OperationMetadata;
import com.google.cloud.speech.v2.RecognitionConfig;
import com.google.cloud.speech.v2.RecognizeRequest;
import com.google.cloud.speech.v2.RecognizeResponse;
import com.google.cloud.speech.v2.Recognizer;
import com.google.cloud.speech.v2.SpeechClient;
import com.google.cloud.speech.v2.SpeechRecognitionAlternative;
import com.google.cloud.speech.v2.SpeechRecognitionResult;
import com.google.protobuf.ByteString;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.concurrent.ExecutionException;

public class QuickstartSampleV2 {

  public static void main(String[] args) throws IOException, ExecutionException,
      InterruptedException {
    String projectId = "my-project-id";
    String filePath = "path/to/audioFile.raw";
    String recognizerId = "my-recognizer-id";
    quickstartSampleV2(projectId, filePath, recognizerId);
  }

  public static void quickstartSampleV2(String projectId, String filePath, String recognizerId)
      throws IOException, ExecutionException, InterruptedException {

    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (SpeechClient speechClient = SpeechClient.create()) {
      Path path = Paths.get(filePath);
      byte[] data = Files.readAllBytes(path);
      ByteString audioBytes = ByteString.copyFrom(data);

      String parent = String.format("projects/%s/locations/global", projectId);

      // First, create a recognizer
      Recognizer recognizer = Recognizer.newBuilder()
          .setModel("latest_long")
          .addLanguageCodes("en-US")
          .build();

      CreateRecognizerRequest createRecognizerRequest = CreateRecognizerRequest.newBuilder()
          .setParent(parent)
          .setRecognizerId(recognizerId)
          .setRecognizer(recognizer)
          .build();

      OperationFuture<Recognizer, OperationMetadata> operationFuture =
          speechClient.createRecognizerAsync(createRecognizerRequest);
      recognizer = operationFuture.get();

      // Next, create the transcription request
      RecognitionConfig recognitionConfig = RecognitionConfig.newBuilder()
          .setAutoDecodingConfig(AutoDetectDecodingConfig.newBuilder().build())
          .build();

      RecognizeRequest request = RecognizeRequest.newBuilder()
          .setConfig(recognitionConfig)
          .setRecognizer(recognizer.getName())
          .setContent(audioBytes)
          .build();

      RecognizeResponse response = speechClient.recognize(request);
      List<SpeechRecognitionResult> results = response.getResultsList();

      for (SpeechRecognitionResult result : results) {
        // There can be several alternative transcripts for a given chunk of speech. Just use the
        // first (most likely) one here.
        if (result.getAlternativesCount() > 0) {
          SpeechRecognitionAlternative alternative = result.getAlternativesList().get(0);
          System.out.printf("Transcription: %s%n", alternative.getTranscript());
        }
      }
    }
  }
}

Python

from google.cloud.speech_v2 import SpeechClient
from google.cloud.speech_v2.types import cloud_speech

def quickstart_v2(
    project_id: str,
    audio_file: str,
) -> cloud_speech.RecognizeResponse:
    """Transcribe an audio file."""
    # Instantiates a client
    client = SpeechClient()

    # Reads a file as bytes
    with open(audio_file, "rb") as f:
        content = f.read()

    config = cloud_speech.RecognitionConfig(
        auto_decoding_config=cloud_speech.AutoDetectDecodingConfig(),
        language_codes=["en-US"],
        model="long",
    )

    request = cloud_speech.RecognizeRequest(
        recognizer=f"projects/{project_id}/locations/global/recognizers/_",
        config=config,
        content=content,
    )

    # Transcribes the audio into text
    response = client.recognize(request=request)

    for result in response.results:
        print(f"Transcript: {result.alternatives[0].transcript}")

    return response

첫 번째 요청을 Speech-to-Text에 보냈습니다.

삭제

이 페이지에서 사용한 리소스 비용이 Google Cloud 계정에 청구되지 않도록 하려면 다음 단계를 수행합니다.

  1. 선택사항: 만든 사용자 인증 정보를 취소하고 로컬 사용자 인증 정보 파일을 삭제합니다.

    gcloud auth application-default revoke
  2. 선택사항: gcloud CLI에서 사용자 인증 정보를 취소합니다.

    gcloud auth revoke

콘솔

  • Google Cloud 콘솔에서 리소스 관리 페이지로 이동합니다.

    리소스 관리로 이동

  • 프로젝트 목록에서 삭제할 프로젝트를 선택하고 삭제를 클릭합니다.
  • 대화상자에서 프로젝트 ID를 입력한 후 종료를 클릭하여 프로젝트를 삭제합니다.
  • gcloud

    Google Cloud 프로젝트를 삭제합니다.

    gcloud projects delete PROJECT_ID

    다음 단계