Esempio n. 1
0
        public string AnalyseText(string text)
        {
            ApiKeyServiceCredentials credentials = new ApiKeyServiceCredentials(ApiKey);
            TextAnalyticsClient      client      = new TextAnalyticsClient(credentials)
            {
                Endpoint = ApiEndpoint
            };

            var result = client.Sentiment(text, "en");

            string convertedResult;

            // This will be changed when the new Text Analytics Client Library v3 comes out from pre-release
            if (result.Score >= 0.60)
            {
                convertedResult = "Positive :-)";
            }
            else if (result.Score >= 0.45)
            {
                convertedResult = "Neutral :-|";
            }
            else
            {
                convertedResult = "Negative :-(";
            }

            return(convertedResult);
        }
Esempio n. 2
0
        public void AnalyseText(string text)
        {
            if (string.IsNullOrWhiteSpace(text))
            {
                return;
            }

            SentimentResult sentiment = textAnalyticsClient.Sentiment(text);
            KeyPhraseResult keywords  = textAnalyticsClient.KeyPhrases(text);

            foreach (string keyword in keywords.KeyPhrases.Select(x => x.ToLower().Trim()))
            {
                if (!keywordCounts.ContainsKey(keyword))
                {
                    keywordCounts.Add(keyword, 1);
                }
                else
                {
                    keywordCounts[keyword]++;
                }
            }

            string sentimentWord  = sentiment.ToDescription();
            string commonKeywords = string.Join(", ",
                                                keywordCounts.OrderByDescending(x => x.Value)
                                                .Take(4)
                                                .Select(x => $"{x.Key} [{x.Value}]"));

            Console.WriteLine($"Sentiment is {sentimentWord} [{sentiment.Score}]");
            Console.WriteLine($" Common keywords are: {commonKeywords}");
            Console.WriteLine();
        }
        public bool GetSentiment(string subscriptionKey, string endpoint, string tweet_body, ILogger log)
        {
            try
            {
                if (null == subscriptionKey)
                {
                    throw new Exception("Please set/export the environment variable: " + key_var);
                }
                if (null == endpoint)
                {
                    throw new Exception("Please set/export the environment variable: " + endpoint_var);
                }

                var credentials            = new ApiKeyServiceClientCredentials(subscriptionKey);
                TextAnalyticsClient client = new TextAnalyticsClient(credentials)
                {
                    Endpoint = endpoint
                };

                // change body to get rid of unicode shit
                var s = Regex.Replace(tweet_body, @"[^\u0020-\u007E]", " ");
                log.LogInformation(s);
                var result = client.Sentiment(s, "en");
                if (result.Score >= .5)
                {
                    return(true);
                }
                return(false);
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Esempio n. 4
0
        private static void ProcessSentiment(string documentid, string text)
        {
            TextAnalyticsClient client = AuthenticateTextAnalytics(_azureRegion, _textAnalyticsKey);

            SentimentResult results = client.Sentiment(text, "en");

            Console.WriteLine("Document ID: {0} , Sentiment Score: {1:0.00}", documentid, results.Score.ToString());
        }
        public SentimentResult ProcessSentiment(string documentid, string text)
        {
            TextAnalyticsClient client = AuthenticateTextAnalytics(_azureRegion, _textAnalyticsKey);

            SentimentResult results = client.Sentiment(text, "en");

            return(results);
        }
        static void Main(string[] args)
        {
            string endpoint =; // insert your endpoint
            string key      =; // insert your key

            var credentials = new ApiKeyServiceClientCredentials(key);
            var client      = new TextAnalyticsClient(credentials)
            {
                Endpoint = endpoint
            };

            var result = client.Sentiment("I had the best day of my life.", "en");

            Console.WriteLine($"Sentiment Score: {result.Score:0.00}");

            result = client.Sentiment("I did not like that movie", "en");
            Console.WriteLine($"Sentiment Score: {result.Score:0.00}");
        }
Esempio n. 7
0
        static void GetChanges(ClientContext SPClientContext, string ListId, TraceWriter log)
        {
            // Get the List
            Web  spWeb       = SPClientContext.Site.RootWeb;
            List changedList = spWeb.Lists.GetById(new Guid(ListId));

            SPClientContext.Load(changedList);
            SPClientContext.ExecuteQuery();

            // Create the ChangeToken and Change Query
            ChangeToken lastChangeToken = new ChangeToken();

            lastChangeToken.StringValue = string.Format("1;3;{0};{1};-1", ListId, DateTime.Now.AddMinutes(-1).ToUniversalTime().Ticks.ToString());
            ChangeToken newChangeToken = new ChangeToken();

            newChangeToken.StringValue = string.Format("1;3;{0};{1};-1", ListId, DateTime.Now.ToUniversalTime().Ticks.ToString());
            ChangeQuery myChangeQuery = new ChangeQuery(false, false);

            myChangeQuery.Item             = true; // Get only Item changes
            myChangeQuery.Add              = true; // Get only the new Items
            myChangeQuery.ChangeTokenStart = lastChangeToken;
            myChangeQuery.ChangeTokenEnd   = newChangeToken;

            // Get all Changes
            var allChanges = changedList.GetChanges(myChangeQuery);

            SPClientContext.Load(allChanges);
            SPClientContext.ExecuteQuery();

            foreach (Change oneChange in allChanges)
            {
                if (oneChange is ChangeItem)
                {
                    // Get what is changed
                    ListItem changedListItem = changedList.GetItemById((oneChange as ChangeItem).ItemId);
                    SPClientContext.Load(changedListItem);
                    SPClientContext.ExecuteQuery();

                    // Create a Text Analytics client
                    ApiKeyServiceClientCredentials myCredentials = new ApiKeyServiceClientCredentials(serviceKey);
                    TextAnalyticsClient            myClient      = new TextAnalyticsClient(myCredentials)
                    {
                        Endpoint = serviceEndpoint
                    };

                    // Call the service
                    SentimentResult myScore = myClient.Sentiment(changedListItem["Comments"].ToString(), "en");

                    // Insert the values back in the Item
                    changedListItem["Sentiment"] = myScore.Score.ToString();
                    changedListItem.Update();
                    SPClientContext.ExecuteQuery();
                }
            }
        }
Esempio n. 8
0
        public static double SelectComments(string inputComment)
        {
            ApiKeyServiceClientCredentials credentials = new ApiKeyServiceClientCredentials(subscriptionKey);
            TextAnalyticsClient            client      = new TextAnalyticsClient(credentials)
            {
                Endpoint = endpoint
            };

            var result = client.Sentiment(inputComment, "en");

            return((double)result.Score);
        }
Esempio n. 9
0
        public IActionResult Index()
        {
            string endpoint = "https://detectsentimentaris.cognitiveservices.azure.com/"; // insert your endpoint
            string key      = "aba934b96e4c4f058d93add4a1182a88";                         // insert your keyy

            var credentials = new ApiKeyServiceClientCredentials(key);
            var client      = new TextAnalyticsClient(credentials)
            {
                Endpoint = endpoint
            };

            var result = client.Sentiment("I had the best day of my life.", "en");

            ViewBag.Score = result.Score;

            result = client.Sentiment("Man, this place really sucks so much", "en");

            ViewBag.Score2 = result.Score;

            return(View());
        }
        public static double SentimentPredict(TranslatedLetter letter)
        {
            ApiKeyServiceClientCredentials credentials = new ApiKeyServiceClientCredentials(_subscriptionKey);
            TextAnalyticsClient            client      = new TextAnalyticsClient(credentials)
            {
                Endpoint = _endPoint
            };

            var result = client.Sentiment(letter.TranslatedMessage, letter.ToLanguage);

            Console.WriteLine($"Sentiment Score: {result.Score:0.00}");

            return(result.Score ?? 0);
        }
Esempio n. 11
0
        public static async Task RecognizeSpeechAsync()
        {
            var speechKey      = ConfigurationManager.AppSettings["Speech:Key"];
            var speechLocation = ConfigurationManager.AppSettings["Speech:Location"];
            var config         = SpeechConfig.FromSubscription(speechKey, speechLocation);
            var key            = ConfigurationManager.AppSettings["TextAnalytics:Key"];
            var endpoint       = ConfigurationManager.AppSettings["TextAnalytics:Endpoint"];

            Initialize(key, endpoint);

            using (var recognizer = new SpeechRecognizer(config))
            {
                Console.WriteLine("Speak something which I can recognize...");

                while (true)
                {
                    var result = await recognizer.RecognizeOnceAsync();

                    if (result.Reason == ResultReason.RecognizedSpeech)
                    {
                        var sentimentResult = client.Sentiment(result.Text, "en");
                        Console.WriteLine(result.Text);
                        if (sentimentResult.Score >= 0.5)
                        {
                            Console.WriteLine("I think you are in a happy mood");
                        }
                        else
                        {
                            Console.WriteLine("I am sorry, I think you are in a sad mood");
                        }
                    }
                    //else if (result.Reason == ResultReason.NoMatch)
                    //{
                    //    Console.WriteLine($"NOMATCH: Speech could not be recognized.");
                    //}
                    else if (result.Reason == ResultReason.Canceled)
                    {
                        var cancellation = CancellationDetails.FromResult(result);
                        Console.WriteLine($"CANCELED: Reason={cancellation.Reason}");

                        if (cancellation.Reason == CancellationReason.Error)
                        {
                            Console.WriteLine($"CANCELED: ErrorCode={cancellation.ErrorCode}");
                            Console.WriteLine($"CANCELED: ErrorDetails={cancellation.ErrorDetails}");
                            Console.WriteLine($"CANCELED: Did you update the subscription info?");
                        }
                    }
                }
            }
        }
Esempio n. 12
0
 public static void Run(
     [QueueTrigger("event-queue")] EventData message,
     [CosmosDB("Data", "Events", Id = "{id}", PartitionKey = "{location}", ConnectionStringSetting = "CosmosDBConnection")] EventData eventData, ILogger log)
 {
     if (eventData != null)
     {
         var sentimentResult = TextAnalyticsClient.Sentiment(eventData.Description);
         eventData.Sentiment = sentimentResult.Score;
     }
     else
     {
         throw new ArgumentNullException($"Could not find Event with id: {message.Id} and partitionKey: {message.Location}");
     }
 }
Esempio n. 13
0
        public async Task Analyze(string endpoint, string key, string sentence)
        {
            var credentials = new ApiKeyServiceClientCredentials(key);
            var client      = new TextAnalyticsClient(credentials)
            {
                Endpoint = endpoint
            };

            var result = client.Sentiment(sentence, "en");

            array.Add(new BsonDocument {
                { "sentence", sentence }, { "score", result.Score }
            });
            total += (double)result.Score;
            Console.WriteLine($"Sentiment Score: {result.Score:0.00}");
        }
Esempio n. 14
0
        public static async Task <double> SentimentPredict(string text)
        {
            var subscriptionKey = await _kv.GetSecretAsync(_kvEndpoint, "TEXT-ANALYTICS-SUBSCRIPTION-KEY");

            var textAnalyticsClientEndpoint = await _kv.GetSecretAsync(_kvEndpoint, "TEXT-ANALYTICS-CLIENT-ENDPOINT");

            ApiKeyServiceClientCredentials credentials = new ApiKeyServiceClientCredentials(subscriptionKey.Value);
            TextAnalyticsClient            client      = new TextAnalyticsClient(credentials)
            {
                Endpoint = textAnalyticsClientEndpoint.Value
            };

            var result = client.Sentiment(text);

            Console.WriteLine($"Sentiment Score: {result.Score:0.00}");

            return(result.Score ?? 0);
        }
        public string PerformSentimentAnalysis(TextTranslationResult input)
        {
            ApiKeyServiceClientCredentials credentials = new ApiKeyServiceClientCredentials(_subscriptionKey);
            TextAnalyticsClient            client      = new TextAnalyticsClient(credentials)
            {
                Endpoint = _textAnalysisEndpoint
            };

            var result = client.Sentiment(input.text, "en");

            if (result.Score >= 0.5)
            {
                return("Nice");
            }
            else
            {
                return("Naughty");
            }
        }
Esempio n. 16
0
        public double GetSentimentScore(string text)
        {
            int retryCount = 0;

            while (retryCount < 3)
            {
                try
                {
                    var sentimentResult = client.Sentiment(text);
                    return(sentimentResult.Score ?? 0.5);
                }
                catch (TaskCanceledException)
                {
                    retryCount++;
                    Console.WriteLine($"TaskCanceledException, retry #{retryCount}");
                }
            }

            Console.Error.WriteLine("Retry limit reached, returning neutral score");
            return(0.5);
        }
Esempio n. 17
0
        private string ReadFileSentiment()
        {
            string analysis = "";

            try
            {   // Open the text file using a stream reader.
                using (StreamReader sr = new StreamReader(_filePath))
                {
                    // Read the stream to a string, and write the string to the console.
                    String line      = sr.ReadToEnd();
                    var    sentiment = _client.Sentiment(line);
                    analysis = JsonConvert.SerializeObject(sentiment);
                }
            }
            catch (IOException e)
            {
                Console.WriteLine("The file could not be read:");
                Console.WriteLine(e.Message);
            }
            return(analysis);
        }
Esempio n. 18
0
        static void Main(string[] args)
        {
            Initialize();

            Console.WriteLine("Type your statement:");
            var statement           = Console.ReadLine();
            var sentimentResult     = client.Sentiment(statement, "en");
            var sentimentResultText = JsonConvert.SerializeObject(sentimentResult, Formatting.Indented);

            Console.WriteLine(sentimentResultText);

            var langResult     = client.DetectLanguage(statement, "US");
            var langResultText = JsonConvert.SerializeObject(langResult, Formatting.Indented);

            Console.WriteLine(langResultText);

            var entitiesResult     = client.Entities(statement);
            var entitiesResultText = JsonConvert.SerializeObject(entitiesResult, Formatting.Indented);

            Console.WriteLine(entitiesResultText);

            Console.ReadLine();
        }
Esempio n. 19
0
 static void Main(string[] args)
 {
     if (!string.IsNullOrEmpty(subscriptionKey) && !string.IsNullOrEmpty(endpoint))
     {
         string textToAnalyze = "今年最強クラスの台風が週末3連休を直撃か...影響とその対策は?";
         ApiKeyServiceClientCredentials credentials = new ApiKeyServiceClientCredentials(subscriptionKey);
         TextAnalyticsClient            client      = new TextAnalyticsClient(credentials)
         {
             Endpoint = endpoint
         };
         OutputEncoding = System.Text.Encoding.UTF8;
         LanguageResult languageResult = client.DetectLanguage(textToAnalyze);
         Console.WriteLine($"Language: {languageResult.DetectedLanguages[0].Name}");
         SentimentResult sentimentResult = client.Sentiment(textToAnalyze, languageResult.DetectedLanguages[0].Iso6391Name);
         Console.WriteLine($"Sentiment Score: {sentimentResult.Score:0.00}");
         Write("Press any key to exit.");
         ReadKey();
     }
     else
     {
         throw new Exception("You must set both TEXT_ANALYTICS_SUBSCRIPTION_KEY and TEXT_ANALYTICS_ENDPOINT:: as environment variables.");
     }
 }
 private static double GetSentiment(TextAnalyticsClient client, string text)
 {
     return((double)client.Sentiment(text).Score);
 }
Esempio n. 21
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            string  requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            Request request     = JsonConvert.DeserializeObject <Request>(requestBody);

            if (request == null || String.IsNullOrEmpty(request.message))
            {
                return(new NoContentResult());
            }

            var credentials         = new Common.ApiKeyServiceClientCredentials(ApiKey);
            var textAnalyticsClient = new TextAnalyticsClient(credentials)
            {
                Endpoint = Endpoint
            };

            var response = new Response();
            var result   = textAnalyticsClient.DetectLanguage(request.message);

            if (result == null)
            {
                return(new BadRequestResult());
            }

            var score = textAnalyticsClient.Sentiment(request.message, result.DetectedLanguages[0].Iso6391Name).Score;

            if (result.DetectedLanguages[0].Iso6391Name != "pt")
            {
                response.Message        = "Somente é permitido textos em português!";
                response.Erro           = true;
                response.RequestMessage = request.message;

                return(new OkObjectResult(response));
            }

            var moderatorCredentials = new ApiKeyModeratorServiceClienteCredentials(CMSubscriptionKey);

            var moderatorClient = new ContentModeratorClient(moderatorCredentials)
            {
                Endpoint = AzureBaseURL
            };

            string text = request.message;

            text.Replace(System.Environment.NewLine, " ");
            byte[]       byteArray = System.Text.Encoding.UTF8.GetBytes(request.message);
            MemoryStream stream    = new MemoryStream(byteArray);

            // Create a Content Moderator client and evaluate the text.
            using (var client = moderatorClient)
            {
                var screenResult = client.TextModeration.ScreenText("text/plain", stream, "eng", true, true, null, true);

                if (screenResult.Classification.ReviewRecommended.HasValue && screenResult.Classification.ReviewRecommended.Value)
                {
                    response.Erro           = true;
                    response.Message        = "Não utilize palavrões!";
                    response.RequestMessage = request.message;
                    response.Score          = score.HasValue ? score.Value : double.NaN;

                    return(new OkObjectResult(response));
                }
            }

            response.Erro           = false;
            response.Message        = "Executado com sucesso.";
            response.Score          = score.HasValue ? score.Value : double.NaN;
            response.RequestMessage = request.message;

            return(new OkObjectResult(response));
        }