azure-ai-translation-text-py について
テキスト翻訳や言語処理を行うアプリケーション向けの、Azure AI Translator用Pythonクライアントライブラリです。文字の変換、辞書検索、文境界の検出にも対応します。
主な機能
- 011つまたは複数の言語へのテキスト翻訳
- 02原文言語の検出
- 03文字体系間の文字変換
- 04訳語と用例の検索
- 05文境界の検出
- 06対応言語の一覧取得
活用シーン
- 01多言語アプリケーション向けのテキスト翻訳
- 02異なる文字体系間のテキスト変換
- 03辞書の訳語や用例の検索
- 04テキストの文単位への分割
インストール
コマンドをコピーしてターミナルで実行します。
$
npx skills add https:/ / github.com/ sickn33/ agentic-awesome-skills --skill azure-ai-translation-text-pyインストール後、Claude Code で/azure-ai-translation-text-pyを入力して読み込まれたか確認します。
詳細
Azure AI Text Translation SDK for Python
Azure AI Translator のテキスト翻訳サービス用クライアントライブラリです。リアルタイムのテキスト翻訳、文字変換、言語操作に対応しています。
インストール
pip install azure-ai-translation-text
環境変数
AZURE_TRANSLATOR_KEY=<your-api-key>
AZURE_TRANSLATOR_REGION=<your-region> # e.g., eastus, westus2
# Or use custom endpoint
AZURE_TRANSLATOR_ENDPOINT=https://<resource>.cognitiveservices.azure.com
認証
リージョンを指定した API キー
import os
from azure.ai.translation.text import TextTranslationClient
from azure.core.credentials import AzureKeyCredential
key = os.environ["AZURE_TRANSLATOR_KEY"]
region = os.environ["AZURE_TRANSLATOR_REGION"]
# Create credential with region
credential = AzureKeyCredential(key)
client = TextTranslationClient(credential=credential, region=region)
カスタムエンドポイントを指定した API キー
endpoint = os.environ["AZURE_TRANSLATOR_ENDPOINT"]
client = TextTranslationClient(
credential=AzureKeyCredential(key),
endpoint=endpoint
)
Entra ID(推奨)
from azure.ai.translation.text import TextTranslationClient
from azure.identity import DefaultAzureCredential
client = TextTranslationClient(
credential=DefaultAzureCredential(),
endpoint=os.environ["AZURE_TRANSLATOR_ENDPOINT"]
)
基本的な翻訳
# 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}")
複数の言語への翻訳
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}")
翻訳元の言語を指定
result = client.translate(
body=["Bonjour le monde"],
from_parameter="fr", # Source is French
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", # From Latin script
to_script="Jpan" # To Japanese script
)
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}")
対応言語の取得
# 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}")
文の区切りの検出
文の境界を特定します。
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" 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}")
非同期クライアント
from azure.ai.translation.text.aio import TextTranslationClient
from azure.core.credentials import AzureKeyCredential
async def translate_text():
async with TextTranslationClient(
credential=AzureKeyCredential(key),
region=region
) as client:
result = await client.translate(
body=["Hello, world!"],
to=["es"]
)
print(result[0].translations[0].text)
クライアントのメソッド
| メソッド | 説明 |
|---|---|
translate | テキストを1つ以上の言語に翻訳します |
transliterate | 文字体系間でテキストを変換します |
detect | テキストの言語を検出します |
find_sentence_boundaries | 文の境界を特定します |
lookup_dictionary_entries | 翻訳を辞書で検索します |
lookup_dictionary_examples | 使用例を取得します |
get_supported_languages | 対応言語を一覧表示します |
ベストプラクティス
- 翻訳をまとめて処理する — 1つのリクエストで複数のテキストを送信します(最大100件)。
- 判明している場合は翻訳元の言語を指定する — 精度が向上します。
- スループットが高いシナリオでは非同期クライアントを使用する
- 言語一覧をキャッシュする — 対応言語は頻繁には変更されません。
- アプリケーションに応じて不適切な表現を適切に処理する
- HTML コンテンツを翻訳する場合は
html text_typeを使用する - 単語の対応付けが必要なアプリケーションではアラインメントを含める
使用する場面
このスキルは、概要で説明されているワークフローまたはアクションを実行する場合に適しています。
制限事項
- このスキルは、タスクが上記の説明の範囲に明確に該当する場合にのみ使用してください。
- 出力を、環境固有の検証、テスト、または専門家によるレビューの代わりとして扱わないでください。
- 必要な入力、権限、安全上の境界、または成功基準が不足している場合は、処理を中止して確認を求めてください。
これらの断片を使用する前に、固定された SDK とリソース API バージョンに照らして、シグネチャおよびバッチ/文字数の上限を確認してください。テキストを翻訳すると、設定されたクラウドサービスに送信されます。機密コンテンツの転送を承認し、ログから機密情報を削除してください。項目ごとのエラー、上限付きの再試行、クォータ制限を適切に処理してください。クライアントを構築しただけでは、翻訳の成功は確認できません。
コメント
Markdown 対応