选项
首页首页 Skill API开发 azure-ai-translation-text-py

azure-ai-translation-text-py

microsoft/skills microsoft/skills

实时翻译文本,检测语言,在不同书写系统之间进行转写,并使用 Azure AI Translator SDK for Python 查询词典条目。

...展开全部
1
更新时间 2026-09-15

Azure AI 文本翻译 Python SDK

用于实时文本翻译、转写和语言操作的 Azure AI 翻译器文本翻译服务的客户端库。

安装

pip install azure-ai-translation-text

环境变量

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>

身份验证与生命周期

🔑 以下每个代码示例都适用两条规则:

  1. 首选 DefaultAzureCredential 它在本地(Azure CLI / VS Code / Developer CLI)和 Azure(托管身份、工作负载身份)中无需更改代码即可工作。避免使用连接字符串、帐户/API 密钥——它们会绕过 Entra 审计和轮换。
    • 本地开发:DefaultAzureCredential 可直接使用。
    • 生产环境:设置 AZURE_TOKEN_CREDENTIALS=prod(或 AZURE_TOKEN_CREDENTIALS=<specific_credential></specific_credential>)以将凭据链限制为生产安全的凭据。
  2. 将每个客户端包装在上下文管理器中,以便确定性地释放 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>

遗留:API 密钥(现有的密钥部署)

新代码应使用上述 DefaultAzureCredential。翻译器服务有两个特性,使得在现有部署中 API 密钥身份验证仍然很常见:

  • 令牌凭据身份验证需要自定义子域端点https://<resource>.cognitiveservices.azure.com</resource>)。如果您只有全局端点(https://api.cognitive.microsofttranslator.com),则必须配置自定义子域,或者在配置之前继续使用基于密钥的路径。
  • 密钥 + 区域 是对全局端点的标准设置。区域作为 Ocp-Apim-Subscription-Region 标头发送,在使用多服务或全局翻译器密钥时必需。
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"])

基本翻译

# 翻译成单一语言
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}")

翻译成多种语言

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}")

指定源语言

result = client.translate(
    body=["Bonjour le monde"],
    from_parameter="fr",  # 源语言为法语
    to=["en", "es"]
)

语言检测

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}")

转写

将文本从一种脚本转换为另一种:

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}")

词典查找

查找替代翻译和定义:

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}")

词典示例

获取翻译的用法示例:

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}")

获取支持的语言

# 获取所有支持的语言
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}")

断句

识别句子边界:

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}")

翻译选项

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}")

异步客户端

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)

客户端方法

方法描述
`translate`将文本翻译成一种或多种语言
`transliterate`在脚本之间转换文本
`detect`检测文本语言
`find_sentence_boundaries`识别句子边界
`lookup_dictionary_entries`翻译的词典查找
`lookup_dictionary_examples`获取用法示例
`get_supported_languages`列出支持的语言

最佳实践

  1. 选择同步或异步并保持一致。 不要在同一个调用路径中混合使用 azure.xxx 同步客户端和 azure.xxx.aio 异步客户端。每个模块选择一种模式。
  2. 始终对客户端和异步凭据使用上下文管理器。 将每个客户端包装在 with Client(...) as client:(同步)或 async with Client(...) as client:(异步)中。对于来自 azure.identity.aio 的异步 DefaultAzureCredential,也使用 async with credential: 以便清理令牌和传输。
  3. 批量翻译 — 在一次请求中发送多个文本(最多 100 个)
  4. 指定源语言 以提高准确性
  5. 使用异步客户端 用于高吞吐量场景
  6. 缓存语言列表 — 支持的语言不经常更改
  7. 适当处理脏话 以适应您的应用程序
  8. 使用 html text_type 翻译 HTML 内容时
  9. 包含对齐 用于需要单词映射的应用程序
在 GitHub 上查看
---
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

复制 复制
快速设置: 将技能文件夹复制到 .claude/skills/ 目录。Claude 将自动检测并使用该技能。

相关技能

agentwallet
更新时间 2026-07-07
brightdata-cli
更新时间 2026-06-29
humanize
更新时间 2026-07-07
korean-stock-search
更新时间 2026-07-08
OR