Exemplo n.º 1
0
        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}"));
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// テキスト化された結果が返ってきた
        /// </summary>
        /// <param name="text">返ってきたテキスト</param>
        /// <param name="isCompleted">行末かどうか</param>
        /// <returns></returns>
        private async Task MicOutput(string text, bool isCompleted)
        {
            if (string.IsNullOrWhiteSpace(text))
            {
                return;
            }

            if (isCompleted)
            {
                var result = await _client.SentimentAsync(text, "ja");

                _recognizedContents.Add(new Sentence
                {
                    Text  = _lastContent,
                    Score = result.Score
                });
            }

            _lastContent = isCompleted ? "" : text;

            // 結果表示用のテキストを作成
            var recognizedText = MessageBuilder.BuildRecognizedText(_recognizedContents, _lastContent);
            var totalScore     = _recognizedContents.Where(c => c.Score.HasValue).Select(c => c.Score.Value).ToList();

            // スレッドを変えて画面を更新
            await RefreshDisplayAsync(totalScore, recognizedText);
        }
Exemplo n.º 3
0
        private static async Task <string> GetSentimentWithCognitiveService(string text, string apiKey)
        {
            ITextAnalyticsClient client = new TextAnalyticsClient(new ApiKeyServiceClientCredentials(apiKey))
            {
                Endpoint = "https://westus.api.cognitive.microsoft.com"
            }; //Replace 'westus' with the correct region for your Text Analytics subscription

            Console.OutputEncoding = System.Text.Encoding.UTF8;

            // Extract the language
            var result = await client.DetectLanguageAsync(false, new LanguageBatchInput(new List <LanguageInput>()
            {
                new LanguageInput(id: "1", text: text)
            }));

            var language = result.Documents?[0].DetectedLanguages?[0].Iso6391Name;

            // Get the sentiment
            var sentimentResult = await client.SentimentAsync(false,
                                                              new MultiLanguageBatchInput(
                                                                  new List <MultiLanguageInput>()
            {
                new MultiLanguageInput(language, "0", text),
            }));

            return(sentimentResult.Documents?[0].Score?.ToString("#.#"));
        }
Exemplo n.º 4
0
        public static async Task <IActionResult> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req, ILogger log, Microsoft.Azure.WebJobs.ExecutionContext context)
        {
            #region Preparation
            var imageUrl = req.Query["imageUrl"];

            var config = new ConfigurationBuilder()
                         .SetBasePath(context.FunctionAppDirectory)
                         .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                         .AddEnvironmentVariables()
                         .Build();

            var textAnalyticsSubscriptionKey = config["textAnalyticsSubscriptionKey"];
            var textAnalyticsEndPoint        = config["textAnalyticsEndPoint"];

            #endregion

            ITextAnalyticsClient client = new TextAnalyticsClient(new ApiKeyServiceClientCredentials(textAnalyticsSubscriptionKey))
            {
                Endpoint = textAnalyticsEndPoint
            };
            var result = await client.SentimentAsync(new MultiLanguageBatchInput(
                                                         new List <MultiLanguageInput>()
            {
                new MultiLanguageInput("tr", "0", "Hava çok güzel!"),
                new MultiLanguageInput("tr", "1", "Hava rezalet!"),
                new MultiLanguageInput("tr", "2", "Hava nasıl?"),
            }));

            return(new OkObjectResult(result));
        }
Exemplo n.º 5
0
        public async Task <TextAnalyticsAnalyzeResponse> Analyze(string text, string languageHint)
        {
            var credentials = new ApiKeyServiceClientCredentials(_subscriptionKey);
            var client      = new TextAnalyticsClient(credentials)
            {
                Endpoint = _endpoint
            };

            var detectedLanguageResult = await client.DetectLanguageAsync(text, languageHint, true);

            if (string.IsNullOrWhiteSpace(languageHint))
            {
                languageHint = detectedLanguageResult.DetectedLanguages.FirstOrDefault()?.Iso6391Name ?? "";
            }

            var entitiesResult   = client.EntitiesAsync(text, languageHint, true);
            var keyPhrasesResult = client.KeyPhrasesAsync(text, languageHint, true);
            var sentimentResult  = client.SentimentAsync(text, languageHint, true);

            await Task.WhenAll(entitiesResult, keyPhrasesResult, sentimentResult);

            return(new TextAnalyticsAnalyzeResponse
            {
                DetectedLanguage = detectedLanguageResult,
                KeyPhrases = keyPhrasesResult.Result,
                Sentiment = sentimentResult.Result,

                Entities = entitiesResult.Result
            });
        }
Exemplo n.º 6
0
        public static async Task Main()
        {
            string text = "SQLSaturday is Awesome!";

            string[] endpoints = new string[] {
                "<endpointGoesHere>",
                "http://localhost:5000"
            };
            string key = "<apiKeyGoesHere>";

            ApiKeyServiceClientCredentials credentials = new ApiKeyServiceClientCredentials(key);

            foreach (string endpoint in endpoints)
            {
                using (TextAnalyticsClient client = new TextAnalyticsClient(credentials)
                {
                    Endpoint = endpoint
                })
                {
                    SentimentResult sentiment = await client.SentimentAsync(text);

                    Console.WriteLine($"Sentiment for text: '{text}'\n On endpoint: '{endpoint}'\n is: {sentiment.Score}\n");
                }
            }

            Console.ReadLine();
        }
Exemplo n.º 7
0
        public static async Task RunAsync(string endpoint, string key)
        {
            var credentials = new ApiKeyServiceClientCredentials(key);
            var client      = new TextAnalyticsClient(credentials)
            {
                Endpoint = endpoint
            };

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

            var result = await client.SentimentAsync(false, inputDocuments);

            // Printing sentiment results
            foreach (var document in result.Documents)
            {
                Console.WriteLine($"Document ID: {document.Id} , Sentiment Score: {document.Score:0.00}");
            }
        }
Exemplo n.º 8
0
        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}");
            }
        }
Exemplo n.º 9
0
        //Get sentiment        //Get sentiment
        public static async Task <double?> SentimentAnalysisAsync(TextAnalyticsClient client, string input)
        {
            //The documents to be analyzed. Add the language of the document. The ID can be any value.
            var sentimentResults = await client.SentimentAsync(
                input,
                "en",
                false);

            //Return the results
            return(sentimentResults.Score);
        }
Exemplo n.º 10
0
        private static async Task <double> SentimentAnalysisExample(TextAnalyticsClient client, string text)
        {
            // The documents to be analyzed. Add the language of the document. The ID can be any value.
            var inputDocuments = new MultiLanguageBatchInput(
                new List <MultiLanguageInput>
            {
                new MultiLanguageInput("ja", "1", text),
            });
            var result = await client.SentimentAsync(false, inputDocuments);

            return((double)result.Documents[0].Score);
        }
Exemplo n.º 11
0
        public static async Task <double?> GetSentimentScoreAsync(string text, string language, IConfigurationRoot config)
        {
            var credentials = new ApiKeyServiceClientCredentials(config["TextAnalyticsApiKey"]);
            var client      = new TextAnalyticsClient(credentials)
            {
                Endpoint = config["TextAnalyticsEndpoint"]
            };

            var result = await client.SentimentAsync(text, language);

            return(result.Score);
        }
        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());
            }
        }
        public string Analyze(string input)
        {
            ITextAnalyticsClient client = new TextAnalyticsClient(new ApiKeyServiceClientCredentials(_subscriptionKey))
            {
                Endpoint = $"https://{_region}.api.cognitive.microsoft.com"
            };
            SentimentBatchResult result = client.SentimentAsync(
                new MultiLanguageBatchInput(
                    SplitFiveHundredChars(input).ToList()
                    )).Result;

            return($"{result.Documents[0].Score:0.00}");
        }
Exemplo n.º 14
0
        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();
        }
Exemplo n.º 15
0
        //Get sentiment
        public static async Task <double?> SentimentAnalysisAsync(TextAnalyticsClient client, string input)
        {
            //The documents to be analyzed. Add the language of the document. The ID can be any value.
            var sentimentResults = await client.SentimentAsync(
                false,
                new MultiLanguageBatchInput(
                    new List <MultiLanguageInput>
            {
                new MultiLanguageInput("en", "1", input)
            }));

            //Return the results
            return(sentimentResults.Documents[0].Score);
        }
Exemplo n.º 16
0
        public static async Task <double> SentimentAnalysisExample(TextAnalyticsClient client, string inputText)
        {
            // The documents to be analyzed. Add the language of the document. The ID can be any value.
            var inputDocuments = new MultiLanguageBatchInput(
                new List <MultiLanguageInput>
            {
                new MultiLanguageInput("en", "1", inputText)
            });
            //...

            var result = await client.SentimentAsync(false, inputDocuments);

            return(Convert.ToDouble(result.Documents[0].Score));
        }
        public async Task <double> GetTextSentimentAsync(string input)
        {
            // Create a client.
            ITextAnalyticsClient client = new TextAnalyticsClient(new ApiKeyServiceClientCredentials(_subscriptionKey))
            {
                Endpoint = _endpoint
            };

            var sentiment = await client.SentimentAsync(new MultiLanguageBatchInput(
                                                            new[] { new MultiLanguageInput(id: "0", language: "en", text: input) }
                                                            ));

            return(sentiment.Documents[0].Score.GetValueOrDefault());
        }
Exemplo n.º 18
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] SantaLetter theLetter,
            ILogger log)
        {
            SantaResults result;

            try
            {
                // Get the languages
                var detectedLanguages = await textClient.DetectLanguageAsync(
                    inputText : theLetter.LetterText,
                    countryHint : ""
                    );

                if (!string.IsNullOrEmpty(detectedLanguages.ErrorMessage))
                {
                    return(new StatusCodeResult(StatusCodes.Status500InternalServerError));
                }

                // Grab the top scoring one
                var theLanguage = detectedLanguages.DetectedLanguages.OrderByDescending(i => i.Score).First();

                // Get the sentiment
                var detectedSentiments = await textClient.SentimentAsync(
                    inputText : theLetter.LetterText,
                    language : theLanguage.Iso6391Name
                    );

                if (!string.IsNullOrEmpty(detectedSentiments.ErrorMessage))
                {
                    return(new StatusCodeResult(StatusCodes.Status500InternalServerError));
                }

                result = new SantaResults
                {
                    DetectedLanguage = theLanguage.Name,
                    KidName          = theLetter.KidName,
                    LetterText       = theLetter.LetterText,
                    SentimentScore   = detectedSentiments.Score.Value
                };
            }
            catch (Exception ex)
            {
                log.LogError(ex.ToString());

                return(new StatusCodeResult(StatusCodes.Status500InternalServerError));
            }

            return(new OkObjectResult(result));
        }
Exemplo n.º 19
0
        public ActionResult TextToSentimentScore()
        {
            ITextAnalyticsClient client = new TextAnalyticsClient(new ApiKeyServiceClientCredentials())
            {
                Endpoint = "https://westeurope.api.cognitive.microsoft.com"
            };

            var result = client.SentimentAsync(new MultiLanguageBatchInput(new List <MultiLanguageInput>
            {
                new MultiLanguageInput("en", "0", text)
            })).Result;

            return(Json(result.Documents.First().Score));
        }
Exemplo n.º 20
0
// ------------------------------------ Cognitive Services ----------------------------------------//

        public static async Task SentimentAnalysisExample(TextAnalyticsClient client)
        {
            WriteLine("----------------------------Sentiment Analysis------------------------");
            // The documents to be analyzed. Add the language of the document (en). The ID can be any value.
            const string  path       = "sample.txt";
            List <string> inputLines = ReadAndDisplay(path);

            WriteLine("--------- Check to make sure the file was read properly and lines stored in list----------");
            for (int i = 0; i < inputLines.Count; i++)
            {
                WriteLine(inputLines[i]);
            }

            // Create this list of Input objects to pass in
            List <MultiLanguageInput> myInputList = new List <MultiLanguageInput>();

            for (int i = 0; i < inputLines.Count; i++)
            {
                int    id    = i + 5;
                string idStr = id.ToString();
                myInputList.Add(
                    new MultiLanguageInput("en", idStr, inputLines[i]));
            }
            var inputDocuments = new MultiLanguageBatchInput(myInputList); // inputs (MultiLanguageBatchInput Objects)
            var result         = await client.SentimentAsync(false, inputDocuments);

            // create a list with corresponding scores
            // then sort list using the lookup score

            List <double> scores = new List <double>();

            // Printing sentiment results
            foreach (var document in result.Documents)
            {
                Console.WriteLine($"Document ID: {document.Id} , Sentiment Score: {document.Score:0.00}");
                scores.Add((double)document.Score);
            }

            // Sort out sad
            //List<MultiLanguageInput> sadList = new List<MultiLanguageInput>();
            // List<MultiLanguageInput> sadList = new List<MultiLanguageInput>();
            for (int i = 0; i < scores.Count; i++)
            {
                if (scores[i] < 0.5)
                {
                    Globals.sadList.Add(myInputList[i]);
                }
            }
        }
Exemplo n.º 21
0
        private static double GetSentiment(string text)
        {
            // Create a client.
            ITextAnalyticsClient client = new TextAnalyticsClient(new ApiKeyServiceClientCredentials())
            {
                Endpoint = "https://westeurope.api.cognitive.microsoft.com/"
            };

            SentimentBatchResult result = client.SentimentAsync(
                new MultiLanguageBatchInput(
                    new List <MultiLanguageInput>()
            {
                new MultiLanguageInput("en", "0", text)
            })).Result;

            return(result.Documents[0].Score.Value);
        }
Exemplo n.º 22
0
        private static async Task <double> GetScore(string id, string text)
        {
            ITextAnalyticsClient client = new TextAnalyticsClient(new ApiKeyServiceClientCredentials())
            {
                Endpoint = "https://eastus.api.cognitive.microsoft.com"
            };
            List <MultiLanguageInput> multiLanguageInputs = new List <MultiLanguageInput>();

            multiLanguageInputs.Add(new MultiLanguageInput()
            {
                Id       = id,
                Text     = text,
                Language = "en"
            });
            SentimentBatchResult result = await client.SentimentAsync(new MultiLanguageBatchInput(multiLanguageInputs));

            return(result.Documents[0].Score ?? 1.0);
        }
Exemplo n.º 23
0
        static public (string identifiedLanguage, string keyPhrases, double sentiment) EvaluateUtterance(TextAnalyticsClient textAnalyticsClient, string utterance)
        {
            string identifiedLanguage = null;
            string keyPhrases         = null;
            double sentiment          = Int32.MinValue;

            var detectLanguageResult = textAnalyticsClient.DetectLanguageAsync(new BatchInput(
                                                                                   new List <Input>()
            {
                new Input("1", utterance),
            })).Result;

            if (detectLanguageResult != null && detectLanguageResult.Errors.Count == 0)
            {
                identifiedLanguage = detectLanguageResult.Documents[0].DetectedLanguages[0].Name;
                string identfiedIsoLanguage = detectLanguageResult.Documents[0].DetectedLanguages[0].Iso6391Name;

                KeyPhraseBatchResult keyPhraseResult = textAnalyticsClient.KeyPhrasesAsync(new MultiLanguageBatchInput(
                                                                                               new List <MultiLanguageInput>()
                {
                    new MultiLanguageInput(identfiedIsoLanguage, "1", utterance)
                })).Result;

                if (keyPhraseResult != null && keyPhraseResult.Errors.Count == 0)
                {
                    // Collapse keyphrases into one space delimited string
                    keyPhrases = String.Join(" ", keyPhraseResult.Documents[0].KeyPhrases.Select(x => x.ToString()).ToArray());

                    SentimentBatchResult sentimentResult = textAnalyticsClient.SentimentAsync(
                        new MultiLanguageBatchInput(
                            new List <MultiLanguageInput>()
                    {
                        new MultiLanguageInput(identfiedIsoLanguage, "0", utterance)
                    })).Result;

                    if (sentimentResult != null && sentimentResult.Errors.Count == 0)
                    {
                        sentiment = sentimentResult.Documents[0].Score.Value;
                    }
                }
            }

            return(identifiedLanguage, keyPhrases, sentiment);
        }
Exemplo n.º 24
0
        static async Task Main(string[] args)
        {
            Console.WriteLine("Get tweets!");

            var auth = new SingleUserAuthorizer
            {
                CredentialStore = new SingleUserInMemoryCredentialStore()
                {
                    ConsumerKey       = TwitterConsumerKey,
                    ConsumerSecret    = TwitterConsumerSecret,
                    AccessToken       = TwitterAccessToken,
                    AccessTokenSecret = TwitterAccessTokenSecret
                }
            };
            await auth.AuthorizeAsync();

            var twitterCtx = new TwitterContext(auth);
            var tweets     = await twitterCtx.GetTweets("cloudbrew");

            var credentials = new ApiKeyServiceClientCredentials(CognitiveServicesKey);
            var client      = new TextAnalyticsClient(credentials)
            {
                Endpoint = CognitiveServicesEndpoint
            };

            foreach (var t in tweets)
            {
                var sentiment = await client.SentimentAsync(t.FullText, t.Lang);

                Console.WriteLine($"ID   : {t.StatusID}");
                Console.WriteLine($"User : {t.User.Name}");
                Console.WriteLine($"Text : {t.FullText}");
                Console.WriteLine($"Score: {sentiment.Score:0.00}");

                if (sentiment.Score > 0.5)
                {
                    await twitterCtx.Retweet(t.StatusID);

                    Console.WriteLine("Retweeted!");
                }
            }
            Console.WriteLine("End");
            Console.ReadLine();
        }
        static void Main(string[] args)
        {
            if (args == null || !args.Any())
            {
                System.Console.WriteLine("Por favor indicar el texto");
                return;
            }

            var text = args[0];


            string endpoint = "https://westeurope.api.cognitive.microsoft.com/";
            string key      = "c50bac85176f4da384d8e2d06bf17d41";

            var credentials = new ApiKeyServiceClientCredentials(key);
            var client      = new TextAnalyticsClient(credentials);

            client.Endpoint = endpoint;


            var input = new List <LanguageInput>();

            input.Add(new LanguageInput(id: "1", text: text));
            var batch    = new LanguageBatchInput(input);
            var analysis = client.DetectLanguageAsync(false, batch).Result;

            foreach (var document in analysis.Documents)
            {
                var language = document.DetectedLanguages.FirstOrDefault()?.Iso6391Name;


                var multiInput = new List <MultiLanguageInput>();
                multiInput.Add(new MultiLanguageInput(language, "1", text));
                var multiBatch      = new MultiLanguageBatchInput(multiInput);
                var sentimentResult = client.SentimentAsync(false, multiBatch).Result;

                foreach (var sentiment in sentimentResult.Documents)
                {
                    System.Console.WriteLine($"{text} : {sentiment.Score}");
                }
            }
        }
Exemplo n.º 26
0
        private static async Task <string> GetSentimentWithCognitiveService(string text, string apiKey)
        {
            ITextAnalyticsClient client = new TextAnalyticsClient(new ApiKeyServiceClientCredentials(apiKey))
            {
                // Replace 'westus' with the correct region for your Text Analytics subscription
                Endpoint = "https://westus.api.cognitive.microsoft.com"
            };

            Console.OutputEncoding = System.Text.Encoding.UTF8;

            // Extract the language
            var result = await client.DetectLanguageAsync(text);

            var language = result.DetectedLanguages?[0].Iso6391Name;

            // Get the sentiment
            var sentimentResult = await client.SentimentAsync(text, language);

            return(sentimentResult?.Score?.ToString("#.#"));
        }
Exemplo n.º 27
0
        public async Task <ResultAnalysis> TextAnalysisAsync(string text)
        {
            ResultAnalysis model = null;

            try
            {
                model = new ResultAnalysis();
                var level = await client.SentimentAsync(text);

                var key = await client.KeyPhrasesAsync(text);

                model.Score = (int)(level.Score * 10);
                model.Key   = key.KeyPhrases;
            }
            catch (Exception ex)
            {
                CoreLogger.Instance.Error(this.CreateMessageLog(ex.Message));
            }
            return(model);
        }
Exemplo n.º 28
0
        public static async Task <double> GetTextSentiment(string input)
        {
            ITextAnalyticsClient client = new TextAnalyticsClient(new ApiKeyServiceClientCredentials())
            {
                Endpoint = "https://westus.api.cognitive.microsoft.com",
            };

            var language = await client.DetectLanguageAsync(languageBatchInput : new LanguageBatchInput(documents: new List <LanguageInput>()
            {
                new LanguageInput(id: "1", text: input)
            }));

            var langCode = language.Documents[0].DetectedLanguages[0].Iso6391Name;

            var sentiment = await client.SentimentAsync(multiLanguageBatchInput : new MultiLanguageBatchInput(new List <MultiLanguageInput>()
            {
                new MultiLanguageInput(id: "1", language: langCode, text: input)
            }));

            return(sentiment.Documents[0].Score.GetValueOrDefault());
        }
Exemplo n.º 29
0
        public static async Task Main()
        {
            string endpoint = "<endpointGoesHere>";
            string key      = "<apiKeyGoesHere>";

            ApiKeyServiceClientCredentials credentials = new ApiKeyServiceClientCredentials(key);

            using (TextAnalyticsClient client = new TextAnalyticsClient(credentials)
            {
                Endpoint = endpoint
            })
            {
                while (true)
                {
                    // Read the users input
                    Console.Write("\n--------------------\nEnter some text: ");

                    string input = Console.ReadLine();

                    // Detect the language
                    LanguageResult languageResult = await client.DetectLanguageAsync(input);

                    Console.WriteLine("\n> Language: " + languageResult.ToDescription());

                    string languageCode = languageResult.HighestLanguageCode();

                    // Detect the sentiment
                    SentimentResult sentimentResult = await client.SentimentAsync(input, languageCode);

                    Console.WriteLine($"> Sentiment: {sentimentResult.Score} - {sentimentResult.ToDescription()}");

                    // Detect the key phrases
                    KeyPhraseResult keyPhraseResult = await client.KeyPhrasesAsync(input, languageCode);

                    Console.WriteLine("> Key Phrases: " + string.Join(", ", keyPhraseResult.KeyPhrases));
                }
            }
        }
        public static async Task TestTextAnalyticsApiKeyAsync(string key, string apiEndpoint)
        {
            bool isUri = !string.IsNullOrEmpty(apiEndpoint) ? Uri.IsWellFormedUriString(apiEndpoint, UriKind.Absolute) : false;

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

                await client.SentimentAsync(multiLanguageBatchInput :
                                            new MultiLanguageBatchInput(
                                                new List <MultiLanguageInput>()
                {
                    new MultiLanguageInput("en", "0", "I had the best day of my life."),
                }));
            }
        }