Beispiel #1
0
        /// <summary>
        /// get emotionality of the text
        /// </summary>
        /// <param name="text">text to analyze</param>
        /// <returns>string with results</returns>
        public static string GetEmotionality(string text)
        {
            string language = DetectLanguage(text);


            BasicAWSCredentials credentials =
                new BasicAWSCredentials("there should be secret id", "there should be secret key");
            AmazonComprehendClient amazonComprehendClient =
                new AmazonComprehendClient(credentials, RegionEndpoint.EUCentral1);

            DetectSentimentRequest detectSentimenteRequest = new DetectSentimentRequest();

            detectSentimenteRequest.Text = text;

            try
            {
                detectSentimenteRequest.LanguageCode = language;
                Task <DetectSentimentResponse> result =
                    amazonComprehendClient.DetectSentimentAsync(detectSentimenteRequest);
                return($"Mixed:{String.Format("{0:f2}", result.Result.SentimentScore.Mixed)}\n" +
                       $"Positive:{String.Format("{0:f2}", result.Result.SentimentScore.Positive)}\n" +
                       $"Neutral:{String.Format("{0:f2}", result.Result.SentimentScore.Neutral)}\n" +
                       $"Negative:{String.Format("{0:f2}", result.Result.SentimentScore.Negative)}");
            }
            catch (Exception)
            {
                return("Language of your text is not supported yet");
            }
        }
        private async Task <Sentiment> GetSentimentFromAWSAsync(String customerContact)
        {
            Sentiment caseSentiment = new Sentiment();

            try
            {
                AmazonComprehendClient comprehendClient = new AmazonComprehendClient(RegionEndpoint.EUWest2);

                Console.WriteLine("Calling DetectSentiment");
                DetectSentimentRequest detectSentimentRequest = new DetectSentimentRequest()
                {
                    Text         = customerContact,
                    LanguageCode = "en"
                };
                DetectSentimentResponse detectSentimentResponse = await comprehendClient.DetectSentimentAsync(detectSentimentRequest);

                caseSentiment.success           = true;
                caseSentiment.sentimentRating   = detectSentimentResponse.Sentiment.ToString().ToLower();
                caseSentiment.sentimentMixed    = ((int)(detectSentimentResponse.SentimentScore.Mixed * 100)).ToString();
                caseSentiment.sentimentNegative = ((int)(detectSentimentResponse.SentimentScore.Negative * 100)).ToString();
                caseSentiment.sentimentNeutral  = ((int)(detectSentimentResponse.SentimentScore.Neutral * 100)).ToString();
                caseSentiment.sentimentPositive = ((int)(detectSentimentResponse.SentimentScore.Positive * 100)).ToString();
                return(caseSentiment);
            }
            catch (Exception error)
            {
                caseSentiment.success = false;
                await SendFailureAsync("Getting Sentiment", error.Message);

                Console.WriteLine("ERROR : GetSentimentFromAWSAsync : " + error.StackTrace);
                return(caseSentiment);
            }
        }
Beispiel #3
0
 public ComprehendMain(string key, string secret, RegionEndpoint region)
 {
     _AccessKey    = key;
     _AccessSecret = secret;
     _Region       = region;
     _Client       = new AmazonComprehendClient(_AccessKey, _AccessSecret, _Region);
 }
        public ComprehendClient(string endpoint)
        {
            AmazonComprehendConfig config = new AmazonComprehendConfig();

            _client   = new AmazonComprehendClient(config);
            _endpoint = endpoint;
        }
Beispiel #5
0
        static void Main(string[] args)
        {
            // Log into client with credentials
            AmazonComprehendClient client = new AmazonComprehendClient(Amazon.RegionEndpoint.USEast1);

            // Load XML doc
            XmlDocument xmlDoc = new XmlDocument();

            xmlDoc.Load("phrases.xml");
            XmlElement  rootElement   = xmlDoc.DocumentElement;
            XmlNodeList rootsChildren = rootElement.ChildNodes;

            foreach (XmlNode node in rootsChildren)
            {
                DetectKeyPhrasesRequest request = new DetectKeyPhrasesRequest
                {
                    Text         = node.InnerText,
                    LanguageCode = "en"
                };

                DetectKeyPhrasesResponse response = client.DetectKeyPhrases(request);
                Console.WriteLine(node.InnerText);
                foreach (KeyPhrase kp in response.KeyPhrases)
                {
                    Console.Write("\t" + kp.Text + " (" + kp.Score + ") \n");
                }
                Console.WriteLine();
            }

            Console.ReadLine();
        }
Beispiel #6
0
        static void ComprehendInputFile(string fileName)
        {
            var inputText = File.ReadAllText(fileName);

            var comprehendClient = new AmazonComprehendClient(Amazon.RegionEndpoint.EUWest1);

            Console.WriteLine("Calling DetectDominantLanguage\n");
            var text1 = DetectDominantLanguage(inputText, comprehendClient);

            Console.WriteLine("Calling DetectEntities\n");
            var text2 = DetectEntities(inputText, comprehendClient);

            Console.WriteLine("Calling DetectKeyPhrases\n");
            var text3 = DetectKeyPhrases(inputText, comprehendClient);

            Console.WriteLine("Calling DetectSentiment\n");
            var text4 = DetectSentiment(inputText, comprehendClient);

            var outputBuilder = new StringBuilder();

            outputBuilder.AppendLine(text1);
            outputBuilder.AppendLine(text2);
            outputBuilder.AppendLine(text3);
            outputBuilder.AppendLine(text4);

            var outputFileName = fileName.Replace(Path.GetExtension(fileName), "_comprehend.txt");

            File.WriteAllText(outputFileName, outputBuilder.ToString());
        }
Beispiel #7
0
        private static string DetectEntities(string text, AmazonComprehendClient comprehendClient)
        {
            var stringBuilder = new StringBuilder();

            var detectEntitiesRequest = new DetectEntitiesRequest()
            {
                Text         = text,
                LanguageCode = "en"
            };

            var detectEntitiesResponse = comprehendClient.DetectEntities(detectEntitiesRequest);

            stringBuilder.AppendLine("Detect Entities:");
            stringBuilder.AppendLine("==========================");

            foreach (var entity in detectEntitiesResponse.Entities)
            {
                stringBuilder.AppendLine(string.Format("Text: {0}, Type: {1}, Score: {2}, BeginOffset: {3}, EndOffset: {4}",
                                                       entity.Text, entity.Type, entity.Score, entity.BeginOffset, entity.EndOffset));
            }

            Console.WriteLine("DetectEntities => Done\n");

            return(stringBuilder.ToString());
        }
Beispiel #8
0
        public override void Invoke(AWSCredentials creds, RegionEndpoint region, int maxItems)
        {
            AmazonComprehendConfig config = new AmazonComprehendConfig();

            config.RegionEndpoint = region;
            ConfigureClient(config);
            AmazonComprehendClient client = new AmazonComprehendClient(creds, config);

            ListTopicsDetectionJobsResponse resp = new ListTopicsDetectionJobsResponse();

            do
            {
                ListTopicsDetectionJobsRequest req = new ListTopicsDetectionJobsRequest
                {
                    NextToken = resp.NextToken
                    ,
                    MaxResults = maxItems
                };

                resp = client.ListTopicsDetectionJobs(req);
                CheckError(resp.HttpStatusCode, "200");

                foreach (var obj in resp.TopicsDetectionJobPropertiesList)
                {
                    AddObject(obj);
                }
            }while (!string.IsNullOrEmpty(resp.NextToken));
        }
        public async Task GetSentiment(CsvWriter writer, IEnumerable <Submission> sentiments)
        {
            var comprehendClient = new AmazonComprehendClient(Amazon.RegionEndpoint.EUWest1);

            foreach (var submission in sentiments)
            {
                // Call DetectKeyPhrases API
                var detectSentimentRequest = new DetectSentimentRequest
                {
                    Text         = submission.title,
                    LanguageCode = "en"
                };
                var detectSentimentResponse = await comprehendClient.DetectSentimentAsync(detectSentimentRequest);

                var score     = detectSentimentResponse.SentimentScore;
                var sentiment = new Sentiment
                {
                    time     = submission.CreatedUtc,
                    title    = submission.title,
                    positive = score.Positive,
                    neutral  = score.Neutral,
                    negative = score.Negative,
                    mixed    = score.Mixed,
                };
                Console.WriteLine($"Processing {submission.CreatedUtc} {submission.title}");
                Console.WriteLine($"Score +ve {sentiment.positive} -- {sentiment.neutral} -ve {sentiment.negative} mixed {sentiment.mixed}");
                writer.WriteRecord(sentiment);
                writer.NextRecord();
                writer.Flush();
            }
        }
Beispiel #10
0
        private List <string> DetectKeyPhrases(string text)
        {
            List <string> keyPhrases = new List <string>();

            if (text.Length > 2500)
            {
                text = text.Substring(0, 2499);
            }

            AmazonComprehendClient comprehendClient = new AmazonComprehendClient(AWS_KEY, AWS_SECRET, Amazon.RegionEndpoint.USWest2);

            // Call DetectKeyPhrases API
            Console.WriteLine("Calling DetectKeyPhrases");
            DetectKeyPhrasesRequest detectKeyPhrasesRequest = new DetectKeyPhrasesRequest()
            {
                Text         = text,
                LanguageCode = "en"
            };

            DetectKeyPhrasesResponse detectKeyPhrasesResponse = comprehendClient.DetectKeyPhrasesAsync(detectKeyPhrasesRequest).Result;

            if (detectKeyPhrasesResponse.HttpStatusCode == System.Net.HttpStatusCode.OK && detectKeyPhrasesResponse.KeyPhrases != null)
            {
                keyPhrases = (from kp in detectKeyPhrasesResponse.KeyPhrases
                              where kp.Score >= MINIMUM_THRESHOLD_SCORE
                              select kp.Text).ToList();
            }

            return(keyPhrases);
        }
Beispiel #11
0
        public DataTable Sentiment(string Text, string Encoding = "en")
        {
            DataTable DT = new DataTable();

            DT.TableName = "Sentiment";
            DT.Columns.Add("Sentiment", typeof(string));
            DT.Columns.Add("Mixed", typeof(float));
            DT.Columns.Add("Positive", typeof(float));
            DT.Columns.Add("Neutral", typeof(float));
            DT.Columns.Add("Negative", typeof(float));
            DetectSentimentRequest request = new DetectSentimentRequest();

            request.LanguageCode = Encoding;
            request.Text         = Text;
            AmazonComprehendClient client = new AmazonComprehendClient(AccessKeyId, SecretAccessKey, Amazon.RegionEndpoint.USWest2);
            var RES = client.DetectSentiment(request);
            var dr  = DT.NewRow();

            dr["Sentiment"] = RES.Sentiment.Value;
            dr["Mixed"]     = RES.SentimentScore.Mixed;
            dr["Positive"]  = RES.SentimentScore.Positive;
            dr["Neutral"]   = RES.SentimentScore.Neutral;
            dr["Negative"]  = RES.SentimentScore.Negative;
            DT.Rows.Add(dr);
            return(DT);
        }
        public async Task <JsonResult> Post(string commentText)
        {
            try
            {
                using (var comprehendClient = new AmazonComprehendClient(Amazon.RegionEndpoint.USEast1))
                {
                    var sentimentResults = await comprehendClient.DetectSentimentAsync(
                        new DetectSentimentRequest()
                    {
                        Text         = commentText,
                        LanguageCode = LanguageCode.En
                    });

                    if (sentimentResults.Sentiment.Value == "NEGATIVE")
                    {
                        using (var snsClient = new AmazonSimpleNotificationServiceClient(Amazon.RegionEndpoint.USEast1))
                        {
                            var response = await snsClient.PublishAsync(new PublishRequest()
                            {
                                Subject   = "Negative Comment",
                                Message   = $"Someone posted this negative comment on your blog. Check it out - {Environment.NewLine} ***** {Environment.NewLine} {commentText} {Environment.NewLine} ***** ",
                                TargetArn = "arn:aws:sns:us-east-1:831210339789:CommentNotifier"
                            });
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                return(new JsonResult(ex.Message));
            }

            return(new JsonResult("Post Successful"));
        }
Beispiel #13
0
 public SentimentMessageProcessor(DiscordClient discordClient,
                                  CloudWatchMetrics metrics,
                                  ILogger <AbstractDiscordMessageProcessor> logger,
                                  AmazonComprehendClient amazonComprehendClient) : base(discordClient, metrics, logger)
 {
     AmazonComprehendClient = amazonComprehendClient;
 }
        public async Task ReceiveQueue(SQSEvent input, ILambdaContext context)
        {
            var messageBody = JsonConvert.DeserializeObject <CommentsQueueRequest>(input.Records[0].Body);

            //DETECT LANGUAGE

            var comprehendClient = new AmazonComprehendClient(Amazon.RegionEndpoint.EUCentral1);

            var detectDominantLanguageRequest = new DetectDominantLanguageRequest
            {
                Text = messageBody.Comment
            };

            var detectDominantLanguageResponse = await comprehendClient.DetectDominantLanguageAsync(detectDominantLanguageRequest);

            if (detectDominantLanguageResponse.HttpStatusCode != HttpStatusCode.OK)
            {
                throw new Exception("NOT FOUND");
            }

            var languageResponse = detectDominantLanguageResponse.Languages.OrderByDescending((x) => x.Score).FirstOrDefault();

            //UPDATE DOCUMENT

            var dynamoDBClient  = new AmazonDynamoDBClient();
            var commentsCatalog = Table.LoadTable(dynamoDBClient, Environment.GetEnvironmentVariable("DBTableName"));

            var commentDocument = new Document();

            commentDocument["id"]       = messageBody.Id;
            commentDocument["language"] = languageResponse.LanguageCode;

            var updatedComment = await commentsCatalog.UpdateItemAsync(commentDocument);
        }
        public static void Sample()
        {
            var comprehendClient = new AmazonComprehendClient(Amazon.RegionEndpoint.USWest2);

            var textList = new List <String>()
            {
                { "I love Seattle" },
                { "Today is Sunday" },
                { "Tomorrow is Monday" },
                { "I love Seattle" }
            };

            // Call detectEntities API
            Console.WriteLine("Calling BatchDetectEntities");
            var batchDetectEntitiesRequest = new BatchDetectEntitiesRequest()
            {
                TextList     = textList,
                LanguageCode = "en"
            };
            var batchDetectEntitiesResponse = comprehendClient.BatchDetectEntities(batchDetectEntitiesRequest);

            foreach (var item in batchDetectEntitiesResponse.ResultList)
            {
                Console.WriteLine("Entities in {0}:", textList[item.Index]);
                foreach (Entity entity in item.Entities)
                {
                    PrintEntity(entity);
                }
            }

            // check if we need to retry failed requests
            if (batchDetectEntitiesResponse.ErrorList.Count != 0)
            {
                Console.WriteLine("Retrying Failed Requests");
                var textToRetry = new List <String>();
                foreach (var errorItem in batchDetectEntitiesResponse.ErrorList)
                {
                    textToRetry.Add(textList[errorItem.Index]);
                }

                batchDetectEntitiesRequest = new BatchDetectEntitiesRequest()
                {
                    TextList     = textToRetry,
                    LanguageCode = "en"
                };

                batchDetectEntitiesResponse = comprehendClient.BatchDetectEntities(batchDetectEntitiesRequest);

                foreach (var item in batchDetectEntitiesResponse.ResultList)
                {
                    Console.WriteLine("Entities in {0}:", textList[item.Index]);
                    foreach (var entity in item.Entities)
                    {
                        PrintEntity(entity);
                    }
                }
            }
            Console.WriteLine("End of DetectEntities");
        }
Beispiel #16
0
        public static string getKeyPhrases(string mailbody)
        {
            var client = AuthenticateClient();
            var result = client.KeyPhrases(mailbody);

            List <string> lkeyPhrases   = new List <string>();
            string        strKeyPhrases = string.Empty;

            foreach (string kp in result.KeyPhrases)
            {
                lkeyPhrases.Add(kp);
            }

            AmazonComprehendClient comprehendClient = new AmazonComprehendClient(Amazon.RegionEndpoint.USWest2);

            DetectSyntaxRequest dsr = new DetectSyntaxRequest()
            {
                Text         = mailbody,
                LanguageCode = "en"
            };
            DetectSyntaxResponse dsrsp           = comprehendClient.DetectSyntax(dsr);
            List <string>        adjectives      = new List <string>();
            List <string>        finalKeyPhrases = new List <string>();

            foreach (SyntaxToken kp in dsrsp.SyntaxTokens)
            {
                if (kp.PartOfSpeech.Tag.Equals("ADJ"))
                {
                    adjectives.Add(kp.Text);
                }
            }
            foreach (var adj in adjectives)
            {
                foreach (var phs in lkeyPhrases)
                {
                    if (phs.Contains(adj))
                    {
                        finalKeyPhrases.Add(phs);
                    }
                }
            }
            string str = "";

            foreach (var fnlKeyPhr in finalKeyPhrases)
            {
                str = str + ' ' + fnlKeyPhr + ' ' + '/';
            }



            var values = new object[2];

            values[0] = "Key Phrases";
            values[1] = str.Substring(0, str.Length - 1);
            return(str.Substring(0, str.Length - 1));
        }
Beispiel #17
0
        public DataTable KeyPhrases(string Text, string Encoding = "en")
        {
            DataTable DT = null;
            DetectKeyPhrasesRequest request = new DetectKeyPhrasesRequest();

            request.LanguageCode = Encoding;
            request.Text         = Text;
            AmazonComprehendClient client = new AmazonComprehendClient(AccessKeyId, SecretAccessKey, Amazon.RegionEndpoint.USWest2);
            var RES = client.DetectKeyPhrases(request);

            DT           = FromEntity(RES.KeyPhrases);
            DT.TableName = "KeyPhrases";
            return(DT);
        }
Beispiel #18
0
        protected IAmazonComprehend CreateClient(AWSCredentials credentials, RegionEndpoint region)
        {
            var config = new AmazonComprehendConfig {
                RegionEndpoint = region
            };

            Amazon.PowerShell.Utils.Common.PopulateConfig(this, config);
            this.CustomizeClientConfig(config);
            var client = new AmazonComprehendClient(credentials, config);

            client.BeforeRequestEvent += RequestEventHandler;
            client.AfterResponseEvent += ResponseEventHandler;
            return(client);
        }
Beispiel #19
0
        private void getKeyPhrases(string mailbody)
        {
            const string collectionUri = "https://dev.azure.com/codeletehackathon";
            const string projectName   = "secondproject";
            const string repoName      = "secondproject";
            const string pat           = "4rm4d2q2wq452n7ce2mqgfj4yyqajoipmez63nvxoveijuphckxq";

            var creds = new VssBasicCredential(string.Empty, pat);

            // Connect to Azure DevOps Services
            var connection = new VssConnection(new Uri(collectionUri), creds);

            // Get a GitHttpClient to talk to the Git endpoints
            var gitClient = connection.GetClient <GitHttpClient>();

            // Get data about a specific repository
            var    repo           = gitClient.GetRepositoryAsync(projectName, repoName).Result;
            var    repoid         = repo.Id;
            string collectionuris = "https://dev.azure.com/codeletehackathon/secondproject/_apis/git/repositories/506f6d44-0a42-4a10-9f75-c89c450c3740/commits?api-version=6.0";

            //String text = "Thank you for helping your project manager, Angela Parmar, on the latest project. Your work reflects your dedication to the project and the organisation.";

            AmazonComprehendClient comprehendClient = new AmazonComprehendClient(Amazon.RegionEndpoint.USWest2);

            // Call DetectKeyPhrases API
            Console.WriteLine("Calling DetectKeyPhrases");
            DetectKeyPhrasesRequest detectKeyPhrasesRequest = new DetectKeyPhrasesRequest()
            {
                Text         = mailbody,
                LanguageCode = "en"
            };
            DetectKeyPhrasesResponse detectKeyPhrasesResponse = comprehendClient.DetectKeyPhrases(detectKeyPhrasesRequest);
            DetectSyntaxRequest      dsr;
            DetectSyntaxResponse     dsresp;
            List <string>            lkeyPhrases = new List <string>();
            string strKeyPhrases = string.Empty;

            foreach (KeyPhrase kp in detectKeyPhrasesResponse.KeyPhrases)
            {
                lkeyPhrases.Add(kp.Text);
                strKeyPhrases = strKeyPhrases + ',' + kp.Text;
            }
            var values = new object[2];

            values[0] = "Key Phrases";
            values[1] = strKeyPhrases.Substring(1);
            dtTextAnalytic.Rows.Add(values);
            Console.WriteLine("Done");
        }
Beispiel #20
0
        /// <summary>
        /// detect language of the text
        /// </summary>
        /// <param name="text">text to analyze</param>
        /// <returns>code of language</returns>
        public static string DetectLanguage(string text)
        {
            BasicAWSCredentials credentials =
                new BasicAWSCredentials("there should be secret id", "there should be secret key");
            AmazonComprehendClient amazonComprehendClient =
                new AmazonComprehendClient(credentials, RegionEndpoint.EUCentral1);

            DetectDominantLanguageRequest detectLanguageRequest = new DetectDominantLanguageRequest();

            detectLanguageRequest.Text = text;

            Task <DetectDominantLanguageResponse> lang =
                amazonComprehendClient.DetectDominantLanguageAsync(detectLanguageRequest);

            return(lang.Result.Languages[0].LanguageCode);
        }
Beispiel #21
0
        static void Main(string[] args)
        {
            // Log into client with credentials
            AmazonComprehendClient client = new AmazonComprehendClient(Amazon.RegionEndpoint.USEast1);

            // Load XML doc
            XmlDocument xmlDoc = new XmlDocument();

            xmlDoc.Load("phrases_old.xml");
            XmlElement  rootElement   = xmlDoc.DocumentElement;
            XmlNodeList rootsChildren = rootElement.ChildNodes;

            // List of language codes
            List <string> languageCodes = new List <string>();

            // Iterate over each child and send request to detect language for inner text of each node
            foreach (XmlNode node in rootsChildren)
            {
                DetectDominantLanguageRequest request = new DetectDominantLanguageRequest
                {
                    Text = node.InnerText
                };

                DetectDominantLanguageResponse response = client.DetectDominantLanguage(request);

                string test = string.Empty;

                // Add language found for each child statement to list
                foreach (DominantLanguage language in response.Languages)
                {
                    test += language.LanguageCode + ", ";
                }
                languageCodes.Add(test);
            }

            // print results of language found
            int i = 0;

            foreach (XmlNode node in rootsChildren)
            {
                Console.Write("Phrase " + node.Attributes[0].Name + ": " + node.Attributes[0].Value + "      ");
                Console.WriteLine(node.Attributes[1].Value + " : " + languageCodes[i].Substring(0, languageCodes[i].Length - 2));
                i++;
            }

            Console.ReadLine();
        }
Beispiel #22
0
        public static void Sample()
        {
            var comprehendClient = new AmazonComprehendClient(Amazon.RegionEndpoint.USWest2);

            String      inputS3Uri        = "s3://input bucket/input path";
            InputFormat inputDocFormat    = InputFormat.ONE_DOC_PER_FILE;
            String      outputS3Uri       = "s3://output bucket/output path";
            String      dataAccessRoleArn = "arn:aws:iam::account ID:role/data access role";
            int         numberOfTopics    = 10;

            var startTopicsDetectionJobRequest = new StartTopicsDetectionJobRequest()
            {
                InputDataConfig = new InputDataConfig()
                {
                    S3Uri       = inputS3Uri,
                    InputFormat = inputDocFormat
                },
                OutputDataConfig = new OutputDataConfig()
                {
                    S3Uri = outputS3Uri
                },
                DataAccessRoleArn = dataAccessRoleArn,
                NumberOfTopics    = numberOfTopics
            };

            var startTopicsDetectionJobResponse = comprehendClient.StartTopicsDetectionJob(startTopicsDetectionJobRequest);

            var jobId = startTopicsDetectionJobResponse.JobId;

            Console.WriteLine("JobId: " + jobId);

            var describeTopicsDetectionJobRequest = new DescribeTopicsDetectionJobRequest()
            {
                JobId = jobId
            };

            var describeTopicsDetectionJobResponse = comprehendClient.DescribeTopicsDetectionJob(describeTopicsDetectionJobRequest);

            PrintJobProperties(describeTopicsDetectionJobResponse.TopicsDetectionJobProperties);

            var listTopicsDetectionJobsResponse = comprehendClient.ListTopicsDetectionJobs(new ListTopicsDetectionJobsRequest());

            foreach (var props in listTopicsDetectionJobsResponse.TopicsDetectionJobPropertiesList)
            {
                PrintJobProperties(props);
            }
        }
        public static void Sample()
        {
            String text = "It is raining today in Seattle";

            var comprehendClient = new AmazonComprehendClient(Amazon.RegionEndpoint.USWest2);

            // Call DetectKeyPhrases API
            Console.WriteLine("Calling DetectSentiment");
            var detectSentimentRequest = new DetectSentimentRequest()
            {
                Text         = text,
                LanguageCode = "en"
            };
            var detectSentimentResponse = comprehendClient.DetectSentiment(detectSentimentRequest);

            Console.WriteLine(detectSentimentResponse.Sentiment);
            Console.WriteLine("Done");
        }
Beispiel #24
0
        /// <summary>
        /// This method calls the DetetectSentimentAsync method to analyze the
        /// supplied text and determine the overal sentiment.
        /// </summary>
        public static async Task Main()
        {
            string text = "It is raining today in Seattle";

            var comprehendClient = new AmazonComprehendClient(Amazon.RegionEndpoint.USWest2);

            // Call DetectKeyPhrases API
            Console.WriteLine("Calling DetectSentiment");
            var detectSentimentRequest = new DetectSentimentRequest()
            {
                Text         = text,
                LanguageCode = "en",
            };
            var detectSentimentResponse = await comprehendClient.DetectSentimentAsync(detectSentimentRequest);

            Console.WriteLine($"Sentiment: {detectSentimentResponse.Sentiment}");
            Console.WriteLine("Done");
        }
Beispiel #25
0
        static void Main(string[] args)
        {
            String text = ExtFunc.Read("Input a text to Sentiment-Analysation i.E \"That was a nice trip. The Hotel was amazing!\"");

            AmazonComprehendClient comprehendClient = new AmazonComprehendClient(
                Amazon.RegionEndpoint.USEast1);

            // Call DetectKeyPhrases API
            Console.WriteLine("Calling DetectSentiment");
            DetectSentimentRequest detectSentimentRequest = new DetectSentimentRequest()
            {
                Text         = text,
                LanguageCode = "en"
            };
            DetectSentimentResponse detectSentimentResponse = comprehendClient.DetectSentiment(detectSentimentRequest);

            Console.WriteLine(detectSentimentResponse.Sentiment);
            Console.WriteLine("Done");
        }
Beispiel #26
0
        private async Task <string> GetComprehendData(string transcriptText, string key)
        {
            JObject transcriptJSON        = JObject.Parse(transcriptText);
            string  test                  = (string)transcriptJSON["Text"];
            AmazonComprehendClient client = new AmazonComprehendClient();


            DetectEntitiesRequest entitiesRequest = new DetectEntitiesRequest();

            entitiesRequest.LanguageCode = LanguageCode.En;
            entitiesRequest.Text         = test;



            DetectSentimentRequest sentimentRequest = new DetectSentimentRequest();

            sentimentRequest.LanguageCode = LanguageCode.En;
            sentimentRequest.Text         = test;

            DetectKeyPhrasesRequest keyPhrasesRequest = new DetectKeyPhrasesRequest();

            keyPhrasesRequest.LanguageCode = LanguageCode.En;
            keyPhrasesRequest.Text         = test;

            DetectEntitiesResponse entitiesResponse = await client.DetectEntitiesAsync(entitiesRequest);

            DetectSentimentResponse setimentResponse = await client.DetectSentimentAsync(sentimentRequest);

            DetectKeyPhrasesResponse keyPhrasesResponse = await client.DetectKeyPhrasesAsync(keyPhrasesRequest);


            CreateKeyPhraseCSV(key, keyPhrasesResponse);
            CreateSetimentJSON(key, setimentResponse);



            //now send the file to s3

            //we need to write two different files, one for setiment and one for Key Phrases.

            return(string.Empty);
        }
        public static void Sample()
        {
            String text = "It is raining today in Seattle";

            var comprehendClient = new AmazonComprehendClient(Amazon.RegionEndpoint.USWest2);

            // Call DetectDominantLanguage API
            Console.WriteLine("Calling DetectDominantLanguage\n");
            var detectDominantLanguageRequest = new DetectDominantLanguageRequest()
            {
                Text = text
            };
            var detectDominantLanguageResponse = comprehendClient.DetectDominantLanguage(detectDominantLanguageRequest);

            foreach (var dl in detectDominantLanguageResponse.Languages)
            {
                Console.WriteLine("Language Code: {0}, Score: {1}", dl.LanguageCode, dl.Score);
            }
            Console.WriteLine("Done");
        }
Beispiel #28
0
        /// <summary>
        /// The main method calls the DetectEntitiesAsync method to find any
        /// entities in the sample code.
        /// </summary>
        public static async Task Main()
        {
            string text = "It is raining today in Seattle";

            var comprehendClient = new AmazonComprehendClient();

            Console.WriteLine("Calling DetectEntities\n");
            var detectEntitiesRequest = new DetectEntitiesRequest()
            {
                Text         = text,
                LanguageCode = "en",
            };
            var detectEntitiesResponse = await comprehendClient.DetectEntitiesAsync(detectEntitiesRequest);

            foreach (var e in detectEntitiesResponse.Entities)
            {
                Console.WriteLine($"Text: {e.Text}, Type: {e.Type}, Score: {e.Score}, BeginOffset: {e.BeginOffset}, EndOffset: {e.EndOffset}");
            }

            Console.WriteLine("Done");
        }
Beispiel #29
0
        private static string DetectSentiment(string text, AmazonComprehendClient comprehendClient)
        {
            var stringBuilder = new StringBuilder();

            var detectSentimentRequest = new DetectSentimentRequest()
            {
                Text         = text,
                LanguageCode = "en"
            };

            var detectSentimentResponse = comprehendClient.DetectSentiment(detectSentimentRequest);

            stringBuilder.AppendLine("Detect Sentiment:");
            stringBuilder.AppendLine("==========================");

            stringBuilder.AppendLine(detectSentimentResponse.Sentiment);

            Console.WriteLine("DetectSentiment => Done\n");

            return(stringBuilder.ToString());
        }
Beispiel #30
0
        /// <summary>
        /// Calls Amazon Comprehend to determine the dominant language used in
        /// the sample text.
        /// </summary>
        public static async Task Main()
        {
            string text = "It is raining today in Seattle.";

            var comprehendClient = new AmazonComprehendClient(Amazon.RegionEndpoint.USWest2);

            Console.WriteLine("Calling DetectDominantLanguage\n");
            var detectDominantLanguageRequest = new DetectDominantLanguageRequest()
            {
                Text = text,
            };

            var detectDominantLanguageResponse = await comprehendClient.DetectDominantLanguageAsync(detectDominantLanguageRequest);

            foreach (var dl in detectDominantLanguageResponse.Languages)
            {
                Console.WriteLine($"Language Code: {dl.LanguageCode}, Score: {dl.Score}");
            }

            Console.WriteLine("Done");
        }