オプション
家 Skill データサイエンスと機械学習 azure-ai-translation-document-py

azure-ai-translation-document-py

microsoft/skills microsoft/skills

Azure AI Document Translation SDK を使用して、書式を維持したまま、Word、PDF、Excel、PowerPoint などのドキュメントを大規模に翻訳できます。

...すべて拡張します
0
更新された時間 2026年9月18日

Python用 Azure AI ドキュメント翻訳 SDK

書式を維持したまま文書を一括翻訳するための、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 キー認証パスでのみ必須

認証とライフサイクル

🔑 以下のすべてのコードサンプルには、次の 2 つのルールが適用されます:

  1. DefaultAzureCredentialを優先してください。コードを変更することなく、ローカル(Azure CLI / VS Code / Developer CLI)およびAzure(マネージド ID、ワークロード ID)で動作します。接続文字列、アカウント/API キーの使用は避けてください。これらはEntraの監査およびローテーションの対象外となります。
    • ローカル開発:DefaultAzureCredentialはそのまま使用できます。
    • 本番環境:AZURE_TOKEN_CREDENTIALS=prod(またはAZURE_TOKEN_CREDENTIALS= )を設定し、資格情報チェーンを本番環境に適した資格情報に制限してください。
  2. すべてのクライアントをコンテキストマネージャーでラップし、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を使用してください。AzureKeyCredentialを使用するのは、Entra ID へまだ移行されていない既存のキーベースのデプロイメントがある場合のみです。たとえば、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 トークンを使用してください:
    • ソース:読み取り、一覧表示
    • 宛先: 書き込み、一覧表示

ベストプラクティス

  1. 同期または非同期のいずれかを選択し、一貫性を保ってください。同じ呼び出しパス内で、azure.xxx同期クライアントとazure.xxx.aio非同期クライアントを混在させないでください。モジュールごとに 1 つのモードを選択してください。
  2. クライアントおよび非同期の認証情報には、常にコンテキストマネージャーを使用してください。すべてのクライアントを、クライアントとして Client(...) as client:(sync) または非同期の場合は Client(...) as client:(async)ラップしてください。 非同期の場合、azure.identity.aioDefaultAzureCredentialを使用する際は、credential: とともに非同期処理を行うことで、トークンとトランスポートが適切にクリーンアップされるようにしてください。
  3. 必要な権限を最小限に抑えたSASトークンを使用してください
  4. poller.status()を使用して長時間実行される操作を監視してください
  5. ドキュメントステータスを反復処理して、ドキュメントレベルのエラーを処理してください
  6. ドメイン固有の用語には用語集を使用する
  7. 言語ごとにターゲットコンテナを分離する
  8. 複数の並行ジョブには非同期クライアントを使用する
  9. ドキュメントを送信する前に、サポートされている形式を確認する
GitHubで見る
---
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

コピー コピー
クイックセットアップ: スキルフォルダを .claude/skills/ にコピーしてください。 Claude はそのスキルを自動的に検出して使用します。
リポジトリ microsoft/skills

関連スキル

web-search
更新された時間 2026年6月29日
webapp-testing
更新された時間 2026年6月29日
lark-base
更新された時間 2026年7月5日
agentmail
更新された時間 2026年6月29日
OR