azure-ai-translation-document-py
microsoft/skills
使用 Azure AI 文件翻譯 SDK,大規模翻譯 Word、PDF、Excel、PowerPoint 及其他文件,並保留原始格式。
...展開全部Azure AI 文件翻譯 SDK(Python 版)
Azure AI Translator 文件翻譯服務的客戶端函式庫,用於批次翻譯文件並保留原始格式。
安裝
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: - 非同步:
使用 `,(...)` 作為 `client` 的 `async` 以及使用 `DefaultAzureCredential()` 作為 `credential` 的 `async`(來自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 Storage
- 請使用具備適當權限的 SAS 憑證:
- 來源:讀取、列出
- 目標:寫入、列出
最佳實務
- 請選擇同步或非同步模式,並保持一致。請勿在同一個呼叫路徑中混合使用
azure.xxx同步客戶端與azure.xxx.aio非同步客戶端。每個模組應選擇一種模式。 - 請務必為客戶端和非同步憑證使用上下文管理器。將每個客戶端
以 `Client(...) as client:(sync)`(同步)或`Client(...) as client:(async)`(非同步)進行封裝。 對於來自azure.identity.aio的非同步DefaultAzureCredential,也請使用async 搭配 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
複製





首頁
