Cloud Code で Cloud クライアント ライブラリを使用する
このページでは、Cloud クライアント ライブラリと Cloud Code をすぐに使い始める方法について説明します。Hello World サンプル アプリケーションを使用して新しい Kubernetes アプリケーションを設定し、Cloud Translation API を使用してレスポンスをスペイン語に翻訳するようにアプリケーションを更新します。
始める前に
- Google Cloud アカウントにログインします。 Google Cloudを初めて使用する場合は、 アカウントを作成して、実際のシナリオでの Google プロダクトのパフォーマンスを評価してください。新規のお客様には、ワークロードの実行、テスト、デプロイができる無料クレジット $300 分を差し上げます。
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
Roles required to select or create a project
- Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
-
Create a project: To create a project, you need the Project Creator role
(
roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.createpermission. Learn how to grant roles.
-
Verify that billing is enabled for your Google Cloud project.
Enable the Google Kubernetes Engine and Cloud Translation APIs.
Roles required to enable APIs
To enable APIs, you need the Service Usage Admin IAM role (
roles/serviceusage.serviceUsageAdmin), which contains theserviceusage.services.enablepermission. Learn how to grant roles.-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
Roles required to select or create a project
- Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
-
Create a project: To create a project, you need the Project Creator role
(
roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.createpermission. Learn how to grant roles.
-
Verify that billing is enabled for your Google Cloud project.
Enable the Google Kubernetes Engine and Cloud Translation APIs.
Roles required to enable APIs
To enable APIs, you need the Service Usage Admin IAM role (
roles/serviceusage.serviceUsageAdmin), which contains theserviceusage.services.enablepermission. Learn how to grant roles.- Git をインストールして、Cloud Code がサンプルのクローン作成などの Git オペレーションを実行できるようにします。
- Cloud Code プラグインをインストールします(まだインストールしていない場合)。
アプリケーションを作成する
- コマンド パレット(
Cmd/Ctrl+Shift+P)を使用して、Cloud Code: 新しいアプリケーション、Kubernetes アプリケーションを実行し、お好みの言語の Hello World アプリを選択します。たとえば、[Node.js: Hello World] を選択すると、スターターの Node.js Hello World アプリが作成されます。 - 新しいアプリケーションを保存します。 アプリケーションが作成されたことを確認する通知が表示され、アプリケーションの新しいウィンドウが開きます。
認証情報の設定
ターミナルを開くには、[ターミナルl] > [新しいターミナル] をクリックします。
API リクエストを認証するためのサービス アカウントを作成します。
gcloud iam service-accounts create \ translation-quickstart \ --project PROJECT_ID
サービス アカウントに Cloud Translation API ユーザーのロールを付与します。
gcloud projects \ add-iam-policy-binding \ PROJECT_ID \ --member='serviceAccount:translation-quickstart@PROJECT_ID.iam.gserviceaccount.com' \ --role='roles/cloudtranslate.user'
サービス アカウント キーを作成します。
gcloud iam service-accounts keys \ create key.json --iam-account \ translation-quickstart@PROJECT_ID.iam.gserviceaccount.com
このキーをデフォルトの認証情報として設定します。
export \ GOOGLE_APPLICATION_CREDENTIALS=key.json
アプリケーションから Cloud Translation API を呼び出す
Go
Cloud Translation API Cloud クライアント ライブラリをインストールします。
- ターミナルを開くには、[ターミナルl] > [新しいターミナル] をクリックします。
次のコマンドを実行します。
go get cloud.google.com/go/translate/apiv3
app.goファイルを作成します。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() { }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 nilmain()関数で、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) }ターミナルからアプリケーションを実行します。
go run app.go
Java
pom.xmlを開き、次のコード スニペットをdependenciesセクションに追加します。<dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <dependency> <groupId>com.google.cloud</groupId> <artifactId>google-cloud-translate</artifactId> </dependency> </dependencies>次に、
pom.xmlファイルのdependencyManagementセクションに次のコード スニペットを追加します。<dependencyManagement> <dependencies> <dependency> <groupId>com.google.cloud</groupId> <artifactId>libraries-bom</artifactId> <version>26.39.0</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement>Google Cloud のサポートされているライブラリの最新バージョンを使用していることを確認します。バージョンの一覧については、Google Cloud のサポートされているライブラリをご覧ください。
Java クラスパス / 構成を同期するかどうかを尋ねられたら、[Always] をクリックします。
app.javaという名前のファイルを作成します。app.javaで、パッケージ定義の後に次のインポートを記述します。import com.google.cloud.translate.v3.LocationName; import com.google.cloud.translate.v3.TranslateTextRequest; import com.google.cloud.translate.v3.TranslateTextResponse; import com.google.cloud.translate.v3.Translation; import com.google.cloud.translate.v3.TranslationServiceClient; import java.io.IOException;AppクラスにtranslateText()メソッドを追加します。このメソッドは、変数を設定してオーバーロードされたtranslateText()メソッドに渡します。次の値は、英語からスペイン語に翻訳します。public static void translateText() throws IOException { String projectId = "<walkthrough-project-id/>"; String targetLanguage = "es"; String text = "Hello world!"; translateText(projectId, targetLanguage, text); }オーバーロードされた
translateText()メソッドを追加します。このメソッドはテキストを受け取り、ターゲット言語に翻訳します。public static void translateText(String projectId, String targetLanguage, String text) throws IOException { try (TranslationServiceClient client = TranslationServiceClient.create()) { LocationName parent = LocationName.of(projectId, "global"); TranslateTextRequest request = TranslateTextRequest.newBuilder() .setParent(parent.toString()) .setMimeType("text/plain") .setTargetLanguageCode(targetLanguage) .addContents(text) .build(); TranslateTextResponse response = client.translateText(request); // Display the translation for each input text provided for (Translation translation : response.getTranslationsList()) { System.out.printf("Translated text: %s\n", translation.getTranslatedText()); } } }mainのプリント ステートメントをtranslateText()の呼び出しに置き換えます。try { translateText(); } catch (IOException e) { e.printStackTrace(); }
Node.js
Cloud Translation API Cloud クライアント ライブラリをインストールします。
[Cloud Code] をクリックし、[Cloud APIs] エクスプローラを展開します。
- [Cloud AI] を展開し、[Cloud Translation API] をクリックします。
- クライアント ライブラリをインストールするには、[NodeJS] をクリックして、play_arrow [ターミナルで実行] をクリックします。
プロジェクトに
app.jsファイルを作成します。app.jsを開き、ファイルの先頭で Translation クライアント ライブラリをインポートします。const {TranslationServiceClient} = require('@google-cloud/translate');Translation API クライアントを作成し、プロジェクト ID、ロケーション、翻訳するテキストの変数を追加します。
// Instantiates a client const translationClient = new TranslationServiceClient(); const projectId = 'PROJECT_ID'; const location = 'global'; const text = 'Hello, world!';
次の
async関数を追加します。この関数は、Hello, world!テキストの言語を検出し、テキストをスペイン語に翻訳します。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}`); } }app.jsファイルの最後でtranslateText()を呼び出します。translateText();アプリケーションを実行するには、コマンド パレット(
Ctrl/Cmd+Shift+Pを押下)を開いて、 Cloud Code: Kubernetes での実行 を実行します。アプリケーションがデプロイされたら、webview に表示された URL を開いて、実行中のサービスを表示します。
Python
Cloud Translation API Cloud クライアント ライブラリをインストールします。
[Cloud Code] をクリックし、[Cloud APIs] エクスプローラを展開します。
- [Cloud AI] を展開し、[Cloud Translation API] をクリックします。
- クライアント ライブラリをインストールするには、[Python] をクリックして、play_arrow [ターミナルで実行] をクリックします。
注: Chromebook などの Linux ベースのオペレーティング システムを使用している場合は、pipではなくpip3を使用するようにコマンドを変更します。Mac を使用している場合は、pip3を使用して--userフラグを追加するようにコマンドを変更します。
プロジェクトに
app.pyファイルを作成します。app.pyで、ファイルの先頭でクライアント ライブラリをインポートします。from google.cloud import translate
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"
英語からスペイン語にテキストを翻訳して結果を出力するには、
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))app.pyの最後にtranslate_text()を呼び出します。translate_text()アプリケーションを実行するには、コマンド パレット(
Ctrl/Cmd+Shift+Pを押下)を開いて、 Cloud Code: Kubernetes での実行 を実行します。アプリケーションがデプロイされたら、webview に表示された URL を開いて、実行中のサービスを表示します。
クリーンアップ
アプリケーションを中止すると、実行中にデプロイされたすべての Kubernetes リソースは自動で削除されます。
このクイックスタートで使用した他のリソースについてアカウントに課金されないようにするには、プロジェクトを再利用する場合、プロジェクトを削除するか、作成したクラスタを削除してください。
クラスタを削除するには:
- Kubernetes Explorer で、クラスタ名を一時停止し、open_in_new [ Google Cloud コンソールで開く] をクリックします。
- [削除] をクリックし、[削除] をクリックします。
プロジェクト(およびクラスタを含む関連リソース)を削除するには、次のようにします。
- Google Cloud コンソールで [リソースの管理] ページに移動します。
- プロジェクト リストで、削除するプロジェクトを選択し、[削除] をクリックします。
- ダイアログでプロジェクト ID を入力し、[シャットダウン] をクリックしてプロジェクトを削除します。
サポートを利用する
フィードバックを送信するには、GitHub で問題を報告します。または、Stack Overflow で質問します。次のステップ
- Cloud Translation API の詳細を確認する
- Cloud クライアント ライブラリの詳細を確認する
- Cloud Code for VS Code の詳細を確認する