快速入門:Azure AI 翻譯工具 REST API

試用最新版的 Azure AI 翻譯工具。 在本快速入門中,您將開始使用翻譯工具服務,以您選擇的程式設計語言和 REST API 翻譯文字。 針對此專案,在您同時學習技術時,建議您使用免費定價層 (F0),並稍後再升級至生產環境的付費層。

必要條件

您需要作用中的 Azure 訂用帳戶。 若還沒有 Azure 訂閱,您可以建立免費帳戶

  • 擁有 Azure 訂閱之後,請在 Azure 入口網站中建立翻譯工具資源

  • 部署資源之後,請選取 [前往資源] 擷取金鑰與端點。

    • 您將需要來自資源的金鑰和端點,以將應用程式連線至翻譯工具服務。 您稍後會在快速入門中將金鑰和端點貼到程式碼中。 您可以在 Azure 入口網站的 [金鑰和端點] 頁面上找到這些值:

      Screenshot: Azure portal keys and endpoint page.

      注意

      • 本快速入門建議使用翻譯工具文字單一服務全域資源。
      • 使用單一服務全域資源,您可在 REST API 要求中包含一個授權標頭 (Ocp-Apim-Subscription-key)。 Ocp-Apim-Subscription-key 的值是翻譯工具文字訂閱的 Azure 祕密金鑰。
      • 如果您選擇使用 Azure AI 多服務或區域翻譯工具資源,則需要兩個驗證標頭 (Ocp-Api-Subscription-KeyOcp-Apim-Subscription-Region)。 Ocp-Apim-Subscription-Region 的值是與您訂閱相關聯的區域。
      • 如需如何使用 Ocp-Apim-Subscription-Region 標頭的詳細資訊,請參閱文字翻譯 REST API 標頭

標頭

若要透過 REST API 呼叫翻譯工具服務,您必須在每個要求中都包含下列標頭。 別擔心,我們會為您在每個程式設計語言的範例程式碼中包含標頭。

如需翻譯工具驗證選項的詳細資訊,「請參閱」翻譯工具 v3 參考指南。

頁首 Condition
Ocp-Apim-Subscription-Key 來自 Azure 入口網站的翻譯工具服務金鑰。 必要
Ocp-Apim-Subscription-Region 資源建立的所在區域。 •使用 Azure AI 多服務或區域 (地理) 資源 (例如 美國西部) 時,為必要項目
•使用單一服務全域翻譯工具資源時,則為選擇性
Content-Type 承載的內容類型。 接受的值為 application/jsoncharset=UTF-8 必要
Content-Length 要求本文的長度 選擇性

重要

完成時,請記得從程式碼中移除金鑰,且不要公開張貼金鑰。 在生產環境中,請使用安全的方式來儲存和存取您的認證,例如 Azure Key Vault。 如需詳細資訊,請參閱 Azure AI 服務安全性一文。

翻譯文字

翻譯工具服務的核心作業是翻譯文字。 在本快速入門中,您要使用您選擇的程式設計語言來建置要求,該語言會採用單一來源 (from) 並提供兩個輸出 (to)。 然後,我們將探討一些可用來同時調整要求和回應的參數。

如需有關 Azure AI 翻譯工具服務要求限制的詳細資訊,請參閱文字翻譯要求限制

設定 Visual Studio 專案

  1. 請確定您已安裝最新版的 Visual Studio IDE

    提示

    如果您尚不熟悉 Visual Studio,可以參考 Visual Studio 簡介 Learn 課程模組。

  2. 開啟 Visual Studio。

  3. 在開始頁面中,請選擇 [建立新專案]

    Screenshot: Visual Studio start window.

  4. 在 [建立新的專案] 頁面的搜尋方塊中,輸入主控台。 選擇 [主控台應用程式] 範本,然後選擇 [下一步]

    Screenshot: Visual Studio's create new project page.

  5. 在 [設定新專案] 對話方塊視窗中,於 [專案名稱] 方塊中輸入 translator_quickstart取消核取 [將解決方案和專案置於相同目錄中] 核取方塊,然後選取 [下一步]。

    Screenshot: Visual Studio's configure new project dialog window.

  6. 在 [其他資訊] 對話視窗中,請確定已選取 [.NET 6.0 (長期支援)]取消核取 [不要使用最上層陳述式] 核取方塊,並選取 [建立]

    Screenshot: Visual Studio's additional information dialog window.

使用 NuGet 安裝 Newtonsoft.json 套件

  1. 在您的 translator_quickstart 專案上按一下滑鼠右鍵,然後選取 [管理 NuGet 套件]

    Screenshot of the NuGet package search box.

  2. 選取 [瀏覽] 索引標籤並鍵入 Newtonsoft.json。

    Screenshot of the NuGet package install window.

  3. 若要將套件新增至您的專案中,請從右側的套件管理員視窗中選取 [安裝]。

    Screenshot of the NuGet package install button.

建置您的 C# 應用程式

注意

  • 從 .NET 6 開始,使用 console 範本的新專案會產生與舊版不同的新程式樣式。
  • 新輸出會使用最新的 C# 功能,以簡化您需要撰寫的程式碼。
  • 當您使用較新版本時,只需要撰寫 Main 方法的本文。 您不需要包含最上層陳述式、全域 Using 指示詞或隱含 Using 指示詞。
  • 如需詳細資訊,請參閱新的 C# 範本產生最上層語句
  1. 開啟 Program.cs 檔案。

  2. 刪除預先存在的程式碼,包含此行 Console.WriteLine("Hello World!")。 將範例程式碼複製並貼入您的應用程式 Program.cs 檔案。 請務必使用 Azure 入口網站翻譯工具執行個體的值來更新索引鍵變數:

using System.Text;
using Newtonsoft.Json;

class Program
{
    private static readonly string key = "<your-translator-key>";
    private static readonly string endpoint = "https://api.cognitive.microsofttranslator.com";

    // location, also known as region.
    // required if you're using a multi-service or regional (not global) resource. It can be found in the Azure portal on the Keys and Endpoint page.
    private static readonly string location = "<YOUR-RESOURCE-LOCATION>";

    static async Task Main(string[] args)
    {
        // Input and output languages are defined as parameters.
        string route = "/translate?api-version=3.0&from=en&to=fr&to=zu";
        string textToTranslate = "I would really like to drive your car around the block a few times!";
        object[] body = new object[] { new { Text = textToTranslate } };
        var requestBody = JsonConvert.SerializeObject(body);

        using (var client = new HttpClient())
        using (var request = new HttpRequestMessage())
        {
            // Build the request.
            request.Method = HttpMethod.Post;
            request.RequestUri = new Uri(endpoint + route);
            request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
            request.Headers.Add("Ocp-Apim-Subscription-Key", key);
            // location required if you're using a multi-service or regional (not global) resource.
            request.Headers.Add("Ocp-Apim-Subscription-Region", location);

            // Send the request and get response.
            HttpResponseMessage response = await client.SendAsync(request).ConfigureAwait(false);
            // Read response as a string.
            string result = await response.Content.ReadAsStringAsync();
            Console.WriteLine(result);
        }
    }
}

執行您的 C# 應用程式

將程式碼範例新增至應用程式之後,請選擇 formRecognizer_quickstart 旁的綠色 [開始] 按鈕來建置和執行程式,或按 F5

Screenshot of the run program button in Visual Studio.

翻譯輸出:

呼叫成功後,您應該會看見下列回應:

[
    {
        "detectedLanguage": {
            "language": "en",
            "score": 1.0
        },
        "translations": [
            {
                "text": "J'aimerais vraiment conduire votre voiture autour du pâté de maisons plusieurs fois!",
                "to": "fr"
            },
            {
                "text": "Ngingathanda ngempela ukushayela imoto yakho endaweni evimbelayo izikhathi ezimbalwa!",
                "to": "zu"
            }
        ]
    }
]

下一步

沒錯,恭喜! 您剛剛學會了使用翻譯工具服務來翻譯文字。

探索我們的操作說明文件,並深入探討翻譯服務功能: