使用 Cloud Translation 連接器執行批次翻譯作業

本教學課程說明如何建立工作流程,使用 Cloud Translation API 連接器以非同步批次模式將檔案翻譯成其他語言。這項功能會在處理輸入內容時,即時提供輸出內容。

建立輸入 Cloud Storage bucket 和檔案

您可以使用 Cloud Storage 儲存物件。物件是不可變更的資料片段,由任何格式的檔案組成,並儲存在稱為 bucket 的容器中。

  1. 建立 Cloud Storage bucket,用來存放要翻譯的檔案:

    BUCKET_INPUT=${GOOGLE_CLOUD_PROJECT}-input-files
    gcloud storage buckets create gs://${BUCKET_INPUT}
  2. 以英文建立兩個檔案,然後上傳至輸入 bucket:

    echo "Hello World!" > file1.txt
    gcloud storage cp file1.txt gs://${BUCKET_INPUT}
    echo "Workflows connectors simplify calling services." > file2.txt
    gcloud storage cp file2.txt gs://${BUCKET_INPUT}

部署及執行工作流程

工作流程是由一系列步驟組成,這些步驟使用 Workflows 語法描述,且可採用 YAML 或 JSON 格式編寫。這是工作流程的定義。建立工作流程後,請部署工作流程,以便執行。

  1. 建立檔案名稱為 workflow.yaml 的文字檔案,並加入下列內容:

    main:
      steps:
      - init:
          assign:
          - projectId: ${sys.get_env("GOOGLE_CLOUD_PROJECT_ID")}
          - location: ${sys.get_env("GOOGLE_CLOUD_LOCATION")}
          - inputBucketName: ${projectId + "-input-files"}
          - outputBucketName: ${projectId + "-output-files-" + string(int(sys.now()))}
      - createOutputBucket:
            call: googleapis.storage.v1.buckets.insert
            args:
              project: ${projectId}
              body:
                name: ${outputBucketName}
      - batchTranslateText:
          call: googleapis.translate.v3beta1.projects.locations.batchTranslateText
          args:
              parent: ${"projects/" + projectId + "/locations/" + location}
              body:
                  inputConfigs:
                    gcsSource:
                      inputUri: ${"gs://" + inputBucketName + "/*"}
                  outputConfig:
                      gcsDestination:
                        outputUriPrefix: ${"gs://" + outputBucketName + "/"}
                  sourceLanguageCode: "en"
                  targetLanguageCodes: ["es", "fr"]
          result: batchTranslateTextResult

    工作流程會指派變數、建立輸出 bucket,並啟動檔案翻譯作業,然後將結果儲存至輸出 bucket。

  2. 建立工作流程後,請部署工作流程:

    gcloud workflows deploy batch-translation --source=workflow.yaml
  3. 執行工作流程:

    gcloud workflows execute batch-translation
  4. 如要查看工作流程狀態,可以執行傳回的指令。例如:

    gcloud workflows executions describe eb4a6239-cffa-4672-81d8-d4caef7d8424 /
      --workflow batch-translation /
      --location us-central1

    工作流程應為 ACTIVE。幾分鐘後,翻譯後的檔案 (法文和西班牙文) 會上傳至輸出值區。

列出輸出值區中的物件

您可以列出輸出 bucket 中的物件,確認工作流程是否正常運作。

  1. 擷取輸出 bucket 名稱:

    gcloud storage ls

    輸出結果會與下列內容相似:

    gs://PROJECT_ID-input-files/
    gs://PROJECT_ID-output-files-TIMESTAMP/

  2. 列出輸出值區中的物件:

    gcloud storage ls gs://PROJECT_ID-output-files-TIMESTAMP/** --recursive

    幾分鐘後,系統會列出翻譯後的檔案,法文和西班牙文各兩個。