Exemple #1
0
 private static string GetSentiment(string text)
 {
     try
     {
         double score = 0;
         var apiKey = "Tu api key de azure cognitive service text"";
         var document = new SentimentDocument()
         {
             Id = "OutlookSergio",
             Text = text,
             Language = "es"
         };
         var request = new SentimentRequest();
         request.Documents.Add(document);
         var client = new SentimentClient(apiKey);
         var response = client.GetSentiment(request);
         foreach (var doc in response.Documents)
         {
             score += doc.Score;
         }
         score = Math.Round((score / response.Documents.Count), 2) * 100;
         return score + "%";
     }
     catch(Exception e)
     {
         return null;
     }
 }
Exemple #2
0
        public async void GIVENAnyMessageActivity_WHENGetSentimentIsInvoked_THENScoreIsBeingReturned(
            ITextAnalyticsClient textAnalyticsClient,
            IActivityAdapter activity,
            double sentiment)
        {
            // Arrange
            var instrumentation = new SentimentClient(textAnalyticsClient);
            var response        = new HttpOperationResponse <SentimentBatchResult>
            {
                Body = new SentimentBatchResult(new[] { new SentimentBatchResultItem(null, sentiment) }),
            };

            Mock.Get(textAnalyticsClient)
            .Setup(tac => tac.SentimentWithHttpMessagesAsync(
                       It.IsAny <bool?>(),
                       It.IsAny <MultiLanguageBatchInput>(),
                       It.IsAny <Dictionary <string, List <string> > >(),
                       It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult(response));

            // Act
            var score = await instrumentation.GetSentiment(activity)
                        .ConfigureAwait(false);

            // Assert
            score.Should().Be(sentiment);
        }
        public static async Task AnalyzeSentimentAsync(string id, string text, string language)
        {
            var document = new SentimentDocument()
            {
                Id       = id,
                Text     = text,
                Language = language
            };

            var client = new SentimentClient(Constants.ApiKey)
            {
                Url = "https://westeurope.api.cognitive.microsoft.com/text/analytics/v2.0/sentiment"
            };

            var request = new SentimentRequest();

            request.Documents.Add(document);

            try
            {
                var response = await client.GetSentimentAsync(request);

                foreach (var doc in response.Documents)
                {
                    Console.WriteLine("Sentiment Score: {0}", doc.Score);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemple #4
0
        private async void Analyze_Text(object sender, RoutedEventArgs e)
        {
            this.Score = "";

            try
            {
                var language = await GetLanguage();

                var document = new SentimentDocument()
                {
                    Id = Guid.NewGuid().ToString(), Text = this.InputText, Language = language
                };

                var request = new SentimentRequest();
                request.Documents.Add(document);

                MainWindow mainWindow = Window.GetWindow(this) as MainWindow;
                var        client     = new SentimentClient(mainWindow._scenariosControl.SubscriptionKey);

                MainWindow.Log("Request: Analyzing sentiment.");
                var response = await client.GetSentimentAsync(request);

                MainWindow.Log("Response: Success. Sentiment analyzed.");

                var score = response.Documents[0].Score * 100;
                this.Score = string.Format("{0}%", score);
            }
            catch (Exception ex)
            {
                MainWindow.Log(ex.Message);
            }
        }
        public FeedbackHandler() : base($"^/{Constants.FeedbackRealm}$")
        {
            _sentimentClient = new SentimentClient(Constants.SentimentApiKey)
            {
                Url = Constants.SentimentUrl
            };

            _keyPhraseClient = new KeyPhraseClient(Constants.SentimentApiKey)
            {
                Url = Constants.KeyPhraseUrl
            };
        }
Exemple #6
0
        public void GivenSentimentClient_WhenDisposeIsInvoked_ThenOtherResourcesAreBeingDisposedAsWell(
            ITextAnalyticsClient textAnalyticsClient)
        {
            // Arrange
            var sentimentClient = new SentimentClient(textAnalyticsClient);

            // Act
            sentimentClient.Dispose();

            // Assert
            Mock.Get(textAnalyticsClient).Verify(sc => sc.Dispose(), Times.Once);
        }
Exemple #7
0
        public async void GivenEmptyMessageActivity_WhenGetSentimentIsInvoked_ThenExceptionIsBeingThrown(
            ITextAnalyticsClient textAnalyticsClient)
        {
            // Arrange
            var instrumentation = new SentimentClient(textAnalyticsClient);
            const IMessageActivity emptyMessageActivity = null;

            // Act
            // Assert
            await Assert.ThrowsAsync <ArgumentNullException>(() => instrumentation.GetSentiment(emptyMessageActivity))
            .ConfigureAwait(false);
        }
        public static float AnalyzeSentiment(string id, string text, string language)
        {
            float score    = 0;
            var   document = new SentimentDocument()
            {
                Id       = id,
                Text     = text,
                Language = language
            };

            var client = new SentimentClient(Constants.ApiKey)
            {
                Url = "https://westeurope.api.cognitive.microsoft.com/text/analytics/v2.0/sentiment"
            };
            var request = new SentimentRequest();

            request.Documents.Add(document);

            try
            {
                var response = client.GetSentiment(request);
                score = response.Documents.First().Score * 100;
            }
            catch (Exception ex)
            {
                var message      = "";
                var innerMessage = "";
                if (!String.IsNullOrEmpty(ex.Message))
                {
                    message = ex.Message;
                }

                try
                {
                    if ((ex.InnerException != null) && (!String.IsNullOrEmpty(ex.InnerException.Message)))
                    {
                        innerMessage = ex.InnerException.Message;
                    }
                }
                catch (Exception innerEx)
                {
                    if ((innerEx.InnerException != null) && (!String.IsNullOrEmpty(innerEx.InnerException.Message)))
                    {
                        innerMessage = innerEx.InnerException.Message;
                    }
                }

                Console.WriteLine(String.Format("Error in AnalyzeSentiment: {0}:{1}", message, innerMessage));
            }
            return(score);
        }
Exemple #9
0
        static void Main(string[] args)
        {
            // MS Cognitive Services API key
            var apiKeyTextAnalytics = "REPLACE_WITH_API_KEY";

            var text = @"A thing of beauty is a joy for ever:
                        Its loveliness increases; it will never
                        Pass into nothingness; but still will keep
                        A bower quiet for us, and a sleep
                        Full of sweet dreams, and health, and quiet breathing.";

            // GET text sentiment
            var sentimentDocument = new SentimentDocument()
            {
                Id       = "Sentiment",
                Text     = text,
                Language = "en"
            };

            Console.WriteLine("Analyzing {0}", sentimentDocument.Id + "..");

            var sentimentRequest = new SentimentRequest();

            sentimentRequest.Documents.Add(sentimentDocument);
            var sentimentClient   = new SentimentClient(apiKeyTextAnalytics);
            var sentimentResponse = sentimentClient.GetSentiment(sentimentRequest);

            Console.WriteLine("   Score: {0}%", (sentimentResponse.Documents[0].Score * 100) + " [0% - negative, 100% - positive]");

            // GET text keyphrases
            var keyPhraseDocument = new KeyPhraseDocument()
            {
                Id       = "KeyPhrases",
                Text     = text,
                Language = "en"
            };

            Console.WriteLine("Recognizing {0}", keyPhraseDocument.Id + "..");

            var keyPhraseRequest = new KeyPhraseRequest();

            keyPhraseRequest.Documents.Add(keyPhraseDocument);
            var keyPhraseClient   = new KeyPhraseClient(apiKeyTextAnalytics);
            var keyPhraseResponse = keyPhraseClient.GetKeyPhrases(keyPhraseRequest);

            foreach (var keyPhrase in keyPhraseResponse.Documents[0].KeyPhrases)
            {
                Console.WriteLine("   KeyPhrase: {0}", keyPhrase);
            }
        }
Exemple #10
0
        public async void GivenDisposedSentimentClient_WhenGetSentimentIsInvoked_ThenExceptionIsBeingThrown(
            ITextAnalyticsClient textAnalyticsClient,
            IMessageActivity activity)
        {
            // Arrange
            var instrumentation = new SentimentClient(textAnalyticsClient);

            instrumentation.Dispose();

            // Act
            // Assert
            await Assert.ThrowsAsync <ObjectDisposedException>(() => instrumentation.GetSentiment(activity))
            .ConfigureAwait(false);
        }
        async Task ExecuteCheckTextAnalyticsApiCommand()
        {
            if (IsBusy)
            {
                return;
            }

            IsBusy = true;

            try
            {
                LanguageClient languageClient = new LanguageClient(ApiKeys.TextAnalyticsApiKey);
                languageClient.Url = "https://westeurope.api.cognitive.microsoft.com/text/analytics/v2.0/languages";
                LanguageRequest lr = new LanguageRequest();
                lr.Documents.Add(new Document()
                {
                    Id   = Guid.NewGuid().ToString(),
                    Text = TextAnalyticsText
                });
                var lrResult = await languageClient.GetLanguagesAsync(lr);

                var language     = lrResult.Documents.First().DetectedLanguages.First().Name;
                var languageCode = lrResult.Documents.First().DetectedLanguages.First().Iso639Name;


                SentimentClient textClient = new SentimentClient(ApiKeys.TextAnalyticsApiKey);
                textClient.Url = "https://westeurope.api.cognitive.microsoft.com/text/analytics/v2.0/sentiment";

                SentimentRequest sr = new SentimentRequest();

                sr.Documents.Add(new SentimentDocument()
                {
                    Id       = Guid.NewGuid().ToString(),
                    Text     = TextAnalyticsText,
                    Language = languageCode
                });

                var result = await textClient.GetSentimentAsync(sr);

                TextAnalyticsResult = $"Language: {language}, Sentiment Score: {result.Documents.First().Score}";
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }
            finally
            {
                IsBusy = false;
            }
        }
Exemple #12
0
        public static float AnalyzeSentiment(string id, string text, string language)
        {
            float score    = 0;
            var   document = new SentimentDocument()
            {
                Id       = id,
                Text     = text,
                Language = language
            };

            var client  = new SentimentClient(Constants.API_KEY);
            var request = new SentimentRequest();

            request.Documents.Add(document);

            try
            {
                var response = client.GetSentiment(request);
                score = response.Documents.First().Score * 100;
            }
            catch (Exception ex)
            {
                var message      = "";
                var innerMessage = "";
                if (!String.IsNullOrEmpty(ex.Message))
                {
                    message = ex.Message;
                }

                try
                {
                    if ((ex.InnerException != null) && (!String.IsNullOrEmpty(ex.InnerException.Message)))
                    {
                        innerMessage = ex.InnerException.Message;
                    }
                }
                catch (Exception innerEx)
                {
                    if ((innerEx.InnerException != null) && (!String.IsNullOrEmpty(innerEx.InnerException.Message)))
                    {
                        innerMessage = innerEx.InnerException.Message;
                    }
                }

                //Console.WriteLine(String.Format("Error in AnalyzeSentiment: {0}:{1}", message, innerMessage));
            }
            return(score);
        }
        public void Analyse(string gitPath)
        {
            var repo = OpenRepository(gitPath);

            if (repo == null)
            {
                return;
            }
            System.Console.WriteLine("OK");

            var commits = repo.Commits.Where(c => !c.Message.StartsWith("Merge")).Take(20);

            if (commits.Count() == 0)
            {
                System.Console.WriteLine("-- No data --");
            }

            var request = new SentimentRequest();

            foreach (var commit in commits)
            {
                var document = new SentimentDocument()
                {
                    Id       = commit.Id.Sha,
                    Text     = commit.Message,
                    Language = "en"
                };
                request.Documents.Add(document);
            }

            var apiKey = System.Configuration.ConfigurationManager.AppSettings["ApiKey"];
            var client = new SentimentClient(apiKey);

            var response = client.GetSentiment(request);
            var scores   = new List <float>();

            foreach (var doc in response.Documents)
            {
                scores.Add(doc.Score);
                System.Console.WriteLine($"Id: {doc.Id} | Score: {(doc.Score * 100)}%");
                if (doc.Score < 0.3 || 0.8 < doc.Score)
                {
                    System.Console.WriteLine($"\t --> {request.Documents.FirstOrDefault(d => d.Id == doc.Id).Text}");
                }
            }
            System.Console.WriteLine($"Average score: {(scores.Average() * 100)}");
        }
        public TextAnalyticsHandler() : base($"^/{Constants.RealmName}$")
        {
            sentimentClient = new SentimentClient(Constants.TextAnalyticsApiKey)
            {
                Url = Constants.SentimentUrl
            };

            keyPhraseClient = new KeyPhraseClient(Constants.TextAnalyticsApiKey)
            {
                Url = Constants.KeyPhraseUrl
            };

            newTaskSubject      = new Subject <TaskItem>();
            modifiedTaskSubject = new Subject <TaskItem>();

            newTaskSubject.Select(async t =>
            {
                t.Score = await GetScore(t);
                t.Tags  = await GetTags(t);
                return(t);
            })
            .Concat()
            .Subscribe(
                UpdateTask,
                ex =>
            {
                Console.WriteLine(ex.Message);
            });

            modifiedTaskSubject
            //.Where(t => t.Text.Length > 10)
            .GroupBy(t => t.Id)
            .SelectMany(g => g.Throttle(TimeSpan.FromSeconds(3)))
            .Select(async t =>
            {
                t.Score = await GetScore(t);
                t.Tags  = await GetTags(t);
                return(t);
            })
            .Concat()
            .Subscribe(
                UpdateTask,
                ex =>
            {
                Console.WriteLine(ex.Message);
            });
        }
Exemple #15
0
        private static int count = 1; // count to keep the ID

        // This methods perform the text analysis and return the score
        public static async Task <string> TextAnalysis(string message)
        {
            client = new SentimentClient(ConfigurationManager.AppSettings["TextAnalyticsApiKey"]); // my API Key
            var request = new SentimentRequest();

            count++; // increment
            var text = new SentimentDocument()
            {
                Id       = count.ToString(),
                Text     = message,
                Language = "en"
            };

            request.Documents.Add(text);
            var response = ((await client.GetSentimentAsync(request)).Documents.FirstOrDefault()).Score; // retrieve the score

            return(string.Format("{0:N2}", response));                                                   // return the result in string (2 Decimal Place)
        }
Exemple #16
0
        private static async Task RunSentimentAnalysis()
        {
            Console.ForegroundColor = ConsoleColor.Gray;
            Console.WriteLine("Begining sentiment analysis ({0})", DateTime.Now.ToString());

            var client = new SentimentClient(textAnalyticsApiKey);

            foreach (var conversation in conversations)
            {
                foreach (var message in conversation.Messages)
                {
                    try
                    {
                        var document = new SentimentDocument()
                        {
                            Id       = message.Id.ToString(),
                            Text     = message.Text,
                            Language = message.Metadata.LanguageName
                        };

                        var request = new SentimentRequest();
                        request.Documents.Add(document);

                        var response = await client.GetSentimentAsync(request);

                        message.Metadata.SentimentScore = response.Documents[0].Score;

                        Console.Write("Conversation {0} | Message {1} | Sentiment Score {2}", conversation.Id, message.Id, message.Metadata.SentimentScore);
                    }
                    catch (Exception ex)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine();
                        Console.WriteLine("Exception encountered ({0})", DateTime.Now.ToString());
                        Console.WriteLine("Conversation {0} | Message {1}", conversation.Id, message.Id);
                        Console.WriteLine(ex.Message);
                    }
                }
            }

            Console.WriteLine("Sentiment analysis complete ({0})", DateTime.Now.ToString());
            Console.WriteLine();
        }
        public void GetSentiment_Positive()
        {
            var text = "I had a wonderful experience! The rooms were wonderful and the staff were helpful.";
            var doc  = new SentimentDocument()
            {
                Id = "TEST001", Text = text, Language = "en"
            };

            var request = new SentimentRequest();

            request.Documents.Add(doc);

            var client   = new SentimentClient(this.apiKey);
            var response = client.GetSentiment(request);

            var score = response.Documents[0].Score;

            Assert.IsTrue(score > 0.5);
        }
        public void GetSentiment_Negative()
        {
            var text = "I had a terrible time at the hotel. The staff were rude and the food was awful.";

            var doc = new SentimentDocument()
            {
                Id = "TEST001", Text = text, Language = "en"
            };

            var request = new SentimentRequest();

            request.Documents.Add(doc);

            var client   = new SentimentClient(this.apiKey);
            var response = client.GetSentiment(request);

            var score = response.Documents[0].Score;

            Assert.IsTrue(score < 0.5);
        }
        private async void Get_Sentiment(string text, string lastNTest)
        {
            try
            {
                var document = new SentimentDocument()
                {
                    Id = Guid.NewGuid().ToString(), Text = text, Language = "en"
                };
                var lastNDocument = new SentimentDocument()
                {
                    Id = Guid.NewGuid().ToString(), Text = lastNTest, Language = "en"
                };

                var request = new SentimentRequest();
                request.Documents.Add(document);
                request.Documents.Add(lastNDocument);

                MainWindow mainWindow = Window.GetWindow(this) as MainWindow;
                var        client     = new SentimentClient(mainWindow._scenariosControl.SubscriptionKey);

                var response = await client.GetSentimentAsync(request);

                Log("Response: Success. Sentiment analyzed.");

                var score      = response.Documents[0].Score * 100;
                var lastNScore = response.Documents[1].Score * 100;
                ((MainWindow)Application.Current.MainWindow)._scenariosControl.LogSentiment(string.Format("Last sentence: {0}%\nLast {1} sentences: {2}%", score, SENTENCE_LIMIT, lastNScore));

                if (sendToPBICheckbox.IsChecked == true)
                {
                    //post(sentimentUrl, "[" + json + "]");
                    string json        = JsonConvert.SerializeObject(new { dt = (DateTime.UtcNow.ToString("s") + "Z"), sentence = text, sentiment_Nlast = score, average_sentiment = lastNScore });
                    Thread myNewThread = new Thread(() => post(sentimentUrl, "[" + json + "]"));
                    myNewThread.Start();
                }
            }
            catch (Exception ex)
            {
                MainWindow.Log(ex.Message);
            }
        }
Exemple #20
0
        /// <summary>
        /// Processes the model asynchronous.
        /// </summary>
        /// <param name="activityContext">The activity context.</param>
        /// <returns>
        /// The output model.
        /// </returns>
        protected override async Task <CustomerReviewSentencesSentimentModel> ProcessModelAsync(
            ActivityContext activityContext)
        {
            Logger.Info(
                $"Analyzing sentiment: {activityContext.InputModel.CorrelationId}");

            try
            {
                var inputModel = activityContext.GetInputModel <CustomerReviewSentencesModel>();

                var sentences = inputModel.Sentences as IList <string> ?? inputModel.Sentences.ToList();

                var textDictionary =
                    sentences.Select((s, idx) => new KeyValuePair <int, string>(idx, s))
                    .ToDictionary(kvp => kvp.Key, kvp => kvp.Value);

                var sentimentResult = await SentimentClient.BatchAnalyzeAsync(textDictionary);

                var sentenceSentimentResults =
                    sentimentResult.Select(
                        kvp =>
                        new SentenceSentimentResult(
                            kvp.Key,
                            textDictionary[kvp.Key],
                            kvp.Value.SentimentType.ToString("G"),
                            kvp.Value.Score));

                return(new CustomerReviewSentencesSentimentModel(
                           inputModel.CustomerReviewModel,
                           sentenceSentimentResults));
            }
            catch (Exception ex)
            {
                Logger.Error(
                    $"Analyze sentiment failed, exception detail: {ex.GetDetailMessage()}, context: {activityContext.ToJsonIndented()}",
                    ex);

                throw;
            }
        }
Exemple #21
0
        private static void GetSentiment()
        {
            var client  = new SentimentClient(apiKey);
            var request = new SentimentRequest();

            var document = new SentimentDocument()
            {
                Id       = "YOUR-UNIQUE-ID",
                Text     = "YOUR-TEXT",
                Language = "en"
            };

            request.Documents.Add(document);

            var response = client.GetSentiment(request);

            foreach (var doc in response.Documents)
            {
                Console.WriteLine("   Document Id: {0}", doc.Id);
                Console.WriteLine("   Score: {0}%", (doc.Score * 100));
            }
        }
Exemple #22
0
        static void Main(string[] args)
        {
            if (args.Length != 2)
            {
                Console.WriteLine("Usage: ");
                Console.WriteLine("  " + System.AppDomain.CurrentDomain.FriendlyName + " <FILENAME> <APIKEY>");
                Environment.Exit(1);
            }
            string bookfile = args[0];
            string apiKey   = args[1];

            Console.WriteLine("Analyzing book: " + bookfile);
            EpubBook epubBook = EpubReader.ReadBook(bookfile);

            string title  = epubBook.Title;
            string author = epubBook.Author;

            Console.WriteLine("Book title: " + title);
            Console.WriteLine();

            double bookScore   = 0.0;
            int    numChapters = 0;

            foreach (EpubChapter chapter in epubBook.Chapters)
            {
                var request = new SentimentRequest();

                string chapterTitle = chapter.Title;

                AppendChapter(ref request, chapter);

                foreach (EpubChapter subChapter in chapter.SubChapters)
                {
                    AppendChapter(ref request, subChapter);
                }

                var client   = new SentimentClient(apiKey);
                var response = client.GetSentiment(request);

                foreach (Microsoft.ProjectOxford.Text.Core.DocumentError e in response.Errors)
                {
                    Console.WriteLine("Errors: " + e.Message);
                }

                double score     = 0.0;
                int    numScores = 0;

                foreach (SentimentDocumentResult r in  response.Documents)
                {
                    score += r.Score;
                    numScores++;
                }

                score /= numScores;

                Console.WriteLine(numChapters + ": " + chapterTitle + ", score: " + score);

                bookScore += score;
                numChapters++;
            }

            bookScore /= numChapters;

            Console.WriteLine();
            Console.WriteLine("Average book sentiment: " + bookScore);
        }