/// <summary>Snippet for AnalyzeSentiment</summary>
 public void AnalyzeSentimentRequestObject()
 {
     // Snippet: AnalyzeSentiment(AnalyzeSentimentRequest, CallSettings)
     // Create client
     LanguageServiceClient languageServiceClient = LanguageServiceClient.Create();
     // Initialize request argument(s)
     AnalyzeSentimentRequest request = new AnalyzeSentimentRequest
     {
         Document     = new Document(),
         EncodingType = EncodingType.None,
     };
     // Make the request
     AnalyzeSentimentResponse response = languageServiceClient.AnalyzeSentiment(request);
     // End snippet
 }
        /// <summary>Snippet for AnalyzeSentimentAsync</summary>
        public async Task AnalyzeSentiment1Async()
        {
            // Snippet: AnalyzeSentimentAsync(Document, EncodingType, CallSettings)
            // Additional: AnalyzeSentimentAsync(Document, EncodingType, CancellationToken)
            // Create client
            LanguageServiceClient languageServiceClient = await LanguageServiceClient.CreateAsync();

            // Initialize request argument(s)
            Document     document     = new Document();
            EncodingType encodingType = EncodingType.None;
            // Make the request
            AnalyzeSentimentResponse response = await languageServiceClient.AnalyzeSentimentAsync(document, encodingType);

            // End snippet
        }
Ejemplo n.º 3
0
 // [START language_sentiment_gcs_core]
 /// <summary>
 /// Analyze sentiment of text stored in GCS
 /// </summary>
 public static void SampleAnalyzeSentiment(string gcsUri)
 {
     LanguageServiceClient languageServiceClient = LanguageServiceClient.Create();
     // string gcsUri = "gs://cloud-samples-data/language/sentiment-positive.txt"
     AnalyzeSentimentRequest request = new AnalyzeSentimentRequest
     {
         Document = new Document
         {
             Type = Document.Types.Type.PlainText,
             GcsContentUri = "gs://cloud-samples-data/language/sentiment-positive.txt",
         },
     };
     AnalyzeSentimentResponse response = languageServiceClient.AnalyzeSentiment(request);
     // FIXME: inspect the results
 }
        public async Task AnalyzeSentimentAsync_RequestObject()
        {
            // Snippet: AnalyzeSentimentAsync(AnalyzeSentimentRequest,CallSettings)
            // Create client
            LanguageServiceClient languageServiceClient = await LanguageServiceClient.CreateAsync();

            // Initialize request argument(s)
            AnalyzeSentimentRequest request = new AnalyzeSentimentRequest
            {
                Document = new Document(),
            };
            // Make the request
            AnalyzeSentimentResponse response = await languageServiceClient.AnalyzeSentimentAsync(request);

            // End snippet
        }
        public void AnalyzeSentiment()
        {
            // Sample: AnalyzeSentiment
            // Additional: AnalyzeSentiment(Document,*)
            LanguageServiceClient client      = LanguageServiceClient.Create();
            Document document                 = Document.FromPlainText("You're simply the best - better than all the rest.");
            AnalyzeSentimentResponse response = client.AnalyzeSentiment(document);

            Console.WriteLine($"Detected language: {response.Language}");
            Console.WriteLine($"Sentiment score: {response.DocumentSentiment.Score}");
            Console.WriteLine($"Sentiment magnitude: {response.DocumentSentiment.Magnitude}");
            // End sample

            // This is fairly positive...
            Assert.True(response.DocumentSentiment.Score > 0.5);
        }
 // [START language_sentiment_text_core]
 /// <summary>
 /// Analyze sentiment of text
 /// </summary>
 public static void SampleAnalyzeSentiment(string textContent, Document.Types.Type type)
 {
     LanguageServiceClient languageServiceClient = LanguageServiceClient.Create();
     // string textContent = "I am so happy and joyful."
     // Document.Types.Type type = Document.Types.Type.PlainText
     AnalyzeSentimentRequest request = new AnalyzeSentimentRequest
     {
         Document = new Document
         {
             Type    = Document.Types.Type.PlainText,
             Content = "I am so happy and joyful.",
         },
     };
     AnalyzeSentimentResponse response = languageServiceClient.AnalyzeSentiment(request);
     // FIXME: inspect the results
 }
        /// <summary>Snippet for AnalyzeSentimentAsync</summary>
        public async Task AnalyzeSentimentRequestObjectAsync()
        {
            // Snippet: AnalyzeSentimentAsync(AnalyzeSentimentRequest, CallSettings)
            // Additional: AnalyzeSentimentAsync(AnalyzeSentimentRequest, CancellationToken)
            // Create client
            LanguageServiceClient languageServiceClient = await LanguageServiceClient.CreateAsync();

            // Initialize request argument(s)
            AnalyzeSentimentRequest request = new AnalyzeSentimentRequest
            {
                Document     = new Document(),
                EncodingType = EncodingType.None,
            };
            // Make the request
            AnalyzeSentimentResponse response = await languageServiceClient.AnalyzeSentimentAsync(request);

            // End snippet
        }
        // ToDo: reimplement based on the sentence offset - check if reliable
        public static DocumentBatchSentiment FromAnnotatedAnalyzeSentimentResponse(AnalyzeSentimentResponse analyzeSentimentResponse)
        {
            // list of scores for each document
            Dictionary <string, List <float> > documentSentiments = new Dictionary <string, List <float> >();
            var documentId = string.Empty;

            var sentenceEnumerator = analyzeSentimentResponse.Sentences.GetEnumerator();

            while (sentenceEnumerator.MoveNext())
            {
                // If the current sentence is the separator then the next one is the document ID
                // Extract the document ID and continue
                if (sentenceEnumerator.Current.Text.Content.Contains(DocumentBatchExtensions.DocumentSeparator))
                {
                    sentenceEnumerator.MoveNext();
                    documentId = sentenceEnumerator.Current.Text.Content;
                    continue;
                }

                // Id there is no current document ID then there is a problem in the sentences
                if (string.IsNullOrWhiteSpace(documentId))
                {
                    throw new Exception("Sentences are not anotated as expected!");
                }

                // Create a new list of scores for the current document if there is none
                if (!documentSentiments.ContainsKey(documentId))
                {
                    documentSentiments.Add(documentId, new List <float>());
                }

                documentSentiments[documentId].Add(sentenceEnumerator.Current.Sentiment.Score);
            }

            return(new DocumentBatchSentiment()
            {
                Documents = documentSentiments.Select(pair => new DocumentSentiment()
                {
                    Id = pair.Key,
                    Score = pair.Value.Average()
                }).ToList()
            });
        }
        public void AnalyzeSentiment2()
        {
            Mock <LanguageService.LanguageServiceClient> mockGrpcClient = new Mock <LanguageService.LanguageServiceClient>(MockBehavior.Strict);
            AnalyzeSentimentRequest request = new AnalyzeSentimentRequest
            {
                Document = new Document(),
            };
            AnalyzeSentimentResponse expectedResponse = new AnalyzeSentimentResponse
            {
                Language = "language-1613589672",
            };

            mockGrpcClient.Setup(x => x.AnalyzeSentiment(request, It.IsAny <CallOptions>()))
            .Returns(expectedResponse);
            LanguageServiceClient    client   = new LanguageServiceClientImpl(mockGrpcClient.Object, null);
            AnalyzeSentimentResponse response = client.AnalyzeSentiment(request);

            Assert.Same(expectedResponse, response);
            mockGrpcClient.VerifyAll();
        }
        public async Task AnalyzeSentimentAsync2()
        {
            Mock <LanguageService.LanguageServiceClient> mockGrpcClient = new Mock <LanguageService.LanguageServiceClient>(MockBehavior.Strict);
            AnalyzeSentimentRequest request = new AnalyzeSentimentRequest
            {
                Document = new Document(),
            };
            AnalyzeSentimentResponse expectedResponse = new AnalyzeSentimentResponse
            {
                Language = "language-1613589672",
            };

            mockGrpcClient.Setup(x => x.AnalyzeSentimentAsync(request, It.IsAny <CallOptions>()))
            .Returns(new Grpc.Core.AsyncUnaryCall <AnalyzeSentimentResponse>(Task.FromResult(expectedResponse), null, null, null, null));
            LanguageServiceClient    client   = new LanguageServiceClientImpl(mockGrpcClient.Object, null);
            AnalyzeSentimentResponse response = await client.AnalyzeSentimentAsync(request);

            Assert.Same(expectedResponse, response);
            mockGrpcClient.VerifyAll();
        }
        public void AnalyzeSentiment2()
        {
            moq::Mock <LanguageService.LanguageServiceClient> mockGrpcClient = new moq::Mock <LanguageService.LanguageServiceClient>(moq::MockBehavior.Strict);
            AnalyzeSentimentRequest request = new AnalyzeSentimentRequest
            {
                Document = new Document(),
            };
            AnalyzeSentimentResponse expectedResponse = new AnalyzeSentimentResponse
            {
                DocumentSentiment = new Sentiment(),
                Language          = "language7dae1285",
                Sentences         = { new Sentence(), },
            };

            mockGrpcClient.Setup(x => x.AnalyzeSentiment(request, moq::It.IsAny <grpccore::CallOptions>())).Returns(expectedResponse);
            LanguageServiceClient    client   = new LanguageServiceClientImpl(mockGrpcClient.Object, null);
            AnalyzeSentimentResponse response = client.AnalyzeSentiment(request.Document);

            xunit::Assert.Same(expectedResponse, response);
            mockGrpcClient.VerifyAll();
        }
        public static int Main(string[] args)
        {
            // Create client
            LanguageServiceClient client = LanguageServiceClient.Create();

            // Initialize request argument(s)
            Document document = new Document
            {
                Content = "Hello, world!",
                Type    = Document.Types.Type.PlainText,
            };

            // Call API method
            AnalyzeSentimentResponse response = client.AnalyzeSentiment(document);

            // Show the result
            Console.WriteLine(response);

            // Success
            Console.WriteLine("Smoke test passed OK");
            return(0);
        }
        public void AnalyzeSentiment_ValidQueryWithDocumentURL()
        {
            Document document = new Document(DocumentType.PLAIN_TEXT, googleCloudUri: VALID_DOC_URL);

            Task <Tuple <AnalyzeSentimentResponse, ResponseStatus> > response = nlIntelligence.AnalyzeSentiment(document, EncodingType.UTF8);

            response.Wait();

            Assert.IsNotNull(response.Result.Item1);
            Assert.AreEqual(response.Result.Item2, NaturalLanguageStatus.OK);

            AnalyzeSentimentResponse sentimentResponse = response.Result.Item1;

            Assert.IsNotNull(sentimentResponse.Sentences);
            Assert.GreaterOrEqual(sentimentResponse.Sentences.Count, 1);

            Assert.IsNotNull(sentimentResponse.Language);
            Assert.IsNotEmpty(sentimentResponse.Language);

            Assert.IsNotNull(sentimentResponse.Sentiment);
            Assert.GreaterOrEqual(sentimentResponse.Sentiment.Magnitude, 0);
            Assert.GreaterOrEqual(sentimentResponse.Sentiment.Score, -1);
            Assert.LessOrEqual(sentimentResponse.Sentiment.Score, 1);

            foreach (Sentence sentence in sentimentResponse.Sentences)
            {
                Assert.IsNotNull(sentence.Sentiment);

                Assert.GreaterOrEqual(sentence.Sentiment.Magnitude, 0);
                Assert.GreaterOrEqual(sentence.Sentiment.Score, -1);
                Assert.LessOrEqual(sentence.Sentiment.Score, 1);

                Assert.IsNotNull(sentence.Text);
                Assert.IsNotNull(sentence.Text.Content);
                Assert.GreaterOrEqual(sentence.Text.BeginOffset, 0);
            }
        }
        public async stt::Task AnalyzeSentiment2Async()
        {
            moq::Mock <LanguageService.LanguageServiceClient> mockGrpcClient = new moq::Mock <LanguageService.LanguageServiceClient>(moq::MockBehavior.Strict);
            AnalyzeSentimentRequest request = new AnalyzeSentimentRequest
            {
                Document = new Document(),
            };
            AnalyzeSentimentResponse expectedResponse = new AnalyzeSentimentResponse
            {
                DocumentSentiment = new Sentiment(),
                Language          = "language7dae1285",
                Sentences         = { new Sentence(), },
            };

            mockGrpcClient.Setup(x => x.AnalyzeSentimentAsync(request, moq::It.IsAny <grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall <AnalyzeSentimentResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
            LanguageServiceClient    client = new LanguageServiceClientImpl(mockGrpcClient.Object, null);
            AnalyzeSentimentResponse responseCallSettings = await client.AnalyzeSentimentAsync(request.Document, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));

            xunit::Assert.Same(expectedResponse, responseCallSettings);
            AnalyzeSentimentResponse responseCancellationToken = await client.AnalyzeSentimentAsync(request.Document, st::CancellationToken.None);

            xunit::Assert.Same(expectedResponse, responseCancellationToken);
            mockGrpcClient.VerifyAll();
        }
Ejemplo n.º 15
0
        public async static Task <Dictionary <string, object> > GoogleNaturalLanguageUnderstanding(AppSettings appSettings, string text)
        {
            string methodName = "GoogleNaturalLanguageUnderstanding";
            Dictionary <string, object> result = new Dictionary <string, object>();

            try
            {
                CommonService.SetGoogleCredentials(@"googleAI-Harima.json");
                var client = LanguageServiceClient.Create();
                AnalyzeSentimentResponse analyzeSentimentResponse = new AnalyzeSentimentResponse();
                try
                {
                    analyzeSentimentResponse = await client.AnalyzeSentimentAsync(new Document()
                    {
                        Content = text,
                        Type    = Document.Types.Type.PlainText
                    });
                }
                catch (Exception e)
                {
                    Log.Write(appSettings, LogEnum.ERROR.ToString(), label, className, methodName, $"ERROR: {text}");
                    Log.Write(appSettings, LogEnum.ERROR.ToString(), $"02{Assembly.GetExecutingAssembly().GetName().Name}", MethodBase.GetCurrentMethod().ReflectedType.Name, methodName, $"Watson error: {e.Source + Environment.NewLine + e.Message}");
                }

                AnalyzeEntitiesResponse analyzeEntitiesResponse = new AnalyzeEntitiesResponse();
                try
                {
                    analyzeEntitiesResponse = await client.AnalyzeEntitiesAsync(new Document()
                    {
                        Content = text,
                        Type    = Document.Types.Type.PlainText
                    });
                }
                catch (Exception e)
                {
                    Log.Write(appSettings, LogEnum.ERROR.ToString(), label, className, methodName, $"ERROR: {text}");
                    Log.Write(appSettings, LogEnum.ERROR.ToString(), $"02{Assembly.GetExecutingAssembly().GetName().Name}", MethodBase.GetCurrentMethod().ReflectedType.Name, methodName, $"Watson error: {e.Source + Environment.NewLine + e.Message}");
                }

                ClassifyTextResponse classifyTextResponse = new ClassifyTextResponse();
                try
                {
                    LanguageTranslatorRequest languageTranslatorRequest = new LanguageTranslatorRequest();
                    languageTranslatorRequest.Text   = text;
                    languageTranslatorRequest.Source = "es";
                    languageTranslatorRequest.Target = "en";
                    string translation = await LanguageTranslatorService.GoogleLanguageTranslator(appSettings, languageTranslatorRequest);

                    classifyTextResponse = await client.ClassifyTextAsync(new Document()
                    {
                        Content = translation,
                        Type    = Document.Types.Type.PlainText
                    });
                }
                catch (Exception e)
                {
                    Log.Write(appSettings, LogEnum.ERROR.ToString(), label, className, methodName, $"ERROR: {text}");
                    Log.Write(appSettings, LogEnum.ERROR.ToString(), $"02{Assembly.GetExecutingAssembly().GetName().Name}", MethodBase.GetCurrentMethod().ReflectedType.Name, methodName, $"Watson error: {e.Source + Environment.NewLine + e.Message}");
                }
                result["sentiment"] = analyzeSentimentResponse;
                result["entities"]  = analyzeEntitiesResponse;
                result["clasifiy"]  = classifyTextResponse;
                return(result);
            }
            catch (Exception e)
            {
                Log.Write(appSettings, LogEnum.ERROR.ToString(), label, className, methodName, $"ERROR: {text}");
                Log.Write(appSettings, LogEnum.ERROR.ToString(), label, className, methodName, $"ERROR: {e.Source + Environment.NewLine + e.Message + Environment.NewLine + e.StackTrace}");
                throw e;
            }
        }