クイック スタート:Ink Recognizer REST API および C# を使用したデジタル インクの認識

注意

Ink Recognizer API は、2020 年 8 月 26 日にプレビューを終了しました。 既存の Ink Recognizer リソースがある場合は、2021 年 1 月 31 日にサービスが完全に廃止されるまで、引き続き使用できます。

このクイックスタートを使用して、Ink Recognizer API へのデジタル インク ストロークの送信を開始します。 この C# アプリケーションは、JSON 形式のインク ストローク データを含む API 要求を送信し、応答を取得します。

このアプリケーションは C# で記述されていますが、API はほとんどのプログラミング言語と互換性のある RESTful Web サービスです。

通常、この API はデジタル インキング アプリから呼び出します。 このクイックスタートでは、JSON ファイルから次の手書きサンプルのインク ストローク データを送信します。

手書きテキストのイメージ

このクイック スタートのソース コードは、GitHub にあります。

前提条件

  • Visual Studio 2017 の任意のエディション。

  • Newtonsoft.Json

    • Visual Studio に Newtonsoft.Json を NuGet パッケージとしてインストールするには、次の手順に従います。
      1. Solution Manager を右クリックします
      2. [NuGet パッケージの管理]
      3. Newtonsoft.Json を探して、パッケージをインストールします
  • Linux/macOS を使用している場合、このアプリケーションは Mono を使用して実行できます。

  • このクイックスタートのインク ストローク データのサンプルは、GitHub にあります。

Ink Recognizer リソースを作成する

注意

2019 年 7 月 1 日より後に作成されたリソースのエンドポイントでは、次に示すカスタム サブドメイン形式を使用します。 リージョンのエンドポイントの詳細および全一覧については、「Cognitive Services のカスタム サブドメイン名」を参照してください。

Azure Cognitive Services は、ユーザーがサブスクライブする Azure リソースによって表されます。 Azure portal を使用して、Ink Recognizer 用のリソースを作成します。

リソースの作成後、Azure portal でリソースを開き、 [クイック スタート] をクリックして、エンドポイントとキーを取得します。

以下の 2 つの環境変数を作成します。

  • INK_RECOGNITION_SUBSCRIPTION_KEY - 要求を認証するためのサブスクリプション キー。

  • INK_RECOGNITION_ENDPOINT - リソースのエンドポイント。 以下のようになります。
    https://<your-custom-subdomain>.api.cognitive.microsoft.com

新しいアプリケーションを作成する

  1. Visual Studio で新しいコンソール ソリューションを作成し、次のパッケージを追加します。

    using System;
    using System.IO;
    using System.Net;
    using System.Net.Http;
    using System.Net.Http.Headers;
    using System.Text;
    using System.Threading.Tasks;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Linq;
    
  2. サブスクリプション キー、エンドポイント、およびサンプル JSON ファイル用の変数を作成します。 エンドポイントは、API にアクセスするために、後で inkRecognitionUrl と結合されます。

    // Add your Ink Recognizer subscription key to your environment variables.
    static readonly string subscriptionKey = Environment.GetEnvironmentVariable("INK_RECOGNIZER_SUBSCRIPTION_KEY");
    
    // Add your Ink Recognizer endpoint to your environment variables.
    // For example: <your-custom-subdomain>.cognitiveservices.azure.com
    static readonly string endpoint = Environment.GetEnvironmentVariable("INK_RECOGNIZER_ENDPOINT");
    static readonly string inkRecognitionUrl = "/inkrecognizer/v1.0-preview/recognize";
    
    // Replace the dataPath string with a path to the JSON formatted ink stroke data.
    // Optionally, use the example-ink-strokes.json file of this sample. Add to your bin\Debug\netcoreapp3.0 project folder.
    static readonly string dataPath = @"PATH_TO_INK_STROKE_DATA";
    

要求を送信する関数を作成する

  1. 上記で作成した変数を取る Request という新しい非同期関数を作成します。

  2. HttpClientオブジェクトを使用して、クライアントのセキュリティ プロトコルとヘッダー情報を設定します。 Ocp-Apim-Subscription-Key ヘッダーには必ずサブスクリプション キーを追加してください。 その後、要求の StringContent オブジェクトを作成します。

  3. PutAsync() を使用して要求を送信します。 要求が成功した場合は、応答を返します。

    static async Task<string> Request(string apiAddress, string endpoint, string subscriptionKey, string requestData)
    {
    
        using (HttpClient client = new HttpClient { BaseAddress = new Uri(apiAddress) })
        {
            System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", subscriptionKey);
    
            var content = new StringContent(requestData, Encoding.UTF8, "application/json");
            var res = await client.PutAsync(endpoint, content);
            if (res.IsSuccessStatusCode)
            {
                return await res.Content.ReadAsStringAsync();
            }
            else
            {
                return $"ErrorCode: {res.StatusCode}";
            }
        }
    }
    

インク認識要求を送信する

  1. recognizeInk() という新しい関数を作成します。 要求を構成し、エンドポイント、サブスクリプション キー、API の URL、デジタル インク ストローク データを指定して Request() 関数を呼び出すことで送信します。

  2. JSON オブジェクトを逆シリアル化し、それをコンソールに書き込みます。

    static void recognizeInk(string requestData)
    {
    
        //construct the request
        var result = Request(
            endpoint,
            inkRecognitionUrl,
            subscriptionKey,
            requestData).Result;
    
        dynamic jsonObj = Newtonsoft.Json.JsonConvert.DeserializeObject(result);
        System.Console.WriteLine(jsonObj);
    }
    

デジタル インク データを読み込む

LoadJson() という関数を作成して、インク データの JSON ファイルを読み込みます。 StreamReader および JsonTextReader を使用して JObject を作成し、それを返します。

public static JObject LoadJson(string fileLocation)
{
    var jsonObj = new JObject();

    using (StreamReader file = File.OpenText(fileLocation))
    using (JsonTextReader reader = new JsonTextReader(file))
    {
        jsonObj = (JObject)JToken.ReadFrom(reader);
    }
    return jsonObj;
}

API 要求を送信する

  1. アプリケーションの main メソッドで、上記で作成した関数を使用して JSON データを読み込みます。

  2. 上記で作成した recognizeInk() 関数を呼び出します。 System.Console.ReadKey() を使用して、アプリケーションの実行後にコンソール ウィンドウを開いたままにします。

    static void Main(string[] args)
    {
    
        var requestData = LoadJson(dataPath);
        string requestString = requestData.ToString(Newtonsoft.Json.Formatting.None);
        recognizeInk(requestString);
        System.Console.WriteLine("\nPress any key to exit ");
        System.Console.ReadKey();
    }
    

アプリケーションを実行し、応答を表示する

アプリケーションを実行します。 成功応答が JSON 形式で返されます。 JSON 応答は GitHub でも確認できます。

次のステップ

デジタル インキング アプリで Ink Recognition API がどのように動作するかを確認するには、GitHub 上の次のサンプル アプリケーションを参照してください。