public async Task SentimentPercentage(string input)
        {
            var document = new SentimentDocument()
            {
                Id       = "1",
                Text     = input,
                Language = "en"
            };

            var request = new SentimentRequest();

            request.Documents.Add(document);

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

            var response = await client.GetSentimentAsync(request);

            float sum = 0, average = 0;

            foreach (var doc in response.Documents)
            {
                sum += (doc.Score * 100);
            }
            average = sum / response.Documents.Count;

            WriteNewLine("\n\nSentiment analysis value is {0}", average.ToString());
        }
Ejemplo n.º 2
0
        static void Main(string[] args)
        {
            var apiKey = "YOUR-TEXT-ANALYTICS-API-SUBSCRIPTION-KEY";

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

            var request = new SentimentRequest();

            request.Documents.Add(document);

            var client = new SentimentClient(apiKey);

            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));
            }

            Console.WriteLine("   Press any key to exit...");
            Console.ReadLine();
        }
Ejemplo n.º 3
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);
            }
        }
Ejemplo n.º 4
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;
     }
 }
        public async Task <float> GetSentimentAnalysisAsync(string text)
        {
            var client = new SentimentClient(this.Settings.Text.Key1)
            {
                Url = this.Settings.Text.EndPoint
            };

            var document = new SentimentDocument
            {
                Id       = Guid.NewGuid().ToString(),
                Text     = text,
                Language = "en"
            };

            var request = new SentimentRequest
            {
                Documents = new List <IDocument> {
                    document
                }
            };

            var response = await client.GetSentimentAsync(request);

            //  Only one document was sent, therefore only one result should be returned.
            var result = response.Documents.FirstOrDefault();

            if (result == null)
            {
                throw new ApplicationException("Text Analysis Failed.");
            }

            return(result.Score);
        }
Ejemplo n.º 6
0
        public async Task <float> MakeRequest(string text)
        {
            var language = await GetLanguage(text);

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

            var request = new SentimentRequest();

            request.Documents.Add(document);

            var client = new SentimentClient(_subKey)
            {
                Url = ConfigurationManager.AppSettings["TextSentimentServiceUrl"] + "/sentiment"
            };

            var response = await client.GetSentimentAsync(request);

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

            return(score);
        }
Ejemplo n.º 7
0
        private async Task MessageReceivedAsync(IDialogContext context, IAwaitable <object> result)
        {
            var activity = await result as Activity;

            var document = new SentimentDocument()
            {
                Id       = "23",
                Text     = activity.Text,
                Language = "en"
            };

            var request = new SentimentRequest();

            request.Documents.Add(document);

            var response = await _cognitiveClient.GetSentimentAsync(request);

            var retrivedDocument = response.Documents.FirstOrDefault();

            var sentimentScore = retrivedDocument.Score;

            // calculate something for us to return
            int length = (activity.Text ?? string.Empty).Length;

            // return our reply to the user
            await context.PostAsync($"You sent {activity.Text} which was {length} characters");

            context.Wait(MessageReceivedAsync);
        }
        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;
            }
        }
        public void Validate_InvalidLanguage()
        {
            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 = "ja"
            };
            var request = new SentimentRequest();

            request.Documents.Add(doc);
            request.Validate();
        }
        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);
        }
Ejemplo n.º 11
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);
            }
        }
Ejemplo n.º 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);
        }
Ejemplo n.º 13
0
        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)}");
        }
Ejemplo n.º 14
0
        public static async Task <float?> GetSentiment(string text)
        {
            var sentimentDocument = new SentimentDocument {
                Id = "1", Text = text
            };
            var sentimentRequest = new SentimentRequest {
                Documents = new List <IDocument> {
                    { sentimentDocument }
                }
            };

            var sentimentResults = await SentimentClient.GetSentimentAsync(sentimentRequest);

            var documentResult = sentimentResults.Documents.FirstOrDefault();

            return(documentResult?.Score);
        }
Ejemplo n.º 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)
        }
        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);
        }
Ejemplo n.º 17
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_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);
            }
        }
Ejemplo n.º 20
0
        static void AppendChapter(ref SentimentRequest request, EpubChapter chapter)
        {
            HtmlDocument htmlDocument = new HtmlDocument();

            htmlDocument.LoadHtml(chapter.HtmlContent);

            StringBuilder sb = new StringBuilder();

            foreach (HtmlNode node in htmlDocument.DocumentNode.SelectNodes("//text()"))
            {
                sb.AppendLine(node.InnerText.Trim());
            }

            string chapterText = sb.ToString();

            int maxCharacters = 3 * 1024; //Max characters that we will send to sentiment API
            int chunks        = (int)Math.Ceiling((double)chapterText.Length / (double)maxCharacters);
            int charsPerChunk = (int)Math.Ceiling((double)chapterText.Length / (double)chunks);

            int offset = 0;

            for (int i = 0; i < chunks; ++i)
            {
                if (offset + charsPerChunk > chapterText.Length)
                {
                    charsPerChunk = chapterText.Length - offset;
                }

                var    testText = chapterText.Substring(offset, charsPerChunk);
                string chunkID  = "CHUNKDOCUMENT" + i;
                var    doc      = new SentimentDocument()
                {
                    Id = chunkID, Text = testText, Language = "en"
                };

                request.Documents.Add(doc);

                offset += charsPerChunk;
            }
        }
Ejemplo n.º 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));
            }
        }
Ejemplo n.º 22
0
        public async Task MessageReceivedAsync(IDialogContext context, IAwaitable <IMessageActivity> argument)
        {
            var message  = await argument;
            var document = new SentimentDocument()
            {
                Id       = "123",
                Text     = message.Text,
                Language = "en"
            };
            var request = new SentimentRequest();

            request.Documents.Add(document);

            var response = await _cognitiveClient.GetSentimentAsync(request);

            var retrievedDocument = response.Documents.FirstOrDefault();
            var sentimentScore    = retrievedDocument.Score;

            await context.PostAsync(message.From.Name + " sentiment for your sentence is: " + sentimentScore + "%");

            context.Wait(MessageReceivedAsync);
        }