.NET 用 Azure Text Translation クライアント ライブラリ - バージョン 1.0.0-beta.1

テキスト翻訳は、Translator サービスのクラウドベースの REST API 機能で、ニューラル機械翻訳テクノロジを使用して、サポートされているすべての言語でソースからターゲットへの迅速かつ正確なテキスト翻訳をリアルタイムで実現します。

.NET 用 Text Translation クライアント ライブラリを使用して、次の手順を実行します。

  • Translate、Transliterate、Dictionary の各操作でサポートされている言語の一覧を返します。

  • 1 つの要求で 1 つのソース言語テキストを複数のターゲット言語テキストにレンダリングします。

  • ソース言語のテキストを別のスクリプトの文字で変換します。

  • ターゲット言語のソース用語に対応する単語を返します。

  • ソース用語とターゲット用語のペアの文法構造とコンテキストの例を返します。

ソースコード | API リファレンス ドキュメント | 製品ドキュメント

作業の開始

パッケージをインストールする

NuGet を使用して .NET 用の Azure Text Translation クライアント ライブラリをインストールします。

dotnet add package Azure.AI.Translation.Text --prerelease

SDK のバージョンとサービスのサポートされる API バージョンの関係を次の表に示します。

SDK バージョン サポートされている API バージョンのサービス
1.0.0-beta.1 3.0

前提条件

クライアントを認証する

クライアント ライブラリを使用したサービスとの対話は、 まず TextTranslationClient クラスのインスタンスの作成から始まります。 API キーTokenCredentialまたはクライアント オブジェクトをインスタンス化する必要があります。 Cognitive Services を使用した認証の詳細については、「 Translator Service への要求を認証する」を参照してください。

API キーを取得する

および は、endpointAPI keyRegionAzure Portal の Cognitive Services リソースまたは Translator サービス リソース情報から取得できます。

または、以下の Azure CLI スニペットを使用して、Translator サービス リソースから API キーを取得します。

az cognitiveservices account keys list --resource-group <your-resource-group-name> --name <your-resource-name>

API キーとリージョン資格情報を使用して を TextTranslationClient 作成する

API キーとリージョンの値を取得したら、 を作成します AzureKeyCredential。 これにより、新しいクライアントを作成せずに API キーを更新できます。

エンドポイントの 値と Regionを使用すると、 AzureKeyCredentialTextTranslationClient を作成できます。

AzureKeyCredential credential = new("<apiKey>");
TextTranslationClient client = new(credential, "<region>");

主要な概念

TextTranslationClient

TextTranslationClientは、Text Translation クライアント ライブラリを使用する開発者向けの主要なインターフェイスです。 サポートされている言語の検出やテキスト翻訳の取得など、テキスト翻訳ツールの特定の用途にアクセスするための同期操作と非同期操作の両方が提供されます。

入力

テキスト要素 (string) は、Translator サービスの翻訳モデルによって処理される入力の 1 つの単位です。 に対する TextTranslationClient 操作は、1 つのテキスト要素またはテキスト要素のコレクションを受け取る場合があります。 テキスト要素の長さの制限、要求の最大サイズ、サポートされているテキスト エンコードについては、 こちらを参照してください

戻り値

などの Response<IReadOnlyList<TranslatedTextItem>>戻り値は、テキスト変換操作の結果です。入力配列内の文字列ごとに 1 つの結果を含む配列が含まれます。 操作の戻り値には、必要に応じて、入力テキスト要素 (検出された言語など) に関する情報を含めることもできます。

スレッド セーフ

すべてのクライアント インスタンス メソッドがスレッド セーフであり、相互に独立していることを保証します (ガイドライン)。 これにより、スレッド間であっても、クライアント インスタンスの再利用に関する推奨事項が常に安全になります。

その他の概念

クライアント オプション | 応答 | へのアクセス実行時間の長い操作 | エラーの | 処理診断 | あざける | クライアントの有効期間

次のセクションでは、上記で作成したclient使用したコード スニペットをいくつか示し、このクライアント ライブラリに存在するメイン機能について説明します。 以下のスニペットのほとんどは非同期サービス呼び出しを使用していますが、パッケージでは同期 API と非同期 API の両方がサポートされていること Azure.AI.Translation.Text に注意してください。

サポートされている言語を取得する

Translator の他の操作で現在サポートされている一連の言語を取得します。

try
{
    Response<GetLanguagesResult> response = await client.GetLanguagesAsync(cancellationToken: CancellationToken.None).ConfigureAwait(false);
    GetLanguagesResult languages = response.Value;

    Console.WriteLine($"Number of supported languages for translate operations: {languages.Translation.Count}.");
}
catch (RequestFailedException exception)
{
    Console.WriteLine($"Error Code: {exception.ErrorCode}");
    Console.WriteLine($"Message: {exception.Message}");
}

エンドポイントの使用に関するサンプルについては、 languages こちらの他のサンプルを参照 してください

言語の概念的な説明については、サービスドキュメントを参照してください。

Translate

1 つの要求で、1 つのソース言語テキストを複数のターゲット言語テキストにレンダリングします。

try
{
    string targetLanguage = "cs";
    string inputText = "This is a test.";

    Response<IReadOnlyList<TranslatedTextItem>> response = await client.TranslateAsync(targetLanguage, inputText).ConfigureAwait(false);
    IReadOnlyList<TranslatedTextItem> translations = response.Value;
    TranslatedTextItem translation = translations.FirstOrDefault();

    Console.WriteLine($"Detected languages of the input text: {translation?.DetectedLanguage?.Language} with score: {translation?.DetectedLanguage?.Score}.");
    Console.WriteLine($"Text was translated to: '{translation?.Translations?.FirstOrDefault().To}' and the result is: '{translation?.Translations?.FirstOrDefault()?.Text}'.");
}
catch (RequestFailedException exception)
{
    Console.WriteLine($"Error Code: {exception.ErrorCode}");
    Console.WriteLine($"Message: {exception.Message}");
}

エンドポイントの使用に関するサンプルについては、 translate こちらの他のサンプルを参照 してください

翻訳の概念については、サービスドキュメントを参照してください。

Transliterate

ソース言語の文字を、ターゲット言語の対応する文字に変換します。

try
{
    string language = "zh-Hans";
    string fromScript = "Hans";
    string toScript = "Latn";

    string inputText = "这是个测试。";

    Response<IReadOnlyList<TransliteratedText>> response = await client.TransliterateAsync(language, fromScript, toScript, inputText).ConfigureAwait(false);
    IReadOnlyList<TransliteratedText> transliterations = response.Value;
    TransliteratedText transliteration = transliterations.FirstOrDefault();

    Console.WriteLine($"Input text was transliterated to '{transliteration?.Script}' script. Transliterated text: '{transliteration?.Text}'.");
}
catch (RequestFailedException exception)
{
    Console.WriteLine($"Error Code: {exception.ErrorCode}");
    Console.WriteLine($"Message: {exception.Message}");
}

エンドポイントの使用に関するサンプルについては、 transliterate こちらの他のサンプルを参照 してください

音訳の概念については、サービスドキュメントを参照してください。

文の分割

文章内で文の境界の位置を識別します。

try
{
    string inputText = "How are you? I am fine. What did you do today?";

    Response<IReadOnlyList<BreakSentenceItem>> response = await client.FindSentenceBoundariesAsync(inputText).ConfigureAwait(false);
    IReadOnlyList<BreakSentenceItem> brokenSentences = response.Value;
    BreakSentenceItem brokenSentence = brokenSentences.FirstOrDefault();

    Console.WriteLine($"Detected languages of the input text: {brokenSentence?.DetectedLanguage?.Language} with score: {brokenSentence?.DetectedLanguage?.Score}.");
    Console.WriteLine($"The detected sentece boundaries: '{string.Join(",", brokenSentence?.SentLen)}'.");

}
catch (RequestFailedException exception)
{
    Console.WriteLine($"Error Code: {exception.ErrorCode}");
    Console.WriteLine($"Message: {exception.Message}");
}

エンドポイントの使用に関するサンプルについては、 break sentece こちらの他のサンプルを参照 してください

中断文の概念については、サービスドキュメントを参照してください。

辞書検索

ターゲット言語から、ソース用語に相当する単語を返します。

try
{
    string sourceLanguage = "en";
    string targetLanguage = "es";
    string inputText = "fly";

    Response<IReadOnlyList<DictionaryLookupItem>> response = await client.LookupDictionaryEntriesAsync(sourceLanguage, targetLanguage, inputText).ConfigureAwait(false);
    IReadOnlyList<DictionaryLookupItem> dictionaryEntries = response.Value;
    DictionaryLookupItem dictionaryEntry = dictionaryEntries.FirstOrDefault();

    Console.WriteLine($"For the given input {dictionaryEntry?.Translations?.Count} entries were found in the dictionary.");
    Console.WriteLine($"First entry: '{dictionaryEntry?.Translations?.FirstOrDefault()?.DisplayTarget}', confidence: {dictionaryEntry?.Translations?.FirstOrDefault()?.Confidence}.");

}
catch (RequestFailedException exception)
{
    Console.WriteLine($"Error Code: {exception.ErrorCode}");
    Console.WriteLine($"Message: {exception.Message}");
}

エンドポイントの使用に関するサンプルについては、 dictionary lookup こちらの他のサンプルを参照 してください

辞書検索の概念については、サービスドキュメントを参照してください。

辞書の例

ソース用語とターゲット用語のペアの文法構造とコンテキストの例を返します。

try
{
    string sourceLanguage = "en";
    string targetLanguage = "es";
    IEnumerable<InputTextWithTranslation> inputTextElements = new[]
    {
        new InputTextWithTranslation("fly", "volar")
    };

    Response<IReadOnlyList<DictionaryExampleItem>> response = await client.LookupDictionaryExamplesAsync(sourceLanguage, targetLanguage, inputTextElements).ConfigureAwait(false);
    IReadOnlyList<DictionaryExampleItem> dictionaryEntries = response.Value;
    DictionaryExampleItem dictionaryEntry = dictionaryEntries.FirstOrDefault();

    Console.WriteLine($"For the given input {dictionaryEntry?.Examples?.Count} examples were found in the dictionary.");
    DictionaryExample firstExample = dictionaryEntry?.Examples?.FirstOrDefault();
    Console.WriteLine($"Example: '{string.Concat(firstExample.TargetPrefix, firstExample.TargetTerm, firstExample.TargetSuffix)}'.");

}
catch (RequestFailedException exception)
{
    Console.WriteLine($"Error Code: {exception.ErrorCode}");
    Console.WriteLine($"Message: {exception.Message}");
}

エンドポイントの使用に関するサンプルについては、 dictionary examples こちらの他のサンプルを参照 してください

辞書の例の概念については、サービスドキュメントを参照してください。

トラブルシューティング

テキスト翻訳クライアント ライブラリを使用して Translator Service と対話する場合、Translator サービスによって返されるエラーは、REST API 要求に対して返されるのと同じ HTTP 状態コードに対応します。

たとえば、ターゲット翻訳言語なしで翻訳要求を送信すると、 400 "Bad Request" を示すエラーが返されます。

try
{
    var translation = client.TranslateAsync(Array.Empty<string>(), new[] { new InputText { Text = "This is a Test" } }).ConfigureAwait(false);
}
catch (RequestFailedException e)
{
    Console.WriteLine(e.ToString());
}

操作のクライアント要求 ID など、追加情報がログに記録されていることがわかります。

Message:
    Azure.RequestFailedException: Service request failed.
    Status: 400 (Bad Request)

Content:
    {"error":{"code":400036,"message":"The target language is not valid."}}

Headers:
    X-RequestId: REDACTED
    Access-Control-Expose-Headers: REDACTED
    X-Content-Type-Options: REDACTED
    Strict-Transport-Security: REDACTED
    Date: Mon, 27 Feb 2023 23:31:37 GMT
    Content-Type: text/plain; charset=utf-8
    Content-Length: 71

コンソール ログの設定

ログを表示する最も簡単な方法は、コンソールログを有効にすることです。 コンソールにメッセージを出力する Azure SDK ログ リスナーを作成するには、AzureEventSourceListener.CreateConsoleLogger メソッドを使用します。

// Setup a listener to monitor logged events.
using AzureEventSourceListener listener = AzureEventSourceListener.CreateConsoleLogger();

その他のログメカニズムの詳細については、 こちらを参照してください

次のステップ

このクライアント ライブラリの使用方法を示すサンプルは、この GitHub リポジトリで入手できます。 サンプルはメイン機能領域ごとに提供され、領域ごとに同期モードと非同期モードの両方でサンプルが提供されます。

共同作成

このライブラリのビルド、テスト、および投稿の詳細については、 CONTRIBUTING.md を参照してください。

このプロジェクトでは、共同作成と提案を歓迎しています。 ほとんどの共同作成では、共同作成者使用許諾契約書 (CLA) にご同意いただき、ご自身の共同作成内容を使用する権利を Microsoft に供与する権利をお持ちであり、かつ実際に供与することを宣言していただく必要があります。 詳細については、「 cla.microsoft.com」を参照してください。

pull request を送信すると、CLA を提供して PR (ラベル、コメントなど) を適宜装飾する必要があるかどうかを CLA ボットが自動的に決定します。 ボットによって提供される手順にそのまま従ってください。 この操作は、Microsoft の CLA を使用するすべてのリポジトリについて、1 回だけ行う必要があります。

このプロジェクトでは、Microsoft オープン ソースの倫理規定を採用しています。 詳しくは、「Code of Conduct FAQ (倫理規定についてよくある質問)」を参照するか、opencode@microsoft.com 宛てに質問またはコメントをお送りください。