Пример #1
0
        private static async Task CalculateSentimentAsync(FeedbackDbContext dbContext)
        {
            // NOTE: Cognetive services accepts up to 1000 "documents" at a time.
            var feedbackBatch = dbContext.Feedbacks.Where(f => !f.SentimentScore.HasValue).Take(1000).ToList();

            if (feedbackBatch.Any())
            {
                Console.WriteLine("Found feedback to analyze...");
                var documents = feedbackBatch.Select(f => new TextDocument(f.Id, f.Content));
                var request   = new TextAnalysisRequest(documents);
                var response  = await TextAnalyzer.CalculateSentimentAsync(request);

                foreach (var sentiment in response.Documents)
                {
                    var feedback = feedbackBatch.Single(f => f.Id == sentiment.Id);
                    feedback.SentimentScore = sentiment.Score;
                }
                await dbContext.SaveChangesAsync();
                await CalculateSentimentAsync(dbContext); // Recursively process until we are done.
            }
            else
            {
                Console.WriteLine("Did not find feedback to analyze.");
            }
        }
        public static async Task <TextAnalysisResponse> CalculateSentimentAsync(TextAnalysisRequest request)
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(BaseUrl);

                // Request headers.
                client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", AccountKey);
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                // Request body must be JSON format.
                var requestJson = JsonConvert.SerializeObject(request);

                // Detect sentiment via API call.
                var uri      = "text/analytics/v2.0/sentiment";
                var response = await CallEndpointAsync(client, uri, requestJson);

                Console.WriteLine("\nDetect sentiment response:\n" + response);

                // Response body also comes back in JSON format.
                return(JsonConvert.DeserializeObject <TextAnalysisResponse>(response));
            }
        }