public async Task <SentimentBatchResult> RunSentimentAnalysisAsync(CidadaoModel cidadao)
        {
            var credentials = new ApiKeyServiceClientCredentials(key);
            var client      = new TextAnalyticsClient(credentials)
            {
                Endpoint = endpoint
            };

            // The documents to be analyzed. Add the language of the document. The ID can be any value.
            var inputDocuments = new MultiLanguageBatchInput(
                new List <MultiLanguageInput>
            {
                new MultiLanguageInput("1", cidadao.texto, "pt"),
            });

            var result = await client.SentimentBatchAsync(inputDocuments);

            // Printing sentiment results
            // Console.WriteLine("===== Sentiment Analysis =====\n");

            //foreach (var document in result.Documents)
            //{

            //    // Console.WriteLine($"Document ID: {document.Id} , Sentiment Score: {document.Score:0.00}");
            //}

            return(result);
        }
Esempio n. 2
0
        public static async Task RunAsync(string endpoint, string key)
        {
            var credentials = new ApiKeyServiceClientCredentials(key);
            var client      = new TextAnalyticsClient(credentials)
            {
                Endpoint = endpoint
            };

            // The documents to be analyzed. Add the language of the document. The ID can be any value.
            var inputDocuments = new MultiLanguageBatchInput(
                new List <MultiLanguageInput>
            {
                new MultiLanguageInput("1", "I had the best day of my life.", "en"),
                new MultiLanguageInput("2", "This was a waste of my time. The speaker put me to sleep.", "en"),
                new MultiLanguageInput("3", "No tengo dinero ni nada que dar...", "es"),
                new MultiLanguageInput("4", "L'hotel veneziano era meraviglioso. È un bellissimo pezzo di architettura.", "it"),
            });

            var result = await client.SentimentBatchAsync(inputDocuments);

            // Printing sentiment results
            Console.WriteLine("===== Sentiment Analysis =====\n");

            foreach (var document in result.Documents)
            {
                Console.WriteLine($"Document ID: {document.Id} , Sentiment Score: {document.Score:0.00}");
            }
            Console.WriteLine();
        }
Esempio n. 3
0
        private static async Task RunSentiment(TextAnalyticsClient client,
                                               MultiLanguageBatchInput docs)
        {
            var res = await client.SentimentBatchAsync(docs);

            foreach (var document in res.Documents)
            {
                Console.WriteLine($"Document ID: {document.Id}, " +
                                  $"Sentiment Score: {document.Score:0.00}");
            }
        }
Esempio n. 4
0
        public string Analyze(string input)
        {
            ITextAnalyticsClient client = new TextAnalyticsClient(new ApiKeyServiceClientCredentials(_subscriptionKey))
            {
                Endpoint = $"https://{_region}.api.cognitive.microsoft.com"
            };
            SentimentBatchResult result = client.SentimentBatchAsync(
                new MultiLanguageBatchInput(
                    SplitFiveHundredChars(input).ToList()
                    )).Result;

            return($"{result.Documents[0].Score:0.00}");
        }
        /// <summary>
        /// Adds sentiment to the given list and returns it.
        /// </summary>
        /// <param name="articles">Articles to enrich.</param>
        /// <returns>Enriched list of articles.</returns>
        async Task <List <Article> > AddSentiments(List <Article> articles)
        {
            // Ensure all required configuration information are available.
            if (ANALYTICS_SUBSCRIPTION_KEY == string.Empty || ANALYTICS_ENDPOINT == string.Empty)
            {
                //throw new MissingMemberException("Azure analystics constants empty. Please set them.");
                return(articles);
            }

            // Setup text analytics client.
            var credentials            = new ApiKeyServiceClientCredentials(ANALYTICS_SUBSCRIPTION_KEY);
            TextAnalyticsClient client = new TextAnalyticsClient(credentials)
            {
                Endpoint = ANALYTICS_ENDPOINT
            };

            // Build batch inputs based on articles.
            var batchInput = new MultiLanguageBatchInput
            {
                Documents = articles.Select(a => new MultiLanguageInput
                {
                    Id       = a.Guid,
                    Language = a.LanguageCode,
                    Text     = a.Description
                }).ToList()
            };

            // Get sentiment analytics from Azure.
            var result = await client.SentimentBatchAsync(batchInput);

            // If any error occures, return the non enriched article list.
            if (result.Errors.Count > 0)
            {
                Console.WriteLine("An error occured");
                return(articles);
            }

            // Enrich atricles with found sentiment score.
            foreach (var document in result.Documents)
            {
                articles.First(a => a.Guid == document.Id).SentimentScore = document.Score ?? -1;
            }

            // Return enriched articles.
            return(articles);
        }
        public static async Task TestTextAnalyticsApiKeyAsync(string key, string apiEndpoint)
        {
            bool isUri = !string.IsNullOrEmpty(apiEndpoint) ? Uri.IsWellFormedUriString(apiEndpoint, UriKind.Absolute) : false;

            if (!isUri)
            {
                throw new ArgumentException("Invalid URI");
            }
            else
            {
                TextAnalyticsClient client = new TextAnalyticsClient(new ApiKeyServiceClientCredentials(key))
                {
                    Endpoint = apiEndpoint
                };

                await client.SentimentBatchAsync(multiLanguageBatchInput :
                                                 new MultiLanguageBatchInput(
                                                     new List <MultiLanguageInput>()
                {
                    new MultiLanguageInput("0", "I had the best day of my life.", "en"),
                }));
            }
        }
        private async void OnAnalyzeButtonClicked(object sender, RoutedEventArgs e)
        {
            Progress.IsActive  = true;
            Overlay.Visibility = Visibility.Visible;
            Output.Items.Clear();

            try
            {
                var hashtag = Hashtag.Text;
                if (!hashtag.StartsWith("#"))
                {
                    hashtag = "#" + hashtag;
                }

                // Get up to 99 tweets
                Auth.SetUserCredentials(_consumerKey, _consumerSecret, _accessToken, _accessTokenSecret);
                var parameters = new SearchTweetsParameters(hashtag);
                //parameters.SearchType = SearchResultType.Recent;
                parameters.SearchType             = SearchResultType.Mixed;
                parameters.MaximumNumberOfResults = 99;
                IEnumerable <ITweet> tweets = null;

                await Task.Run(() =>
                {
                    tweets = Search.SearchTweets(parameters);
                });

                // Stop if no tweets were retrieved
                if (tweets.Count() == 0)
                {
                    await new MessageDialog("Hashtag not found", "Error").ShowAsync();
                    return;
                }

                // Clean the tweets, show them in the ListBox, and package them
                // for the Text Analytics API
                int id = 1;
                List <MultiLanguageInput> input = new List <MultiLanguageInput>();

                foreach (var tweet in tweets)
                {
                    var text = Regex.Replace(tweet.Text, @"http[^\s]+", "").Replace("\"", "\\\"").Replace("\n", " ");
                    input.Add(new MultiLanguageInput((id++).ToString(), text));
                    Output.Items.Add(text);
                }

                var batch = new MultiLanguageBatchInput(input);

                // Analyze the tweets for sentiment
                TextAnalyticsClient client = new TextAnalyticsClient(
                    new ApiKeyServiceClientCredentials(_key),
                    new System.Net.Http.DelegatingHandler[] { }
                    );

                client.Endpoint = _uri;
                var results = await client.SentimentBatchAsync(batch);

                Progress.IsActive  = false;
                Overlay.Visibility = Visibility.Collapsed;

                // Show the average sentiment score for all tweets
                var score = results.Documents.Select(x => x.Score).Average();
                await new MessageDialog($"Sentiment: {score:F2}").ShowAsync();
            }
            catch (Exception ex)
            {
                Progress.IsActive  = false;
                Overlay.Visibility = Visibility.Collapsed;
                await new MessageDialog(ex.Message).ShowAsync();
            }
            finally
            {
                Progress.IsActive  = false;
                Overlay.Visibility = Visibility.Collapsed;
            }
        }