public static void Run( [ServiceBusTrigger("newreview", "sentiment", Connection = "topicConnectionString")] string topicMessage, ILogger log, [Blob("reviewsentiment", FileAccess.Read, Connection = "storageConnectionString")] CloudBlobContainer blobContainer ) { DecoratedReviewerMessage decoratedMessage = JsonConvert.DeserializeObject <DecoratedReviewerMessage>(topicMessage); CloudBlockBlob blob = blobContainer.GetBlockBlobReference($"{decoratedMessage.MessageProperties.RequestCorrelationId}.json"); ITextAnalyticsClient client = new TextAnalyticsClient(new ApiKeyServiceClientCredentials()) { Endpoint = Environment.GetEnvironmentVariable("textAnalyticsEndpoint") }; SentimentBatchResult sentimentResult = client.SentimentAsync(false, new MultiLanguageBatchInput( new List <MultiLanguageInput>() { new MultiLanguageInput("en", "0", decoratedMessage.verbatim) } ) ).Result; try { blob.UploadTextAsync(JsonConvert.SerializeObject(sentimentResult.Documents[0].Score)); log.LogInformation($"[Request Correlation ID: {decoratedMessage.MessageProperties.RequestCorrelationId}] :: Sentiment score submitted :: Score of {sentimentResult.Documents[0].Score:0.000}"); } catch (Exception ex) { log.LogInformation($"[Request Correlation ID: {decoratedMessage.MessageProperties.RequestCorrelationId}] :: Incomplete Sentiment Score Analysis :: {ex.Message}"); } }
private async Task <double?> MakeAnalysisRequest(string text) { LanguageBatchResult result = await client.DetectLanguageAsync( new BatchInput( new List <Input>() { new Input("1", text) })); var detectedLanguage = result.Documents.First().DetectedLanguages.First(); var englishProbability = detectedLanguage.Name == "English" ? detectedLanguage.Score : 0; SentimentBatchResult sentimentResult = await client.SentimentAsync( new MultiLanguageBatchInput(new List <MultiLanguageInput>() { new MultiLanguageInput(detectedLanguage.Iso6391Name, "1", text) })); double?sentiment = 0; if (sentimentResult.Documents.Any()) { sentiment = sentimentResult.Documents.First().Score; } return((englishProbability + sentiment) / 2); }
public static double GetSentiment(string msg) { // Create a client. ITextAnalyticsAPI client = new TextAnalyticsAPI(); client.AzureRegion = AzureRegions.Westcentralus; client.SubscriptionKey = "d828157edb4e4ceaa79109372f3d18c4"; Console.OutputEncoding = System.Text.Encoding.UTF8; SentimentBatchResult result3 = client.Sentiment( new MultiLanguageBatchInput( new List <MultiLanguageInput>() { new MultiLanguageInput("en", "0", msg) })); // Printing sentiment results foreach (var document in result3.Documents) { Console.WriteLine("Document ID: {0} , Sentiment Score: {1:0.00}", document.Id, document.Score); } double res = 0d; var item = result3.Documents.FirstOrDefault(); if (item != null) { res = item.Score.GetValueOrDefault(); } return(res); }
/// <summary> /// This method gets the list of inputs and sends them off to the API /// to get a list of sentiment results returned. /// </summary> /// <param name="Inputs"></param> public void Sentiment(List <MultiLanguageInput> Inputs) { if (Inputs == null) { return; } List <List <MultiLanguageInput> > Lists = SplitIntoChunks(Inputs, 1000); try { for (int i = 0; i < Lists.Count; i++) { SentimentBatchResult result = client.SentimentAsync(new MultiLanguageBatchInput(Lists[i])).Result; // Printing sentiment results foreach (var document in result.Documents) { //{1:0.00} gets 0.00 instead of 0.000000000000 -> if (document.Score != null) { SentimentsList.Add("Document ID: " + document.Id + ", Sentiment Score: " + document.Score); SentimentOccurrences.Add(document.Score.ToString()); } } System.Threading.Thread.Sleep(delay); } } catch (Exception ex) { System.Windows.Forms.MessageBox.Show("Error: " + ex.Message); } }
public static async Task <SentimentResult> GetTextSentimentAsync(string input, string language = "en") { SentimentResult sentimentResult = new SentimentResult() { Score = 0.5 }; if (!string.IsNullOrEmpty(input)) { SentimentBatchResult result = await AnalyticsClient.SentimentAsync(new MultiLanguageBatchInput( new List <MultiLanguageInput>() { new MultiLanguageInput(language, "0", input) })); if (result.Documents != null) { sentimentResult.Score = (double)result.Documents[0].Score; } if (result.Errors != null) { // Just return the neutral value } } return(sentimentResult); }
public SentimentBatchResult getSentiment() { // Extracting sentiment SentimentBatchResult result = client.Sentiment(getMultiLanguageBatchInput()); return(result); }
public static async Task <SentimentResult> GetSentimentAsync(string[] input, string language = "en") { if (input == null) { throw new ArgumentNullException("input"); } if (!input.Any()) { throw new ArgumentException("Input array is empty."); } var inputList = new List <MultiLanguageInput>(); for (int i = 0; i < input.Length; i++) { inputList.Add(new MultiLanguageInput(language, i.ToString(), input[i])); } SentimentBatchResult result = await client.SentimentAsync(multiLanguageBatchInput : new MultiLanguageBatchInput(inputList)); IEnumerable <double> scores = result.Documents.OrderBy(x => x.Id).Select(x => x.Score.GetValueOrDefault()); return(new SentimentResult { Scores = scores }); }
public static List <string> getAnalitcsResult(string inputText) { ITextAnalyticsAPI client = new TextAnalyticsAPI(); client.AzureRegion = AzureRegions.Westcentralus; client.SubscriptionKey = ""; List <string> strList = new List <string>(); KeyPhraseBatchResult result2 = client.KeyPhrases( new MultiLanguageBatchInput( new List <MultiLanguageInput>() { new MultiLanguageInput("en", "1", inputText) })); strList.Add(result2.Documents[0].KeyPhrases[0]); SentimentBatchResult result3 = client.Sentiment( new MultiLanguageBatchInput( new List <MultiLanguageInput>() { new MultiLanguageInput("en", "1", inputText) })); strList.Add(result3.Documents[0].Score.ToString()); return(strList); }
private void AnalizeFeelings() { string text = m_InputText.Text; m_FeelingsText.Text = "Phrase: " + text + '\n'; client.AzureRegion = AzureRegions.Westcentralus; client.SubscriptionKey = m_SentimentKey; SentimentBatchResult m_SentimentList = client.Sentiment( new MultiLanguageBatchInput( new List <MultiLanguageInput>() { // The text is always in english new MultiLanguageInput("en", "0", text) })); foreach (var document in m_SentimentList.Documents) { m_FeelingsText.Text += "Sentiment Score: " + document.Score + '\n'; double score = (double)document.Score; if (score < 0.2) { m_FeelingsText.Text += "Sentiment: Bad"; } else if (score < 0.8) { m_FeelingsText.Text += "Sentiment: Neutral"; } else { m_FeelingsText.Text += "Sentiment: Good"; } } }
private static void SentimentConsoleInput(ITextAnalyticsAPI client) { // Extracting sentiment Console.WriteLine("\n\n===== SENTIMENT ANALYSIS CONSOLE INPUT ======"); var canBreak = false; for (; ;) { Console.WriteLine("Please type your comment and press 'Enter', 'Q' or 'q' to exit."); var input = Console.ReadLine(); canBreak = input.Equals("q", StringComparison.OrdinalIgnoreCase); if (canBreak) { Console.WriteLine("Exit."); break; } SentimentBatchResult result = client.Sentiment(new MultiLanguageBatchInput(new List <MultiLanguageInput> { new MultiLanguageInput() { Id = DateTimeOffset.UtcNow.ToFileTime().ToString(), Text = input } })); foreach (var document in result.Documents) { Console.WriteLine($"Document ID: {document.Id} , Sentiment Score: {document.Score:0.00} , Text: {input}"); } Console.WriteLine(); } }
private double?ExtractSentiments(List <string> Queries) { // Create a client. ITextAnalyticsAPI client = new TextAnalyticsAPI(new ApiKeyServiceClientCredentials()); client.AzureRegion = AzureRegions.Westus; MultiLanguageBatchInput multiLanguageBatchInput = new MultiLanguageBatchInput(); multiLanguageBatchInput.Documents = new List <MultiLanguageInput>(); for (int i = 0; i < Queries.Count; i++) { multiLanguageBatchInput.Documents.Add(new MultiLanguageInput("en", i.ToString(), Queries[i])); } SentimentBatchResult sentimentBatchResult = client.SentimentAsync(multiLanguageBatchInput).Result; double?score = 0; // Printing sentiment results foreach (var document in sentimentBatchResult.Documents) { score += document.Score; } return(score / sentimentBatchResult.Documents.Count); }
private async Task MessageReceivedAsync(IDialogContext context, IAwaitable <IMessageActivity> result) { var message = await result; //Sentiment analysis ITextAnalyticsAPI client = new TextAnalyticsAPI { AzureRegion = AzureRegions.Westcentralus, SubscriptionKey = "Replace with your key" }; if ((message.Text != null) && (message.Text.Trim().Length > 0)) { SentimentBatchResult sentimentResult = client.Sentiment(new MultiLanguageBatchInput( new List <MultiLanguageInput>() { new MultiLanguageInput("en", "0", message.Text), })); double sentiment = sentimentResult.Documents.First().Score ?? 0; // Completes the dialog, remove it from the stack and return the result. context.Done(sentiment); } else { await context.PostAsync("I'm sorry, I don't understand your reply. How are you (e.g. 'Fine', 'I feel sick')?"); context.Wait(this.MessageReceivedAsync); } }
public virtual async Task DoTask(IDialogContext context, IAwaitable <IMessageActivity> activity) { var response = await activity; var responseText = response.Text; // Create a client. ITextAnalyticsAPI client = new TextAnalyticsAPI(); client.AzureRegion = AzureRegions.Westcentralus; client.SubscriptionKey = "af0b5df9f3e34a45b7eb149b8a911782"; SentimentBatchResult result3 = client.Sentiment( new MultiLanguageBatchInput( new List <MultiLanguageInput>() { new MultiLanguageInput("en", "0", responseText) })); // Printing language results. var score = result3.Documents.First().Score; reviewdetails review = new reviewdetails() { Review = responseText, SentimentScore = (double)score }; await AzureManager.AzureManagerInstance.PostReview(review); var message = "Thank you for reviewing our bot.\n\nWe will continue to improve this bot further."; await context.PostAsync(message); context.Done(this); }
public static async Task <IActionResult> WhatDidYouSay( [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger log) { log.LogInformation("Functions with Fabian Text Analyisi Cog Svcs about to begin..."); IncomingText input = GetTextInfo(req); ITextAnalyticsClient client = new TextAnalyticsClient(new ApiKeyServiceClientCredentials()) { Endpoint = "https://eastus2.api.cognitive.microsoft.com" }; if (string.IsNullOrWhiteSpace(input.Text)) { return(new BadRequestObjectResult("Please pass an image URL on the query string or in the request body")); } else { SentimentBatchResult result = client.SentimentAsync( new MultiLanguageBatchInput( new List <MultiLanguageInput>() { new MultiLanguageInput(input.Language, input.Id, input.Text), })).Result; var outputItem = JsonConvert.SerializeObject(result.Documents[0].Score); log.LogInformation($"Evauated Sentiment of thet text: \"{input.Text}\" is: {outputItem}"); return(new OkObjectResult($"{outputItem}")); } }
private String SentimentAnalysis(String text) { // Create a client. ITextAnalyticsAPI client = new TextAnalyticsAPI(); client.AzureRegion = AzureRegions.Westus; client.SubscriptionKey = "0e9cc6838a504e2194eb09d155678423"; Console.OutputEncoding = System.Text.Encoding.UTF8; String result = ""; SentimentBatchResult result3 = client.Sentiment( new MultiLanguageBatchInput( new List <MultiLanguageInput>() { new MultiLanguageInput("en", "1", text) //new MultiLanguageInput("en", "1", "This was a waste of my time. The speaker put me to sleep."), //new MultiLanguageInput("es", "2", "No tengo dinero ni nada que dar..."), //new MultiLanguageInput("it", "3", "L'hotel veneziano era meraviglioso. È un bellissimo pezzo di architettura."), })); //String answer = ""; //// Printing sentiment results foreach (var document in result3.Documents) { Console.WriteLine("Document ID: {0} , Sentiment Score: {1:0.00}", document.Id, document.Score); result += String.Format("Document ID: {0} , Sentiment Score: {1:0.00}", document.Id, document.Score); } return(result); }
public async Task GivenSomeContent_GetSentimentAsync_ReturnsExpectedResult() { // Arrange. var logger = new Mock <ILogger>(); var textAnalyticsClient = new Mock <ITextAnalyticsApiWrapper>(); var analyzer = new Analysis.AzureSentimentAnalyzer(logger.Object, textAnalyticsClient.Object); var content = new Dictionary <string, Tuple <string, double> > { { "this is great", new Tuple <string, double>("1", 0.9) }, { "this is bad", new Tuple <string, double>("2", 0.1) } }; var results = new SentimentBatchResult(content.Select(c => new SentimentBatchResultItem(c.Value.Item2, c.Value.Item1)) .ToList()); textAnalyticsClient.Setup(x => x.SentimentAsync(It.IsAny <IList <MultiLanguageInput> >(), CancellationToken.None)) .ReturnsAsync(results); // Act. var result = await analyzer.GetSentimentAsync(content.Keys); // Assert. textAnalyticsClient.VerifyAll(); result.Keys.Count.ShouldBe(content.Count); foreach (var expected in content) { result.ShouldContainKeyAndValue(expected.Key, expected.Value.Item2); } }
private async Task <IEnumerable <AnalysisResult> > GetAnalysisResultsAsync(MultiLanguageBatchInput batchInput) { KeyPhraseBatchResult keyPhraseBatchResult = await _textAnalyticsAPI.KeyPhrasesAsync(batchInput); SentimentBatchResult sentimentBatchResult = await _textAnalyticsAPI.SentimentAsync(batchInput); foreach (var keyPhrase in keyPhraseBatchResult.Documents) { string tweet = batchInput.Documents .Where(d => d.Id == keyPhrase.Id) .Select(t => t.Text) .FirstOrDefault(); var sentiment = sentimentBatchResult.Documents .Where(s => s.Id == keyPhrase.Id) .FirstOrDefault(); if (IsSignificant(sentiment.Score) && !keyPhrase.KeyPhrases.Count().Equals(0)) { AnalysisResult analysisResult = new AnalysisResult { KeyPhrases = keyPhrase.KeyPhrases, Attitude = DeriveAttitude(sentiment.Score), Tweet = tweet }; _analysisResults.Add(analysisResult); } } return(_analysisResults); }
private static Rating GetSentimentAnalysis(TraceWriter log, Rating rating) { // Handle sentiment analysis for usernotes // Create a client. ITextAnalyticsAPI client = new TextAnalyticsAPI { AzureRegion = AzureRegions.Westus, SubscriptionKey = Environment.GetEnvironmentVariable("COGNITIVE_SERVICES_KEY") }; Guid sentimentId = Guid.NewGuid(); SentimentBatchResult result = client.Sentiment( new MultiLanguageBatchInput( new List <MultiLanguageInput>() { new MultiLanguageInput("en", sentimentId.ToString(), rating.UserNotes), })); // Printing sentiment results foreach (var document in result.Documents) { log.Info($"Document ID: {document.Id} , Sentiment Score: {document.Score}"); rating.SentimentScore = (float)document.Score; } return(rating); }
public static async Task Run([CosmosDBTrigger( databaseName: "Your_database_name", collectionName: "Review", ConnectionStringSetting = "CosmosDbConnectionString", LeaseCollectionName = "leases")] IReadOnlyList <Document> documents, [DocumentDB(databaseName: "Your_database_name", collectionName: "Review", ConnectionStringSetting = "CosmosDbConnectionString", CreateIfNotExists = false)] IAsyncCollector <dynamic> results, TraceWriter log) { if (documents != null && documents.Count > 0) { log.Verbose($"Documents modified {documents.Count}"); log.Verbose($"First document Id { documents[0].Id}"); ITextAnalyticsAPI client = new TextAnalyticsAPI(); client.AzureRegion = AzureRegions.Westcentralus; client.SubscriptionKey = "<Your_Subscription_Key>"; string languageToAnalyze = "en"; int cnt = 0; foreach (var document in documents) { if (!string.IsNullOrEmpty(document.GetPropertyValue <string>("Satisfaction"))) { continue; } var content = document.GetPropertyValue <string>("Content"); SentimentBatchResult result = client.Sentiment( new MultiLanguageBatchInput( new List <MultiLanguageInput> { new MultiLanguageInput(languageToAnalyze, id: cnt.ToString(), text: content) } ) ); cnt++; var evaluationResult = result.Documents[0].Score; var newDocument = new { id = document.Id, Content = content, Satisfaction = evaluationResult }; await results.AddAsync(newDocument); log.Verbose($"Review evaluated: {content}"); log.Verbose($"Evaluation result: {evaluationResult}"); } } }
private async Task <IList <double?> > GetSentimentBatchAsync(IList <string> batchInputText) { SentimentBatchResult result = await textAnalyticsClient.SentimentAsync( new MultiLanguageBatchInput( batchInputText.Select((text, index) => new MultiLanguageInput("en", $"{index + 1}", text)).ToList() ) ); return(result.Documents.Select(s => s.Score).ToList()); }
public void printSentiment(SentimentBatchResult result) { // Printing sentiment results Console.WriteLine("\n\n===== SENTIMENT ANALYSIS ======"); foreach (var document in result.Documents) { Console.WriteLine("Document ID: {0} , Sentiment Score: {1:0.00}", document.Id, document.Score); } Console.ReadKey(); }
public async Task <double> GetSentimentAsync(string text) { // Build our request model MultiLanguageBatchInput requestDocument = GetSingleInput(text); // Get the result SentimentBatchResult result = await PostSentimentRequestAsync(requestDocument); // Return the single sentiment value return(result.Documents.Single().Score.Value); }
public double?SentimentText(ITextAnalyticsClient client, string identity, string text) { SentimentBatchResult result = client.SentimentAsync( new MultiLanguageBatchInput( new List <MultiLanguageInput>() { new MultiLanguageInput(identity, "1", text) })).Result; return(result.Documents[0].Score); }
private void ReturnSentiment(string userInput, string lang) { SentimentBatchResult sentiment = client.Sentiment(new MultiLanguageBatchInput(new List <MultiLanguageInput>() { new MultiLanguageInput(lang, "0", userInput) })); foreach (var document in sentiment.Documents) { Console.WriteLine("Sentiment score of inserted text is {0}\n", Math.Round(document.Score.Value, 2)); } }
/// <summary> /// Query the Azure congnitive analytics API for text analysis. This utilizes a nuget package and is largely the example /// code they provided with a few tweaks. /// </summary> /// <param name="body">Text body to be analyzed</param> /// <returns>an instance of the Analytics class that has the relevant parts of the analysis repackaged for ease of use</returns> public Analytics Analyze(string body)//Note: this was private, but that made testing the controller difficult { // Create a client. ITextAnalyticsAPI client = new TextAnalyticsAPI(); client.AzureRegion = AzureRegions.Westcentralus; client.SubscriptionKey = Configuration["textAPIKey"]; // initialize output vars List <string> keyPhrases = new List <string>(); float sentiment = 0; Console.OutputEncoding = System.Text.Encoding.UTF8; // Getting key-phrases // this is taken almost word for word from the example code in the docs for the API KeyPhraseBatchResult result2 = client.KeyPhrases( new MultiLanguageBatchInput( new List <MultiLanguageInput>() { new MultiLanguageInput("en", "3", body), })); // Unpack key phrases into list foreach (var document in result2.Documents) { foreach (string keyphrase in document.KeyPhrases) { keyPhrases.Add(keyphrase); } } // Extracting sentiment SentimentBatchResult result3 = client.Sentiment( new MultiLanguageBatchInput( new List <MultiLanguageInput>() { new MultiLanguageInput("en", "0", body) })); // Unpack sentiment results foreach (var document in result3.Documents) { sentiment = (float)document.Score; } // Repack analysis into analytics instance for convenience of use. return(new Analytics() { Keywords = keyPhrases, Sentiment = sentiment }); }
public void Sentiment() { using (MockContext context = MockContext.Start(this.GetType().FullName)) { HttpMockServer.Initialize(this.GetType().FullName, "Sentiment"); ITextAnalyticsClient client = GetClient(HttpMockServer.CreateInstance()); SentimentBatchResult result = client.Sentiment( "I love my team mates"); Assert.True(result.Documents[0].Score > 0); } }
public static async Task <SentimentKeyWords> BuildSentimentKeyWordsScoreAsync(string text, string language) { try { // Create a client. ITextAnalyticsClient client = new TextAnalyticsClient(new ApiKeyServiceClientCredentials()) { Endpoint = WebConfiguration.TextAnalyticsEndPoint, }; //Replace 'westus' with the correct region for your Text Analytics subscription SentimentBatchResult resultSentiment = await client.SentimentAsync(false, new MultiLanguageBatchInput( new List <MultiLanguageInput>() { new MultiLanguageInput(language, "0", text), })); KeyPhraseBatchResult resultKeyWords = await client.KeyPhrasesAsync(false, new MultiLanguageBatchInput( new List <MultiLanguageInput>() { new MultiLanguageInput(language, "3", text), })); var scoreResult = resultSentiment.Documents.FirstOrDefault(); string keywordsResult = string.Empty; StringBuilder builder = new StringBuilder(); var keyWords = resultKeyWords.Documents; foreach (var document in keyWords) { foreach (string keyphrase in document.KeyPhrases) { builder.Append(keyphrase).Append(" | "); } } var result = new SentimentKeyWords() { Score = scoreResult != null ? scoreResult.Score : 0, KeyWords = builder != null?builder.ToString() : string.Empty }; return(result); } catch (Exception ex) { SharedHelper.GetFullException(ex); return(new SentimentKeyWords()); } }
private void EmotionRecognition(ITextAnalyticsClient client, string text, string language) { SentimentBatchResult result = client.SentimentAsync(new MultiLanguageBatchInput( new List <MultiLanguageInput>() { new MultiLanguageInput(language, "1", text) })).Result; foreach (var document in result.Documents) { Console.WriteLine($"Document ID: {document.Id} , Sentiment Score: {document.Score}"); } }
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}"); }
static void Main(string[] args) { // Create a client. ITextAnalyticsClient client = new TextAnalyticsClient(new ApiKeyServiceClientCredentials()) { Endpoint = "https://westus.api.cognitive.microsoft.com" }; //Replace 'westus' with the correct region for your Text Analytics subscription Console.OutputEncoding = System.Text.Encoding.UTF8; // Extracting sentiment Console.WriteLine("\n\n===== SENTIMENT ANALYSIS ======"); var extractedtext = RecognizeSpeechAsync(); string text = extractedtext.Result; SentimentBatchResult result3 = client.SentimentAsync( new MultiLanguageBatchInput( new List <MultiLanguageInput>() { new MultiLanguageInput("en", "0", text), })).Result; // Printing sentiment results foreach (var document in result3.Documents) { Console.WriteLine($"Sentiment Score: {document.Score:0.00} of 1.00"); Console.WriteLine($"Higher score you get, more positive your speech is. "); if (document.Score > 0.5) { Console.WriteLine($"RESULT: The speech may be positive."); } else if (document.Score == 0.5) { Console.WriteLine($"RESULT: The speech may be neuter."); } else { Console.WriteLine($"RESULT: The speech may be negative."); } } Console.ReadLine(); }