azure-ai-translation-document-py
microsoft/skills
Azure AI 문서 번역 SDK를 사용하여 서식을 유지한 채 Word, PDF, Excel, PowerPoint 및 기타 문서를 대량으로 번역하세요.
...모든 것을 확장하십시오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 키 인증 경로에서만 필수
인증 및 수명 주기
🔑 아래의 모든 코드 예제에는 다음 두 가지 규칙이 적용됩니다:
DefaultAzureCredential을우선적으로 사용하십시오. 코드 변경 없이 로컬(Azure CLI / VS Code / Developer CLI) 및 Azure(관리형 ID, 워크로드 ID)에서 모두 작동합니다. 연결 문자열, 계정/API 키는 사용하지 마십시오. 이러한 방법은 Entra 감사 및 키 순환을 우회합니다.
- 로컬 개발:
DefaultAzureCredential은별다른 설정 없이 바로 작동합니다.- 프로덕션:
AZURE_TOKEN_CREDENTIALS=prod(또는AZURE_TOKEN_CREDENTIALS=)를 설정하여 자격 증명 체인을 프로덕션에 안전한 자격 증명만 사용하도록 제한하십시오.- 모든 클라이언트를 컨텍스트 매니저로 감싸서 HTTP 전송, 소켓 및 토큰 캐시가 결정론적으로 해제되도록 하십시오:
- 동기식:
(...) as client: - 비동기:
및(...)을 클라이언트로 사용하는 async DefaultAzureCredential()을 자격 증명으로 사용하는 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을 사용해야 합니다. 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 토큰을 사용하십시오:
- 소스: 읽기, 목록 조회
- 대상: 쓰기, 나열
모범 사례
- 동기(sync) 또는 비동기(async) 중 하나를 선택하고 일관성을 유지하십시오. 동일한 호출 경로 내에서
azure.xxx동기 클라이언트와azure.xxx.aio비동기 클라이언트를 혼합하여 사용하지 마십시오. 모듈당 하나의 모드를 선택하십시오. - 클라이언트 및 비동기 자격 증명에는 항상 컨텍스트 관리자를 사용하십시오. 모든 클라이언트를
Client(...) as client:(동기) 또는Client(...) as client: (비동기)로감싸십시오.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
복사





집
