コード例 #1
0
        public void SentimentAnalysis_Negative_Sentiment()
        {
            string         textToAnalyse = @"@talk2GLOBE Why can't I use my postpaid line as a billing method for Google Play?";
            SentimentScore score         = Analyze(textToAnalyse);

            Assert.AreEqual(SentimentScore.Negative, score);
        }
コード例 #2
0
        public void SentimentAnalysis_Neutral_Sentiment()
        {
            string         textToAnalyse = @"Maven Wave Partners is looking for: Google Deployment Lead https://t.co/LJPPQL6pkV #job";
            SentimentScore score         = Analyze(textToAnalyse);

            Assert.AreEqual(SentimentScore.Neutral, score);
        }
コード例 #3
0
        // private static readonly HttpClient SingleClient = new HttpClient();

        // If your activity returns a value, derive from CodeActivity<TResult>
        // and return the value from the Execute method.
        protected override void Execute(NativeActivityContext context)
        {
            var    text     = Text.Get(context);
            string filePath = File_Path.Get(context);
            string apiKey   = API_KEY.Get(context);

            if (filePath != null)
            {
                var credential = GoogleCredential.FromFile(filePath).CreateScoped(LanguageServiceClient.DefaultScopes);
                var channel    = new Grpc.Core.Channel(LanguageServiceClient.DefaultEndpoint.ToString(), credential.ToChannelCredentials());

                var client = LanguageServiceClient.Create(channel);

                var response = client.AnalyzeSentiment(new Document()
                {
                    Content = text,
                    Type    = Document.Types.Type.PlainText
                });

                var sentiment = response.DocumentSentiment;

                // Console.WriteLine($"Score: {sentiment.Score}");
                // Console.WriteLine($"Magnitude: {sentiment.Magnitude}");

                SentimentScore.Set(context, sentiment.Score);
                SentimentMagnitude.Set(context, sentiment.Magnitude);
            }

            else if (apiKey != null)
            {
                // @TODO Authentication using API Key [Work in progress]
                var nlp_base_url = "https://language.googleapis.com/v1beta2/";
                var operation    = "documents:analyzeSentiment";
                var key          = "?key=" + API_KEY.Get(context);


                var request_url = nlp_base_url + operation + key;

                object content = new
                {
                    document = new
                    {
                        content = text,
                        type    = "PLAIN_TEXT"
                    },
                    encodingType = "UTF8"
                };


                Task <(HttpResponseMessage, String)> response_message = Task.Run(() => PostBasicAsync(request_url, content));
                response_message.Wait();
                (HttpResponseMessage result_json, String stringContent) = response_message.Result;

                // string request_content = stringContent.ReadAsStringAsync().Result;

                // ContentBody.Set(context, "\nStringContent - \n" + stringContent);

                GoogleNLPResponseMessage.Set(context, result_json);
            }
        }
コード例 #4
0
        public void SentimentAnalysis_Positive_Sentiment()
        {
            string         textToAnalyse = @"That was..Interesting. I mean I love Google photos .. but yes.. interesting, especially when Japan is mostly iPhone. https://t.co/0WsJnGzUyy";
            SentimentScore score         = Analyze(textToAnalyse);

            Assert.AreEqual(SentimentScore.Positive, score);
        }
コード例 #5
0
 private static SentimentScoreResponse Map(SentimentScore score)
 {
     return new SentimentScoreResponse
     {
         Label = score.Label,
         Score = score.Score?.ToDictionary(x => x.Key, x => x.Value)
     };
 }
コード例 #6
0
        static SentimentScore Analyze(string textToAnalyze)
        {
            SentimentScore ret = new SentimentScore();

            try
            {
                string url = string.Format("http://www.sentiment140.com/api/classify?text={0}",
                                           HttpUtility.UrlEncode(textToAnalyze, Encoding.UTF8));
                var response = HttpWebRequest.Create(url).GetResponse();

                using (var streamReader = new StreamReader(response.GetResponseStream()))
                {
                    try
                    {
                        // Read from source
                        var line = streamReader.ReadLine();

                        // Parse
                        var jObject = JObject.Parse(line);

                        int polarity = jObject.SelectToken("results", true).SelectToken("polarity", true).Value <int>();
                        switch (polarity)
                        {
                        case 0: ret.Score = SentimentScore.score.Negative;
                            ret.Sentiment = "Negative";
                            break;

                        case 4: ret.Score = SentimentScore.score.Positive;
                            ret.Sentiment = "Positive";
                            break;

                        // 2 or others
                        default: ret.Score = SentimentScore.score.Neutral;
                            ret.Sentiment  = "Neutral";
                            break;
                        }
                    }
                    catch (Exception)
                    {
                        ret.Score     = SentimentScore.score.Neutral;
                        ret.Sentiment = "Neutral";
                        return(ret);
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Sentiment calculation FAILED with:/n{0}", e);
                ret.Score     = SentimentScore.score.Neutral;
                ret.Sentiment = "Neutral";
                return(ret);
            }
            return(ret);
        }
コード例 #7
0
        public static Dictionary <string, double> GetScore(this SentimentScore sentimentScore)
        {
            var map = new Dictionary <string, double>
            {
                { KnownSentiment.Positive, sentimentScore.Positive },
                { KnownSentiment.Negative, sentimentScore.Negative },
                { KnownSentiment.Mixed, sentimentScore.Mixed },
                { KnownSentiment.Neutral, sentimentScore.Neutral }
            };

            return(map);
        }
コード例 #8
0
ファイル: SentimentService.cs プロジェクト: Valchris/ddbot
        public async Task <List <SentimentScore> > AnalyzeMessage(List <SentimentMessage> messages)
        {
            var inputs = new List <MultiLanguageInput>();
            var i      = 0;

            foreach (var msg in messages)
            {
                inputs.Add(new MultiLanguageInput("en", (i++).ToString(), msg.Content));
            }

            SentimentBatchResult result = await client.SentimentAsync(new MultiLanguageBatchInput(inputs));

            List <SentimentScore> output = new List <SentimentScore>();


            i = 0;
            if (result?.Documents != null)
            {
                foreach (var document in result.Documents)
                {
                    var latestScore = new SentimentScore()
                    {
                        Author    = messages[i].Author,
                        AuthorId  = messages[i].AuthorId,
                        ChannelId = messages[i].ChannelId,
                        Score     = result.Documents[i].Score ?? -1,
                        Timestamp = messages[i].Timestamp
                    };
                    i++;

                    output.Add(latestScore);
                    Console.WriteLine($"Score logged: {latestScore.Author}: {latestScore.Score}. Channel: {latestScore.ChannelId}, Timestamp: {latestScore.Timestamp}");
                }
            }
            else
            {
                Console.WriteLine($"Invalid results from sentiment service: {result?.Documents}");
            }

            return(output);
        }
コード例 #9
0
        public SentimentHistoryService(Config config)
        {
            this.semaphore = new SemaphoreSlim(1);
            this.scores    = new Dictionary <string, LinkedList <SentimentScore> >();
            this.config    = config;

            semaphore.Wait();
            try
            {
                // bootstrap existing data
                if (File.Exists(DataFilePath))
                {
                    var dbLines = File.ReadAllLines(DataFilePath);
                    foreach (var line in dbLines)
                    {
                        var parts = line.Split('\t');
                        if (parts.Length == 5)
                        {
                            var score = new SentimentScore()
                            {
                                Author    = parts[0],
                                AuthorId  = ulong.Parse(parts[1]),
                                ChannelId = ulong.Parse(parts[2]),
                                Score     = double.Parse(parts[3]),
                                Timestamp = DateTime.Parse(parts[4])
                            };
                            var list = this.CreateListIfNeeded(score.ChannelId.ToString());
                            list.AddLast(score);
                        }
                        else
                        {
                            Console.WriteLine($"Invalid bootstrap data in {DataFilePath}, data: {line}");
                        }
                    }
                }
            }
            finally
            {
                semaphore.Release();
            }
        }
コード例 #10
0
 /// <summary>
 /// Creates new instance of <see cref="Sentiment"/>.
 /// </summary>
 /// <param name="score">Sentiment score.</param>
 /// <param name="probability">Sentiment probability (certainty).</param>
 public Sentiment(SentimentScore score, double probability)
 {
     Score       = score;
     Probability = probability;
 }
コード例 #11
0
        static SentimentScore Analyze(string textToAnalyze)
        {
            SentimentScore ret = new SentimentScore();
            try
            {
                string url = string.Format("http://www.sentiment140.com/api/classify?text={0}",
                                            HttpUtility.UrlEncode(textToAnalyze, Encoding.UTF8));
                var response = HttpWebRequest.Create(url).GetResponse();

                using (var streamReader = new StreamReader(response.GetResponseStream()))
                {
                    try
                    {
                        // Read from source
                        var line = streamReader.ReadLine();

                        // Parse
                        var jObject = JObject.Parse(line);

                        int polarity = jObject.SelectToken("results", true).SelectToken("polarity", true).Value<int>();
                        switch (polarity)
                        {
                            case 0: ret.Score = SentimentScore.score.Negative;
                                    ret.Sentiment = "Negative";
                                break;
                            case 4: ret.Score = SentimentScore.score.Positive;
                                    ret.Sentiment = "Positive";
                                break;
                            // 2 or others
                            default: ret.Score = SentimentScore.score.Neutral;
                                     ret.Sentiment = "Neutral";
                                break;
                        }
                    }
                    catch (Exception)
                    {
                        ret.Score = SentimentScore.score.Neutral;
                        ret.Sentiment = "Neutral";
                        return ret;
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Sentiment calculation FAILED with:/n{0}", e);
                ret.Score = SentimentScore.score.Neutral;
                ret.Sentiment = "Neutral";
                return ret;
            }
            return ret;
        }