Speech-to-Text 클라이언트 라이브러리

}

이 페이지에서는 Speech-to-Text API의 Cloud 클라이언트 라이브러리를 시작하는 방법을 보여줍니다. 클라이언트 라이브러리를 사용하면 지원되는 언어로 Google Cloud API에 쉽게 액세스할 수 있습니다. 원시 요청을 서버에 보내 Google Cloud API를 직접 사용할 수 있지만 클라이언트 라이브러리는 작성해야 하는 코드 양을 크게 줄여 주는 간소화 기능을 제공합니다.

클라이언트 라이브러리 설명에서 Cloud 클라이언트 라이브러리 및 이전 Google API 클라이언트 라이브러리에 대해 자세히 알아보세요.

클라이언트 라이브러리 설치

C#

Install-Package Google.Cloud.Speech.V2

자세한 내용은 C# 개발 환경 설정을 참조하세요.

Go

go get cloud.google.com/go/speech/apiv2

자세한 내용은 Go 개발 환경 설정을 참조하세요.

Java

Maven을 사용하는 경우 pom.xml 파일에 다음을 추가합니다. BOM에 대한 자세한 내용은 Google Cloud Platform 라이브러리 BOM을 참조하세요.

<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>com.google.cloud</groupId>
      <artifactId>libraries-bom</artifactId>
      <version>26.37.0</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>

<dependencies>
  <dependency>
    <groupId>com.google.cloud</groupId>
    <artifactId>google-cloud-speech</artifactId>
  </dependency>

Gradle을 사용하는 경우 종속 항목에 다음을 추가합니다.

implementation 'com.google.cloud:google-cloud-speech:4.36.0'

SBT를 사용하는 경우 종속 항목에 다음을 추가합니다.

libraryDependencies += "com.google.cloud" % "google-cloud-speech" % "4.36.0"

Visual Studio Code, IntelliJ 또는 Eclipse를 사용하는 경우 다음 IDE 플러그인을 사용하여 클라이언트 라이브러리를 프로젝트에 추가할 수 있습니다.

이 플러그인은 서비스 계정의 키 관리와 같은 추가 기능을 제공합니다. 자세한 내용은 각 플러그인의 문서를 참조하세요.

자세한 내용은 자바 개발 환경 설정을 참조하세요.

Node.js

npm install --save @google-cloud/speech

자세한 내용은 Node.js 개발 환경 설정을 참조하세요.

PHP

composer require google/cloud/speech

자세한 내용은 Google Cloud에서 PHP 사용을 참조하세요.

Python

pip install --upgrade google-cloud-speech

자세한 내용은 Python 개발 환경 설정을 참조하세요.

Ruby

gem install google-cloud-speech

자세한 내용은 Ruby 개발 환경 설정을 참조하세요.

인증 설정

Google Cloud API 호출을 인증하기 위해 클라이언트 라이브러리는 애플리케이션 기본 사용자 인증 정보(ADC)를 지원합니다. 라이브러리가 정의된 위치 집합에서 사용자 인증 정보를 찾고 이러한 사용자 인증 정보를 사용하여 API에 대한 요청을 인증합니다. ADC를 사용하면 애플리케이션 코드를 수정할 필요 없이 로컬 개발 또는 프로덕션과 같은 다양한 환경에서 애플리케이션에 사용자 인증 정보를 제공할 수 있습니다.

프로덕션 환경에서 ADC를 설정하는 방법은 서비스와 컨텍스트에 따라 다릅니다. 자세한 내용은 애플리케이션 기본 사용자 인증 정보 설정을 참조하세요.

로컬 개발 환경의 경우 Google 계정과 연결된 사용자 인증 정보를 사용하여 ADC를 설정할 수 있습니다.

  1. gcloud CLI를 설치하고 초기화합니다.

    gcloud CLI를 초기화할 때 애플리케이션에 필요한 리소스에 액세스할 수 있는 권한이 있는 Google Cloud 프로젝트를 지정해야 합니다.

  2. 사용자 인증 정보 파일을 만듭니다.

    gcloud auth application-default login

    로그인 화면이 표시됩니다. 로그인 후 사용자 인증 정보는 ADC에 사용하는 로컬 사용자 인증 정보 파일에 저장됩니다.

클라이언트 라이브러리 사용

다음 예시에서는 클라이언트 라이브러리를 사용하는 방법을 보여줍니다.

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

추가 리소스

C#

다음 목록에는 C#용 클라이언트 라이브러리와 관련된 추가 리소스에 대한 링크가 포함되어 있습니다.

Go

다음 목록에는 Go용 클라이언트 라이브러리와 관련된 추가 리소스에 대한 링크가 포함되어 있습니다.

Java

다음 목록에는 자바용 클라이언트 라이브러리와 관련된 추가 리소스에 대한 링크가 포함되어 있습니다.

Node.js

다음 목록에는 Node.js용 클라이언트 라이브러리와 관련된 추가 리소스에 대한 링크가 포함되어 있습니다.

PHP

다음 목록에는 PHP용 클라이언트 라이브러리와 관련된 추가 리소스에 대한 링크가 포함되어 있습니다.

Python

다음 목록에는 Python용 클라이언트 라이브러리와 관련된 추가 리소스에 대한 링크가 포함되어 있습니다.

Ruby

다음 목록에는 Ruby용 클라이언트 라이브러리와 관련된 추가 리소스의 링크가 포함되어 있습니다.