你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

批量文档翻译客户端库

文档翻译是 Azure AI 翻译服务的一项基于云的功能,它以受支持的语言和各种文件格式异步翻译整个文档。 在本快速入门中,了解如何使用文档翻译和所选编程语言将源文档翻译为目标语言,同时保留结构和文本格式。

重要

  • 目前,只有翻译(单服务)资源中支持文档翻译,并且 Azure AI 服务(多服务)资源中未包含该功能。

  • 付费层支持文档翻译。 Language Studio 仅支持 S1 或 D3 实例层。 建议选择“标准 S1”以试用文档翻译。 请参阅 Azure AI 服务定价 - 翻译

先决条件

要开始,需要:

存储容器授权

可以选择以下选项之一来授权访问翻译器资源。

✔️ 托管标识。 托管标识是一个服务主体,用于为 Azure 托管资源创建 Microsoft Entra 标识和特定权限。 托管标识使你无需在代码中嵌入凭据即可运行翻译器应用程序。 托管标识是授予存储数据访问权限的一种更安全的方式,取代了在源和目标 URL 中包含共享访问签名令牌 (SAS) 的要求。

若要了解详细信息,请参阅用于文档翻译的托管标识

Screenshot of managed identity flow (RBAC).

✔️ 共享访问签名 (SAS)。 共享访问签名是向翻译器服务授予指定时间段内受限访问权限的 URL。 若要使用此方法,需要为源容器和目标容器创建共享访问签名 (SAS) 令牌。 sourceUrltargetUrl 必须包含作为查询字符串追加的共享访问签名 (SAS) 令牌。 可将该令牌分配到容器或特定的 Blob。

  • 源容器或 Blob 必须指定读取和列出访问权限
  • 目标容器或 Blob 必须指定写入和列出访问权限

若要了解详细信息,请参阅创建 SAS 令牌

Screenshot of a resource URI with a SAS token.

生成应用程序

有多种工具可用于创建、生成和运行翻译器 C#/.NET 应用程序。 在这里,我们将指导你使用命令行接口 (CLI) 或 Visual Studio。 选择以下选项卡之一以开始使用:

设置项目

在控制台窗口(例如 cmd、PowerShell 或 Bash)中,使用 dotnet new 命令创建名为 batch-document-translation 的新控制台应用。 此命令将创建包含单个源文件的简单“Hello World”C# 项目:Program.cs

dotnet new console -n batch-document-translation

将目录更改为新创建的应用文件夹。 使用以下命令生成应用程序:

dotnet build

生成输出不应包含警告或错误。

...
Build succeeded.
 0 Warning(s)
 0 Error(s)
...

安装客户端库

在应用程序目录中,安装适用于 .NET 的文档翻译客户端库:

dotnet add package Azure.AI.Translation.Document --version 1.0.0

翻译文档或批处理文件

  1. 对于此项目,你需要将源文档上传到源容器。 可以为此快速入门下载文档翻译示例文档。 源语言为英语。

  2. 在首选的编辑器或 IDE 中,从项目目录打开 Program.cs 文件。 删除现有的代码,包括 Console.WriteLine("Hello World!") 行。

  3. 在应用程序的 Program.cs 中,为密钥和自定义终结点创建变量。 有关详细信息, 请参阅检索密钥和自定义域终结点

    private static readonly string endpoint = "<your-document-translation-endpoint>";
    private static readonly string key = "<your-key>";
    
  4. 调用 StartTranslationAsync 方法,以针对单个 Blob 容器中的一个或多个文档启动翻译操作。

  5. 若要调用 StartTranslationAsync,需要初始化包含 sourceUritargetUritargetLanguageCode 参数的 DocumentTranslationInput 对象:

    • 对于托管标识授权,请创建以下变量:

      • sourceUri。 包含要翻译的文档的源容器的 URL。

      • targetUri 翻译后的文档要写入到的目标容器的 URL。

      • targetLanguageCode。 翻译后的文档的语言代码。 可以在我们的语言支持页上找到语言代码。

        若要查找源和目标 URL,请导航到 Azure 门户中的存储帐户。 在左侧边栏中的“数据存储”下,选择“容器”,然后按照以下步骤检索源文档和目标容器 URLS

        Source 目标
        1. 选中源容器旁边的复选框 1. 选中目标容器旁边的复选框。
        2.在主窗口区域中,选择要翻译的文件或文档。 2. 选择右侧的省略号,然后选择“属性”。
        3. 源 URL 位于“属性”列表的顶部。 3. 目标 URL 位于“属性”列表的顶部。
    • 对于共享访问签名 (SAS) 授权,请创建以下变量

      • sourceUri。 包含要翻译的文档的源容器的 SAS URI,其中追加了一个 SAS 令牌作为查询字符串。
      • targetUri 要将已翻译文档写入到的目标容器的 SAS URI,其中追加了一个 SAS 令牌作为查询字符串。
      • targetLanguageCode。 翻译后的文档的语言代码。 可以在我们的语言支持页上找到语言代码。

代码示例

重要

完成后,请记住将密钥从代码中删除,并且永远不要公开发布该密钥。 对于生产来说,请使用安全的方式存储和访问凭据,例如 Azure Key Vault。 有关详细信息,请参阅 Azure AI 服务安全性

在应用程序的 Program.cs 文件中输入以下代码示例:


using Azure;
using Azure.AI.Translation.Document;
using System;
using System.Threading;
using System.Text;

class Program {

  // create variables for your custom endpoint and resource key
  private static readonly string endpoint = "<your-document-translation-endpoint>";
  private static readonly string key = "<your-key>";

  static async Task Main(string[] args) {

    // create variables for your sourceUrl, targetUrl, and targetLanguageCode
    Uri sourceUri = new Uri("<sourceUrl>");
    Uri targetUri = new Uri("<targetUrl>");
    string targetLanguage = "<targetLanguageCode>"

    // initialize a new instance  of the DocumentTranslationClient object to interact with the Document Translation feature
    DocumentTranslationClient client = new DocumentTranslationClient(new Uri(endpoint), new AzureKeyCredential(key));

    // initialize a new instance of the `DocumentTranslationInput` object to provide the location of input for the translation operation
    DocumentTranslationInput input = new DocumentTranslationInput(sourceUri, targetUri, targetLanguage);

    // initialize a new instance of the DocumentTranslationOperation class to track the status of the translation operation
    DocumentTranslationOperation operation = await client.StartTranslationAsync(input);

    await operation.WaitForCompletionAsync();

    Console.WriteLine($"  Status: {operation.Status}");
    Console.WriteLine($"  Created on: {operation.CreatedOn}");
    Console.WriteLine($"  Last modified: {operation.LastModified}");
    Console.WriteLine($"  Total documents: {operation.DocumentsTotal}");
    Console.WriteLine($"    Succeeded: {operation.DocumentsSucceeded}");
    Console.WriteLine($"    Failed: {operation.DocumentsFailed}");
    Console.WriteLine($"    In Progress: {operation.DocumentsInProgress}");
    Console.WriteLine($"    Not started: {operation.DocumentsNotStarted}");

    await foreach(DocumentStatusResult document in operation.Value) {
      Console.WriteLine($"Document with Id: {document.Id}");
      Console.WriteLine($"  Status:{document.Status}");
      if (document.Status == DocumentTranslationStatus.Succeeded) {
        Console.WriteLine($"  Translated Document Uri: {document.TranslatedDocumentUri}");
        Console.WriteLine($"  Translated to language: {document.TranslatedToLanguageCode}.");
        Console.WriteLine($"  Document source Uri: {document.SourceDocumentUri}");
      } else {
        Console.WriteLine($"  Error Code: {document.Error.Code}");
        Console.WriteLine($"  Message: {document.Error.Message}");
      }
    }
  }
}

运行应用程序

将代码示例添加到应用程序后,通过在终端中键入以下命令,从项目目录运行该应用程序:

  dotnet run

下面是预期输出的代码段:

Screenshot of the Visual Studio Code output in the terminal window.

就这么简单! 你刚才已创建了一个可以使用 .NET 客户端库翻译存储容器中的文档的程序。

设置项目

请确保安装了最新版本的 Python

安装客户端库

安装最新版本的文档翻译客户端库:

pip install azure-ai-translation-document==1.0.0

翻译文档或批处理文件

  1. 对于此项目,你需要将源文档上传到源容器。 可以为此快速入门下载文档翻译示例文档。 源语言为英语。

  2. 在 Python 应用程序文件中,为资源密钥和自定义终结点创建变量。 有关详细信息, 请参阅检索密钥和自定义域终结点

key = "<your-key>"
endpoint = "<your-custom-endpoint>"

  1. 初始化包含 endpointkey 参数的 DocumentTranslationClient 对象。

  2. 调用 begin_translation 方法并传入 sourceUritargetUritargetLanguageCode 参数。

    • 对于托管标识授权,请创建以下变量:

      • sourceUri。 包含要翻译的文档的源容器的 URL。

      • targetUri 翻译后的文档要写入到的目标容器的 URL。

      • targetLanguageCode。 翻译后的文档的语言代码。 可以在我们的语言支持页上找到语言代码。

        若要查找源和目标 URL,请导航到 Azure 门户中的存储帐户。 在左侧边栏中的“数据存储”下,选择“容器”,然后按照以下步骤检索源文档和目标容器 URLS

        Source 目标
        1. 选中源容器旁边的复选框 1. 选中目标容器旁边的复选框。
        2.在主窗口区域中,选择要翻译的文件或文档。 2. 选择右侧的省略号,然后选择“属性”。
        3. 源 URL 位于“属性”列表的顶部。 3. 目标 URL 位于“属性”列表的顶部。
    • 对于共享访问签名 (SAS) 授权,请创建以下变量

      • sourceUri。 包含要翻译的文档的源容器的 SAS URI,其中追加了一个 SAS 令牌作为查询字符串。
      • targetUri 要将已翻译文档写入到的目标容器的 SAS URI,其中追加了一个 SAS 令牌作为查询字符串。
      • targetLanguageCode。 翻译后的文档的语言代码。 可以在我们的语言支持页上找到语言代码。

代码示例

重要

完成后,请记住将密钥从代码中删除,并且永远不要公开发布该密钥。 对于生产来说,请使用安全的方式存储和访问凭据,例如 Azure Key Vault。 有关详细信息,请参阅 Azure AI 服务安全性

在 Python 应用程序中输入以下代码示例:


#  import libraries
from azure.core.credentials import AzureKeyCredential
from azure.ai.translation.document import DocumentTranslationClient

# create variables for your resource key, custom endpoint, sourceUrl, targetUrl, and targetLanguage
key = "<your-key>"
endpoint = "<your-custom-endpoint>"
sourceUri = "<your-container-sourceUrl>"
targetUri = "<your-container-targetUrl>"
targetLanguage = "<target-language-code>"


# initialize a new instance of the DocumentTranslationClient object to interact with the Document Translation feature
client = DocumentTranslationClient(endpoint, AzureKeyCredential(key))

# include source and target locations and target language code for the begin translation operation
poller = client.begin_translation(sourceUri, targetUri, targetLanguage)
result = poller.result()

print("Status: {}".format(poller.status()))
print("Created on: {}".format(poller.details.created_on))
print("Last updated on: {}".format(poller.details.last_updated_on))
print(
    "Total number of translations on documents: {}".format(
        poller.details.documents_total_count
    )
)

print("\nOf total documents...")
print("{} failed".format(poller.details.documents_failed_count))
print("{} succeeded".format(poller.details.documents_succeeded_count))

for document in result:
    print("Document ID: {}".format(document.id))
    print("Document status: {}".format(document.status))
    if document.status == "Succeeded":
        print("Source document location: {}".format(document.source_document_url))
        print(
            "Translated document location: {}".format(document.translated_document_url)
        )
        print("Translated to language: {}\n".format(document.translated_to))
    else:
        print(
            "Error Code: {}, Message: {}\n".format(
                document.error.code, document.error.message
            )
        )

运行应用程序

将代码示例添加到应用程序后,请在终端中键入以下命令:

python asynchronous-sdk.py

下面是预期输出的片段:

Screenshot of the Python output in the terminal window.

就这么简单! 你刚才已创建了一个可以使用 Python 客户端库翻译存储容器中的文档的程序。

下一步