在 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. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  3. Make sure that billing is enabled for your Google Cloud project.

  4. Enable the Google Kubernetes Engine and Cloud Translation APIs.

    Enable the APIs

  5. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  6. Make sure that billing is enabled for your Google Cloud project.

  7. Enable the Google Kubernetes Engine and Cloud Translation APIs.

    Enable the APIs

  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. 如要開啟終端機,請依序點選「Terminal」>「New Terminal」

  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. 如要開啟終端機,請依序點選「Terminal」>「New Terminal」
    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() 函式中新增下列程式碼,用於翻譯指定文字。依序選取「File」>「Save」來重新設定程式碼格式:

    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
    

Java

  1. 開啟 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>
    
  2. 接著,在 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 支援的程式庫」。

  3. 系統詢問您是否要同步處理 Java 類別路徑/設定時,請按一下「Always」(一律)

  4. 建立名為 app.java 的檔案。

  5. 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;
    
  6. translateText() 方法新增至 App 類別。這個方法會設定變數,並將其傳送至過載的 translateText() 方法。下列值會將英文翻譯成西班牙文:

    public static void translateText() throws IOException {
      String projectId = "<walkthrough-project-id/>";
      String targetLanguage = "es";
      String text = "Hello world!";
      translateText(projectId, targetLanguage, text);
    }
    
  7. 新增過載的 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());
        }
      }
    }
    
  8. main 中的輸出陳述式替換為呼叫 translateText()

    try {
      translateText();
    }
    catch (IOException e) {
      e.printStackTrace();
    }
    

Node.js

  1. 安裝 Cloud Translation API Cloud 用戶端程式庫:

    1. 按一下「Cloud Code」,然後展開「Cloud APIs」Explorer。
    2. 展開「Cloud AI」,然後按一下「Cloud Translation API」
    3. 如要安裝用戶端程式庫,請依序點選「NodeJS」和「Run in terminal」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. 新增下列 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}`);
        }
    }
    
  6. app.js 檔案結尾呼叫 translateText()

    translateText();
    
  7. 如要執行應用程式,請開啟指令面板 (按下 Ctrl/Cmd + Shift + P 鍵),然後執行「Cloud Code: Run on Kubernetes」

  8. 應用程式部署完成後,請開啟 webview 中顯示的網址,查看執行中的服務。

Python

  1. 安裝 Cloud Translation API Cloud 用戶端程式庫:

    1. 按一下「Cloud Code」,然後展開「Cloud APIs」Explorer。
    2. 展開「Cloud AI」,然後按一下「Cloud Translation API」
    3. 如要安裝用戶端程式庫,請依序點選「Python」play_arrow「在終端機中執行」
      注意:如果您使用的是 Chromebook 等以 Linux 為基礎的作業系統,請修改指令,改用 pip3 而非 pip。如果您使用的是 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: Run on Kubernetes」

  8. 應用程式部署完成後,請開啟 webview 中顯示的網址,查看執行中的服務。

清除所用資源

停止應用程式後,系統會自動刪除執行期間部署的所有 Kubernetes 資源。

如要避免系統向您的帳戶收取這份快速入門課程中所用其他資源的費用,請務必刪除專案,或刪除您建立的叢集 (如果您想重複使用專案的話)。

如要刪除叢集:

  1. 在 Kubernetes Explorer 中,暫停在叢集名稱上,然後按一下「open_in_new」open_in_new「Open in Google Cloud console」(在控制台中開啟)。
  2. 按一下「Delete」(刪除),然後點選「Delete」(刪除)

如要刪除專案 (以及相關聯的資源,包括任何叢集),請按照下列步驟操作:

  1. In the Google Cloud console, go to the Manage resources page.

    Go to Manage resources

  2. In the project list, select the project that you want to delete, and then click Delete.
  3. In the dialog, type the project ID, and then click Shut down to delete the project.

取得支援

如要提供意見回饋,請在 GitHub 上回報問題,或在 Stack Overflow 上提問。

後續步驟