使用 Cloud Translation 连接器运行批量翻译

本教程介绍了如何创建一个工作流,该工作流使用 Cloud Translation API 连接器在异步批量模式下将文件翻译为其他语言。这样一来,系统便可在处理输入内容的同时提供实时输出。

创建输入 Cloud Storage 存储桶和文件

您可以使用 Cloud Storage 存储对象。对象是由任意格式的文件组成的不可变的数据段,存储在称为存储分区的容器中。

  1. 创建 Cloud Storage 存储桶以保存要翻译的文件:

    BUCKET_INPUT=${GOOGLE_CLOUD_PROJECT}-input-files
    gcloud storage buckets create gs://${BUCKET_INPUT}
  2. 使用英语创建两个文件,并将它们上传到输入存储桶:

    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

    工作流会分配变量、创建输出存储桶并启动文件翻译,并将结果保存到输出存储桶。

  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。几分钟后,翻译后的文件(法语和西班牙语)会上传到输出存储桶。

列出输出存储桶中的对象

通过列出输出存储桶中的对象,您可以确认工作流是否按预期工作。

  1. 检索输出存储桶名称:

    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

    几分钟后,系统会列出翻译后的文件,每种语言(法语和西班牙语)各两个。