使用模型翻译文本(V3 Beta 版)

使用模型翻译文本。

代码示例

Node.js

试用此示例之前,请按照 Cloud Translation 快速入门:使用客户端库中的 Node.js 设置说明进行操作。如需了解详情,请参阅 Cloud Translation Node.js API 参考文档

如需向 Cloud Translation 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const location = 'global';
// const modelId = 'YOUR_MODEL_ID';

// Imports the Google Cloud Translation library
const {TranslationServiceClient} = require('@google-cloud/translate').v3beta1;
const automl = require('@google-cloud/automl');

// Instantiates a client
const translationClient = new TranslationServiceClient();
const autoMLClient = new automl.AutoMlClient();
async function translateTextWithModel() {
  const model = autoMLClient.modelPath(projectId, location, modelId);
  // Construct request
  const request = {
    parent: translationClient.locationPath(projectId, location),
    contents: [text],
    mimeType: 'text/plain', // mime types: text/plain, text/html
    sourceLanguageCode: 'en-US',
    targetLanguageCode: 'ja',
    model: model,
  };

  // Run request
  const [response] = await translationClient.translateText(request);

  for (const translation of response.translations) {
    console.log(`Translated Content: ${translation.translatedText}`);
  }
}

translateTextWithModel();

后续步骤

如需搜索和过滤其他 Google Cloud 产品的代码示例,请参阅 Google Cloud 示例浏览器