azure-ai-translation-text-py
microsoft/skills
실시간으로 텍스트를 번역하고, 언어를 감지하며, 문자 간 전사하고, Azure AI Translator SDK for Python을 사용하여 사전 항목을 조회합니다.
...모든 것을 확장하십시오Azure AI Text Translation SDK for Python
실시간 텍스트 번역, 음역 및 언어 작업을 위한 Azure AI Translator 텍스트 번역 서비스용 클라이언트 라이브러리입니다.
Installation
pip install azure-ai-translation-text
Environment Variables
AZURE_TRANSLATOR_ENDPOINT=https://<resource>.cognitiveservices.azure.com # Entra ID 인증에 필요(사용자 지정 서브도메인 엔드포인트여야 함)
AZURE_TOKEN_CREDENTIALS=prod # 프로덕션에서 DefaultAzureCredential을 사용하는 경우에만 필요
# 다음 레거시 API 키 인증 경로에서만 필요:
AZURE_TRANSLATOR_KEY=<your-api-key>
AZURE_TRANSLATOR_REGION=<your-region> # 예: eastus, westus2; 전역 엔드포인트에 대해 키로 인증할 때 필요
</your-region></your-api-key></resource>Authentication & Lifecycle
🔑 아래 모든 코드 샘플에 적용되는 두 가지 규칙이 있습니다:
DefaultAzureCredential을 선호하십시오. 로컬(Azure CLI / VS Code / Developer CLI)과 Azure(관리된 ID, 작업부서 ID) 모두에서 코드 변경 없이 작동하며 연결 문자열, 계정/API 키를 피하십시오. 이는 Entra 감사 및 회전 우회합니다.
- 로컬 개발:
DefaultAzureCredential은 그대로 작동합니다.- 프로덕션:
AZURE_TOKEN_CREDENTIALS=prod(또는AZURE_TOKEN_CREDENTIALS=<specific_credential></specific_credential>)를 설정하여 자격 증명 체인을 프로덕션 안전 자격 증명으로 제한합니다.- 모든 클라이언트를 컨텍스트 관리자로 래핑하여 HTTP 전송, 소켓 및 토큰 캐시를 결정적으로 해제합니다:
- 동기:
with <client>(...) as client:</client>- 비동기:
async with <client>(...) as client:</client>및async with DefaultAzureCredential() as credential:(azure.identity.aio에서)코드 조각은 이 설정을 축약할 수 있지만, 프로덕션 코드는 항상 두 규칙을 따라야 합니다.
import os
from azure.identity import DefaultAzureCredential, ManagedIdentityCredential
from azure.ai.translation.text import TextTranslationClient
# 로컬 개발: DefaultAzureCredential. 프로덕션: AZURE_TOKEN_CREDENTIALS=prod 또는 AZURE_TOKEN_CREDENTIALS=<specific_credential> 설정
credential = DefaultAzureCredential(require_envvar=True)
# 또는 프로덕션에서 특정 자격 증명을 직접 사용:
# https://learn.microsoft.com/python/api/overview/azure/identity-readme?view=azure-python#credential-classes 참조
# credential = ManagedIdentityCredential()
with TextTranslationClient(
endpoint=os.environ["AZURE_TRANSLATOR_ENDPOINT"],
credential=credential,
) as client:
result = client.translate(body=["Hello, world!"], to=["es"])
</specific_credential>Legacy: API Key (existing keyed deployments)
새 코드에서는 위의 DefaultAzureCredential을 사용해야 합니다. Translator 서비스에는 기존 배포에서 API 키 인증이 여전히 일반적인 두 가지 특성이 있습니다:
- 토큰 자격 증명 인증에는 사용자 지정 서브도메인 엔드포인트(
https://<resource>.cognitiveservices.azure.com</resource>)가 필요합니다. 전역 엔드포인트(https://api.cognitive.microsofttranslator.com)만 있는 경우, 사용자 지정 서브도메인을 프로비저닝하거나 프로비저닝할 때까지 키 기반 경로에 머물러야 합니다. - 키 + 지역은 전역 엔드포인트에 대한 표준 설정입니다. 지역은
Ocp-Apim-Subscription-Region헤더로 전송되며, 다중 서비스 또는 전역 Translator 키를 사용할 때 항상 필요합니다.
import os
from azure.core.credentials import AzureKeyCredential
from azure.ai.translation.text import TextTranslationClient
# 전역 엔드포인트에 대한 키 + 지역 (가장 일반적인 키 설정)
with TextTranslationClient(
credential=AzureKeyCredential(os.environ["AZURE_TRANSLATOR_KEY"]),
region=os.environ["AZURE_TRANSLATOR_REGION"],
) as client:
result = client.translate(body=["Hello, world!"], to=["es"])
# 사용자 지정 서브도메인 엔드포인트에 대한 키 (지역 불필요)
with TextTranslationClient(
endpoint=os.environ["AZURE_TRANSLATOR_ENDPOINT"],
credential=AzureKeyCredential(os.environ["AZURE_TRANSLATOR_KEY"]),
) as client:
result = client.translate(body=["Hello, world!"], to=["es"])
Basic Translation
# 단일 언어로 번역
result = client.translate(
body=["Hello, how are you?", "Welcome to Azure!"],
to=["es"] # 스페인어
)
for item in result:
for translation in item.translations:
print(f"Translated: {translation.text}")
print(f"Target language: {translation.to}")
Translate to Multiple Languages
result = client.translate(
body=["Hello, world!"],
to=["es", "fr", "de", "ja"] # 스페인어, 프랑스어, 독일어, 일본어
)
for item in result:
print(f"Source: {item.detected_language.language if item.detected_language else 'unknown'}")
for translation in item.translations:
print(f" {translation.to}: {translation.text}")
Specify Source Language
result = client.translate(
body=["Bonjour le monde"],
from_parameter="fr", # 소스는 프랑스어
to=["en", "es"]
)
Language Detection
result = client.translate(
body=["Hola, como estas?"],
to=["en"]
)
for item in result:
if item.detected_language:
print(f"Detected language: {item.detected_language.language}")
print(f"Confidence: {item.detected_language.score:.2f}")
Transliteration
한 글체에서 다른 글체로 텍스트 변환:
result = client.transliterate(
body=["konnichiwa"],
language="ja",
from_script="Latn", # 라틴 글체에서
to_script="Jpan" # 일본어 글체로
)
for item in result:
print(f"Transliterated: {item.text}")
print(f"Script: {item.script}")
Dictionary Lookup
대체 번역 및 정의 찾기:
result = client.lookup_dictionary_entries(
body=["fly"],
from_parameter="en",
to="es"
)
for item in result:
print(f"Source: {item.normalized_source} ({item.display_source})")
for translation in item.translations:
print(f" Translation: {translation.normalized_target}")
print(f" Part of speech: {translation.pos_tag}")
print(f" Confidence: {translation.confidence:.2f}")
Dictionary Examples
번역에 대한 사용 예제 가져오기:
from azure.ai.translation.text.models import DictionaryExampleTextItem
result = client.lookup_dictionary_examples(
body=[DictionaryExampleTextItem(text="fly", translation="volar")],
from_parameter="en",
to="es"
)
for item in result:
for example in item.examples:
print(f"Source: {example.source_prefix}{example.source_term}{example.source_suffix}")
print(f"Target: {example.target_prefix}{example.target_term}{example.target_suffix}")
Get Supported Languages
# 모든 지원 언어 가져오기
languages = client.get_supported_languages()
# 번역 언어
print("Translation languages:")
for code, lang in languages.translation.items():
print(f" {code}: {lang.name} ({lang.native_name})")
# 음역 언어
print("\nTransliteration languages:")
for code, lang in languages.transliteration.items():
print(f" {code}: {lang.name}")
for script in lang.scripts:
print(f" {script.code} -> {[t.code for t in script.to_scripts]}")
# 사전 언어
print("\nDictionary languages:")
for code, lang in languages.dictionary.items():
print(f" {code}: {lang.name}")
Break Sentence
문장 경계 식별:
result = client.find_sentence_boundaries(
body=["Hello! How are you? I hope you are well."],
language="en"
)
for item in result:
print(f"Sentence lengths: {item.sent_len}")
Translation Options
result = client.translate(
body=["Hello, world!"],
to=["de"],
text_type="html", # "plain" 또는 "html"
profanity_action="Marked", # "NoAction", "Deleted", "Marked"
profanity_marker="Asterisk", # "Asterisk", "Tag"
include_alignment=True, # 단어 정렬 포함
include_sentence_length=True # 문장 경계 포함
)
for item in result:
translation = item.translations[0]
print(f"Translated: {translation.text}")
if translation.alignment:
print(f"Alignment: {translation.alignment.proj}")
if translation.sent_len:
print(f"Sentence lengths: {translation.sent_len.src_sent_len}")
Async Client
from azure.ai.translation.text.aio import TextTranslationClient
from azure.identity.aio import DefaultAzureCredential
async def translate_text():
async with DefaultAzureCredential() as credential:
async with TextTranslationClient(
credential=credential,
endpoint=endpoint,
) as client:
result = await client.translate(
body=["Hello, world!"],
to=["es"]
)
print(result[0].translations[0].text)
Client Methods
| Method | Description |
|---|---|
| `translate` | 텍스트를 하나 이상의 언어로 번역 |
| `transliterate` | 글체 간 텍스트 변환 |
| `detect` | 텍스트의 언어 감지 |
| `find_sentence_boundaries` | 문장 경계 식별 |
| `lookup_dictionary_entries` | 번역을 위한 사전 조회 |
| `lookup_dictionary_examples` | 사용 예제 가져오기 |
| `get_supported_languages` | 지원 언어 목록 |
Best Practices
- 동기 또는 비동기 중 하나를 선택하고 일관되게 유지하십시오. 동일한 호출 경로에서
azure.xxx동기 클라이언트와azure.xxx.aio비동기 클라이언트를 혼합하지 마십시오. 모듈당 하나의 모드를 선택하십시오. - 클라이언트 및 비동기 자격 증명에 항상 컨텍스트 관리자를 사용하십시오. 모든 클라이언트를
with Client(...) as client:(동기) 또는async with Client(...) as client:(비동기)로 래핑하십시오.azure.identity.aio의 비동기DefaultAzureCredential의 경우, 토큰과 전송이 정리되도록async with credential:도 사용하십시오. - 배치 번역 — 한 요청에 여러 텍스트 보내기(최대 100개)
- 소스 언어 지정 — 알려진 경우 정확도 향상을 위해
- 비동기 클라이언트 사용 — 높은 처리량 시나리오용
- 언어 목록 캐싱 — 지원 언어는 자주 변경되지 않음
- 부적절한 언어 처리 — 애플리케이션에 적절하게
- html text_type 사용 — HTML 콘텐츠 번역 시
- 정렬 포함 — 단어 매핑이 필요한 애플리케이션용
---
name: azure-ai-translation-text-py
description: Translate text in real-time, detect languages, transliterate between scripts, and look up dictionary entries using Azure AI Translator SDK for Python.
license: MIT
---
# Azure AI Text Translation SDK for Python
Client library for Azure AI Translator text translation service for real-time text translation, transliteration, and language operations.
## Installation
```bash
pip install azure-ai-translation-text
```
## Environment Variables
```bash
AZURE_TRANSLATOR_ENDPOINT=https://<resource>.cognitiveservices.azure.com # Required for Entra ID auth (must be a custom subdomain endpoint)
AZURE_TOKEN_CREDENTIALS=prod # Required only if DefaultAzureCredential is used in production
# Only required for the legacy API-key auth path below:
AZURE_TRANSLATOR_KEY=<your-api-key>
AZURE_TRANSLATOR_REGION=<your-region> # e.g., eastus, westus2; required when authenticating with a key against the global endpoint
```
## 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.text import TextTranslationClient
# 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 TextTranslationClient(
endpoint=os.environ["AZURE_TRANSLATOR_ENDPOINT"],
credential=credential,
) as client:
result = client.translate(body=["Hello, world!"], to=["es"])
```
### Legacy: API Key (existing keyed deployments)
New code should use `DefaultAzureCredential` above. The Translator service has two specifics that make API-key auth still common in existing deployments:
- **Token-credential auth requires a custom subdomain endpoint** (`https://<resource>.cognitiveservices.azure.com`). If you only have the global endpoint (`https://api.cognitive.microsofttranslator.com`), you must either provision a custom subdomain or stay on the key-based path until you do.
- **Key + region** is the canonical setup against the global endpoint. The region is sent as the `Ocp-Apim-Subscription-Region` header and is required whenever you use a multi-service or global Translator key.
```python
import os
from azure.core.credentials import AzureKeyCredential
from azure.ai.translation.text import TextTranslationClient
# Key + region against the global endpoint (most common keyed setup)
with TextTranslationClient(
credential=AzureKeyCredential(os.environ["AZURE_TRANSLATOR_KEY"]),
region=os.environ["AZURE_TRANSLATOR_REGION"],
) as client:
result = client.translate(body=["Hello, world!"], to=["es"])
# Key against a custom subdomain endpoint (no region required)
with TextTranslationClient(
endpoint=os.environ["AZURE_TRANSLATOR_ENDPOINT"],
credential=AzureKeyCredential(os.environ["AZURE_TRANSLATOR_KEY"]),
) as client:
result = client.translate(body=["Hello, world!"], to=["es"])
```
## Basic Translation
```python
# Translate to a single language
result = client.translate(
body=["Hello, how are you?", "Welcome to Azure!"],
to=["es"] # Spanish
)
for item in result:
for translation in item.translations:
print(f"Translated: {translation.text}")
print(f"Target language: {translation.to}")
```
## Translate to Multiple Languages
```python
result = client.translate(
body=["Hello, world!"],
to=["es", "fr", "de", "ja"] # Spanish, French, German, Japanese
)
for item in result:
print(f"Source: {item.detected_language.language if item.detected_language else 'unknown'}")
for translation in item.translations:
print(f" {translation.to}: {translation.text}")
```
## Specify Source Language
```python
result = client.translate(
body=["Bonjour le monde"],
from_parameter="fr", # Source is French
to=["en", "es"]
)
```
## Language Detection
```python
result = client.translate(
body=["Hola, como estas?"],
to=["en"]
)
for item in result:
if item.detected_language:
print(f"Detected language: {item.detected_language.language}")
print(f"Confidence: {item.detected_language.score:.2f}")
```
## Transliteration
Convert text from one script to another:
```python
result = client.transliterate(
body=["konnichiwa"],
language="ja",
from_script="Latn", # From Latin script
to_script="Jpan" # To Japanese script
)
for item in result:
print(f"Transliterated: {item.text}")
print(f"Script: {item.script}")
```
## Dictionary Lookup
Find alternate translations and definitions:
```python
result = client.lookup_dictionary_entries(
body=["fly"],
from_parameter="en",
to="es"
)
for item in result:
print(f"Source: {item.normalized_source} ({item.display_source})")
for translation in item.translations:
print(f" Translation: {translation.normalized_target}")
print(f" Part of speech: {translation.pos_tag}")
print(f" Confidence: {translation.confidence:.2f}")
```
## Dictionary Examples
Get usage examples for translations:
```python
from azure.ai.translation.text.models import DictionaryExampleTextItem
result = client.lookup_dictionary_examples(
body=[DictionaryExampleTextItem(text="fly", translation="volar")],
from_parameter="en",
to="es"
)
for item in result:
for example in item.examples:
print(f"Source: {example.source_prefix}{example.source_term}{example.source_suffix}")
print(f"Target: {example.target_prefix}{example.target_term}{example.target_suffix}")
```
## Get Supported Languages
```python
# Get all supported languages
languages = client.get_supported_languages()
# Translation languages
print("Translation languages:")
for code, lang in languages.translation.items():
print(f" {code}: {lang.name} ({lang.native_name})")
# Transliteration languages
print("\nTransliteration languages:")
for code, lang in languages.transliteration.items():
print(f" {code}: {lang.name}")
for script in lang.scripts:
print(f" {script.code} -> {[t.code for t in script.to_scripts]}")
# Dictionary languages
print("\nDictionary languages:")
for code, lang in languages.dictionary.items():
print(f" {code}: {lang.name}")
```
## Break Sentence
Identify sentence boundaries:
```python
result = client.find_sentence_boundaries(
body=["Hello! How are you? I hope you are well."],
language="en"
)
for item in result:
print(f"Sentence lengths: {item.sent_len}")
```
## Translation Options
```python
result = client.translate(
body=["Hello, world!"],
to=["de"],
text_type="html", # "plain" or "html"
profanity_action="Marked", # "NoAction", "Deleted", "Marked"
profanity_marker="Asterisk", # "Asterisk", "Tag"
include_alignment=True, # Include word alignment
include_sentence_length=True # Include sentence boundaries
)
for item in result:
translation = item.translations[0]
print(f"Translated: {translation.text}")
if translation.alignment:
print(f"Alignment: {translation.alignment.proj}")
if translation.sent_len:
print(f"Sentence lengths: {translation.sent_len.src_sent_len}")
```
## Async Client
```python
from azure.ai.translation.text.aio import TextTranslationClient
from azure.identity.aio import DefaultAzureCredential
async def translate_text():
async with DefaultAzureCredential() as credential:
async with TextTranslationClient(
credential=credential,
endpoint=endpoint,
) as client:
result = await client.translate(
body=["Hello, world!"],
to=["es"]
)
print(result[0].translations[0].text)
```
## Client Methods
| Method | Description |
|--------|-------------|
| `translate` | Translate text to one or more languages |
| `transliterate` | Convert text between scripts |
| `detect` | Detect language of text |
| `find_sentence_boundaries` | Identify sentence boundaries |
| `lookup_dictionary_entries` | Dictionary lookup for translations |
| `lookup_dictionary_examples` | Get usage examples |
| `get_supported_languages` | List supported languages |
## 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. **Batch translations** — Send multiple texts in one request (up to 100)
4. **Specify source language** when known to improve accuracy
5. **Use async client** for high-throughput scenarios
6. **Cache language list** — Supported languages don't change frequently
7. **Handle profanity** appropriately for your application
8. **Use html text_type** when translating HTML content
9. **Include alignment** for applications needing word mapping
모든 파일
0개 파일azure-ai-translation-text-py 설치
스킬 파일을 다운로드하여 .claude/skills/ 디렉토리에 추출하세요.
ZIP 다운로드저장소를 클론하고 스킬 파일을 프로젝트에 복사하세요.
git clone https://github.com/microsoft/skills/tree/main/.github/plugins/azure-sdk-python/skills/azure-ai-translation-text-py # Copy SKILL.md to your .claude/skills/ directory
복사





집
