public void AnalyzeSentimentBatchConvenience()
        {
            string endpoint        = Environment.GetEnvironmentVariable("TEXT_ANALYTICS_ENDPOINT");
            string subscriptionKey = Environment.GetEnvironmentVariable("TEXT_ANALYTICS_SUBSCRIPTION_KEY");

            var client = new TextAnalyticsClient(new Uri(endpoint), subscriptionKey);

            var inputs = new List <string>
            {
                "That was the best day of my life!",
                "This food is very bad.",
                "I'm not sure how I feel about this product.",
                "Pike place market is my favorite Seattle attraction.",
            };

            Debug.WriteLine($"Analyzing sentiment for inputs:");
            foreach (string input in inputs)
            {
                Debug.WriteLine($"    {input}");
            }

            #region Snippet:TextAnalyticsSample2AnalyzeSentimentConvenience
            AnalyzeSentimentResultCollection results = client.AnalyzeSentiment(inputs);
            #endregion

            Debug.WriteLine($"Predicted sentiments are:");
            foreach (AnalyzeSentimentResult result in results)
            {
                TextSentiment sentiment = result.DocumentSentiment;
                Debug.WriteLine($"Document sentiment is {sentiment.SentimentClass.ToString()}, with scores: ");
                Debug.WriteLine($"    Positive score: {sentiment.PositiveScore:0.00}.");
                Debug.WriteLine($"    Neutral score: {sentiment.NeutralScore:0.00}.");
                Debug.WriteLine($"    Negative score: {sentiment.NegativeScore:0.00}.");
            }
        }
示例#2
0
        public static DocumentSentiment ToDocumentSentiment(JObject input)
        {
            var ti = typeof(DocumentSentiment).GetTypeInfo().DeclaredConstructors.First();

            Type[] paramTypes = new Type[] {
                typeof(TextSentiment),
                typeof(double),
                typeof(double),
                typeof(double),
                typeof(List<SentenceSentiment>)
            };

            var score = ToSentimentConfidenceScores(input);

            var sentences = input.Value<JArray>("Sentences")
                        .Select(s => ToSentenceSentiment((JObject)s)).ToList();


            TextSentiment ts = TextSentiment.Neutral;
            #region GetDocumentOverall Sentiment
            int sentencesPositive = sentences.Count(s =>
                GetSentenceTextSentiment(s) == TextSentiment.Positive);
            int sentencesNegative = sentences.Count(s =>
                GetSentenceTextSentiment(s) == TextSentiment.Negative);
            int sentencesNeutral = sentences.Count(s =>
                GetSentenceTextSentiment(s) == TextSentiment.Neutral);
            if ((sentencesPositive > 0) && (sentencesNegative > 0))
            {
                ts = TextSentiment.Mixed;
            }
            else if (sentencesPositive > 0)
            {
                ts = TextSentiment.Positive;
            }
            else if (sentencesNegative > 0)
            {
                ts = TextSentiment.Negative;
            } 
            #endregion

            object[] paramValues = new object[] {
                ts,
                score.Positive,
                score.Neutral,
                score.Negative,
                sentences
            };

            DocumentSentiment instance = null;
            try
            {
                instance = TypeHelpers.Construct<DocumentSentiment>(
                    paramTypes, paramValues);
            }
            catch (Exception)
            {
            }

            return instance;
        }
        internal DocumentSentimentInternal(string id, TextSentiment sentiment, TextDocumentStatistics?statistics, SentimentConfidenceScores confidenceScores, IEnumerable <SentenceSentimentInternal> sentences, IEnumerable <TextAnalyticsWarningInternal> warnings)
        {
            if (id == null)
            {
                throw new ArgumentNullException(nameof(id));
            }
            if (confidenceScores == null)
            {
                throw new ArgumentNullException(nameof(confidenceScores));
            }
            if (sentences == null)
            {
                throw new ArgumentNullException(nameof(sentences));
            }
            if (warnings == null)
            {
                throw new ArgumentNullException(nameof(warnings));
            }

            Id               = id;
            Sentiment        = sentiment;
            Statistics       = statistics;
            ConfidenceScores = confidenceScores;
            Sentences        = sentences.ToList();
            Warnings         = warnings.ToList();
        }
 internal SentenceSentiment(TextSentiment sentiment, double positiveScore, double neutralScore, double negativeScore, int offset, int length)
 {
     Sentiment        = sentiment;
     ConfidenceScores = new SentimentConfidenceScores(positiveScore, neutralScore, negativeScore);
     GraphemeOffset   = offset;
     GraphemeLength   = length;
 }
        internal static SentimentResponseDocumentsItem DeserializeSentimentResponseDocumentsItem(JsonElement element)
        {
            TextSentiment                     sentiment        = default;
            SentimentConfidenceScores         confidenceScores = default;
            IList <SentenceSentimentInternal> sentences        = default;
            string id = default;
            IList <DocumentWarning>           warnings   = default;
            Optional <TextDocumentStatistics> statistics = default;

            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("sentiment"))
                {
                    sentiment = property.Value.GetString().ToTextSentiment();
                    continue;
                }
                if (property.NameEquals("confidenceScores"))
                {
                    confidenceScores = SentimentConfidenceScores.DeserializeSentimentConfidenceScores(property.Value);
                    continue;
                }
                if (property.NameEquals("sentences"))
                {
                    List <SentenceSentimentInternal> array = new List <SentenceSentimentInternal>();
                    foreach (var item in property.Value.EnumerateArray())
                    {
                        array.Add(SentenceSentimentInternal.DeserializeSentenceSentimentInternal(item));
                    }
                    sentences = array;
                    continue;
                }
                if (property.NameEquals("id"))
                {
                    id = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("warnings"))
                {
                    List <DocumentWarning> array = new List <DocumentWarning>();
                    foreach (var item in property.Value.EnumerateArray())
                    {
                        array.Add(DocumentWarning.DeserializeDocumentWarning(item));
                    }
                    warnings = array;
                    continue;
                }
                if (property.NameEquals("statistics"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    statistics = TextDocumentStatistics.DeserializeTextDocumentStatistics(property.Value);
                    continue;
                }
            }
            return(new SentimentResponseDocumentsItem(id, warnings, Optional.ToNullable(statistics), sentiment, confidenceScores, sentences));
        }
        public void MergeFrom(AnnotationPayload other)
        {
            if (other == null)
            {
                return;
            }
            if (other.AnnotationSpecId.Length != 0)
            {
                AnnotationSpecId = other.AnnotationSpecId;
            }
            if (other.DisplayName.Length != 0)
            {
                DisplayName = other.DisplayName;
            }
            switch (other.DetailCase)
            {
            case DetailOneofCase.Translation:
                if (Translation == null)
                {
                    Translation = new global::Google.Cloud.AutoML.V1.TranslationAnnotation();
                }
                Translation.MergeFrom(other.Translation);
                break;

            case DetailOneofCase.Classification:
                if (Classification == null)
                {
                    Classification = new global::Google.Cloud.AutoML.V1.ClassificationAnnotation();
                }
                Classification.MergeFrom(other.Classification);
                break;

            case DetailOneofCase.ImageObjectDetection:
                if (ImageObjectDetection == null)
                {
                    ImageObjectDetection = new global::Google.Cloud.AutoML.V1.ImageObjectDetectionAnnotation();
                }
                ImageObjectDetection.MergeFrom(other.ImageObjectDetection);
                break;

            case DetailOneofCase.TextExtraction:
                if (TextExtraction == null)
                {
                    TextExtraction = new global::Google.Cloud.AutoML.V1.TextExtractionAnnotation();
                }
                TextExtraction.MergeFrom(other.TextExtraction);
                break;

            case DetailOneofCase.TextSentiment:
                if (TextSentiment == null)
                {
                    TextSentiment = new global::Google.Cloud.AutoML.V1.TextSentimentAnnotation();
                }
                TextSentiment.MergeFrom(other.TextSentiment);
                break;
            }

            _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
        }
 /// <summary>
 /// 分析結果をコンソールに出力
 /// </summary>
 /// <param name="text"></param>
 /// <param name="sentiment"></param>
 /// <param name="scores"></param>
 private void ConsoleOutput(string text, TextSentiment sentiment, SentimentConfidenceScores scores)
 {
     Console.WriteLine($"\tText: \"{text}\"");
     Console.WriteLine($"\tSentence sentiment: {sentiment}");
     Console.WriteLine($"\tPositive score: {scores.Positive:0.00}");
     Console.WriteLine($"\tNegative score: {scores.Negative:0.00}");
     Console.WriteLine($"\tNeutral score: {scores.Neutral:0.00}\n");
 }
 internal DocumentSentimentInternal(string id, TextSentiment sentiment, TextDocumentStatistics?statistics, SentimentConfidenceScores confidenceScores, IReadOnlyList <SentenceSentimentInternal> sentences, IReadOnlyList <TextAnalyticsWarningInternal> warnings)
 {
     Id               = id;
     Sentiment        = sentiment;
     Statistics       = statistics;
     ConfidenceScores = confidenceScores;
     Sentences        = sentences;
     Warnings         = warnings;
 }
示例#9
0
        public async Task AnalyzeSentimentWithLanguageTest()
        {
            TextAnalyticsClient client = GetClient();
            string input = "El mejor test del mundo!";

            AnalyzeSentimentResult result = await client.AnalyzeSentimentAsync(input, "es");

            TextSentiment sentiment = result.DocumentSentiment;

            Assert.AreEqual("Positive", sentiment.SentimentClass.ToString());
        }
        internal static DocumentSentimentInternal DeserializeDocumentSentimentInternal(JsonElement element)
        {
            string        id        = default;
            TextSentiment sentiment = default;
            Optional <TextDocumentStatistics>            statistics       = default;
            SentimentConfidenceScores                    confidenceScores = default;
            IReadOnlyList <SentenceSentimentInternal>    sentences        = default;
            IReadOnlyList <TextAnalyticsWarningInternal> warnings         = default;

            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("id"))
                {
                    id = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("sentiment"))
                {
                    sentiment = property.Value.GetString().ToTextSentiment();
                    continue;
                }
                if (property.NameEquals("statistics"))
                {
                    statistics = TextDocumentStatistics.DeserializeTextDocumentStatistics(property.Value);
                    continue;
                }
                if (property.NameEquals("confidenceScores"))
                {
                    confidenceScores = SentimentConfidenceScores.DeserializeSentimentConfidenceScores(property.Value);
                    continue;
                }
                if (property.NameEquals("sentences"))
                {
                    List <SentenceSentimentInternal> array = new List <SentenceSentimentInternal>();
                    foreach (var item in property.Value.EnumerateArray())
                    {
                        array.Add(SentenceSentimentInternal.DeserializeSentenceSentimentInternal(item));
                    }
                    sentences = array;
                    continue;
                }
                if (property.NameEquals("warnings"))
                {
                    List <TextAnalyticsWarningInternal> array = new List <TextAnalyticsWarningInternal>();
                    foreach (var item in property.Value.EnumerateArray())
                    {
                        array.Add(TextAnalyticsWarningInternal.DeserializeTextAnalyticsWarningInternal(item));
                    }
                    warnings = array;
                    continue;
                }
            }
            return(new DocumentSentimentInternal(id, sentiment, Optional.ToNullable(statistics), confidenceScores, sentences, warnings));
        }
示例#11
0
        private static string ConvertSentimentToEmoji(TextSentiment sentiment)
        {
            string x = sentiment switch
            {
                TextSentiment.Positive => "🙂",
                TextSentiment.Neutral => "😐",
                TextSentiment.Negative => "🙁",
                TextSentiment.Mixed => "😖",
                _ => "❓",
            };

            return(x);
        }
示例#12
0
        private static TextSentiment GetSentiment(string usertext, ILogger log)
        {
            AzureKeyCredential credentials = new AzureKeyCredential(Environment.GetEnvironmentVariable("COG_KEY"));
            Uri endpoint = new Uri(Environment.GetEnvironmentVariable("COG_EP"));
            var client   = new TextAnalyticsClient(endpoint, credentials);

            log.LogInformation($" gor sentence to analyze: {usertext}");
            DocumentSentiment documentSentiment = client.AnalyzeSentiment(usertext);
            TextSentiment     ts = documentSentiment.Sentiment;

            log.LogInformation($"CreateRating:Sentiment Score is: {ts}");
            return(ts);
        }
示例#13
0
        public override int GetHashCode()
        {
            int hash = 1;

            if (detailCase_ == DetailOneofCase.Translation)
            {
                hash ^= Translation.GetHashCode();
            }
            if (detailCase_ == DetailOneofCase.Classification)
            {
                hash ^= Classification.GetHashCode();
            }
            if (detailCase_ == DetailOneofCase.ImageObjectDetection)
            {
                hash ^= ImageObjectDetection.GetHashCode();
            }
            if (detailCase_ == DetailOneofCase.VideoClassification)
            {
                hash ^= VideoClassification.GetHashCode();
            }
            if (detailCase_ == DetailOneofCase.VideoObjectTracking)
            {
                hash ^= VideoObjectTracking.GetHashCode();
            }
            if (detailCase_ == DetailOneofCase.TextExtraction)
            {
                hash ^= TextExtraction.GetHashCode();
            }
            if (detailCase_ == DetailOneofCase.TextSentiment)
            {
                hash ^= TextSentiment.GetHashCode();
            }
            if (detailCase_ == DetailOneofCase.Tables)
            {
                hash ^= Tables.GetHashCode();
            }
            if (AnnotationSpecId.Length != 0)
            {
                hash ^= AnnotationSpecId.GetHashCode();
            }
            if (DisplayName.Length != 0)
            {
                hash ^= DisplayName.GetHashCode();
            }
            hash ^= (int)detailCase_;
            if (_unknownFields != null)
            {
                hash ^= _unknownFields.GetHashCode();
            }
            return(hash);
        }
示例#14
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("CreateRating function processed a request.");

            string DatabaseName            = Environment.GetEnvironmentVariable("COSMOS_DB_NAME");
            string CollectionName          = Environment.GetEnvironmentVariable("COSMOS_COLLECTION");
            string ConnectionStringSetting = Environment.GetEnvironmentVariable("COSMOS_CS");

            CosmosClient cosmosClient    = new CosmosClient(ConnectionStringSetting);
            Container    cosmosContainer = cosmosClient.GetContainer(DatabaseName, CollectionName);

            // string name = req.Query["name"];
            var    aRating     = new Rating();
            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();

            log.LogInformation($"CreateRating : got string data: {requestBody}");
            dynamic data = JsonConvert.DeserializeObject(requestBody);

            log.LogInformation("CreateRating : got dynamic data");
            aRating.userId       = data?.userId;
            aRating.productId    = data?.productId;
            aRating.locationName = data?.locationName;
            string s_rating = data?.rating;

            aRating.rating    = (string.IsNullOrEmpty(s_rating))? 0: int.Parse(s_rating);
            aRating.userNotes = data?.userNotes;
            aRating.timestamp = new DateTime();
            aRating.id        = Guid.NewGuid().ToString();
            Boolean ValidUser = await ValidateUserId(aRating.userId, log);

            Boolean ValidProduct = await ValidateProductId(aRating.productId, log);

            if (!ValidUser || !ValidProduct || !ValidateRating(aRating.rating))
            {
                string errorresponse = "One or more items does not exist, please try again";
                return(new NotFoundObjectResult(errorresponse));
            }
            TextSentiment score = GetSentiment(aRating.userNotes, log);

            aRating.Sentiment = score.ToString();
            string okresponse = JsonConvert.SerializeObject(aRating);



            ItemResponse <Rating> ratingResponse = await cosmosContainer.CreateItemAsync <Rating>(aRating, new PartitionKey(aRating.id));

            return(new OkObjectResult(okresponse));
        }
示例#15
0
        public async Task AnalyzeSentimentTest()
        {
            TextAnalyticsClient client = GetClient();
            string input = "That was the best day of my life!";

            AnalyzeSentimentResult result = await client.AnalyzeSentimentAsync(input);

            TextSentiment sentiment = result.DocumentSentiment;

            Assert.AreEqual("Positive", sentiment.SentimentClass.ToString());
            Assert.IsNotNull(sentiment.PositiveScore);
            Assert.IsNotNull(sentiment.NeutralScore);
            Assert.IsNotNull(sentiment.NegativeScore);
            Assert.IsNotNull(sentiment.Offset);
        }
        public void AnalyzeSentiment()
        {
            string endpoint        = Environment.GetEnvironmentVariable("TEXT_ANALYTICS_ENDPOINT");
            string subscriptionKey = Environment.GetEnvironmentVariable("TEXT_ANALYTICS_SUBSCRIPTION_KEY");

            // Instantiate a client that will be used to call the service.
            var client = new TextAnalyticsClient(new Uri(endpoint), subscriptionKey);

            string input = "That was the best day of my life!";

            Debug.WriteLine($"Analyzing sentiment for input: \"{input}\"");
            AnalyzeSentimentResult result    = client.AnalyzeSentiment(input).Value;
            TextSentiment          sentiment = result.DocumentSentiment;

            Debug.WriteLine($"Sentiment was {sentiment.SentimentClass.ToString()}, with scores: ");
            Debug.WriteLine($"    Positive score: {sentiment.PositiveScore:0.00}.");
            Debug.WriteLine($"    Neutral score: {sentiment.NeutralScore:0.00}.");
            Debug.WriteLine($"    Negative score: {sentiment.NeutralScore:0.00}.");
        }
        public void AnalyzeSentiment()
        {
            string endpoint        = Environment.GetEnvironmentVariable("TEXT_ANALYTICS_ENDPOINT");
            string subscriptionKey = Environment.GetEnvironmentVariable("TEXT_ANALYTICS_SUBSCRIPTION_KEY");

            #region Snippet:TextAnalyticsSample2CreateClient
            var client = new TextAnalyticsClient(new Uri(endpoint), new TextAnalyticsSubscriptionKeyCredential(subscriptionKey));
            #endregion

            #region Snippet:AnalyzeSentiment
            string input = "That was the best day of my life!";

            AnalyzeSentimentResult result    = client.AnalyzeSentiment(input);
            TextSentiment          sentiment = result.DocumentSentiment;

            Console.WriteLine($"Sentiment was {sentiment.SentimentClass.ToString()}, with scores: ");
            Console.WriteLine($"    Positive score: {sentiment.PositiveScore:0.00}.");
            Console.WriteLine($"    Neutral score: {sentiment.NeutralScore:0.00}.");
            Console.WriteLine($"    Negative score: {sentiment.NegativeScore:0.00}.");
            #endregion
        }
示例#18
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req
            )
        {
            string TextInput = await DeserializerRequest(req);

            if (TextInput.Length < 3)
            {
                return(new BadRequestObjectResult("Input Text is too short (min is 3) "));
            }

            if (TextInput.Length > 5000)
            {
                return(new BadRequestObjectResult("Input Text is too long ! (Max is 5000) "));
            }

            List <string> TextSplitIntoList = new List <string>();

            TextSplitIntoList.AddRange(TextInput.Split('\n'));
            TextSplitIntoList.RemoveAll(x => string.IsNullOrEmpty(x));

            if (TextSplitIntoList.Count > 10)
            {
                return(new BadRequestObjectResult("Input text has too many lines (Maximum of 10 Lines)"));
            }

            string[] TextSplitIntoLines = TextSplitIntoList.ToArray();

            TextSentiment Sentiment = await GetSentiment(TextInput);

            String[] TalkingPoints = await TextAnalisis(TextInput);

            String SentimentEmoji = ConvertSentimentToEmoji(Sentiment);

            LinesSentiment[] SentimentsBreakdown = await GetSentimentLines(TextSplitIntoLines);

            FunctionResult result = new FunctionResult(SentimentEmoji, TalkingPoints, SentimentsBreakdown);

            return(new OkObjectResult(JsonConvert.SerializeObject(result)));
        }
示例#19
0
        public static SentenceSentiment ToSentenceSentiment(JObject input)
        {
            var ti = typeof(SentenceSentiment).GetTypeInfo().DeclaredConstructors.First();

             
            Type[] paramTypes = new Type[] {
                typeof(TextSentiment),
                typeof(double),
                typeof(double),
                typeof(double),
                typeof(int),
                typeof(int)
            };

            TextSentiment ts = (TextSentiment)input.Value<int>("Sentiment");
            var score = ToSentimentConfidenceScores(input.Value<JObject>("ConfidenceScores"));

            object[] paramValues = new object[] {
                ts,
                score.Positive,
                score.Neutral,
                score.Negative,
                input.Value<int>("GraphemeOffset"),
                input.Value<int>("GraphemeLength")
            };

            SentenceSentiment instance = default(SentenceSentiment);
            try
            {
                instance = TypeHelpers.Construct<SentenceSentiment>(
                    paramTypes, paramValues);
            }
            catch (Exception)
            {
            }
            
            return instance;            
        }
示例#20
0
        public SentimentDocumentResult(string id, IEnumerable <DocumentWarning> warnings, TextSentiment sentiment, SentimentConfidenceScores confidenceScores, IEnumerable <SentenceSentimentInternal> sentences) : base(id, warnings)
        {
            if (id == null)
            {
                throw new ArgumentNullException(nameof(id));
            }
            if (warnings == null)
            {
                throw new ArgumentNullException(nameof(warnings));
            }
            if (confidenceScores == null)
            {
                throw new ArgumentNullException(nameof(confidenceScores));
            }
            if (sentences == null)
            {
                throw new ArgumentNullException(nameof(sentences));
            }

            Sentiment        = sentiment;
            ConfidenceScores = confidenceScores;
            Sentences        = sentences.ToList();
        }
示例#21
0
 internal SentenceSentiment(TextSentiment sentiment, string text, double positiveScore, double neutralScore, double negativeScore)
 {
     Sentiment        = sentiment;
     Text             = text;
     ConfidenceScores = new SentimentConfidenceScores(positiveScore, neutralScore, negativeScore);
 }
 public SentimentResponseDocumentsItem(string id, IEnumerable <DocumentWarning> warnings, TextSentiment sentiment, SentimentConfidenceScores confidenceScores, IEnumerable <SentenceSentimentInternal> sentences) : base(id, warnings, sentiment, confidenceScores, sentences)
 {
     if (id == null)
     {
         throw new ArgumentNullException(nameof(id));
     }
     if (warnings == null)
     {
         throw new ArgumentNullException(nameof(warnings));
     }
     if (confidenceScores == null)
     {
         throw new ArgumentNullException(nameof(confidenceScores));
     }
     if (sentences == null)
     {
         throw new ArgumentNullException(nameof(sentences));
     }
 }
 internal SentimentResponseDocumentsItem(string id, IList <DocumentWarning> warnings, TextDocumentStatistics?statistics, TextSentiment sentiment, SentimentConfidenceScores confidenceScores, IList <SentenceSentimentInternal> sentences) : base(id, warnings, statistics, sentiment, confidenceScores, sentences)
 {
 }
示例#24
0
 internal SentimentDocumentResult(string id, IList <DocumentWarning> warnings, TextDocumentStatistics?statistics, TextSentiment sentiment, SentimentConfidenceScores confidenceScores, IList <SentenceSentimentInternal> sentences) : base(id, warnings, statistics)
 {
     Sentiment        = sentiment;
     ConfidenceScores = confidenceScores;
     Sentences        = sentences;
 }
 public void SetSentiment(TextSentiment value)
 {
     textSentiment = value;
 }