빠른 시작: Ink Recognizer REST API와 C#으로 디지털 잉크 인식
참고
2020년 8월 26일에 Ink Recognizer API의 미리 보기가 종료되었습니다. 기존 Ink Recognizer 리소스가 있는 경우 2021년 1월 31일에 서비스가 완전히 사용 중지될 때까지 계속 사용할 수 있습니다.
이 빠른 시작을 사용하여 디지털 잉크 스트로크를 Ink Recognizer API에 보내기 시작합니다. 이 C# 애플리케이션은 JSON 형식의 잉크 스트로크 데이터가 포함된 API 요청을 보내고 응답을 받습니다.
이 애플리케이션은 C#으로 작성되었지만, API는 대부분의 프로그래밍 언어와 호환되는 RESTful 웹 서비스입니다.
일반적으로 API는 디지털 잉크 입력 앱에서 호출합니다. 이 빠른 시작은 JSON 파일에서 다음 필기 샘플에 대한 잉크 스트로크 데이터를 보냅니다.
이 빠른 시작의 소스 코드는 GitHub에서 확인할 수 있습니다.
사전 요구 사항
Visual Studio 2017의 모든 버전.
-
- Visual Studio에서 Newtonsoft.Json을 NuGet 패키지로 설치하려면 다음을 수행합니다.
- 솔루션 관리자를 마우스 오른쪽 단추로 클릭합니다.
- NuGet 패키지 관리...
-
Newtonsoft.Json
을 검색하고 패키지를 설치합니다.
- Visual Studio에서 Newtonsoft.Json을 NuGet 패키지로 설치하려면 다음을 수행합니다.
Linux/MacOS를 사용하는 경우 이 애플리케이션은 Mono를 사용하여 실행할 수 있습니다.
이 빠른 시작의 잉크 스트로크 데이터 예제는 GitHub에서 찾을 수 있습니다.
Ink Recognizer 리소스 만들기
참고
2019년 7월 1일 이후에 생성된 리소스의 엔드포인트는 아래에 표시된 사용자 지정 하위 도메인 형식을 사용합니다. 자세한 내용 및 지역별 엔드포인트의 전체 목록은 Cognitive Services에 대한 사용자 지정 하위 도메인 이름을 참조하세요.
Azure Cognitive Services는 구독하는 Azure 리소스로 표시됩니다. Azure Portal을 사용하여 잉크 인식기에 대한 리소스를 만듭니다.
리소스를 만든 후 Azure Portal에서 리소스를 열고 빠른 시작을 클릭하여 엔드포인트와 키를 가져옵니다.
두 개의 환경 변수를 만듭니다.
INK_RECOGNITION_SUBSCRIPTION_KEY
- 요청을 인증하기 위한 구독 키입니다.INK_RECOGNITION_ENDPOINT
- 리소스에 대한 엔드포인트입니다. 다음과 같이 표시됩니다.
https://<your-custom-subdomain>.api.cognitive.microsoft.com
새 애플리케이션 만들기
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;
구독 키, 엔드포인트 및 예제 JSON 파일에 대한 변수를 만듭니다. 엔드포인트는 나중에
inkRecognitionUrl
과 결합되어 API에 액세스합니다.// 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";
요청을 보내는 함수 만들기
위에서 만든 변수를 사용하는
Request
라는 새 비동기 함수를 만듭니다.HttpClient
개체를 사용하여 클라이언트의 보안 프로토콜과 헤더 정보를 설정합니다.Ocp-Apim-Subscription-Key
헤더에 구독 키를 추가해야 합니다. 그런 다음, 요청에 대한StringContent
개체를 만듭니다.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}"; } } }
잉크 인식 요청 보내기
recognizeInk()
라는 새 함수를 만듭니다. 요청을 구성하고 엔드포인트, 구독 키, API용 URL 및 디지털 잉크 스트로크 데이터와 함께Request()
함수를 호출하여 보냅니다.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 요청 보내기
애플리케이션의 main 메서드에서 위에서 만든 함수를 사용하여 JSON 데이터를 로드합니다.
위에서 만든
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 형식으로 반환됩니다. 또한 GitHub에서 JSON 응답을 찾을 수 있습니다.
다음 단계
Ink Recognizer API가 디지털 잉크 입력 앱에서 어떻게 작동하는지 알아보려면 GitHub에서 다음 샘플 애플리케이션을 살펴보세요.