きなこもち.net

.NET Framework × UiPath,Orchestrator × Azure × AWS × Angularなどの忘備録

Text Analytics × Http Client × Sample Code

せっかくHttpClientについてと、Cognitive ServicesのText Analyticsを知ったので、サンプルコードを書いてみました。

特に何もないですが、今後も使っていけそうなコードなので、TFSだけでなくこっちでもメモしておきます!
整理したTextAnalyticsUtilのコードはべ別途Gitに公開します!
Gitの登録しないと・・・

なお、Newtonsoft.Jsonを使っているので、NugetでNewtonsoftの最新版を取得してから利用してください。

using Newtonsoft.Json;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

class TextAnalyticsUtil
    {
        private static readonly string uri = "https://eastasia.api.cognitive.microsoft.com/text/analytics/v2.0/keyPhrases";
        private HttpClient aClient = new HttpClient();

             public async Task ExecuteTextAnalyticsSample(string targetMessage)
        {
            aClient.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "サブスクリプションキー");

            // JSON としてシリアライズし POST するデータ 
            var model = new RequesttModel.Rootobject();
            model.documents = new List<RequesttModel.Document>();
            model.documents.Add(new RequesttModel.Document()
            {
                id = "1",
                language = "ja",
                text = targetMessage
            });

            HttpResponseMessage aResponse = null;
            byte[] byteData = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(model));
            using (var content = new ByteArrayContent(byteData))
            {
                content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                aResponse = await aClient.PostAsync(uri, content);
            }

            if (aResponse.IsSuccessStatusCode)
            {
                using (var readst = await aResponse.Content.ReadAsStreamAsync())
                using (var stream = new StreamReader(readst))
                {
                    var result =
                        JsonConvert.DeserializeObject<ResponseModel.Keyphrases>(stream.ReadToEnd());
                }
            }
        }


    }


ModelはJsonを貼り付けただけのものですが、以下のものを使っています。

    public class RequesttModel
    {

        public class Rootobject
        {
            public List<Document> documents { get; set; }
        }

        public class Document
        {
            public string language { get; set; }
            public string id { get; set; }
            public string text { get; set; }
        }

    }
    public class ResponseModel
    {

        public class Rootobject
        {

            public Languagedetection languageDetection { get; set; }
            public Keyphrases keyPhrases { get; set; }
            public Sentiment sentiment { get; set; }
        }

        public class Languagedetection
        {
            public List<Document> documents { get; set; }
            public List<object> errors { get; set; }
        }

        public class Document
        {
            public string id { get; set; }
            public List<Detectedlanguage> detectedLanguages { get; set; }
        }

        public class Detectedlanguage
        {
            public string name { get; set; }
            public string iso6391Name { get; set; }
            public float score { get; set; }
        }

        public class Keyphrases
        {
            public List<Document1> documents { get; set; }
            public List<object> errors { get; set; }
        }

        public class Document1
        {
            public string id { get; set; }
            public List<string> keyPhrases { get; set; }
        }

        public class Sentiment
        {
            public List<Document2> documents { get; set; }
            public List<object> errors { get; set; }
        }

        public class Document2
        {
            public string id { get; set; }
            public float score { get; set; }
        }
    }