azure-ai-translation-document-py
microsoft/skills
使用 Azure AI 文档翻译 SDK,在保持格式不变的前提下,大规模翻译 Word、PDF、Excel、PowerPoint 及其他文档。
...展开全部Azure AI 文档翻译 Python SDK
Azure AI 翻译器文档翻译服务的客户端库,用于在保持格式的同时批量翻译文档。
安装
pip install azure-ai-translation-document
环境变量
AZURE_DOCUMENT_TRANSLATION_ENDPOINT=https://.cognitiveservices.azure.com # 所有身份验证方法均需此变量
# 源文档和目标文档的存储位置
AZURE_SOURCE_CONTAINER_URL=https://.blob.core.windows.net/? # 所有身份验证方法均需此项
AZURE_TARGET_CONTAINER_URL=https://.blob.core.windows.net/? # 所有身份验证方法均需此项
AZURE_TOKEN_CREDENTIALS=prod # 仅当在生产环境中使用 DefaultAzureCredential 时才需要
AZURE_DOCUMENT_TRANSLATION_KEY= # 仅适用于下方的旧版 API 密钥身份验证路径
身份验证与生命周期
🔑 以下每个代码示例均遵循两条规则:
- 优先使用
DefaultAzureCredential。它既可在本地(Azure CLI / VS Code / 开发者 CLI)使用,也可在 Azure(托管身份、工作负载身份)中使用,且无需修改代码。避免使用连接字符串、账户/API 密钥——这些会绕过 Entra 的审计和轮换机制。
- 本地开发:
DefaultAzureCredential直接即可使用。- 生产环境:将
AZURE_TOKEN_CREDENTIALS设置为prod(或AZURE_TOKEN_CREDENTIALS=),以将凭据链限制为生产环境安全的凭据。- 将每个客户端封装在上下文管理器中,以确保 HTTP 传输、套接字和令牌缓存能以可预测的方式释放:
- 同步模式:
使用 ``(...) as client: - 异步:
async with以及(...) as client: async with DefaultAzureCredential() as credential:(来自azure.identity.aio)代码片段可能会简化此配置,但生产环境中的代码应始终遵循这两条规则。
import os
from azure.identity import DefaultAzureCredential, ManagedIdentityCredential
from azure.ai.translation.document import DocumentTranslationClient
# 本地开发:DefaultAzureCredential。生产环境:设置 AZURE_TOKEN_CREDENTIALS=prod 或 AZURE_TOKEN_CREDENTIALS=
credential = DefaultAzureCredential(require_envvar=True)
# 或者在生产环境中直接使用特定凭据:
# 参见 https://learn.microsoft.com/python/api/overview/azure/identity-readme?view=azure-python#credential-classes
# credential = ManagedIdentityCredential()
with DocumentTranslationClient(
endpoint=os.environ["AZURE_DOCUMENT_TRANSLATION_ENDPOINT"],
credential=credential,
) as client:
statuses = list(client.list_translation_statuses())
旧版:API 密钥(现有的基于密钥的部署)
新代码应使用上文提到的DefaultAzureCredential。仅当您有尚未迁移到 Entra ID 的现有基于密钥的部署时,才应使用AzureKeyCredential—— 例如,仍在完成 Entra 部署的受监管环境。
import os
from azure.core.credentials import AzureKeyCredential
from azure.ai.translation.document import DocumentTranslationClient, SingleDocumentTranslationClient
with DocumentTranslationClient(
endpoint=os.environ["AZURE_DOCUMENT_TRANSLATION_ENDPOINT"],
credential=AzureKeyCredential(os.environ["AZURE_DOCUMENT_TRANSLATION_KEY"]),
) as client:
statuses = list(client.list_translation_statuses())
# SingleDocumentTranslationClient 接受相同的基于密钥的凭据。
基础文档翻译
from azure.ai.translation.document import DocumentTranslationInput, TranslationTarget
source_url = os.environ["AZURE_SOURCE_CONTAINER_URL"]
target_url = os.environ["AZURE_TARGET_CONTAINER_URL"]
# 启动翻译任务
poller = client.begin_translation(
inputs=[
DocumentTranslationInput(
source_url=source_url,
targets=[
TranslationTarget(
target_url=target_url,
language="es" # 翻译为西班牙语
)
]
)
]
)
# 等待任务完成
result = poller.result()
print(f"状态:{poller.status()}")
print(f"翻译成功的文档:{poller.details.documents_succeeded_count}")
print(f"翻译失败的文档:{poller.details.documents_failed_count}")
多种目标语言
poller = client.begin_translation(
inputs=[
DocumentTranslationInput(
source_url=source_url,
targets=[
TranslationTarget(target_url=target_url_es, language="es"),
TranslationTarget(target_url=target_url_fr, language="fr"),
TranslationTarget(target_url=target_url_de, language="de")
]
)
]
)
翻译单个文档
from azure.ai.translation.document import SingleDocumentTranslationClient
from azure.identity import DefaultAzureCredential
with open("document.docx", "rb") as f:
document_content = f.read()
with SingleDocumentTranslationClient(endpoint, DefaultAzureCredential()) as single_client:
result = single_client.translate(
body=document_content,
target_language="es",
content_type="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
)
# 保存翻译后的文档
with open("document_es.docx", "wb") as f:
f.write(result)
检查翻译状态
# 获取所有翻译操作
operations = client.list_translation_statuses()
for op in operations:
print(f"操作 ID:{op.id}")
print(f"状态:{op.status}")
print(f"创建时间:{op.created_on}")
print(f"文档总数:{op.documents_total_count}")
print(f"成功:{op.documents_succeeded_count}")
print(f"失败:{op.documents_failed_count}")
列出文档状态
# 获取任务中单个文档的状态
operation_id = poller.id
document_statuses = client.list_document_statuses(operation_id)
for doc in document_statuses:
print(f"文档: {doc.source_document_url}")
print(f" 状态:{doc.status}")
print(f" 翻译为:{doc.translated_to}")
if doc.error:
print(f" 错误:{doc.error.message}")
取消翻译
# 取消正在进行的翻译
client.cancel_translation(operation_id)
使用术语表
from azure.ai.translation.document import TranslationGlossary
poller = client.begin_translation(
inputs=[
DocumentTranslationInput(
source_url=source_url,
targets=[
TranslationTarget(
target_url=target_url,
language="es",
glossaries=[
TranslationGlossary(
glossary_url="https://.blob.core.windows.net/glossary/terms.csv?",
file_format="csv"
)
]
)
]
)
]
)
支持的文档格式
# 获取支持的格式
formats = client.get_supported_document_formats()
for fmt in formats:
print(f"格式:{fmt.format}")
print(f" 文件扩展名:{fmt.file_extensions}")
print(f" 内容类型:{fmt.content_types}")
支持的语言
# 获取支持的语言
languages = client.get_supported_languages()
for lang in languages:
print(f"语言: {lang.name} ({lang.code})")
异步客户端
from azure.ai.translation.document.aio import DocumentTranslationClient
from azure.identity.aio import DefaultAzureCredential
async def translate_documents():
async with DefaultAzureCredential() as credential:
async with DocumentTranslationClient(
endpoint=endpoint,
credential=credential,
) as client:
poller = await client.begin_translation(inputs=[...])
result = await poller.result()
支持的格式
| 类别 | 格式 |
|---|---|
| 文档 | DOCX、PDF、PPTX、XLSX、HTML、TXT、RTF |
| 结构化 | CSV、TSV、JSON、XML |
| 本地化 | XLIFF、XLF、MHTML |
存储要求
- 源和目标容器必须是 Azure Blob 存储
- 使用具有适当权限的 SAS 令牌:
- 源:读取、列出
- 目标:写入、列出
最佳实践
- 选择同步或异步模式,并保持一致。请勿在同一调用路径中混合使用
azure.xxx同步客户端与azure.xxx.aio异步客户端。每个模块应选择一种模式。 - 始终为客户端和异步凭据使用上下文管理器。将每个客户端
用 Client(...) as client:(sync) 或async with Client(...) as client:(async) 进行封装。 对于来自azure.identity.aio的异步DefaultAzureCredential,也请使用异步模式并添加 credential:,以便对令牌和传输进行清理。 - 使用仅包含最低必要权限的SAS 令牌
- 使用
poller.status()监控长时间运行的操作 - 通过遍历文档状态来处理文档级别的错误
- 使用术语表管理领域特定术语
- 为每种语言分别设置目标容器
- 使用异步客户端处理多个并发任务
- 提交文档前检查支持的格式
---
name: azure-ai-translation-document-py
description: Translate Word, PDF, Excel, PowerPoint, and other documents at scale using Azure AI Document Translation SDK with format preservation.
license: MIT
---
# Azure AI Document Translation SDK for Python
Client library for Azure AI Translator document translation service for batch document translation with format preservation.
## Installation
```bash
pip install azure-ai-translation-document
```
## Environment Variables
```bash
AZURE_DOCUMENT_TRANSLATION_ENDPOINT=https://<resource>.cognitiveservices.azure.com # Required for all auth methods
# Storage for source and target documents
AZURE_SOURCE_CONTAINER_URL=https://<storage>.blob.core.windows.net/<container>?<sas> # Required for all auth methods
AZURE_TARGET_CONTAINER_URL=https://<storage>.blob.core.windows.net/<container>?<sas> # Required for all auth methods
AZURE_TOKEN_CREDENTIALS=prod # Required only if DefaultAzureCredential is used in production
AZURE_DOCUMENT_TRANSLATION_KEY=<your-api-key> # Only required for the legacy API-key auth path below
```
## Authentication & Lifecycle
> **🔑 Two rules apply to every code sample below:**
>
> 1. **Prefer `DefaultAzureCredential`.** It works locally (Azure CLI / VS Code / Developer CLI) and in Azure (managed identity, workload identity) with no code change. Avoid connection strings, account/API keys — they bypass Entra audit and rotation.
> - Local dev: `DefaultAzureCredential` works as-is.
> - Production: set `AZURE_TOKEN_CREDENTIALS=prod` (or `AZURE_TOKEN_CREDENTIALS=<specific_credential>`) to constrain the credential chain to production-safe credentials.
> 2. **Wrap every client in a context manager** so HTTP transports, sockets, and token caches are released deterministically:
> - Sync: `with <Client>(...) as client:`
> - Async: `async with <Client>(...) as client:` **and** `async with DefaultAzureCredential() as credential:` (from `azure.identity.aio`)
>
> Snippets may abbreviate this setup, but production code should always follow both rules.
```python
import os
from azure.identity import DefaultAzureCredential, ManagedIdentityCredential
from azure.ai.translation.document import DocumentTranslationClient
# Local dev: DefaultAzureCredential. Production: set AZURE_TOKEN_CREDENTIALS=prod or AZURE_TOKEN_CREDENTIALS=<specific_credential>
credential = DefaultAzureCredential(require_envvar=True)
# Or use a specific credential directly in production:
# See https://learn.microsoft.com/python/api/overview/azure/identity-readme?view=azure-python#credential-classes
# credential = ManagedIdentityCredential()
with DocumentTranslationClient(
endpoint=os.environ["AZURE_DOCUMENT_TRANSLATION_ENDPOINT"],
credential=credential,
) as client:
statuses = list(client.list_translation_statuses())
```
### Legacy: API Key (existing keyed deployments)
New code should use `DefaultAzureCredential` above. Use `AzureKeyCredential` only if you have an existing keyed deployment that hasn't been migrated to Entra ID yet — for example, regulated environments still completing their Entra rollout.
```python
import os
from azure.core.credentials import AzureKeyCredential
from azure.ai.translation.document import DocumentTranslationClient, SingleDocumentTranslationClient
with DocumentTranslationClient(
endpoint=os.environ["AZURE_DOCUMENT_TRANSLATION_ENDPOINT"],
credential=AzureKeyCredential(os.environ["AZURE_DOCUMENT_TRANSLATION_KEY"]),
) as client:
statuses = list(client.list_translation_statuses())
# SingleDocumentTranslationClient accepts the same key-based credential.
```
## Basic Document Translation
```python
from azure.ai.translation.document import DocumentTranslationInput, TranslationTarget
source_url = os.environ["AZURE_SOURCE_CONTAINER_URL"]
target_url = os.environ["AZURE_TARGET_CONTAINER_URL"]
# Start translation job
poller = client.begin_translation(
inputs=[
DocumentTranslationInput(
source_url=source_url,
targets=[
TranslationTarget(
target_url=target_url,
language="es" # Translate to Spanish
)
]
)
]
)
# Wait for completion
result = poller.result()
print(f"Status: {poller.status()}")
print(f"Documents translated: {poller.details.documents_succeeded_count}")
print(f"Documents failed: {poller.details.documents_failed_count}")
```
## Multiple Target Languages
```python
poller = client.begin_translation(
inputs=[
DocumentTranslationInput(
source_url=source_url,
targets=[
TranslationTarget(target_url=target_url_es, language="es"),
TranslationTarget(target_url=target_url_fr, language="fr"),
TranslationTarget(target_url=target_url_de, language="de")
]
)
]
)
```
## Translate Single Document
```python
from azure.ai.translation.document import SingleDocumentTranslationClient
from azure.identity import DefaultAzureCredential
with open("document.docx", "rb") as f:
document_content = f.read()
with SingleDocumentTranslationClient(endpoint, DefaultAzureCredential()) as single_client:
result = single_client.translate(
body=document_content,
target_language="es",
content_type="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
)
# Save translated document
with open("document_es.docx", "wb") as f:
f.write(result)
```
## Check Translation Status
```python
# Get all translation operations
operations = client.list_translation_statuses()
for op in operations:
print(f"Operation ID: {op.id}")
print(f"Status: {op.status}")
print(f"Created: {op.created_on}")
print(f"Total documents: {op.documents_total_count}")
print(f"Succeeded: {op.documents_succeeded_count}")
print(f"Failed: {op.documents_failed_count}")
```
## List Document Statuses
```python
# Get status of individual documents in a job
operation_id = poller.id
document_statuses = client.list_document_statuses(operation_id)
for doc in document_statuses:
print(f"Document: {doc.source_document_url}")
print(f" Status: {doc.status}")
print(f" Translated to: {doc.translated_to}")
if doc.error:
print(f" Error: {doc.error.message}")
```
## Cancel Translation
```python
# Cancel a running translation
client.cancel_translation(operation_id)
```
## Using Glossary
```python
from azure.ai.translation.document import TranslationGlossary
poller = client.begin_translation(
inputs=[
DocumentTranslationInput(
source_url=source_url,
targets=[
TranslationTarget(
target_url=target_url,
language="es",
glossaries=[
TranslationGlossary(
glossary_url="https://<storage>.blob.core.windows.net/glossary/terms.csv?<sas>",
file_format="csv"
)
]
)
]
)
]
)
```
## Supported Document Formats
```python
# Get supported formats
formats = client.get_supported_document_formats()
for fmt in formats:
print(f"Format: {fmt.format}")
print(f" Extensions: {fmt.file_extensions}")
print(f" Content types: {fmt.content_types}")
```
## Supported Languages
```python
# Get supported languages
languages = client.get_supported_languages()
for lang in languages:
print(f"Language: {lang.name} ({lang.code})")
```
## Async Client
```python
from azure.ai.translation.document.aio import DocumentTranslationClient
from azure.identity.aio import DefaultAzureCredential
async def translate_documents():
async with DefaultAzureCredential() as credential:
async with DocumentTranslationClient(
endpoint=endpoint,
credential=credential,
) as client:
poller = await client.begin_translation(inputs=[...])
result = await poller.result()
```
## Supported Formats
| Category | Formats |
|----------|---------|
| Documents | DOCX, PDF, PPTX, XLSX, HTML, TXT, RTF |
| Structured | CSV, TSV, JSON, XML |
| Localization | XLIFF, XLF, MHTML |
## Storage Requirements
- Source and target containers must be Azure Blob Storage
- Use SAS tokens with appropriate permissions:
- Source: Read, List
- Target: Write, List
## Best Practices
1. **Pick sync OR async and stay consistent.** Do not mix `azure.xxx` sync clients with `azure.xxx.aio` async clients in the same call path. Choose one mode per module.
2. **Always use context managers for clients and async credentials.** Wrap every client in `with Client(...) as client:` (sync) or `async with Client(...) as client:` (async). For async `DefaultAzureCredential` from `azure.identity.aio`, also use `async with credential:` so tokens and transports are cleaned up.
3. **Use SAS tokens** with minimal required permissions
4. **Monitor long-running operations** with `poller.status()`
5. **Handle document-level errors** by iterating document statuses
6. **Use glossaries** for domain-specific terminology
7. **Separate target containers** for each language
8. **Use async client** for multiple concurrent jobs
9. **Check supported formats** before submitting documents
所有文件
0 个文件安装 azure-ai-translation-document-py
下载技能文件并将其解压到 .claude/skills/ 目录中。
下载ZIP克隆仓库并复制技能文件到您的项目中。
git clone https://github.com/microsoft/skills/tree/main/.github/plugins/azure-sdk-python/skills/azure-ai-translation-document-py # Copy SKILL.md to your .claude/skills/ directory
复制





首页
