Cloud Code で Cloud クライアント ライブラリを使用する

このページでは、Cloud クライアント ライブラリと Cloud Code をすぐに使い始める方法について説明します。Hello World サンプル アプリケーションを使用して新しい Kubernetes アプリケーションを設定し、Cloud Translation API を使用してレスポンスをスペイン語に翻訳するようにアプリケーションを更新します。

始める前に

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. Google Cloud Console の [プロジェクト セレクタ] ページで、Google Cloud プロジェクトを選択または作成します。

    プロジェクト セレクタに移動

  3. Google Cloud プロジェクトで課金が有効になっていることを確認します

  4. Google Kubernetes Engine and Cloud Translation API を有効にします。

    API を有効にする

  5. Google Cloud Console の [プロジェクト セレクタ] ページで、Google Cloud プロジェクトを選択または作成します。

    プロジェクト セレクタに移動

  6. Google Cloud プロジェクトで課金が有効になっていることを確認します

  7. Google Kubernetes Engine and Cloud Translation API を有効にします。

    API を有効にする

  8. Git をインストールして、Cloud Code がサンプルのクローン作成などの Git オペレーションを実行できるようにします。
  9. Cloud Code プラグインをインストールします(まだインストールしていない場合)。

アプリケーションの作成

  1. コマンド パレット(Cmd/Ctrl +Shift +P )を使用して、Cloud Code: 新しいアプリケーションKubernetes アプリケーションを実行し、お好みの言語の Hello World アプリを選択します。たとえば、スターターの Node.js Hello World アプリを作成するには、[Node.js: Hello World] を選択します。
  2. 新しいアプリケーションを保存します。 アプリケーションが作成されたことを確認する通知が表示され、アプリケーションの新しいウィンドウが開きます。

認証情報の設定

  1. ターミナルを開くには、[ターミナル] > [新しいターミナル] をクリックします。

  2. API リクエストを認証するためのサービス アカウントを作成します。

    gcloud iam service-accounts create \
    translation-quickstart \
    --project PROJECT_ID
    
  3. サービス アカウントに Cloud Translation API ユーザーのロールを付与します。

    gcloud projects \
    add-iam-policy-binding \
    PROJECT_ID \
    --member='serviceAccount:translation-quickstart@PROJECT_ID.iam.gserviceaccount.com' \
    --role='roles/cloudtranslate.user'
    
  4. サービス アカウント キーを作成します。

    gcloud iam service-accounts keys \
    create key.json --iam-account \
    translation-quickstart@PROJECT_ID.iam.gserviceaccount.com
    
  5. このキーをデフォルトの認証情報として設定します。

    export \
     GOOGLE_APPLICATION_CREDENTIALS=key.json
    

アプリケーションから Cloud Translation API を呼び出す

Go

  1. Cloud Translation API の Cloud クライアント ライブラリをインストールします。

    1. ターミナルを開くには、[ターミナル] > [新しいターミナル] をクリックします。
    2. 次のコマンドを実行します。

      go get cloud.google.com/go/translate/apiv3
      
  2. app.go ファイルを作成します。

  3. app.go を開き、パッケージ名、インポート、アプリ スケルトンを追加します。

    package main
    
    import (
      "context"
      "fmt"
    
      translate "cloud.google.com/go/translate/apiv3"
      translatepb "google.golang.org/genproto/googleapis/cloud/translate/v3"
    )
    
    func translateText(w io.Writer, projectID string, sourceLang string, targetLang string, text string) error {
    
    }
    
    func main() {
    
    }
    
  4. translateText() 関数に、指定したテキストを翻訳する次のコードを追加します。[ファイル] > [保存] を選択して、コードの形式を変更します。

    ctx := context.Background()
    client, err := translate.NewTranslationClient(ctx)
    if err != nil {
      return fmt.Errorf("NewTranslationClient: %v", err)
    }
    defer client.Close()
    
    req := &translatepb.TranslateTextRequest{
      Parent:             fmt.Sprintf("projects/%s/locations/global", projectID),
      SourceLanguageCode: sourceLang,
      TargetLanguageCode: targetLang,
      MimeType:           "text/plain", // Mime types: "text/plain", "text/html"
      Contents:           []string{text},
    }
    
    resp, err := client.TranslateText(ctx, req)
    if err != nil {
      return fmt.Errorf("TranslateText: %v", err)
    }
    
    // Display the translation for each input text provided
    for _, translation := range resp.GetTranslations() {
      fmt.Fprintf(w, "Translated text: %v\n", translation.GetTranslatedText())
    }
    
    return nil
    
  5. main() 関数で、translateText() を呼び出します。次のパラメータ値は、英語をスペイン語に翻訳します。

    projectID := "<var>PROJECT_ID</var>"
    sourceLang := "en-US"
    targetLang := "es"
    text := "Text to translate"
    
    err := translateText(os.Stdout, projectID, sourceLang, targetLang, text)
    if err != nil {
      fmt.Print(err)
    }
    
  6. ターミナルからアプリケーションを実行します。

    go run app.go
    

Node.js

  1. Cloud Translation API の Cloud クライアント ライブラリをインストールします。

    1. [Cloud Code] をクリックし、[Cloud APIs] エクスプローラを展開します。
    2. [Cloud AI] を展開し、[Cloud Translation API] をクリックします。
    3. クライアント ライブラリをインストールするには、[NodeJS] をクリックして、play_arrow [ターミナルで実行] をクリックします。
  2. プロジェクト内で app.js ファイルを作成します。

  3. app.js を開き、ファイルの先頭で Translation クライアント ライブラリをインポートします。

    const {TranslationServiceClient} = require('@google-cloud/translate');
    
  4. Translation API クライアントを作成し、プロジェクト ID、ロケーション、翻訳するテキストの変数を追加します。

    // Instantiates a client
    const translationClient = new TranslationServiceClient();
    
    const projectId = 'PROJECT_ID';
    const location = 'global';
    const text = 'Hello, world!';
    
  5. Hello, world! テキストの言語を検出し、テキストをスペイン語に翻訳する次の async 関数を追加します。

    async function translateText() {
        // Construct request
        const request = {
            parent: `projects/PROJECT_ID/locations/LOCATION`,
            contents: [text],
            mimeType: 'text/plain', // mime types: text/plain, text/html
            sourceLanguageCode: 'en',
            targetLanguageCode: 'es',
        };
    
        // Run request
        const [response] = await translationClient.translateText(request);
    
        for (const translation of response.translations) {
            console.log(`Translation: ${translation.translatedText}`);
        }
    }
    
  6. app.js ファイルの最後で translateText() を呼び出します。

    translateText();
    
  7. アプリケーションを実行するには、コマンド パレット(Ctrl/Cmd +Shift +P を押下)を開いて、 Cloud Code: Kubernetes での実行 を実行します。

  8. アプリケーションがデプロイされたら、webview に表示された URL を開いて、実行中のサービスを表示します。

Python

  1. Cloud Translation API の Cloud クライアント ライブラリをインストールします。

    1. [Cloud Code] をクリックし、[Cloud APIs] エクスプローラを展開します。
    2. [Cloud AI] を展開し、[Cloud Translation API] をクリックします。
    3. クライアント ライブラリをインストールするには、[Python] をクリックして、play_arrow [ターミナルで実行] をクリックします。
      注: Chromebook などの Linux ベースのオペレーティング システムを使用している場合は、pip ではなく pip3 を使用するようにコマンドを変更します。Mac を使用している場合は、pip3 を使用して --user フラグを追加するようにコマンドを変更します。
  2. プロジェクト内で app.py ファイルを作成します。

  3. app.py で、ファイルの先頭でクライアント ライブラリをインポートします。

    from google.cloud import translate
    
  4. translate_text 関数を追加します。これにより、Cloud Translation API を操作するために、クライアントを初期化します。

    def translate_text(text="Hello, world!", project_id="PROJECT_ID"):
    
    client = translate.TranslationServiceClient()
    location = "global"
    parent = "projects/PROJECT_ID/locations/LOCATION"
    
  5. テキストを英語からスペイン語に翻訳して結果を出力するには、translate_text 関数で次の呼び出しを Cloud Translation API Cloud クライアント ライブラリに追加します。

       response = client.translate_text(
        request={
            "parent": parent,
            "contents": [text],
            "mime_type": "text/plain",
            "source_language_code": "en-US",
            "target_language_code": "es",
        }
    )
    
    for translation in response.translations:
        print("Translated text: {}".format(translation.translated_text))
    
  6. app.py の最後で translate_text() を呼び出します。

    translate_text()
    
  7. アプリケーションを実行するには、コマンド パレット(Ctrl/Cmd +Shift +P を押下)を開いて、 Cloud Code: Kubernetes での実行 を実行します。

  8. アプリケーションがデプロイされたら、webview に表示された URL を開いて、実行中のサービスを表示します。

クリーンアップ

アプリケーションを中止すると、実行中にデプロイされたすべての Kubernetes リソースは自動で削除されます。

このクイックスタートで使用した他のリソースについてアカウントに課金されないようにするには、プロジェクトを再利用する場合、プロジェクトを削除するか、作成したクラスタを削除してください。

クラスタを削除するには:

  1. Kubernetes Explorer で、クラスタ名を一時停止し、open_in_new [Google Cloud コンソールで開く] をクリックします。
  2. [削除] をクリックし、[削除] をクリックします。

プロジェクト(およびクラスタを含む関連リソース)を削除するには、次のようにします。

  1. Google Cloud コンソールで、[リソースの管理] ページに移動します。

    [リソースの管理] に移動

  2. プロジェクト リストで、削除するプロジェクトを選択し、[削除] をクリックします。
  3. ダイアログでプロジェクト ID を入力し、[シャットダウン] をクリックしてプロジェクトを削除します。

サポートを利用する

フィードバックを送信するには、GitHub で問題を報告します。または、Stack Overflow で質問します。

次のステップ